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

lightningnetwork / lnd / 13374835583

17 Feb 2025 04:33PM UTC coverage: 57.633% (-1.2%) from 58.788%
13374835583

Pull #9518

github

starius
walletrpc: fix description of bumpfee.immediate

It waits for the next block and sends CPFP even if there are no other
inputs to form a batch.
Pull Request #9518: walletrpc: fix description of bumpfee.immediate

103406 of 179421 relevant lines covered (57.63%)

24899.98 hits per line

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

0.28
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

139
        // EndorsementExperimentEnd is the time after which nodes should stop
140
        // propagating experimental endorsement signals.
141
        //
142
        // Per blip04: January 1, 2026 12:00:00 AM UTC in unix seconds.
143
        EndorsementExperimentEnd = time.Unix(1767225600, 0)
144
)
145

146
// errPeerAlreadyConnected is an error returned by the server when we're
147
// commanded to connect to a peer, but they're already connected.
148
type errPeerAlreadyConnected struct {
149
        peer *peer.Brontide
150
}
151

152
// Error returns the human readable version of this error type.
153
//
154
// NOTE: Part of the error interface.
155
func (e *errPeerAlreadyConnected) Error() string {
×
156
        return fmt.Sprintf("already connected to peer: %v", e.peer)
×
157
}
×
158

159
// server is the main server of the Lightning Network Daemon. The server houses
160
// global state pertaining to the wallet, database, and the rpcserver.
161
// Additionally, the server is also used as a central messaging bus to interact
162
// with any of its companion objects.
163
type server struct {
164
        active   int32 // atomic
165
        stopping int32 // atomic
166

167
        start sync.Once
168
        stop  sync.Once
169

170
        cfg *Config
171

172
        implCfg *ImplementationCfg
173

174
        // identityECDH is an ECDH capable wrapper for the private key used
175
        // to authenticate any incoming connections.
176
        identityECDH keychain.SingleKeyECDH
177

178
        // identityKeyLoc is the key locator for the above wrapped identity key.
179
        identityKeyLoc keychain.KeyLocator
180

181
        // nodeSigner is an implementation of the MessageSigner implementation
182
        // that's backed by the identity private key of the running lnd node.
183
        nodeSigner *netann.NodeSigner
184

185
        chanStatusMgr *netann.ChanStatusManager
186

187
        // listenAddrs is the list of addresses the server is currently
188
        // listening on.
189
        listenAddrs []net.Addr
190

191
        // torController is a client that will communicate with a locally
192
        // running Tor server. This client will handle initiating and
193
        // authenticating the connection to the Tor server, automatically
194
        // creating and setting up onion services, etc.
195
        torController *tor.Controller
196

197
        // natTraversal is the specific NAT traversal technique used to
198
        // automatically set up port forwarding rules in order to advertise to
199
        // the network that the node is accepting inbound connections.
200
        natTraversal nat.Traversal
201

202
        // lastDetectedIP is the last IP detected by the NAT traversal technique
203
        // above. This IP will be watched periodically in a goroutine in order
204
        // to handle dynamic IP changes.
205
        lastDetectedIP net.IP
206

207
        mu sync.RWMutex
208

209
        // peersByPub is a map of the active peers.
210
        //
211
        // NOTE: The key used here is the raw bytes of the peer's public key to
212
        // string conversion, which means it cannot be printed using `%s` as it
213
        // will just print the binary.
214
        //
215
        // TODO(yy): Use the hex string instead.
216
        peersByPub map[string]*peer.Brontide
217

218
        inboundPeers  map[string]*peer.Brontide
219
        outboundPeers map[string]*peer.Brontide
220

221
        peerConnectedListeners    map[string][]chan<- lnpeer.Peer
222
        peerDisconnectedListeners map[string][]chan<- struct{}
223

224
        // TODO(yy): the Brontide.Start doesn't know this value, which means it
225
        // will continue to send messages even if there are no active channels
226
        // and the value below is false. Once it's pruned, all its connections
227
        // will be closed, thus the Brontide.Start will return an error.
228
        persistentPeers        map[string]bool
229
        persistentPeersBackoff map[string]time.Duration
230
        persistentPeerAddrs    map[string][]*lnwire.NetAddress
231
        persistentConnReqs     map[string][]*connmgr.ConnReq
232
        persistentRetryCancels map[string]chan struct{}
233

234
        // peerErrors keeps a set of peer error buffers for peers that have
235
        // disconnected from us. This allows us to track historic peer errors
236
        // over connections. The string of the peer's compressed pubkey is used
237
        // as a key for this map.
238
        peerErrors map[string]*queue.CircularBuffer
239

240
        // ignorePeerTermination tracks peers for which the server has initiated
241
        // a disconnect. Adding a peer to this map causes the peer termination
242
        // watcher to short circuit in the event that peers are purposefully
243
        // disconnected.
244
        ignorePeerTermination map[*peer.Brontide]struct{}
245

246
        // scheduledPeerConnection maps a pubkey string to a callback that
247
        // should be executed in the peerTerminationWatcher the prior peer with
248
        // the same pubkey exits.  This allows the server to wait until the
249
        // prior peer has cleaned up successfully, before adding the new peer
250
        // intended to replace it.
251
        scheduledPeerConnection map[string]func()
252

253
        // pongBuf is a shared pong reply buffer we'll use across all active
254
        // peer goroutines. We know the max size of a pong message
255
        // (lnwire.MaxPongBytes), so we can allocate this ahead of time, and
256
        // avoid allocations each time we need to send a pong message.
257
        pongBuf []byte
258

259
        cc *chainreg.ChainControl
260

261
        fundingMgr *funding.Manager
262

263
        graphDB *graphdb.ChannelGraph
264

265
        chanStateDB *channeldb.ChannelStateDB
266

267
        addrSource channeldb.AddrSource
268

269
        // miscDB is the DB that contains all "other" databases within the main
270
        // channel DB that haven't been separated out yet.
271
        miscDB *channeldb.DB
272

273
        invoicesDB invoices.InvoiceDB
274

275
        aliasMgr *aliasmgr.Manager
276

277
        htlcSwitch *htlcswitch.Switch
278

279
        interceptableSwitch *htlcswitch.InterceptableSwitch
280

281
        invoices *invoices.InvoiceRegistry
282

283
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
284

285
        channelNotifier *channelnotifier.ChannelNotifier
286

287
        peerNotifier *peernotifier.PeerNotifier
288

289
        htlcNotifier *htlcswitch.HtlcNotifier
290

291
        witnessBeacon contractcourt.WitnessBeacon
292

293
        breachArbitrator *contractcourt.BreachArbitrator
294

295
        missionController *routing.MissionController
296
        defaultMC         *routing.MissionControl
297

298
        graphBuilder *graph.Builder
299

300
        chanRouter *routing.ChannelRouter
301

302
        controlTower routing.ControlTower
303

304
        authGossiper *discovery.AuthenticatedGossiper
305

306
        localChanMgr *localchans.Manager
307

308
        utxoNursery *contractcourt.UtxoNursery
309

310
        sweeper *sweep.UtxoSweeper
311

312
        chainArb *contractcourt.ChainArbitrator
313

314
        sphinx *hop.OnionProcessor
315

316
        towerClientMgr *wtclient.Manager
317

318
        connMgr *connmgr.ConnManager
319

320
        sigPool *lnwallet.SigPool
321

322
        writePool *pool.Write
323

324
        readPool *pool.Read
325

326
        tlsManager *TLSManager
327

328
        // featureMgr dispatches feature vectors for various contexts within the
329
        // daemon.
330
        featureMgr *feature.Manager
331

332
        // currentNodeAnn is the node announcement that has been broadcast to
333
        // the network upon startup, if the attributes of the node (us) has
334
        // changed since last start.
335
        currentNodeAnn *lnwire.NodeAnnouncement
336

337
        // chansToRestore is the set of channels that upon starting, the server
338
        // should attempt to restore/recover.
339
        chansToRestore walletunlocker.ChannelsToRecover
340

341
        // chanSubSwapper is a sub-system that will ensure our on-disk channel
342
        // backups are consistent at all times. It interacts with the
343
        // channelNotifier to be notified of newly opened and closed channels.
344
        chanSubSwapper *chanbackup.SubSwapper
345

346
        // chanEventStore tracks the behaviour of channels and their remote peers to
347
        // provide insights into their health and performance.
348
        chanEventStore *chanfitness.ChannelEventStore
349

350
        hostAnn *netann.HostAnnouncer
351

352
        // livenessMonitor monitors that lnd has access to critical resources.
353
        livenessMonitor *healthcheck.Monitor
354

355
        customMessageServer *subscribe.Server
356

357
        // txPublisher is a publisher with fee-bumping capability.
358
        txPublisher *sweep.TxPublisher
359

360
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
361
        // of new blocks.
362
        blockbeatDispatcher *chainio.BlockbeatDispatcher
363

364
        quit chan struct{}
365

366
        wg sync.WaitGroup
367
}
368

369
// updatePersistentPeerAddrs subscribes to topology changes and stores
370
// advertised addresses for any NodeAnnouncements from our persisted peers.
371
func (s *server) updatePersistentPeerAddrs() error {
×
372
        graphSub, err := s.graphBuilder.SubscribeTopology()
×
373
        if err != nil {
×
374
                return err
×
375
        }
×
376

377
        s.wg.Add(1)
×
378
        go func() {
×
379
                defer func() {
×
380
                        graphSub.Cancel()
×
381
                        s.wg.Done()
×
382
                }()
×
383

384
                for {
×
385
                        select {
×
386
                        case <-s.quit:
×
387
                                return
×
388

389
                        case topChange, ok := <-graphSub.TopologyChanges:
×
390
                                // If the router is shutting down, then we will
×
391
                                // as well.
×
392
                                if !ok {
×
393
                                        return
×
394
                                }
×
395

396
                                for _, update := range topChange.NodeUpdates {
×
397
                                        pubKeyStr := string(
×
398
                                                update.IdentityKey.
×
399
                                                        SerializeCompressed(),
×
400
                                        )
×
401

×
402
                                        // We only care about updates from
×
403
                                        // our persistentPeers.
×
404
                                        s.mu.RLock()
×
405
                                        _, ok := s.persistentPeers[pubKeyStr]
×
406
                                        s.mu.RUnlock()
×
407
                                        if !ok {
×
408
                                                continue
×
409
                                        }
410

411
                                        addrs := make([]*lnwire.NetAddress, 0,
×
412
                                                len(update.Addresses))
×
413

×
414
                                        for _, addr := range update.Addresses {
×
415
                                                addrs = append(addrs,
×
416
                                                        &lnwire.NetAddress{
×
417
                                                                IdentityKey: update.IdentityKey,
×
418
                                                                Address:     addr,
×
419
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
420
                                                        },
×
421
                                                )
×
422
                                        }
×
423

424
                                        s.mu.Lock()
×
425

×
426
                                        // Update the stored addresses for this
×
427
                                        // to peer to reflect the new set.
×
428
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
×
429

×
430
                                        // If there are no outstanding
×
431
                                        // connection requests for this peer
×
432
                                        // then our work is done since we are
×
433
                                        // not currently trying to connect to
×
434
                                        // them.
×
435
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
×
436
                                                s.mu.Unlock()
×
437
                                                continue
×
438
                                        }
439

440
                                        s.mu.Unlock()
×
441

×
442
                                        s.connectToPersistentPeer(pubKeyStr)
×
443
                                }
444
                        }
445
                }
446
        }()
447

448
        return nil
×
449
}
450

451
// CustomMessage is a custom message that is received from a peer.
452
type CustomMessage struct {
453
        // Peer is the peer pubkey
454
        Peer [33]byte
455

456
        // Msg is the custom wire message.
457
        Msg *lnwire.Custom
458
}
459

460
// parseAddr parses an address from its string format to a net.Addr.
461
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
×
462
        var (
×
463
                host string
×
464
                port int
×
465
        )
×
466

×
467
        // Split the address into its host and port components.
×
468
        h, p, err := net.SplitHostPort(address)
×
469
        if err != nil {
×
470
                // If a port wasn't specified, we'll assume the address only
×
471
                // contains the host so we'll use the default port.
×
472
                host = address
×
473
                port = defaultPeerPort
×
474
        } else {
×
475
                // Otherwise, we'll note both the host and ports.
×
476
                host = h
×
477
                portNum, err := strconv.Atoi(p)
×
478
                if err != nil {
×
479
                        return nil, err
×
480
                }
×
481
                port = portNum
×
482
        }
483

484
        if tor.IsOnionHost(host) {
×
485
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
486
        }
×
487

488
        // If the host is part of a TCP address, we'll use the network
489
        // specific ResolveTCPAddr function in order to resolve these
490
        // addresses over Tor in order to prevent leaking your real IP
491
        // address.
492
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
×
493
        return netCfg.ResolveTCPAddr("tcp", hostPort)
×
494
}
495

496
// noiseDial is a factory function which creates a connmgr compliant dialing
497
// function by returning a closure which includes the server's identity key.
498
func noiseDial(idKey keychain.SingleKeyECDH,
499
        netCfg tor.Net, timeout time.Duration) func(net.Addr) (net.Conn, error) {
×
500

×
501
        return func(a net.Addr) (net.Conn, error) {
×
502
                lnAddr := a.(*lnwire.NetAddress)
×
503
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
×
504
        }
×
505
}
506

507
// newServer creates a new instance of the server which is to listen using the
508
// passed listener address.
509
func newServer(cfg *Config, listenAddrs []net.Addr,
510
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
511
        nodeKeyDesc *keychain.KeyDescriptor,
512
        chansToRestore walletunlocker.ChannelsToRecover,
513
        chanPredicate chanacceptor.ChannelAcceptor,
514
        torController *tor.Controller, tlsManager *TLSManager,
515
        leaderElector cluster.LeaderElector,
516
        implCfg *ImplementationCfg) (*server, error) {
×
517

×
518
        var (
×
519
                err         error
×
520
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
×
521

×
522
                // We just derived the full descriptor, so we know the public
×
523
                // key is set on it.
×
524
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
×
525
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
×
526
                )
×
527
        )
×
528

×
529
        listeners := make([]net.Listener, len(listenAddrs))
×
530
        for i, listenAddr := range listenAddrs {
×
531
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
×
532
                // doesn't need to call the general lndResolveTCP function
×
533
                // since we are resolving a local address.
×
534
                listeners[i], err = brontide.NewListener(
×
535
                        nodeKeyECDH, listenAddr.String(),
×
536
                )
×
537
                if err != nil {
×
538
                        return nil, err
×
539
                }
×
540
        }
541

542
        var serializedPubKey [33]byte
×
543
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
544

×
545
        netParams := cfg.ActiveNetParams.Params
×
546

×
547
        // Initialize the sphinx router.
×
548
        replayLog := htlcswitch.NewDecayedLog(
×
549
                dbs.DecayedLogDB, cc.ChainNotifier,
×
550
        )
×
551
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
×
552

×
553
        writeBufferPool := pool.NewWriteBuffer(
×
554
                pool.DefaultWriteBufferGCInterval,
×
555
                pool.DefaultWriteBufferExpiryInterval,
×
556
        )
×
557

×
558
        writePool := pool.NewWrite(
×
559
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
×
560
        )
×
561

×
562
        readBufferPool := pool.NewReadBuffer(
×
563
                pool.DefaultReadBufferGCInterval,
×
564
                pool.DefaultReadBufferExpiryInterval,
×
565
        )
×
566

×
567
        readPool := pool.NewRead(
×
568
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
×
569
        )
×
570

×
571
        // If the taproot overlay flag is set, but we don't have an aux funding
×
572
        // controller, then we'll exit as this is incompatible.
×
573
        if cfg.ProtocolOptions.TaprootOverlayChans &&
×
574
                implCfg.AuxFundingController.IsNone() {
×
575

×
576
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
577
                        "aux controllers")
×
578
        }
×
579

580
        //nolint:ll
581
        featureMgr, err := feature.NewManager(feature.Config{
×
582
                NoTLVOnion:                cfg.ProtocolOptions.LegacyOnion(),
×
583
                NoStaticRemoteKey:         cfg.ProtocolOptions.NoStaticRemoteKey(),
×
584
                NoAnchors:                 cfg.ProtocolOptions.NoAnchorCommitments(),
×
585
                NoWumbo:                   !cfg.ProtocolOptions.Wumbo(),
×
586
                NoScriptEnforcementLease:  cfg.ProtocolOptions.NoScriptEnforcementLease(),
×
587
                NoKeysend:                 !cfg.AcceptKeySend,
×
588
                NoOptionScidAlias:         !cfg.ProtocolOptions.ScidAlias(),
×
589
                NoZeroConf:                !cfg.ProtocolOptions.ZeroConf(),
×
590
                NoAnySegwit:               cfg.ProtocolOptions.NoAnySegwit(),
×
591
                CustomFeatures:            cfg.ProtocolOptions.CustomFeatures(),
×
592
                NoTaprootChans:            !cfg.ProtocolOptions.TaprootChans,
×
593
                NoTaprootOverlay:          !cfg.ProtocolOptions.TaprootOverlayChans,
×
594
                NoRouteBlinding:           cfg.ProtocolOptions.NoRouteBlinding(),
×
595
                NoExperimentalEndorsement: cfg.ProtocolOptions.NoExperimentalEndorsement(),
×
596
                NoQuiescence:              cfg.ProtocolOptions.NoQuiescence(),
×
597
        })
×
598
        if err != nil {
×
599
                return nil, err
×
600
        }
×
601

602
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
×
603
        registryConfig := invoices.RegistryConfig{
×
604
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
×
605
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
×
606
                Clock:                       clock.NewDefaultClock(),
×
607
                AcceptKeySend:               cfg.AcceptKeySend,
×
608
                AcceptAMP:                   cfg.AcceptAMP,
×
609
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
×
610
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
×
611
                KeysendHoldTime:             cfg.KeysendHoldTime,
×
612
                HtlcInterceptor:             invoiceHtlcModifier,
×
613
        }
×
614

×
615
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
×
616

×
617
        s := &server{
×
618
                cfg:            cfg,
×
619
                implCfg:        implCfg,
×
620
                graphDB:        dbs.GraphDB,
×
621
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
×
622
                addrSource:     addrSource,
×
623
                miscDB:         dbs.ChanStateDB,
×
624
                invoicesDB:     dbs.InvoiceDB,
×
625
                cc:             cc,
×
626
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
×
627
                writePool:      writePool,
×
628
                readPool:       readPool,
×
629
                chansToRestore: chansToRestore,
×
630

×
631
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
×
632
                        cc.ChainNotifier,
×
633
                ),
×
634
                channelNotifier: channelnotifier.New(
×
635
                        dbs.ChanStateDB.ChannelStateDB(),
×
636
                ),
×
637

×
638
                identityECDH:   nodeKeyECDH,
×
639
                identityKeyLoc: nodeKeyDesc.KeyLocator,
×
640
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
×
641

×
642
                listenAddrs: listenAddrs,
×
643

×
644
                // TODO(roasbeef): derive proper onion key based on rotation
×
645
                // schedule
×
646
                sphinx: hop.NewOnionProcessor(sphinxRouter),
×
647

×
648
                torController: torController,
×
649

×
650
                persistentPeers:         make(map[string]bool),
×
651
                persistentPeersBackoff:  make(map[string]time.Duration),
×
652
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
×
653
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
×
654
                persistentRetryCancels:  make(map[string]chan struct{}),
×
655
                peerErrors:              make(map[string]*queue.CircularBuffer),
×
656
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
×
657
                scheduledPeerConnection: make(map[string]func()),
×
658
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
×
659

×
660
                peersByPub:                make(map[string]*peer.Brontide),
×
661
                inboundPeers:              make(map[string]*peer.Brontide),
×
662
                outboundPeers:             make(map[string]*peer.Brontide),
×
663
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
×
664
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
×
665

×
666
                invoiceHtlcModifier: invoiceHtlcModifier,
×
667

×
668
                customMessageServer: subscribe.NewServer(),
×
669

×
670
                tlsManager: tlsManager,
×
671

×
672
                featureMgr: featureMgr,
×
673
                quit:       make(chan struct{}),
×
674
        }
×
675

×
676
        // Start the low-level services once they are initialized.
×
677
        //
×
678
        // TODO(yy): break the server startup into four steps,
×
679
        // 1. init the low-level services.
×
680
        // 2. start the low-level services.
×
681
        // 3. init the high-level services.
×
682
        // 4. start the high-level services.
×
683
        if err := s.startLowLevelServices(); err != nil {
×
684
                return nil, err
×
685
        }
×
686

687
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
×
688
        if err != nil {
×
689
                return nil, err
×
690
        }
×
691

692
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
×
693
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
×
694
                uint32(currentHeight), currentHash, cc.ChainNotifier,
×
695
        )
×
696
        s.invoices = invoices.NewRegistry(
×
697
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
×
698
        )
×
699

×
700
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
×
701

×
702
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
×
703
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
704

×
705
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
×
706
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
×
707
                if err != nil {
×
708
                        return err
×
709
                }
×
710

711
                s.htlcSwitch.UpdateLinkAliases(link)
×
712

×
713
                return nil
×
714
        }
715

716
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
×
717
        if err != nil {
×
718
                return nil, err
×
719
        }
×
720

721
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
×
722
                DB:                   dbs.ChanStateDB,
×
723
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
×
724
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
×
725
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
×
726
                LocalChannelClose: func(pubKey []byte,
×
727
                        request *htlcswitch.ChanClose) {
×
728

×
729
                        peer, err := s.FindPeerByPubStr(string(pubKey))
×
730
                        if err != nil {
×
731
                                srvrLog.Errorf("unable to close channel, peer"+
×
732
                                        " with %v id can't be found: %v",
×
733
                                        pubKey, err,
×
734
                                )
×
735
                                return
×
736
                        }
×
737

738
                        peer.HandleLocalCloseChanReqs(request)
×
739
                },
740
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
741
                SwitchPackager:         channeldb.NewSwitchPackager(),
742
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
743
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
744
                Notifier:               s.cc.ChainNotifier,
745
                HtlcNotifier:           s.htlcNotifier,
746
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
747
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
748
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
749
                AllowCircularRoute:     cfg.AllowCircularRoute,
750
                RejectHTLC:             cfg.RejectHTLC,
751
                Clock:                  clock.NewDefaultClock(),
752
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
753
                MaxFeeExposure:         thresholdMSats,
754
                SignAliasUpdate:        s.signAliasUpdate,
755
                IsAlias:                aliasmgr.IsAlias,
756
        }, uint32(currentHeight))
757
        if err != nil {
×
758
                return nil, err
×
759
        }
×
760
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
×
761
                &htlcswitch.InterceptableSwitchConfig{
×
762
                        Switch:             s.htlcSwitch,
×
763
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
×
764
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
×
765
                        RequireInterceptor: s.cfg.RequireInterceptor,
×
766
                        Notifier:           s.cc.ChainNotifier,
×
767
                },
×
768
        )
×
769
        if err != nil {
×
770
                return nil, err
×
771
        }
×
772

773
        s.witnessBeacon = newPreimageBeacon(
×
774
                dbs.ChanStateDB.NewWitnessCache(),
×
775
                s.interceptableSwitch.ForwardPacket,
×
776
        )
×
777

×
778
        chanStatusMgrCfg := &netann.ChanStatusConfig{
×
779
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
×
780
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
×
781
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
×
782
                OurPubKey:                nodeKeyDesc.PubKey,
×
783
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
×
784
                MessageSigner:            s.nodeSigner,
×
785
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
×
786
                ApplyChannelUpdate:       s.applyChannelUpdate,
×
787
                DB:                       s.chanStateDB,
×
788
                Graph:                    dbs.GraphDB,
×
789
        }
×
790

×
791
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
×
792
        if err != nil {
×
793
                return nil, err
×
794
        }
×
795
        s.chanStatusMgr = chanStatusMgr
×
796

×
797
        // If enabled, use either UPnP or NAT-PMP to automatically configure
×
798
        // port forwarding for users behind a NAT.
×
799
        if cfg.NAT {
×
800
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
801

×
802
                discoveryTimeout := time.Duration(10 * time.Second)
×
803

×
804
                ctx, cancel := context.WithTimeout(
×
805
                        context.Background(), discoveryTimeout,
×
806
                )
×
807
                defer cancel()
×
808
                upnp, err := nat.DiscoverUPnP(ctx)
×
809
                if err == nil {
×
810
                        s.natTraversal = upnp
×
811
                } else {
×
812
                        // If we were not able to discover a UPnP enabled device
×
813
                        // on the local network, we'll fall back to attempting
×
814
                        // to discover a NAT-PMP enabled device.
×
815
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
816
                                "device on the local network: %v", err)
×
817

×
818
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
819
                                "enabled device")
×
820

×
821
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
822
                        if err != nil {
×
823
                                err := fmt.Errorf("unable to discover a "+
×
824
                                        "NAT-PMP enabled device on the local "+
×
825
                                        "network: %v", err)
×
826
                                srvrLog.Error(err)
×
827
                                return nil, err
×
828
                        }
×
829

830
                        s.natTraversal = pmp
×
831
                }
832
        }
833

834
        // If we were requested to automatically configure port forwarding,
835
        // we'll use the ports that the server will be listening on.
836
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
×
837
        for idx, ip := range cfg.ExternalIPs {
×
838
                externalIPStrings[idx] = ip.String()
×
839
        }
×
840
        if s.natTraversal != nil {
×
841
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
842
                for _, listenAddr := range listenAddrs {
×
843
                        // At this point, the listen addresses should have
×
844
                        // already been normalized, so it's safe to ignore the
×
845
                        // errors.
×
846
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
847
                        port, _ := strconv.Atoi(portStr)
×
848

×
849
                        listenPorts = append(listenPorts, uint16(port))
×
850
                }
×
851

852
                ips, err := s.configurePortForwarding(listenPorts...)
×
853
                if err != nil {
×
854
                        srvrLog.Errorf("Unable to automatically set up port "+
×
855
                                "forwarding using %s: %v",
×
856
                                s.natTraversal.Name(), err)
×
857
                } else {
×
858
                        srvrLog.Infof("Automatically set up port forwarding "+
×
859
                                "using %s to advertise external IP",
×
860
                                s.natTraversal.Name())
×
861
                        externalIPStrings = append(externalIPStrings, ips...)
×
862
                }
×
863
        }
864

865
        // If external IP addresses have been specified, add those to the list
866
        // of this server's addresses.
867
        externalIPs, err := lncfg.NormalizeAddresses(
×
868
                externalIPStrings, strconv.Itoa(defaultPeerPort),
×
869
                cfg.net.ResolveTCPAddr,
×
870
        )
×
871
        if err != nil {
×
872
                return nil, err
×
873
        }
×
874

875
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
×
876
        selfAddrs = append(selfAddrs, externalIPs...)
×
877

×
878
        // We'll now reconstruct a node announcement based on our current
×
879
        // configuration so we can send it out as a sort of heart beat within
×
880
        // the network.
×
881
        //
×
882
        // We'll start by parsing the node color from configuration.
×
883
        color, err := lncfg.ParseHexColor(cfg.Color)
×
884
        if err != nil {
×
885
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
886
                return nil, err
×
887
        }
×
888

889
        // If no alias is provided, default to first 10 characters of public
890
        // key.
891
        alias := cfg.Alias
×
892
        if alias == "" {
×
893
                alias = hex.EncodeToString(serializedPubKey[:10])
×
894
        }
×
895
        nodeAlias, err := lnwire.NewNodeAlias(alias)
×
896
        if err != nil {
×
897
                return nil, err
×
898
        }
×
899
        selfNode := &models.LightningNode{
×
900
                HaveNodeAnnouncement: true,
×
901
                LastUpdate:           time.Now(),
×
902
                Addresses:            selfAddrs,
×
903
                Alias:                nodeAlias.String(),
×
904
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
×
905
                Color:                color,
×
906
        }
×
907
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
908

×
909
        // Based on the disk representation of the node announcement generated
×
910
        // above, we'll generate a node announcement that can go out on the
×
911
        // network so we can properly sign it.
×
912
        nodeAnn, err := selfNode.NodeAnnouncement(false)
×
913
        if err != nil {
×
914
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
915
        }
×
916

917
        // With the announcement generated, we'll sign it to properly
918
        // authenticate the message on the network.
919
        authSig, err := netann.SignAnnouncement(
×
920
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
×
921
        )
×
922
        if err != nil {
×
923
                return nil, fmt.Errorf("unable to generate signature for "+
×
924
                        "self node announcement: %v", err)
×
925
        }
×
926
        selfNode.AuthSigBytes = authSig.Serialize()
×
927
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
×
928
                selfNode.AuthSigBytes,
×
929
        )
×
930
        if err != nil {
×
931
                return nil, err
×
932
        }
×
933

934
        // Finally, we'll update the representation on disk, and update our
935
        // cached in-memory version as well.
936
        if err := dbs.GraphDB.SetSourceNode(selfNode); err != nil {
×
937
                return nil, fmt.Errorf("can't set self node: %w", err)
×
938
        }
×
939
        s.currentNodeAnn = nodeAnn
×
940

×
941
        // The router will get access to the payment ID sequencer, such that it
×
942
        // can generate unique payment IDs.
×
943
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
×
944
        if err != nil {
×
945
                return nil, err
×
946
        }
×
947

948
        // Instantiate mission control with config from the sub server.
949
        //
950
        // TODO(joostjager): When we are further in the process of moving to sub
951
        // servers, the mission control instance itself can be moved there too.
952
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
×
953

×
954
        // We only initialize a probability estimator if there's no custom one.
×
955
        var estimator routing.Estimator
×
956
        if cfg.Estimator != nil {
×
957
                estimator = cfg.Estimator
×
958
        } else {
×
959
                switch routingConfig.ProbabilityEstimatorType {
×
960
                case routing.AprioriEstimatorName:
×
961
                        aCfg := routingConfig.AprioriConfig
×
962
                        aprioriConfig := routing.AprioriConfig{
×
963
                                AprioriHopProbability: aCfg.HopProbability,
×
964
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
×
965
                                AprioriWeight:         aCfg.Weight,
×
966
                                CapacityFraction:      aCfg.CapacityFraction,
×
967
                        }
×
968

×
969
                        estimator, err = routing.NewAprioriEstimator(
×
970
                                aprioriConfig,
×
971
                        )
×
972
                        if err != nil {
×
973
                                return nil, err
×
974
                        }
×
975

976
                case routing.BimodalEstimatorName:
×
977
                        bCfg := routingConfig.BimodalConfig
×
978
                        bimodalConfig := routing.BimodalConfig{
×
979
                                BimodalNodeWeight: bCfg.NodeWeight,
×
980
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
981
                                        bCfg.Scale,
×
982
                                ),
×
983
                                BimodalDecayTime: bCfg.DecayTime,
×
984
                        }
×
985

×
986
                        estimator, err = routing.NewBimodalEstimator(
×
987
                                bimodalConfig,
×
988
                        )
×
989
                        if err != nil {
×
990
                                return nil, err
×
991
                        }
×
992

993
                default:
×
994
                        return nil, fmt.Errorf("unknown estimator type %v",
×
995
                                routingConfig.ProbabilityEstimatorType)
×
996
                }
997
        }
998

999
        mcCfg := &routing.MissionControlConfig{
×
1000
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
×
1001
                Estimator:               estimator,
×
1002
                MaxMcHistory:            routingConfig.MaxMcHistory,
×
1003
                McFlushInterval:         routingConfig.McFlushInterval,
×
1004
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
×
1005
        }
×
1006

×
1007
        s.missionController, err = routing.NewMissionController(
×
1008
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
×
1009
        )
×
1010
        if err != nil {
×
1011
                return nil, fmt.Errorf("can't create mission control "+
×
1012
                        "manager: %w", err)
×
1013
        }
×
1014
        s.defaultMC, err = s.missionController.GetNamespacedStore(
×
1015
                routing.DefaultMissionControlNamespace,
×
1016
        )
×
1017
        if err != nil {
×
1018
                return nil, fmt.Errorf("can't create mission control in the "+
×
1019
                        "default namespace: %w", err)
×
1020
        }
×
1021

1022
        srvrLog.Debugf("Instantiating payment session source with config: "+
×
1023
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
×
1024
                int64(routingConfig.AttemptCost),
×
1025
                float64(routingConfig.AttemptCostPPM)/10000,
×
1026
                routingConfig.MinRouteProbability)
×
1027

×
1028
        pathFindingConfig := routing.PathFindingConfig{
×
1029
                AttemptCost: lnwire.NewMSatFromSatoshis(
×
1030
                        routingConfig.AttemptCost,
×
1031
                ),
×
1032
                AttemptCostPPM: routingConfig.AttemptCostPPM,
×
1033
                MinProbability: routingConfig.MinRouteProbability,
×
1034
        }
×
1035

×
1036
        sourceNode, err := dbs.GraphDB.SourceNode()
×
1037
        if err != nil {
×
1038
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1039
        }
×
1040
        paymentSessionSource := &routing.SessionSource{
×
1041
                GraphSessionFactory: graphsession.NewGraphSessionFactory(
×
1042
                        dbs.GraphDB,
×
1043
                ),
×
1044
                SourceNode:        sourceNode,
×
1045
                MissionControl:    s.defaultMC,
×
1046
                GetLink:           s.htlcSwitch.GetLinkByShortID,
×
1047
                PathFindingConfig: pathFindingConfig,
×
1048
        }
×
1049

×
1050
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
×
1051

×
1052
        s.controlTower = routing.NewControlTower(paymentControl)
×
1053

×
1054
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
×
1055
                cfg.Routing.StrictZombiePruning
×
1056

×
1057
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
×
1058
                SelfNode:            selfNode.PubKeyBytes,
×
1059
                Graph:               dbs.GraphDB,
×
1060
                Chain:               cc.ChainIO,
×
1061
                ChainView:           cc.ChainView,
×
1062
                Notifier:            cc.ChainNotifier,
×
1063
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
×
1064
                GraphPruneInterval:  time.Hour,
×
1065
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
×
1066
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
×
1067
                StrictZombiePruning: strictPruning,
×
1068
                IsAlias:             aliasmgr.IsAlias,
×
1069
        })
×
1070
        if err != nil {
×
1071
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1072
        }
×
1073

1074
        s.chanRouter, err = routing.New(routing.Config{
×
1075
                SelfNode:           selfNode.PubKeyBytes,
×
1076
                RoutingGraph:       graphsession.NewRoutingGraph(dbs.GraphDB),
×
1077
                Chain:              cc.ChainIO,
×
1078
                Payer:              s.htlcSwitch,
×
1079
                Control:            s.controlTower,
×
1080
                MissionControl:     s.defaultMC,
×
1081
                SessionSource:      paymentSessionSource,
×
1082
                GetLink:            s.htlcSwitch.GetLinkByShortID,
×
1083
                NextPaymentID:      sequencer.NextID,
×
1084
                PathFindingConfig:  pathFindingConfig,
×
1085
                Clock:              clock.NewDefaultClock(),
×
1086
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
×
1087
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
×
1088
                TrafficShaper:      implCfg.TrafficShaper,
×
1089
        })
×
1090
        if err != nil {
×
1091
                return nil, fmt.Errorf("can't create router: %w", err)
×
1092
        }
×
1093

1094
        chanSeries := discovery.NewChanSeries(s.graphDB)
×
1095
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
×
1096
        if err != nil {
×
1097
                return nil, err
×
1098
        }
×
1099
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
×
1100
        if err != nil {
×
1101
                return nil, err
×
1102
        }
×
1103

1104
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
×
1105

×
1106
        s.authGossiper = discovery.New(discovery.Config{
×
1107
                Graph:                 s.graphBuilder,
×
1108
                ChainIO:               s.cc.ChainIO,
×
1109
                Notifier:              s.cc.ChainNotifier,
×
1110
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
×
1111
                Broadcast:             s.BroadcastMessage,
×
1112
                ChanSeries:            chanSeries,
×
1113
                NotifyWhenOnline:      s.NotifyWhenOnline,
×
1114
                NotifyWhenOffline:     s.NotifyWhenOffline,
×
1115
                FetchSelfAnnouncement: s.getNodeAnnouncement,
×
1116
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
×
1117
                        error) {
×
1118

×
1119
                        return s.genNodeAnnouncement(nil)
×
1120
                },
×
1121
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1122
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1123
                RetransmitTicker:        ticker.New(time.Minute * 30),
1124
                RebroadcastInterval:     time.Hour * 24,
1125
                WaitingProofStore:       waitingProofStore,
1126
                MessageStore:            gossipMessageStore,
1127
                AnnSigner:               s.nodeSigner,
1128
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1129
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1130
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1131
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1132
                MinimumBatchSize:        10,
1133
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1134
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1135
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1136
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1137
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1138
                IsAlias:                 aliasmgr.IsAlias,
1139
                SignAliasUpdate:         s.signAliasUpdate,
1140
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1141
                GetAlias:                s.aliasMgr.GetPeerAlias,
1142
                FindChannel:             s.findChannel,
1143
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1144
                ScidCloser:              scidCloserMan,
1145
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1146
        }, nodeKeyDesc)
1147

1148
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
×
1149
        //nolint:ll
×
1150
        s.localChanMgr = &localchans.Manager{
×
1151
                SelfPub:              nodeKeyDesc.PubKey,
×
1152
                DefaultRoutingPolicy: cc.RoutingPolicy,
×
1153
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
×
1154
                        *models.ChannelEdgePolicy) error) error {
×
1155

×
1156
                        return s.graphDB.ForEachNodeChannel(selfVertex,
×
1157
                                func(_ kvdb.RTx, c *models.ChannelEdgeInfo,
×
1158
                                        e *models.ChannelEdgePolicy,
×
1159
                                        _ *models.ChannelEdgePolicy) error {
×
1160

×
1161
                                        // NOTE: The invoked callback here may
×
1162
                                        // receive a nil channel policy.
×
1163
                                        return cb(c, e)
×
1164
                                },
×
1165
                        )
1166
                },
1167
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1168
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1169
                FetchChannel:              s.chanStateDB.FetchChannel,
1170
                AddEdge: func(edge *models.ChannelEdgeInfo) error {
×
1171
                        return s.graphBuilder.AddEdge(edge)
×
1172
                },
×
1173
        }
1174

1175
        utxnStore, err := contractcourt.NewNurseryStore(
×
1176
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
×
1177
        )
×
1178
        if err != nil {
×
1179
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1180
                return nil, err
×
1181
        }
×
1182

1183
        sweeperStore, err := sweep.NewSweeperStore(
×
1184
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
×
1185
        )
×
1186
        if err != nil {
×
1187
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1188
                return nil, err
×
1189
        }
×
1190

1191
        aggregator := sweep.NewBudgetAggregator(
×
1192
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
×
1193
                s.implCfg.AuxSweeper,
×
1194
        )
×
1195

×
1196
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
×
1197
                Signer:     cc.Wallet.Cfg.Signer,
×
1198
                Wallet:     cc.Wallet,
×
1199
                Estimator:  cc.FeeEstimator,
×
1200
                Notifier:   cc.ChainNotifier,
×
1201
                AuxSweeper: s.implCfg.AuxSweeper,
×
1202
        })
×
1203

×
1204
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
×
1205
                FeeEstimator: cc.FeeEstimator,
×
1206
                GenSweepScript: newSweepPkScriptGen(
×
1207
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
×
1208
                ),
×
1209
                Signer:               cc.Wallet.Cfg.Signer,
×
1210
                Wallet:               newSweeperWallet(cc.Wallet),
×
1211
                Mempool:              cc.MempoolNotifier,
×
1212
                Notifier:             cc.ChainNotifier,
×
1213
                Store:                sweeperStore,
×
1214
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
×
1215
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
×
1216
                Aggregator:           aggregator,
×
1217
                Publisher:            s.txPublisher,
×
1218
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
×
1219
        })
×
1220

×
1221
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
×
1222
                ChainIO:             cc.ChainIO,
×
1223
                ConfDepth:           1,
×
1224
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
×
1225
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
×
1226
                Notifier:            cc.ChainNotifier,
×
1227
                PublishTransaction:  cc.Wallet.PublishTransaction,
×
1228
                Store:               utxnStore,
×
1229
                SweepInput:          s.sweeper.SweepInput,
×
1230
                Budget:              s.cfg.Sweeper.Budget,
×
1231
        })
×
1232

×
1233
        // Construct a closure that wraps the htlcswitch's CloseLink method.
×
1234
        closeLink := func(chanPoint *wire.OutPoint,
×
1235
                closureType contractcourt.ChannelCloseType) {
×
1236
                // TODO(conner): Properly respect the update and error channels
×
1237
                // returned by CloseLink.
×
1238

×
1239
                // Instruct the switch to close the channel.  Provide no close out
×
1240
                // delivery script or target fee per kw because user input is not
×
1241
                // available when the remote peer closes the channel.
×
1242
                s.htlcSwitch.CloseLink(chanPoint, closureType, 0, 0, nil)
×
1243
        }
×
1244

1245
        // We will use the following channel to reliably hand off contract
1246
        // breach events from the ChannelArbitrator to the BreachArbitrator,
1247
        contractBreaches := make(chan *contractcourt.ContractBreachEvent, 1)
×
1248

×
1249
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
×
1250
                &contractcourt.BreachConfig{
×
1251
                        CloseLink: closeLink,
×
1252
                        DB:        s.chanStateDB,
×
1253
                        Estimator: s.cc.FeeEstimator,
×
1254
                        GenSweepScript: newSweepPkScriptGen(
×
1255
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
×
1256
                        ),
×
1257
                        Notifier:           cc.ChainNotifier,
×
1258
                        PublishTransaction: cc.Wallet.PublishTransaction,
×
1259
                        ContractBreaches:   contractBreaches,
×
1260
                        Signer:             cc.Wallet.Cfg.Signer,
×
1261
                        Store: contractcourt.NewRetributionStore(
×
1262
                                dbs.ChanStateDB,
×
1263
                        ),
×
1264
                        AuxSweeper: s.implCfg.AuxSweeper,
×
1265
                },
×
1266
        )
×
1267

×
1268
        //nolint:ll
×
1269
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
×
1270
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
×
1271
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
×
1272
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
×
1273
                NewSweepAddr: func() ([]byte, error) {
×
1274
                        addr, err := newSweepPkScriptGen(
×
1275
                                cc.Wallet, netParams,
×
1276
                        )().Unpack()
×
1277
                        if err != nil {
×
1278
                                return nil, err
×
1279
                        }
×
1280

1281
                        return addr.DeliveryAddress, nil
×
1282
                },
1283
                PublishTx: cc.Wallet.PublishTransaction,
1284
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
×
1285
                        for _, msg := range msgs {
×
1286
                                err := s.htlcSwitch.ProcessContractResolution(msg)
×
1287
                                if err != nil {
×
1288
                                        return err
×
1289
                                }
×
1290
                        }
1291
                        return nil
×
1292
                },
1293
                IncubateOutputs: func(chanPoint wire.OutPoint,
1294
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1295
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1296
                        broadcastHeight uint32,
1297
                        deadlineHeight fn.Option[int32]) error {
×
1298

×
1299
                        return s.utxoNursery.IncubateOutputs(
×
1300
                                chanPoint, outHtlcRes, inHtlcRes,
×
1301
                                broadcastHeight, deadlineHeight,
×
1302
                        )
×
1303
                },
×
1304
                PreimageDB:   s.witnessBeacon,
1305
                Notifier:     cc.ChainNotifier,
1306
                Mempool:      cc.MempoolNotifier,
1307
                Signer:       cc.Wallet.Cfg.Signer,
1308
                FeeEstimator: cc.FeeEstimator,
1309
                ChainIO:      cc.ChainIO,
1310
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
×
1311
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
1312
                        s.htlcSwitch.RemoveLink(chanID)
×
1313
                        return nil
×
1314
                },
×
1315
                IsOurAddress: cc.Wallet.IsOurAddress,
1316
                ContractBreach: func(chanPoint wire.OutPoint,
1317
                        breachRet *lnwallet.BreachRetribution) error {
×
1318

×
1319
                        // processACK will handle the BreachArbitrator ACKing
×
1320
                        // the event.
×
1321
                        finalErr := make(chan error, 1)
×
1322
                        processACK := func(brarErr error) {
×
1323
                                if brarErr != nil {
×
1324
                                        finalErr <- brarErr
×
1325
                                        return
×
1326
                                }
×
1327

1328
                                // If the BreachArbitrator successfully handled
1329
                                // the event, we can signal that the handoff
1330
                                // was successful.
1331
                                finalErr <- nil
×
1332
                        }
1333

1334
                        event := &contractcourt.ContractBreachEvent{
×
1335
                                ChanPoint:         chanPoint,
×
1336
                                ProcessACK:        processACK,
×
1337
                                BreachRetribution: breachRet,
×
1338
                        }
×
1339

×
1340
                        // Send the contract breach event to the
×
1341
                        // BreachArbitrator.
×
1342
                        select {
×
1343
                        case contractBreaches <- event:
×
1344
                        case <-s.quit:
×
1345
                                return ErrServerShuttingDown
×
1346
                        }
1347

1348
                        // We'll wait for a final error to be available from
1349
                        // the BreachArbitrator.
1350
                        select {
×
1351
                        case err := <-finalErr:
×
1352
                                return err
×
1353
                        case <-s.quit:
×
1354
                                return ErrServerShuttingDown
×
1355
                        }
1356
                },
1357
                DisableChannel: func(chanPoint wire.OutPoint) error {
×
1358
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
×
1359
                },
×
1360
                Sweeper:                       s.sweeper,
1361
                Registry:                      s.invoices,
1362
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1363
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1364
                OnionProcessor:                s.sphinx,
1365
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1366
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1367
                Clock:                         clock.NewDefaultClock(),
1368
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1369
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1370
                HtlcNotifier:                  s.htlcNotifier,
1371
                Budget:                        *s.cfg.Sweeper.Budget,
1372

1373
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1374
                QueryIncomingCircuit: func(
1375
                        circuit models.CircuitKey) *models.CircuitKey {
×
1376

×
1377
                        // Get the circuit map.
×
1378
                        circuits := s.htlcSwitch.CircuitLookup()
×
1379

×
1380
                        // Lookup the outgoing circuit.
×
1381
                        pc := circuits.LookupOpenCircuit(circuit)
×
1382
                        if pc == nil {
×
1383
                                return nil
×
1384
                        }
×
1385

1386
                        return &pc.Incoming
×
1387
                },
1388
                AuxLeafStore: implCfg.AuxLeafStore,
1389
                AuxSigner:    implCfg.AuxSigner,
1390
                AuxResolver:  implCfg.AuxContractResolver,
1391
        }, dbs.ChanStateDB)
1392

1393
        // Select the configuration and funding parameters for Bitcoin.
1394
        chainCfg := cfg.Bitcoin
×
1395
        minRemoteDelay := funding.MinBtcRemoteDelay
×
1396
        maxRemoteDelay := funding.MaxBtcRemoteDelay
×
1397

×
1398
        var chanIDSeed [32]byte
×
1399
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
×
1400
                return nil, err
×
1401
        }
×
1402

1403
        // Wrap the DeleteChannelEdges method so that the funding manager can
1404
        // use it without depending on several layers of indirection.
1405
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
×
1406
                *models.ChannelEdgePolicy, error) {
×
1407

×
1408
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
×
1409
                        scid.ToUint64(),
×
1410
                )
×
1411
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
×
1412
                        // This is unlikely but there is a slim chance of this
×
1413
                        // being hit if lnd was killed via SIGKILL and the
×
1414
                        // funding manager was stepping through the delete
×
1415
                        // alias edge logic.
×
1416
                        return nil, nil
×
1417
                } else if err != nil {
×
1418
                        return nil, err
×
1419
                }
×
1420

1421
                // Grab our key to find our policy.
1422
                var ourKey [33]byte
×
1423
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
1424

×
1425
                var ourPolicy *models.ChannelEdgePolicy
×
1426
                if info != nil && info.NodeKey1Bytes == ourKey {
×
1427
                        ourPolicy = e1
×
1428
                } else {
×
1429
                        ourPolicy = e2
×
1430
                }
×
1431

1432
                if ourPolicy == nil {
×
1433
                        // Something is wrong, so return an error.
×
1434
                        return nil, fmt.Errorf("we don't have an edge")
×
1435
                }
×
1436

1437
                err = s.graphDB.DeleteChannelEdges(
×
1438
                        false, false, scid.ToUint64(),
×
1439
                )
×
1440
                return ourPolicy, err
×
1441
        }
1442

1443
        // For the reservationTimeout and the zombieSweeperInterval different
1444
        // values are set in case we are in a dev environment so enhance test
1445
        // capacilities.
1446
        reservationTimeout := chanfunding.DefaultReservationTimeout
×
1447
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
×
1448

×
1449
        // Get the development config for funding manager. If we are not in
×
1450
        // development mode, this would be nil.
×
1451
        var devCfg *funding.DevConfig
×
1452
        if lncfg.IsDevBuild() {
×
1453
                devCfg = &funding.DevConfig{
×
1454
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
×
1455
                }
×
1456

×
1457
                reservationTimeout = cfg.Dev.GetReservationTimeout()
×
1458
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
×
1459

×
1460
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
×
1461
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
×
1462
                        devCfg, reservationTimeout, zombieSweeperInterval)
×
1463
        }
×
1464

1465
        //nolint:ll
1466
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
×
1467
                Dev:                devCfg,
×
1468
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
×
1469
                IDKey:              nodeKeyDesc.PubKey,
×
1470
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
×
1471
                Wallet:             cc.Wallet,
×
1472
                PublishTransaction: cc.Wallet.PublishTransaction,
×
1473
                UpdateLabel: func(hash chainhash.Hash, label string) error {
×
1474
                        return cc.Wallet.LabelTransaction(hash, label, true)
×
1475
                },
×
1476
                Notifier:     cc.ChainNotifier,
1477
                ChannelDB:    s.chanStateDB,
1478
                FeeEstimator: cc.FeeEstimator,
1479
                SignMessage:  cc.MsgSigner.SignMessage,
1480
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1481
                        error) {
×
1482

×
1483
                        return s.genNodeAnnouncement(nil)
×
1484
                },
×
1485
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1486
                NotifyWhenOnline:     s.NotifyWhenOnline,
1487
                TempChanIDSeed:       chanIDSeed,
1488
                FindChannel:          s.findChannel,
1489
                DefaultRoutingPolicy: cc.RoutingPolicy,
1490
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1491
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1492
                        pushAmt lnwire.MilliSatoshi) uint16 {
×
1493
                        // For large channels we increase the number
×
1494
                        // of confirmations we require for the
×
1495
                        // channel to be considered open. As it is
×
1496
                        // always the responder that gets to choose
×
1497
                        // value, the pushAmt is value being pushed
×
1498
                        // to us. This means we have more to lose
×
1499
                        // in the case this gets re-orged out, and
×
1500
                        // we will require more confirmations before
×
1501
                        // we consider it open.
×
1502

×
1503
                        // In case the user has explicitly specified
×
1504
                        // a default value for the number of
×
1505
                        // confirmations, we use it.
×
1506
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
×
1507
                        if defaultConf != 0 {
×
1508
                                return defaultConf
×
1509
                        }
×
1510

1511
                        minConf := uint64(3)
×
1512
                        maxConf := uint64(6)
×
1513

×
1514
                        // If this is a wumbo channel, then we'll require the
×
1515
                        // max amount of confirmations.
×
1516
                        if chanAmt > MaxFundingAmount {
×
1517
                                return uint16(maxConf)
×
1518
                        }
×
1519

1520
                        // If not we return a value scaled linearly
1521
                        // between 3 and 6, depending on channel size.
1522
                        // TODO(halseth): Use 1 as minimum?
1523
                        maxChannelSize := uint64(
×
1524
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1525
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1526
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1527
                        if conf < minConf {
×
1528
                                conf = minConf
×
1529
                        }
×
1530
                        if conf > maxConf {
×
1531
                                conf = maxConf
×
1532
                        }
×
1533
                        return uint16(conf)
×
1534
                },
1535
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
×
1536
                        // We scale the remote CSV delay (the time the
×
1537
                        // remote have to claim funds in case of a unilateral
×
1538
                        // close) linearly from minRemoteDelay blocks
×
1539
                        // for small channels, to maxRemoteDelay blocks
×
1540
                        // for channels of size MaxFundingAmount.
×
1541

×
1542
                        // In case the user has explicitly specified
×
1543
                        // a default value for the remote delay, we
×
1544
                        // use it.
×
1545
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
×
1546
                        if defaultDelay > 0 {
×
1547
                                return defaultDelay
×
1548
                        }
×
1549

1550
                        // If this is a wumbo channel, then we'll require the
1551
                        // max value.
1552
                        if chanAmt > MaxFundingAmount {
×
1553
                                return maxRemoteDelay
×
1554
                        }
×
1555

1556
                        // If not we scale according to channel size.
1557
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1558
                                chanAmt / MaxFundingAmount)
×
1559
                        if delay < minRemoteDelay {
×
1560
                                delay = minRemoteDelay
×
1561
                        }
×
1562
                        if delay > maxRemoteDelay {
×
1563
                                delay = maxRemoteDelay
×
1564
                        }
×
1565
                        return delay
×
1566
                },
1567
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1568
                        peerKey *btcec.PublicKey) error {
×
1569

×
1570
                        // First, we'll mark this new peer as a persistent peer
×
1571
                        // for re-connection purposes. If the peer is not yet
×
1572
                        // tracked or the user hasn't requested it to be perm,
×
1573
                        // we'll set false to prevent the server from continuing
×
1574
                        // to connect to this peer even if the number of
×
1575
                        // channels with this peer is zero.
×
1576
                        s.mu.Lock()
×
1577
                        pubStr := string(peerKey.SerializeCompressed())
×
1578
                        if _, ok := s.persistentPeers[pubStr]; !ok {
×
1579
                                s.persistentPeers[pubStr] = false
×
1580
                        }
×
1581
                        s.mu.Unlock()
×
1582

×
1583
                        // With that taken care of, we'll send this channel to
×
1584
                        // the chain arb so it can react to on-chain events.
×
1585
                        return s.chainArb.WatchNewChannel(channel)
×
1586
                },
1587
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
×
1588
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
×
1589
                        return s.htlcSwitch.UpdateShortChanID(cid)
×
1590
                },
×
1591
                RequiredRemoteChanReserve: func(chanAmt,
1592
                        dustLimit btcutil.Amount) btcutil.Amount {
×
1593

×
1594
                        // By default, we'll require the remote peer to maintain
×
1595
                        // at least 1% of the total channel capacity at all
×
1596
                        // times. If this value ends up dipping below the dust
×
1597
                        // limit, then we'll use the dust limit itself as the
×
1598
                        // reserve as required by BOLT #2.
×
1599
                        reserve := chanAmt / 100
×
1600
                        if reserve < dustLimit {
×
1601
                                reserve = dustLimit
×
1602
                        }
×
1603

1604
                        return reserve
×
1605
                },
1606
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
×
1607
                        // By default, we'll allow the remote peer to fully
×
1608
                        // utilize the full bandwidth of the channel, minus our
×
1609
                        // required reserve.
×
1610
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
×
1611
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
×
1612
                },
×
1613
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
×
1614
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
×
1615
                                return cfg.DefaultRemoteMaxHtlcs
×
1616
                        }
×
1617

1618
                        // By default, we'll permit them to utilize the full
1619
                        // channel bandwidth.
1620
                        return uint16(input.MaxHTLCNumber / 2)
×
1621
                },
1622
                ZombieSweeperInterval:         zombieSweeperInterval,
1623
                ReservationTimeout:            reservationTimeout,
1624
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1625
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1626
                MaxPendingChannels:            cfg.MaxPendingChannels,
1627
                RejectPush:                    cfg.RejectPush,
1628
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1629
                NotifyOpenChannelEvent:        s.channelNotifier.NotifyOpenChannelEvent,
1630
                OpenChannelPredicate:          chanPredicate,
1631
                NotifyPendingOpenChannelEvent: s.channelNotifier.NotifyPendingOpenChannelEvent,
1632
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1633
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1634
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1635
                DeleteAliasEdge:      deleteAliasEdge,
1636
                AliasManager:         s.aliasMgr,
1637
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1638
                AuxFundingController: implCfg.AuxFundingController,
1639
                AuxSigner:            implCfg.AuxSigner,
1640
                AuxResolver:          implCfg.AuxContractResolver,
1641
        })
1642
        if err != nil {
×
1643
                return nil, err
×
1644
        }
×
1645

1646
        // Next, we'll assemble the sub-system that will maintain an on-disk
1647
        // static backup of the latest channel state.
1648
        chanNotifier := &channelNotifier{
×
1649
                chanNotifier: s.channelNotifier,
×
1650
                addrs:        s.addrSource,
×
1651
        }
×
1652
        backupFile := chanbackup.NewMultiFile(
×
1653
                cfg.BackupFilePath, cfg.NoBackupArchive,
×
1654
        )
×
1655
        startingChans, err := chanbackup.FetchStaticChanBackups(
×
1656
                s.chanStateDB, s.addrSource,
×
1657
        )
×
1658
        if err != nil {
×
1659
                return nil, err
×
1660
        }
×
1661
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
×
1662
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
×
1663
        )
×
1664
        if err != nil {
×
1665
                return nil, err
×
1666
        }
×
1667

1668
        // Assemble a peer notifier which will provide clients with subscriptions
1669
        // to peer online and offline events.
1670
        s.peerNotifier = peernotifier.New()
×
1671

×
1672
        // Create a channel event store which monitors all open channels.
×
1673
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
×
1674
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
×
1675
                        return s.channelNotifier.SubscribeChannelEvents()
×
1676
                },
×
1677
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
×
1678
                        return s.peerNotifier.SubscribePeerEvents()
×
1679
                },
×
1680
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1681
                Clock:           clock.NewDefaultClock(),
1682
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1683
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1684
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1685
        })
1686

1687
        if cfg.WtClient.Active {
×
1688
                policy := wtpolicy.DefaultPolicy()
×
1689
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
×
1690

×
1691
                // We expose the sweep fee rate in sat/vbyte, but the tower
×
1692
                // protocol operations on sat/kw.
×
1693
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
×
1694
                        1000 * cfg.WtClient.SweepFeeRate,
×
1695
                )
×
1696

×
1697
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
×
1698

×
1699
                if err := policy.Validate(); err != nil {
×
1700
                        return nil, err
×
1701
                }
×
1702

1703
                // authDial is the wrapper around the btrontide.Dial for the
1704
                // watchtower.
1705
                authDial := func(localKey keychain.SingleKeyECDH,
×
1706
                        netAddr *lnwire.NetAddress,
×
1707
                        dialer tor.DialFunc) (wtserver.Peer, error) {
×
1708

×
1709
                        return brontide.Dial(
×
1710
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
×
1711
                        )
×
1712
                }
×
1713

1714
                // buildBreachRetribution is a call-back that can be used to
1715
                // query the BreachRetribution info and channel type given a
1716
                // channel ID and commitment height.
1717
                buildBreachRetribution := func(chanID lnwire.ChannelID,
×
1718
                        commitHeight uint64) (*lnwallet.BreachRetribution,
×
1719
                        channeldb.ChannelType, error) {
×
1720

×
1721
                        channel, err := s.chanStateDB.FetchChannelByID(
×
1722
                                nil, chanID,
×
1723
                        )
×
1724
                        if err != nil {
×
1725
                                return nil, 0, err
×
1726
                        }
×
1727

1728
                        br, err := lnwallet.NewBreachRetribution(
×
1729
                                channel, commitHeight, 0, nil,
×
1730
                                implCfg.AuxLeafStore,
×
1731
                                implCfg.AuxContractResolver,
×
1732
                        )
×
1733
                        if err != nil {
×
1734
                                return nil, 0, err
×
1735
                        }
×
1736

1737
                        return br, channel.ChanType, nil
×
1738
                }
1739

1740
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
×
1741

×
1742
                // Copy the policy for legacy channels and set the blob flag
×
1743
                // signalling support for anchor channels.
×
1744
                anchorPolicy := policy
×
1745
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
×
1746

×
1747
                // Copy the policy for legacy channels and set the blob flag
×
1748
                // signalling support for taproot channels.
×
1749
                taprootPolicy := policy
×
1750
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
×
1751
                        blob.FlagTaprootChannel,
×
1752
                )
×
1753

×
1754
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
×
1755
                        FetchClosedChannel:     fetchClosedChannel,
×
1756
                        BuildBreachRetribution: buildBreachRetribution,
×
1757
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
×
1758
                        ChainNotifier:          s.cc.ChainNotifier,
×
1759
                        SubscribeChannelEvents: func() (subscribe.Subscription,
×
1760
                                error) {
×
1761

×
1762
                                return s.channelNotifier.
×
1763
                                        SubscribeChannelEvents()
×
1764
                        },
×
1765
                        Signer: cc.Wallet.Cfg.Signer,
1766
                        NewAddress: func() ([]byte, error) {
×
1767
                                addr, err := newSweepPkScriptGen(
×
1768
                                        cc.Wallet, netParams,
×
1769
                                )().Unpack()
×
1770
                                if err != nil {
×
1771
                                        return nil, err
×
1772
                                }
×
1773

1774
                                return addr.DeliveryAddress, nil
×
1775
                        },
1776
                        SecretKeyRing:      s.cc.KeyRing,
1777
                        Dial:               cfg.net.Dial,
1778
                        AuthDial:           authDial,
1779
                        DB:                 dbs.TowerClientDB,
1780
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1781
                        MinBackoff:         10 * time.Second,
1782
                        MaxBackoff:         5 * time.Minute,
1783
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1784
                }, policy, anchorPolicy, taprootPolicy)
1785
                if err != nil {
×
1786
                        return nil, err
×
1787
                }
×
1788
        }
1789

1790
        if len(cfg.ExternalHosts) != 0 {
×
1791
                advertisedIPs := make(map[string]struct{})
×
1792
                for _, addr := range s.currentNodeAnn.Addresses {
×
1793
                        advertisedIPs[addr.String()] = struct{}{}
×
1794
                }
×
1795

1796
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1797
                        Hosts:         cfg.ExternalHosts,
×
1798
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1799
                        LookupHost: func(host string) (net.Addr, error) {
×
1800
                                return lncfg.ParseAddressString(
×
1801
                                        host, strconv.Itoa(defaultPeerPort),
×
1802
                                        cfg.net.ResolveTCPAddr,
×
1803
                                )
×
1804
                        },
×
1805
                        AdvertisedIPs: advertisedIPs,
1806
                        AnnounceNewIPs: netann.IPAnnouncer(
1807
                                func(modifier ...netann.NodeAnnModifier) (
1808
                                        lnwire.NodeAnnouncement, error) {
×
1809

×
1810
                                        return s.genNodeAnnouncement(
×
1811
                                                nil, modifier...,
×
1812
                                        )
×
1813
                                }),
×
1814
                })
1815
        }
1816

1817
        // Create liveness monitor.
1818
        s.createLivenessMonitor(cfg, cc, leaderElector)
×
1819

×
1820
        // Create the connection manager which will be responsible for
×
1821
        // maintaining persistent outbound connections and also accepting new
×
1822
        // incoming connections
×
1823
        cmgr, err := connmgr.New(&connmgr.Config{
×
1824
                Listeners:      listeners,
×
1825
                OnAccept:       s.InboundPeerConnected,
×
1826
                RetryDuration:  time.Second * 5,
×
1827
                TargetOutbound: 100,
×
1828
                Dial: noiseDial(
×
1829
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
×
1830
                ),
×
1831
                OnConnection: s.OutboundPeerConnected,
×
1832
        })
×
1833
        if err != nil {
×
1834
                return nil, err
×
1835
        }
×
1836
        s.connMgr = cmgr
×
1837

×
1838
        // Finally, register the subsystems in blockbeat.
×
1839
        s.registerBlockConsumers()
×
1840

×
1841
        return s, nil
×
1842
}
1843

1844
// UpdateRoutingConfig is a callback function to update the routing config
1845
// values in the main cfg.
1846
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
×
1847
        routerCfg := s.cfg.SubRPCServers.RouterRPC
×
1848

×
1849
        switch c := cfg.Estimator.Config().(type) {
×
1850
        case routing.AprioriConfig:
×
1851
                routerCfg.ProbabilityEstimatorType =
×
1852
                        routing.AprioriEstimatorName
×
1853

×
1854
                targetCfg := routerCfg.AprioriConfig
×
1855
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
×
1856
                targetCfg.Weight = c.AprioriWeight
×
1857
                targetCfg.CapacityFraction = c.CapacityFraction
×
1858
                targetCfg.HopProbability = c.AprioriHopProbability
×
1859

1860
        case routing.BimodalConfig:
×
1861
                routerCfg.ProbabilityEstimatorType =
×
1862
                        routing.BimodalEstimatorName
×
1863

×
1864
                targetCfg := routerCfg.BimodalConfig
×
1865
                targetCfg.Scale = int64(c.BimodalScaleMsat)
×
1866
                targetCfg.NodeWeight = c.BimodalNodeWeight
×
1867
                targetCfg.DecayTime = c.BimodalDecayTime
×
1868
        }
1869

1870
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
×
1871
}
1872

1873
// registerBlockConsumers registers the subsystems that consume block events.
1874
// By calling `RegisterQueue`, a list of subsystems are registered in the
1875
// blockbeat for block notifications. When a new block arrives, the subsystems
1876
// in the same queue are notified sequentially, and different queues are
1877
// notified concurrently.
1878
//
1879
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1880
// a new `RegisterQueue` call.
1881
func (s *server) registerBlockConsumers() {
×
1882
        // In this queue, when a new block arrives, it will be received and
×
1883
        // processed in this order: chainArb -> sweeper -> txPublisher.
×
1884
        consumers := []chainio.Consumer{
×
1885
                s.chainArb,
×
1886
                s.sweeper,
×
1887
                s.txPublisher,
×
1888
        }
×
1889
        s.blockbeatDispatcher.RegisterQueue(consumers)
×
1890
}
×
1891

1892
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1893
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1894
// may differ from what is on disk.
1895
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1896
        error) {
×
1897

×
1898
        data, err := u.DataToSign()
×
1899
        if err != nil {
×
1900
                return nil, err
×
1901
        }
×
1902

1903
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
×
1904
}
1905

1906
// createLivenessMonitor creates a set of health checks using our configured
1907
// values and uses these checks to create a liveness monitor. Available
1908
// health checks,
1909
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1910
//   - diskCheck
1911
//   - tlsHealthCheck
1912
//   - torController, only created when tor is enabled.
1913
//
1914
// If a health check has been disabled by setting attempts to 0, our monitor
1915
// will not run it.
1916
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1917
        leaderElector cluster.LeaderElector) {
×
1918

×
1919
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
×
1920
        if cfg.Bitcoin.Node == "nochainbackend" {
×
1921
                srvrLog.Info("Disabling chain backend checks for " +
×
1922
                        "nochainbackend mode")
×
1923

×
1924
                chainBackendAttempts = 0
×
1925
        }
×
1926

1927
        chainHealthCheck := healthcheck.NewObservation(
×
1928
                "chain backend",
×
1929
                cc.HealthCheck,
×
1930
                cfg.HealthChecks.ChainCheck.Interval,
×
1931
                cfg.HealthChecks.ChainCheck.Timeout,
×
1932
                cfg.HealthChecks.ChainCheck.Backoff,
×
1933
                chainBackendAttempts,
×
1934
        )
×
1935

×
1936
        diskCheck := healthcheck.NewObservation(
×
1937
                "disk space",
×
1938
                func() error {
×
1939
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1940
                                cfg.LndDir,
×
1941
                        )
×
1942
                        if err != nil {
×
1943
                                return err
×
1944
                        }
×
1945

1946
                        // If we have more free space than we require,
1947
                        // we return a nil error.
1948
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1949
                                return nil
×
1950
                        }
×
1951

1952
                        return fmt.Errorf("require: %v free space, got: %v",
×
1953
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1954
                                free)
×
1955
                },
1956
                cfg.HealthChecks.DiskCheck.Interval,
1957
                cfg.HealthChecks.DiskCheck.Timeout,
1958
                cfg.HealthChecks.DiskCheck.Backoff,
1959
                cfg.HealthChecks.DiskCheck.Attempts,
1960
        )
1961

1962
        tlsHealthCheck := healthcheck.NewObservation(
×
1963
                "tls",
×
1964
                func() error {
×
1965
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1966
                                s.cc.KeyRing,
×
1967
                        )
×
1968
                        if err != nil {
×
1969
                                return err
×
1970
                        }
×
1971
                        if expired {
×
1972
                                return fmt.Errorf("TLS certificate is "+
×
1973
                                        "expired as of %v", expTime)
×
1974
                        }
×
1975

1976
                        // If the certificate is not outdated, no error needs
1977
                        // to be returned
1978
                        return nil
×
1979
                },
1980
                cfg.HealthChecks.TLSCheck.Interval,
1981
                cfg.HealthChecks.TLSCheck.Timeout,
1982
                cfg.HealthChecks.TLSCheck.Backoff,
1983
                cfg.HealthChecks.TLSCheck.Attempts,
1984
        )
1985

1986
        checks := []*healthcheck.Observation{
×
1987
                chainHealthCheck, diskCheck, tlsHealthCheck,
×
1988
        }
×
1989

×
1990
        // If Tor is enabled, add the healthcheck for tor connection.
×
1991
        if s.torController != nil {
×
1992
                torConnectionCheck := healthcheck.NewObservation(
×
1993
                        "tor connection",
×
1994
                        func() error {
×
1995
                                return healthcheck.CheckTorServiceStatus(
×
1996
                                        s.torController,
×
1997
                                        s.createNewHiddenService,
×
1998
                                )
×
1999
                        },
×
2000
                        cfg.HealthChecks.TorConnection.Interval,
2001
                        cfg.HealthChecks.TorConnection.Timeout,
2002
                        cfg.HealthChecks.TorConnection.Backoff,
2003
                        cfg.HealthChecks.TorConnection.Attempts,
2004
                )
2005
                checks = append(checks, torConnectionCheck)
×
2006
        }
2007

2008
        // If remote signing is enabled, add the healthcheck for the remote
2009
        // signing RPC interface.
2010
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
×
2011
                // Because we have two cascading timeouts here, we need to add
×
2012
                // some slack to the "outer" one of them in case the "inner"
×
2013
                // returns exactly on time.
×
2014
                overhead := time.Millisecond * 10
×
2015

×
2016
                remoteSignerConnectionCheck := healthcheck.NewObservation(
×
2017
                        "remote signer connection",
×
2018
                        rpcwallet.HealthCheck(
×
2019
                                s.cfg.RemoteSigner,
×
2020

×
2021
                                // For the health check we might to be even
×
2022
                                // stricter than the initial/normal connect, so
×
2023
                                // we use the health check timeout here.
×
2024
                                cfg.HealthChecks.RemoteSigner.Timeout,
×
2025
                        ),
×
2026
                        cfg.HealthChecks.RemoteSigner.Interval,
×
2027
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
×
2028
                        cfg.HealthChecks.RemoteSigner.Backoff,
×
2029
                        cfg.HealthChecks.RemoteSigner.Attempts,
×
2030
                )
×
2031
                checks = append(checks, remoteSignerConnectionCheck)
×
2032
        }
×
2033

2034
        // If we have a leader elector, we add a health check to ensure we are
2035
        // still the leader. During normal operation, we should always be the
2036
        // leader, but there are circumstances where this may change, such as
2037
        // when we lose network connectivity for long enough expiring out lease.
2038
        if leaderElector != nil {
×
2039
                leaderCheck := healthcheck.NewObservation(
×
2040
                        "leader status",
×
2041
                        func() error {
×
2042
                                // Check if we are still the leader. Note that
×
2043
                                // we don't need to use a timeout context here
×
2044
                                // as the healthcheck observer will handle the
×
2045
                                // timeout case for us.
×
2046
                                timeoutCtx, cancel := context.WithTimeout(
×
2047
                                        context.Background(),
×
2048
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2049
                                )
×
2050
                                defer cancel()
×
2051

×
2052
                                leader, err := leaderElector.IsLeader(
×
2053
                                        timeoutCtx,
×
2054
                                )
×
2055
                                if err != nil {
×
2056
                                        return fmt.Errorf("unable to check if "+
×
2057
                                                "still leader: %v", err)
×
2058
                                }
×
2059

2060
                                if !leader {
×
2061
                                        srvrLog.Debug("Not the current leader")
×
2062
                                        return fmt.Errorf("not the current " +
×
2063
                                                "leader")
×
2064
                                }
×
2065

2066
                                return nil
×
2067
                        },
2068
                        cfg.HealthChecks.LeaderCheck.Interval,
2069
                        cfg.HealthChecks.LeaderCheck.Timeout,
2070
                        cfg.HealthChecks.LeaderCheck.Backoff,
2071
                        cfg.HealthChecks.LeaderCheck.Attempts,
2072
                )
2073

2074
                checks = append(checks, leaderCheck)
×
2075
        }
2076

2077
        // If we have not disabled all of our health checks, we create a
2078
        // liveness monitor with our configured checks.
2079
        s.livenessMonitor = healthcheck.NewMonitor(
×
2080
                &healthcheck.Config{
×
2081
                        Checks:   checks,
×
2082
                        Shutdown: srvrLog.Criticalf,
×
2083
                },
×
2084
        )
×
2085
}
2086

2087
// Started returns true if the server has been started, and false otherwise.
2088
// NOTE: This function is safe for concurrent access.
2089
func (s *server) Started() bool {
×
2090
        return atomic.LoadInt32(&s.active) != 0
×
2091
}
×
2092

2093
// cleaner is used to aggregate "cleanup" functions during an operation that
2094
// starts several subsystems. In case one of the subsystem fails to start
2095
// and a proper resource cleanup is required, the "run" method achieves this
2096
// by running all these added "cleanup" functions.
2097
type cleaner []func() error
2098

2099
// add is used to add a cleanup function to be called when
2100
// the run function is executed.
2101
func (c cleaner) add(cleanup func() error) cleaner {
×
2102
        return append(c, cleanup)
×
2103
}
×
2104

2105
// run is used to run all the previousely added cleanup functions.
2106
func (c cleaner) run() {
×
2107
        for i := len(c) - 1; i >= 0; i-- {
×
2108
                if err := c[i](); err != nil {
×
2109
                        srvrLog.Infof("Cleanup failed: %v", err)
×
2110
                }
×
2111
        }
2112
}
2113

2114
// startLowLevelServices starts the low-level services of the server. These
2115
// services must be started successfully before running the main server. The
2116
// services are,
2117
// 1. the chain notifier.
2118
//
2119
// TODO(yy): identify and add more low-level services here.
2120
func (s *server) startLowLevelServices() error {
×
2121
        var startErr error
×
2122

×
2123
        cleanup := cleaner{}
×
2124

×
2125
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
×
2126
        if err := s.cc.ChainNotifier.Start(); err != nil {
×
2127
                startErr = err
×
2128
        }
×
2129

2130
        if startErr != nil {
×
2131
                cleanup.run()
×
2132
        }
×
2133

2134
        return startErr
×
2135
}
2136

2137
// Start starts the main daemon server, all requested listeners, and any helper
2138
// goroutines.
2139
// NOTE: This function is safe for concurrent access.
2140
//
2141
//nolint:funlen
2142
func (s *server) Start() error {
×
2143
        // Get the current blockbeat.
×
2144
        beat, err := s.getStartingBeat()
×
2145
        if err != nil {
×
2146
                return err
×
2147
        }
×
2148

2149
        var startErr error
×
2150

×
2151
        // If one sub system fails to start, the following code ensures that the
×
2152
        // previous started ones are stopped. It also ensures a proper wallet
×
2153
        // shutdown which is important for releasing its resources (boltdb, etc...)
×
2154
        cleanup := cleaner{}
×
2155

×
2156
        s.start.Do(func() {
×
2157
                cleanup = cleanup.add(s.customMessageServer.Stop)
×
2158
                if err := s.customMessageServer.Start(); err != nil {
×
2159
                        startErr = err
×
2160
                        return
×
2161
                }
×
2162

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

2171
                if s.livenessMonitor != nil {
×
2172
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
×
2173
                        if err := s.livenessMonitor.Start(); err != nil {
×
2174
                                startErr = err
×
2175
                                return
×
2176
                        }
×
2177
                }
2178

2179
                // Start the notification server. This is used so channel
2180
                // management goroutines can be notified when a funding
2181
                // transaction reaches a sufficient number of confirmations, or
2182
                // when the input for the funding transaction is spent in an
2183
                // attempt at an uncooperative close by the counterparty.
2184
                cleanup = cleanup.add(s.sigPool.Stop)
×
2185
                if err := s.sigPool.Start(); err != nil {
×
2186
                        startErr = err
×
2187
                        return
×
2188
                }
×
2189

2190
                cleanup = cleanup.add(s.writePool.Stop)
×
2191
                if err := s.writePool.Start(); err != nil {
×
2192
                        startErr = err
×
2193
                        return
×
2194
                }
×
2195

2196
                cleanup = cleanup.add(s.readPool.Stop)
×
2197
                if err := s.readPool.Start(); err != nil {
×
2198
                        startErr = err
×
2199
                        return
×
2200
                }
×
2201

2202
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
×
2203
                if err := s.cc.BestBlockTracker.Start(); err != nil {
×
2204
                        startErr = err
×
2205
                        return
×
2206
                }
×
2207

2208
                cleanup = cleanup.add(s.channelNotifier.Stop)
×
2209
                if err := s.channelNotifier.Start(); err != nil {
×
2210
                        startErr = err
×
2211
                        return
×
2212
                }
×
2213

2214
                cleanup = cleanup.add(func() error {
×
2215
                        return s.peerNotifier.Stop()
×
2216
                })
×
2217
                if err := s.peerNotifier.Start(); err != nil {
×
2218
                        startErr = err
×
2219
                        return
×
2220
                }
×
2221

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

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

2236
                cleanup = cleanup.add(s.txPublisher.Stop)
×
2237
                if err := s.txPublisher.Start(beat); err != nil {
×
2238
                        startErr = err
×
2239
                        return
×
2240
                }
×
2241

2242
                cleanup = cleanup.add(s.sweeper.Stop)
×
2243
                if err := s.sweeper.Start(beat); err != nil {
×
2244
                        startErr = err
×
2245
                        return
×
2246
                }
×
2247

2248
                cleanup = cleanup.add(s.utxoNursery.Stop)
×
2249
                if err := s.utxoNursery.Start(); err != nil {
×
2250
                        startErr = err
×
2251
                        return
×
2252
                }
×
2253

2254
                cleanup = cleanup.add(s.breachArbitrator.Stop)
×
2255
                if err := s.breachArbitrator.Start(); err != nil {
×
2256
                        startErr = err
×
2257
                        return
×
2258
                }
×
2259

2260
                cleanup = cleanup.add(s.fundingMgr.Stop)
×
2261
                if err := s.fundingMgr.Start(); err != nil {
×
2262
                        startErr = err
×
2263
                        return
×
2264
                }
×
2265

2266
                // htlcSwitch must be started before chainArb since the latter
2267
                // relies on htlcSwitch to deliver resolution message upon
2268
                // start.
2269
                cleanup = cleanup.add(s.htlcSwitch.Stop)
×
2270
                if err := s.htlcSwitch.Start(); err != nil {
×
2271
                        startErr = err
×
2272
                        return
×
2273
                }
×
2274

2275
                cleanup = cleanup.add(s.interceptableSwitch.Stop)
×
2276
                if err := s.interceptableSwitch.Start(); err != nil {
×
2277
                        startErr = err
×
2278
                        return
×
2279
                }
×
2280

2281
                cleanup = cleanup.add(s.invoiceHtlcModifier.Stop)
×
2282
                if err := s.invoiceHtlcModifier.Start(); err != nil {
×
2283
                        startErr = err
×
2284
                        return
×
2285
                }
×
2286

2287
                cleanup = cleanup.add(s.chainArb.Stop)
×
2288
                if err := s.chainArb.Start(beat); err != nil {
×
2289
                        startErr = err
×
2290
                        return
×
2291
                }
×
2292

2293
                cleanup = cleanup.add(s.graphBuilder.Stop)
×
2294
                if err := s.graphBuilder.Start(); err != nil {
×
2295
                        startErr = err
×
2296
                        return
×
2297
                }
×
2298

2299
                cleanup = cleanup.add(s.chanRouter.Stop)
×
2300
                if err := s.chanRouter.Start(); err != nil {
×
2301
                        startErr = err
×
2302
                        return
×
2303
                }
×
2304
                // The authGossiper depends on the chanRouter and therefore
2305
                // should be started after it.
2306
                cleanup = cleanup.add(s.authGossiper.Stop)
×
2307
                if err := s.authGossiper.Start(); err != nil {
×
2308
                        startErr = err
×
2309
                        return
×
2310
                }
×
2311

2312
                cleanup = cleanup.add(s.invoices.Stop)
×
2313
                if err := s.invoices.Start(); err != nil {
×
2314
                        startErr = err
×
2315
                        return
×
2316
                }
×
2317

2318
                cleanup = cleanup.add(s.sphinx.Stop)
×
2319
                if err := s.sphinx.Start(); err != nil {
×
2320
                        startErr = err
×
2321
                        return
×
2322
                }
×
2323

2324
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
×
2325
                if err := s.chanStatusMgr.Start(); err != nil {
×
2326
                        startErr = err
×
2327
                        return
×
2328
                }
×
2329

2330
                cleanup = cleanup.add(s.chanEventStore.Stop)
×
2331
                if err := s.chanEventStore.Start(); err != nil {
×
2332
                        startErr = err
×
2333
                        return
×
2334
                }
×
2335

2336
                cleanup.add(func() error {
×
2337
                        s.missionController.StopStoreTickers()
×
2338
                        return nil
×
2339
                })
×
2340
                s.missionController.RunStoreTickers()
×
2341

×
2342
                // Before we start the connMgr, we'll check to see if we have
×
2343
                // any backups to recover. We do this now as we want to ensure
×
2344
                // that have all the information we need to handle channel
×
2345
                // recovery _before_ we even accept connections from any peers.
×
2346
                chanRestorer := &chanDBRestorer{
×
2347
                        db:         s.chanStateDB,
×
2348
                        secretKeys: s.cc.KeyRing,
×
2349
                        chainArb:   s.chainArb,
×
2350
                }
×
2351
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
×
2352
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2353
                                s.chansToRestore.PackedSingleChanBackups,
×
2354
                                s.cc.KeyRing, chanRestorer, s,
×
2355
                        )
×
2356
                        if err != nil {
×
2357
                                startErr = fmt.Errorf("unable to unpack single "+
×
2358
                                        "backups: %v", err)
×
2359
                                return
×
2360
                        }
×
2361
                }
2362
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
×
2363
                        _, err := chanbackup.UnpackAndRecoverMulti(
×
2364
                                s.chansToRestore.PackedMultiChanBackup,
×
2365
                                s.cc.KeyRing, chanRestorer, s,
×
2366
                        )
×
2367
                        if err != nil {
×
2368
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2369
                                        "backup: %v", err)
×
2370
                                return
×
2371
                        }
×
2372
                }
2373

2374
                // chanSubSwapper must be started after the `channelNotifier`
2375
                // because it depends on channel events as a synchronization
2376
                // point.
2377
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
×
2378
                if err := s.chanSubSwapper.Start(); err != nil {
×
2379
                        startErr = err
×
2380
                        return
×
2381
                }
×
2382

2383
                if s.torController != nil {
×
2384
                        cleanup = cleanup.add(s.torController.Stop)
×
2385
                        if err := s.createNewHiddenService(); err != nil {
×
2386
                                startErr = err
×
2387
                                return
×
2388
                        }
×
2389
                }
2390

2391
                if s.natTraversal != nil {
×
2392
                        s.wg.Add(1)
×
2393
                        go s.watchExternalIP()
×
2394
                }
×
2395

2396
                // Start connmgr last to prevent connections before init.
2397
                cleanup = cleanup.add(func() error {
×
2398
                        s.connMgr.Stop()
×
2399
                        return nil
×
2400
                })
×
2401
                s.connMgr.Start()
×
2402

×
2403
                // If peers are specified as a config option, we'll add those
×
2404
                // peers first.
×
2405
                for _, peerAddrCfg := range s.cfg.AddPeers {
×
2406
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
×
2407
                                peerAddrCfg,
×
2408
                        )
×
2409
                        if err != nil {
×
2410
                                startErr = fmt.Errorf("unable to parse peer "+
×
2411
                                        "pubkey from config: %v", err)
×
2412
                                return
×
2413
                        }
×
2414
                        addr, err := parseAddr(parsedHost, s.cfg.net)
×
2415
                        if err != nil {
×
2416
                                startErr = fmt.Errorf("unable to parse peer "+
×
2417
                                        "address provided as a config option: "+
×
2418
                                        "%v", err)
×
2419
                                return
×
2420
                        }
×
2421

2422
                        peerAddr := &lnwire.NetAddress{
×
2423
                                IdentityKey: parsedPubkey,
×
2424
                                Address:     addr,
×
2425
                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
2426
                        }
×
2427

×
2428
                        err = s.ConnectToPeer(
×
2429
                                peerAddr, true,
×
2430
                                s.cfg.ConnectionTimeout,
×
2431
                        )
×
2432
                        if err != nil {
×
2433
                                startErr = fmt.Errorf("unable to connect to "+
×
2434
                                        "peer address provided as a config "+
×
2435
                                        "option: %v", err)
×
2436
                                return
×
2437
                        }
×
2438
                }
2439

2440
                // Subscribe to NodeAnnouncements that advertise new addresses
2441
                // our persistent peers.
2442
                if err := s.updatePersistentPeerAddrs(); err != nil {
×
2443
                        startErr = err
×
2444
                        return
×
2445
                }
×
2446

2447
                // With all the relevant sub-systems started, we'll now attempt
2448
                // to establish persistent connections to our direct channel
2449
                // collaborators within the network. Before doing so however,
2450
                // we'll prune our set of link nodes found within the database
2451
                // to ensure we don't reconnect to any nodes we no longer have
2452
                // open channels with.
2453
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
×
2454
                        startErr = err
×
2455
                        return
×
2456
                }
×
2457
                if err := s.establishPersistentConnections(); err != nil {
×
2458
                        startErr = err
×
2459
                        return
×
2460
                }
×
2461

2462
                // setSeedList is a helper function that turns multiple DNS seed
2463
                // server tuples from the command line or config file into the
2464
                // data structure we need and does a basic formal sanity check
2465
                // in the process.
2466
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
×
2467
                        if len(tuples) == 0 {
×
2468
                                return
×
2469
                        }
×
2470

2471
                        result := make([][2]string, len(tuples))
×
2472
                        for idx, tuple := range tuples {
×
2473
                                tuple = strings.TrimSpace(tuple)
×
2474
                                if len(tuple) == 0 {
×
2475
                                        return
×
2476
                                }
×
2477

2478
                                servers := strings.Split(tuple, ",")
×
2479
                                if len(servers) > 2 || len(servers) == 0 {
×
2480
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2481
                                                "seed tuple: %v", servers)
×
2482
                                        return
×
2483
                                }
×
2484

2485
                                copy(result[idx][:], servers)
×
2486
                        }
2487

2488
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2489
                }
2490

2491
                // Let users overwrite the DNS seed nodes. We only allow them
2492
                // for bitcoin mainnet/testnet/signet.
2493
                if s.cfg.Bitcoin.MainNet {
×
2494
                        setSeedList(
×
2495
                                s.cfg.Bitcoin.DNSSeeds,
×
2496
                                chainreg.BitcoinMainnetGenesis,
×
2497
                        )
×
2498
                }
×
2499
                if s.cfg.Bitcoin.TestNet3 {
×
2500
                        setSeedList(
×
2501
                                s.cfg.Bitcoin.DNSSeeds,
×
2502
                                chainreg.BitcoinTestnetGenesis,
×
2503
                        )
×
2504
                }
×
2505
                if s.cfg.Bitcoin.SigNet {
×
2506
                        setSeedList(
×
2507
                                s.cfg.Bitcoin.DNSSeeds,
×
2508
                                chainreg.BitcoinSignetGenesis,
×
2509
                        )
×
2510
                }
×
2511

2512
                // If network bootstrapping hasn't been disabled, then we'll
2513
                // configure the set of active bootstrappers, and launch a
2514
                // dedicated goroutine to maintain a set of persistent
2515
                // connections.
2516
                if shouldPeerBootstrap(s.cfg) {
×
2517
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2518
                        if err != nil {
×
2519
                                startErr = err
×
2520
                                return
×
2521
                        }
×
2522

2523
                        s.wg.Add(1)
×
2524
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2525
                } else {
×
2526
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
×
2527
                }
×
2528

2529
                // Start the blockbeat after all other subsystems have been
2530
                // started so they are ready to receive new blocks.
2531
                cleanup = cleanup.add(func() error {
×
2532
                        s.blockbeatDispatcher.Stop()
×
2533
                        return nil
×
2534
                })
×
2535
                if err := s.blockbeatDispatcher.Start(); err != nil {
×
2536
                        startErr = err
×
2537
                        return
×
2538
                }
×
2539

2540
                // Set the active flag now that we've completed the full
2541
                // startup.
2542
                atomic.StoreInt32(&s.active, 1)
×
2543
        })
2544

2545
        if startErr != nil {
×
2546
                cleanup.run()
×
2547
        }
×
2548
        return startErr
×
2549
}
2550

2551
// Stop gracefully shutsdown the main daemon server. This function will signal
2552
// any active goroutines, or helper objects to exit, then blocks until they've
2553
// all successfully exited. Additionally, any/all listeners are closed.
2554
// NOTE: This function is safe for concurrent access.
2555
func (s *server) Stop() error {
×
2556
        s.stop.Do(func() {
×
2557
                atomic.StoreInt32(&s.stopping, 1)
×
2558

×
2559
                close(s.quit)
×
2560

×
2561
                // Shutdown connMgr first to prevent conns during shutdown.
×
2562
                s.connMgr.Stop()
×
2563

×
2564
                // Stop dispatching blocks to other systems immediately.
×
2565
                s.blockbeatDispatcher.Stop()
×
2566

×
2567
                // Shutdown the wallet, funding manager, and the rpc server.
×
2568
                if err := s.chanStatusMgr.Stop(); err != nil {
×
2569
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2570
                }
×
2571
                if err := s.htlcSwitch.Stop(); err != nil {
×
2572
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2573
                }
×
2574
                if err := s.sphinx.Stop(); err != nil {
×
2575
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2576
                }
×
2577
                if err := s.invoices.Stop(); err != nil {
×
2578
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2579
                }
×
2580
                if err := s.interceptableSwitch.Stop(); err != nil {
×
2581
                        srvrLog.Warnf("failed to stop interceptable "+
×
2582
                                "switch: %v", err)
×
2583
                }
×
2584
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
×
2585
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2586
                                "modifier: %v", err)
×
2587
                }
×
2588
                if err := s.chanRouter.Stop(); err != nil {
×
2589
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2590
                }
×
2591
                if err := s.graphBuilder.Stop(); err != nil {
×
2592
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2593
                }
×
2594
                if err := s.chainArb.Stop(); err != nil {
×
2595
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2596
                }
×
2597
                if err := s.fundingMgr.Stop(); err != nil {
×
2598
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2599
                }
×
2600
                if err := s.breachArbitrator.Stop(); err != nil {
×
2601
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2602
                                err)
×
2603
                }
×
2604
                if err := s.utxoNursery.Stop(); err != nil {
×
2605
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2606
                }
×
2607
                if err := s.authGossiper.Stop(); err != nil {
×
2608
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2609
                }
×
2610
                if err := s.sweeper.Stop(); err != nil {
×
2611
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2612
                }
×
2613
                if err := s.txPublisher.Stop(); err != nil {
×
2614
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2615
                }
×
2616
                if err := s.channelNotifier.Stop(); err != nil {
×
2617
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2618
                }
×
2619
                if err := s.peerNotifier.Stop(); err != nil {
×
2620
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2621
                }
×
2622
                if err := s.htlcNotifier.Stop(); err != nil {
×
2623
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2624
                }
×
2625

2626
                // Update channel.backup file. Make sure to do it before
2627
                // stopping chanSubSwapper.
2628
                singles, err := chanbackup.FetchStaticChanBackups(
×
2629
                        s.chanStateDB, s.addrSource,
×
2630
                )
×
2631
                if err != nil {
×
2632
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2633
                                err)
×
2634
                } else {
×
2635
                        err := s.chanSubSwapper.ManualUpdate(singles)
×
2636
                        if err != nil {
×
2637
                                srvrLog.Warnf("Manual update of channel "+
×
2638
                                        "backup failed: %v", err)
×
2639
                        }
×
2640
                }
2641

2642
                if err := s.chanSubSwapper.Stop(); err != nil {
×
2643
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2644
                }
×
2645
                if err := s.cc.ChainNotifier.Stop(); err != nil {
×
2646
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2647
                }
×
2648
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
×
2649
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2650
                                err)
×
2651
                }
×
2652
                if err := s.chanEventStore.Stop(); err != nil {
×
2653
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2654
                                err)
×
2655
                }
×
2656
                s.missionController.StopStoreTickers()
×
2657

×
2658
                // Disconnect from each active peers to ensure that
×
2659
                // peerTerminationWatchers signal completion to each peer.
×
2660
                for _, peer := range s.Peers() {
×
2661
                        err := s.DisconnectPeer(peer.IdentityKey())
×
2662
                        if err != nil {
×
2663
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2664
                                        "received error: %v", peer.IdentityKey(),
×
2665
                                        err,
×
2666
                                )
×
2667
                        }
×
2668
                }
2669

2670
                // Now that all connections have been torn down, stop the tower
2671
                // client which will reliably flush all queued states to the
2672
                // tower. If this is halted for any reason, the force quit timer
2673
                // will kick in and abort to allow this method to return.
2674
                if s.towerClientMgr != nil {
×
2675
                        if err := s.towerClientMgr.Stop(); err != nil {
×
2676
                                srvrLog.Warnf("Unable to shut down tower "+
×
2677
                                        "client manager: %v", err)
×
2678
                        }
×
2679
                }
2680

2681
                if s.hostAnn != nil {
×
2682
                        if err := s.hostAnn.Stop(); err != nil {
×
2683
                                srvrLog.Warnf("unable to shut down host "+
×
2684
                                        "annoucner: %v", err)
×
2685
                        }
×
2686
                }
2687

2688
                if s.livenessMonitor != nil {
×
2689
                        if err := s.livenessMonitor.Stop(); err != nil {
×
2690
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2691
                                        "monitor: %v", err)
×
2692
                        }
×
2693
                }
2694

2695
                // Wait for all lingering goroutines to quit.
2696
                srvrLog.Debug("Waiting for server to shutdown...")
×
2697
                s.wg.Wait()
×
2698

×
2699
                srvrLog.Debug("Stopping buffer pools...")
×
2700
                s.sigPool.Stop()
×
2701
                s.writePool.Stop()
×
2702
                s.readPool.Stop()
×
2703
        })
2704

2705
        return nil
×
2706
}
2707

2708
// Stopped returns true if the server has been instructed to shutdown.
2709
// NOTE: This function is safe for concurrent access.
2710
func (s *server) Stopped() bool {
×
2711
        return atomic.LoadInt32(&s.stopping) != 0
×
2712
}
×
2713

2714
// configurePortForwarding attempts to set up port forwarding for the different
2715
// ports that the server will be listening on.
2716
//
2717
// NOTE: This should only be used when using some kind of NAT traversal to
2718
// automatically set up forwarding rules.
2719
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2720
        ip, err := s.natTraversal.ExternalIP()
×
2721
        if err != nil {
×
2722
                return nil, err
×
2723
        }
×
2724
        s.lastDetectedIP = ip
×
2725

×
2726
        externalIPs := make([]string, 0, len(ports))
×
2727
        for _, port := range ports {
×
2728
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2729
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2730
                        continue
×
2731
                }
2732

2733
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2734
                externalIPs = append(externalIPs, hostIP)
×
2735
        }
2736

2737
        return externalIPs, nil
×
2738
}
2739

2740
// removePortForwarding attempts to clear the forwarding rules for the different
2741
// ports the server is currently listening on.
2742
//
2743
// NOTE: This should only be used when using some kind of NAT traversal to
2744
// automatically set up forwarding rules.
2745
func (s *server) removePortForwarding() {
×
2746
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2747
        for _, port := range forwardedPorts {
×
2748
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2749
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2750
                                "port %d: %v", port, err)
×
2751
                }
×
2752
        }
2753
}
2754

2755
// watchExternalIP continuously checks for an updated external IP address every
2756
// 15 minutes. Once a new IP address has been detected, it will automatically
2757
// handle port forwarding rules and send updated node announcements to the
2758
// currently connected peers.
2759
//
2760
// NOTE: This MUST be run as a goroutine.
2761
func (s *server) watchExternalIP() {
×
2762
        defer s.wg.Done()
×
2763

×
2764
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2765
        // up by the server.
×
2766
        defer s.removePortForwarding()
×
2767

×
2768
        // Keep track of the external IPs set by the user to avoid replacing
×
2769
        // them when detecting a new IP.
×
2770
        ipsSetByUser := make(map[string]struct{})
×
2771
        for _, ip := range s.cfg.ExternalIPs {
×
2772
                ipsSetByUser[ip.String()] = struct{}{}
×
2773
        }
×
2774

2775
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2776

×
2777
        ticker := time.NewTicker(15 * time.Minute)
×
2778
        defer ticker.Stop()
×
2779
out:
×
2780
        for {
×
2781
                select {
×
2782
                case <-ticker.C:
×
2783
                        // We'll start off by making sure a new IP address has
×
2784
                        // been detected.
×
2785
                        ip, err := s.natTraversal.ExternalIP()
×
2786
                        if err != nil {
×
2787
                                srvrLog.Debugf("Unable to retrieve the "+
×
2788
                                        "external IP address: %v", err)
×
2789
                                continue
×
2790
                        }
2791

2792
                        // Periodically renew the NAT port forwarding.
2793
                        for _, port := range forwardedPorts {
×
2794
                                err := s.natTraversal.AddPortMapping(port)
×
2795
                                if err != nil {
×
2796
                                        srvrLog.Warnf("Unable to automatically "+
×
2797
                                                "re-create port forwarding using %s: %v",
×
2798
                                                s.natTraversal.Name(), err)
×
2799
                                } else {
×
2800
                                        srvrLog.Debugf("Automatically re-created "+
×
2801
                                                "forwarding for port %d using %s to "+
×
2802
                                                "advertise external IP",
×
2803
                                                port, s.natTraversal.Name())
×
2804
                                }
×
2805
                        }
2806

2807
                        if ip.Equal(s.lastDetectedIP) {
×
2808
                                continue
×
2809
                        }
2810

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

×
2813
                        // Next, we'll craft the new addresses that will be
×
2814
                        // included in the new node announcement and advertised
×
2815
                        // to the network. Each address will consist of the new
×
2816
                        // IP detected and one of the currently advertised
×
2817
                        // ports.
×
2818
                        var newAddrs []net.Addr
×
2819
                        for _, port := range forwardedPorts {
×
2820
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2821
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2822
                                if err != nil {
×
2823
                                        srvrLog.Debugf("Unable to resolve "+
×
2824
                                                "host %v: %v", addr, err)
×
2825
                                        continue
×
2826
                                }
2827

2828
                                newAddrs = append(newAddrs, addr)
×
2829
                        }
2830

2831
                        // Skip the update if we weren't able to resolve any of
2832
                        // the new addresses.
2833
                        if len(newAddrs) == 0 {
×
2834
                                srvrLog.Debug("Skipping node announcement " +
×
2835
                                        "update due to not being able to " +
×
2836
                                        "resolve any new addresses")
×
2837
                                continue
×
2838
                        }
2839

2840
                        // Now, we'll need to update the addresses in our node's
2841
                        // announcement in order to propagate the update
2842
                        // throughout the network. We'll only include addresses
2843
                        // that have a different IP from the previous one, as
2844
                        // the previous IP is no longer valid.
2845
                        currentNodeAnn := s.getNodeAnnouncement()
×
2846

×
2847
                        for _, addr := range currentNodeAnn.Addresses {
×
2848
                                host, _, err := net.SplitHostPort(addr.String())
×
2849
                                if err != nil {
×
2850
                                        srvrLog.Debugf("Unable to determine "+
×
2851
                                                "host from address %v: %v",
×
2852
                                                addr, err)
×
2853
                                        continue
×
2854
                                }
2855

2856
                                // We'll also make sure to include external IPs
2857
                                // set manually by the user.
2858
                                _, setByUser := ipsSetByUser[addr.String()]
×
2859
                                if setByUser || host != s.lastDetectedIP.String() {
×
2860
                                        newAddrs = append(newAddrs, addr)
×
2861
                                }
×
2862
                        }
2863

2864
                        // Then, we'll generate a new timestamped node
2865
                        // announcement with the updated addresses and broadcast
2866
                        // it to our peers.
2867
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2868
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2869
                        )
×
2870
                        if err != nil {
×
2871
                                srvrLog.Debugf("Unable to generate new node "+
×
2872
                                        "announcement: %v", err)
×
2873
                                continue
×
2874
                        }
2875

2876
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2877
                        if err != nil {
×
2878
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2879
                                        "announcement to peers: %v", err)
×
2880
                                continue
×
2881
                        }
2882

2883
                        // Finally, update the last IP seen to the current one.
2884
                        s.lastDetectedIP = ip
×
2885
                case <-s.quit:
×
2886
                        break out
×
2887
                }
2888
        }
2889
}
2890

2891
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2892
// based on the server, and currently active bootstrap mechanisms as defined
2893
// within the current configuration.
2894
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2895
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2896

×
2897
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2898

×
2899
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2900
        // this can be used by default if we've already partially seeded the
×
2901
        // network.
×
2902
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2903
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
2904
        if err != nil {
×
2905
                return nil, err
×
2906
        }
×
2907
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2908

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

×
2914
                // If we have a set of DNS seeds for this chain, then we'll add
×
2915
                // it as an additional bootstrapping source.
×
2916
                if ok {
×
2917
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2918
                                "seeds: %v", dnsSeeds)
×
2919

×
2920
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2921
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2922
                        )
×
2923
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2924
                }
×
2925
        }
2926

2927
        return bootStrappers, nil
×
2928
}
2929

2930
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2931
// needs to ignore, which is made of three parts,
2932
//   - the node itself needs to be skipped as it doesn't make sense to connect
2933
//     to itself.
2934
//   - the peers that already have connections with, as in s.peersByPub.
2935
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2936
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2937
        s.mu.RLock()
×
2938
        defer s.mu.RUnlock()
×
2939

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

×
2942
        // We should ignore ourselves from bootstrapping.
×
2943
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2944
        ignore[selfKey] = struct{}{}
×
2945

×
2946
        // Ignore all connected peers.
×
2947
        for _, peer := range s.peersByPub {
×
2948
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2949
                ignore[nID] = struct{}{}
×
2950
        }
×
2951

2952
        // Ignore all persistent peers as they have a dedicated reconnecting
2953
        // process.
2954
        for pubKeyStr := range s.persistentPeers {
×
2955
                var nID autopilot.NodeID
×
2956
                copy(nID[:], []byte(pubKeyStr))
×
2957
                ignore[nID] = struct{}{}
×
2958
        }
×
2959

2960
        return ignore
×
2961
}
2962

2963
// peerBootstrapper is a goroutine which is tasked with attempting to establish
2964
// and maintain a target minimum number of outbound connections. With this
2965
// invariant, we ensure that our node is connected to a diverse set of peers
2966
// and that nodes newly joining the network receive an up to date network view
2967
// as soon as possible.
2968
func (s *server) peerBootstrapper(numTargetPeers uint32,
2969
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2970

×
2971
        defer s.wg.Done()
×
2972

×
2973
        // Before we continue, init the ignore peers map.
×
2974
        ignoreList := s.createBootstrapIgnorePeers()
×
2975

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

×
2980
        // Once done, we'll attempt to maintain our target minimum number of
×
2981
        // peers.
×
2982
        //
×
2983
        // We'll use a 15 second backoff, and double the time every time an
×
2984
        // epoch fails up to a ceiling.
×
2985
        backOff := time.Second * 15
×
2986

×
2987
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2988
        // see if we've reached our minimum number of peers.
×
2989
        sampleTicker := time.NewTicker(backOff)
×
2990
        defer sampleTicker.Stop()
×
2991

×
2992
        // We'll use the number of attempts and errors to determine if we need
×
2993
        // to increase the time between discovery epochs.
×
2994
        var epochErrors uint32 // To be used atomically.
×
2995
        var epochAttempts uint32
×
2996

×
2997
        for {
×
2998
                select {
×
2999
                // The ticker has just woken us up, so we'll need to check if
3000
                // we need to attempt to connect our to any more peers.
3001
                case <-sampleTicker.C:
×
3002
                        // Obtain the current number of peers, so we can gauge
×
3003
                        // if we need to sample more peers or not.
×
3004
                        s.mu.RLock()
×
3005
                        numActivePeers := uint32(len(s.peersByPub))
×
3006
                        s.mu.RUnlock()
×
3007

×
3008
                        // If we have enough peers, then we can loop back
×
3009
                        // around to the next round as we're done here.
×
3010
                        if numActivePeers >= numTargetPeers {
×
3011
                                continue
×
3012
                        }
3013

3014
                        // If all of our attempts failed during this last back
3015
                        // off period, then will increase our backoff to 5
3016
                        // minute ceiling to avoid an excessive number of
3017
                        // queries
3018
                        //
3019
                        // TODO(roasbeef): add reverse policy too?
3020

3021
                        if epochAttempts > 0 &&
×
3022
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3023

×
3024
                                sampleTicker.Stop()
×
3025

×
3026
                                backOff *= 2
×
3027
                                if backOff > bootstrapBackOffCeiling {
×
3028
                                        backOff = bootstrapBackOffCeiling
×
3029
                                }
×
3030

3031
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3032
                                        "%v", backOff)
×
3033
                                sampleTicker = time.NewTicker(backOff)
×
3034
                                continue
×
3035
                        }
3036

3037
                        atomic.StoreUint32(&epochErrors, 0)
×
3038
                        epochAttempts = 0
×
3039

×
3040
                        // Since we know need more peers, we'll compute the
×
3041
                        // exact number we need to reach our threshold.
×
3042
                        numNeeded := numTargetPeers - numActivePeers
×
3043

×
3044
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3045
                                "peers", numNeeded)
×
3046

×
3047
                        // With the number of peers we need calculated, we'll
×
3048
                        // query the network bootstrappers to sample a set of
×
3049
                        // random addrs for us.
×
3050
                        //
×
3051
                        // Before we continue, get a copy of the ignore peers
×
3052
                        // map.
×
3053
                        ignoreList = s.createBootstrapIgnorePeers()
×
3054

×
3055
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3056
                                ignoreList, numNeeded*2, bootstrappers...,
×
3057
                        )
×
3058
                        if err != nil {
×
3059
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3060
                                        "peers: %v", err)
×
3061
                                continue
×
3062
                        }
3063

3064
                        // Finally, we'll launch a new goroutine for each
3065
                        // prospective peer candidates.
3066
                        for _, addr := range peerAddrs {
×
3067
                                epochAttempts++
×
3068

×
3069
                                go func(a *lnwire.NetAddress) {
×
3070
                                        // TODO(roasbeef): can do AS, subnet,
×
3071
                                        // country diversity, etc
×
3072
                                        errChan := make(chan error, 1)
×
3073
                                        s.connectToPeer(
×
3074
                                                a, errChan,
×
3075
                                                s.cfg.ConnectionTimeout,
×
3076
                                        )
×
3077
                                        select {
×
3078
                                        case err := <-errChan:
×
3079
                                                if err == nil {
×
3080
                                                        return
×
3081
                                                }
×
3082

3083
                                                srvrLog.Errorf("Unable to "+
×
3084
                                                        "connect to %v: %v",
×
3085
                                                        a, err)
×
3086
                                                atomic.AddUint32(&epochErrors, 1)
×
3087
                                        case <-s.quit:
×
3088
                                        }
3089
                                }(addr)
3090
                        }
3091
                case <-s.quit:
×
3092
                        return
×
3093
                }
3094
        }
3095
}
3096

3097
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3098
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3099
// query back off each time we encounter a failure.
3100
const bootstrapBackOffCeiling = time.Minute * 5
3101

3102
// initialPeerBootstrap attempts to continuously connect to peers on startup
3103
// until the target number of peers has been reached. This ensures that nodes
3104
// receive an up to date network view as soon as possible.
3105
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
3106
        numTargetPeers uint32,
3107
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3108

×
3109
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3110
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3111

×
3112
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3113
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3114
        var delaySignal <-chan time.Time
×
3115
        delayTime := time.Second * 2
×
3116

×
3117
        // As want to be more aggressive, we'll use a lower back off celling
×
3118
        // then the main peer bootstrap logic.
×
3119
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3120

×
3121
        for attempts := 0; ; attempts++ {
×
3122
                // Check if the server has been requested to shut down in order
×
3123
                // to prevent blocking.
×
3124
                if s.Stopped() {
×
3125
                        return
×
3126
                }
×
3127

3128
                // We can exit our aggressive initial peer bootstrapping stage
3129
                // if we've reached out target number of peers.
3130
                s.mu.RLock()
×
3131
                numActivePeers := uint32(len(s.peersByPub))
×
3132
                s.mu.RUnlock()
×
3133

×
3134
                if numActivePeers >= numTargetPeers {
×
3135
                        return
×
3136
                }
×
3137

3138
                if attempts > 0 {
×
3139
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3140
                                "bootstrap peers (attempt #%v)", delayTime,
×
3141
                                attempts)
×
3142

×
3143
                        // We've completed at least one iterating and haven't
×
3144
                        // finished, so we'll start to insert a delay period
×
3145
                        // between each attempt.
×
3146
                        delaySignal = time.After(delayTime)
×
3147
                        select {
×
3148
                        case <-delaySignal:
×
3149
                        case <-s.quit:
×
3150
                                return
×
3151
                        }
3152

3153
                        // After our delay, we'll double the time we wait up to
3154
                        // the max back off period.
3155
                        delayTime *= 2
×
3156
                        if delayTime > backOffCeiling {
×
3157
                                delayTime = backOffCeiling
×
3158
                        }
×
3159
                }
3160

3161
                // Otherwise, we'll request for the remaining number of peers
3162
                // in order to reach our target.
3163
                peersNeeded := numTargetPeers - numActivePeers
×
3164
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3165
                        ignore, peersNeeded, bootstrappers...,
×
3166
                )
×
3167
                if err != nil {
×
3168
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3169
                                "peers: %v", err)
×
3170
                        continue
×
3171
                }
3172

3173
                // Then, we'll attempt to establish a connection to the
3174
                // different peer addresses retrieved by our bootstrappers.
3175
                var wg sync.WaitGroup
×
3176
                for _, bootstrapAddr := range bootstrapAddrs {
×
3177
                        wg.Add(1)
×
3178
                        go func(addr *lnwire.NetAddress) {
×
3179
                                defer wg.Done()
×
3180

×
3181
                                errChan := make(chan error, 1)
×
3182
                                go s.connectToPeer(
×
3183
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3184
                                )
×
3185

×
3186
                                // We'll only allow this connection attempt to
×
3187
                                // take up to 3 seconds. This allows us to move
×
3188
                                // quickly by discarding peers that are slowing
×
3189
                                // us down.
×
3190
                                select {
×
3191
                                case err := <-errChan:
×
3192
                                        if err == nil {
×
3193
                                                return
×
3194
                                        }
×
3195
                                        srvrLog.Errorf("Unable to connect to "+
×
3196
                                                "%v: %v", addr, err)
×
3197
                                // TODO: tune timeout? 3 seconds might be *too*
3198
                                // aggressive but works well.
3199
                                case <-time.After(3 * time.Second):
×
3200
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3201
                                                "to not establishing a "+
×
3202
                                                "connection within 3 seconds",
×
3203
                                                addr)
×
3204
                                case <-s.quit:
×
3205
                                }
3206
                        }(bootstrapAddr)
3207
                }
3208

3209
                wg.Wait()
×
3210
        }
3211
}
3212

3213
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3214
// order to listen for inbound connections over Tor.
3215
func (s *server) createNewHiddenService() error {
×
3216
        // Determine the different ports the server is listening on. The onion
×
3217
        // service's virtual port will map to these ports and one will be picked
×
3218
        // at random when the onion service is being accessed.
×
3219
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3220
        for _, listenAddr := range s.listenAddrs {
×
3221
                port := listenAddr.(*net.TCPAddr).Port
×
3222
                listenPorts = append(listenPorts, port)
×
3223
        }
×
3224

3225
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3226
        if err != nil {
×
3227
                return err
×
3228
        }
×
3229

3230
        // Once the port mapping has been set, we can go ahead and automatically
3231
        // create our onion service. The service's private key will be saved to
3232
        // disk in order to regain access to this service when restarting `lnd`.
3233
        onionCfg := tor.AddOnionConfig{
×
3234
                VirtualPort: defaultPeerPort,
×
3235
                TargetPorts: listenPorts,
×
3236
                Store: tor.NewOnionFile(
×
3237
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3238
                        encrypter,
×
3239
                ),
×
3240
        }
×
3241

×
3242
        switch {
×
3243
        case s.cfg.Tor.V2:
×
3244
                onionCfg.Type = tor.V2
×
3245
        case s.cfg.Tor.V3:
×
3246
                onionCfg.Type = tor.V3
×
3247
        }
3248

3249
        addr, err := s.torController.AddOnion(onionCfg)
×
3250
        if err != nil {
×
3251
                return err
×
3252
        }
×
3253

3254
        // Now that the onion service has been created, we'll add the onion
3255
        // address it can be reached at to our list of advertised addresses.
3256
        newNodeAnn, err := s.genNodeAnnouncement(
×
3257
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3258
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3259
                },
×
3260
        )
3261
        if err != nil {
×
3262
                return fmt.Errorf("unable to generate new node "+
×
3263
                        "announcement: %v", err)
×
3264
        }
×
3265

3266
        // Finally, we'll update the on-disk version of our announcement so it
3267
        // will eventually propagate to nodes in the network.
3268
        selfNode := &models.LightningNode{
×
3269
                HaveNodeAnnouncement: true,
×
3270
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3271
                Addresses:            newNodeAnn.Addresses,
×
3272
                Alias:                newNodeAnn.Alias.String(),
×
3273
                Features: lnwire.NewFeatureVector(
×
3274
                        newNodeAnn.Features, lnwire.Features,
×
3275
                ),
×
3276
                Color:        newNodeAnn.RGBColor,
×
3277
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3278
        }
×
3279
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3280
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3281
                return fmt.Errorf("can't set self node: %w", err)
×
3282
        }
×
3283

3284
        return nil
×
3285
}
3286

3287
// findChannel finds a channel given a public key and ChannelID. It is an
3288
// optimization that is quicker than seeking for a channel given only the
3289
// ChannelID.
3290
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3291
        *channeldb.OpenChannel, error) {
×
3292

×
3293
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
×
3294
        if err != nil {
×
3295
                return nil, err
×
3296
        }
×
3297

3298
        for _, channel := range nodeChans {
×
3299
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
×
3300
                        return channel, nil
×
3301
                }
×
3302
        }
3303

3304
        return nil, fmt.Errorf("unable to find channel")
×
3305
}
3306

3307
// getNodeAnnouncement fetches the current, fully signed node announcement.
3308
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
×
3309
        s.mu.Lock()
×
3310
        defer s.mu.Unlock()
×
3311

×
3312
        return *s.currentNodeAnn
×
3313
}
×
3314

3315
// genNodeAnnouncement generates and returns the current fully signed node
3316
// announcement. The time stamp of the announcement will be updated in order
3317
// to ensure it propagates through the network.
3318
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3319
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
×
3320

×
3321
        s.mu.Lock()
×
3322
        defer s.mu.Unlock()
×
3323

×
3324
        // First, try to update our feature manager with the updated set of
×
3325
        // features.
×
3326
        if features != nil {
×
3327
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
×
3328
                        feature.SetNodeAnn: features,
×
3329
                }
×
3330
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
×
3331
                if err != nil {
×
3332
                        return lnwire.NodeAnnouncement{}, err
×
3333
                }
×
3334

3335
                // If we could successfully update our feature manager, add
3336
                // an update modifier to include these new features to our
3337
                // set.
3338
                modifiers = append(
×
3339
                        modifiers, netann.NodeAnnSetFeatures(features),
×
3340
                )
×
3341
        }
3342

3343
        // Always update the timestamp when refreshing to ensure the update
3344
        // propagates.
3345
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
×
3346

×
3347
        // Apply the requested changes to the node announcement.
×
3348
        for _, modifier := range modifiers {
×
3349
                modifier(s.currentNodeAnn)
×
3350
        }
×
3351

3352
        // Sign a new update after applying all of the passed modifiers.
3353
        err := netann.SignNodeAnnouncement(
×
3354
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
×
3355
        )
×
3356
        if err != nil {
×
3357
                return lnwire.NodeAnnouncement{}, err
×
3358
        }
×
3359

3360
        return *s.currentNodeAnn, nil
×
3361
}
3362

3363
// updateAndBroadcastSelfNode generates a new node announcement
3364
// applying the giving modifiers and updating the time stamp
3365
// to ensure it propagates through the network. Then it broadcasts
3366
// it to the network.
3367
func (s *server) updateAndBroadcastSelfNode(features *lnwire.RawFeatureVector,
3368
        modifiers ...netann.NodeAnnModifier) error {
×
3369

×
3370
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
×
3371
        if err != nil {
×
3372
                return fmt.Errorf("unable to generate new node "+
×
3373
                        "announcement: %v", err)
×
3374
        }
×
3375

3376
        // Update the on-disk version of our announcement.
3377
        // Load and modify self node istead of creating anew instance so we
3378
        // don't risk overwriting any existing values.
3379
        selfNode, err := s.graphDB.SourceNode()
×
3380
        if err != nil {
×
3381
                return fmt.Errorf("unable to get current source node: %w", err)
×
3382
        }
×
3383

3384
        selfNode.HaveNodeAnnouncement = true
×
3385
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
×
3386
        selfNode.Addresses = newNodeAnn.Addresses
×
3387
        selfNode.Alias = newNodeAnn.Alias.String()
×
3388
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
×
3389
        selfNode.Color = newNodeAnn.RGBColor
×
3390
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
×
3391

×
3392
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3393

×
3394
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3395
                return fmt.Errorf("can't set self node: %w", err)
×
3396
        }
×
3397

3398
        // Finally, propagate it to the nodes in the network.
3399
        err = s.BroadcastMessage(nil, &newNodeAnn)
×
3400
        if err != nil {
×
3401
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3402
                        "announcement to peers: %v", err)
×
3403
                return err
×
3404
        }
×
3405

3406
        return nil
×
3407
}
3408

3409
type nodeAddresses struct {
3410
        pubKey    *btcec.PublicKey
3411
        addresses []net.Addr
3412
}
3413

3414
// establishPersistentConnections attempts to establish persistent connections
3415
// to all our direct channel collaborators. In order to promote liveness of our
3416
// active channels, we instruct the connection manager to attempt to establish
3417
// and maintain persistent connections to all our direct channel counterparties.
3418
func (s *server) establishPersistentConnections() error {
×
3419
        // nodeAddrsMap stores the combination of node public keys and addresses
×
3420
        // that we'll attempt to reconnect to. PubKey strings are used as keys
×
3421
        // since other PubKey forms can't be compared.
×
3422
        nodeAddrsMap := map[string]*nodeAddresses{}
×
3423

×
3424
        // Iterate through the list of LinkNodes to find addresses we should
×
3425
        // attempt to connect to based on our set of previous connections. Set
×
3426
        // the reconnection port to the default peer port.
×
3427
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
×
3428
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
×
3429
                return err
×
3430
        }
×
3431
        for _, node := range linkNodes {
×
3432
                pubStr := string(node.IdentityPub.SerializeCompressed())
×
3433
                nodeAddrs := &nodeAddresses{
×
3434
                        pubKey:    node.IdentityPub,
×
3435
                        addresses: node.Addresses,
×
3436
                }
×
3437
                nodeAddrsMap[pubStr] = nodeAddrs
×
3438
        }
×
3439

3440
        // After checking our previous connections for addresses to connect to,
3441
        // iterate through the nodes in our channel graph to find addresses
3442
        // that have been added via NodeAnnouncement messages.
3443
        sourceNode, err := s.graphDB.SourceNode()
×
3444
        if err != nil {
×
3445
                return err
×
3446
        }
×
3447

3448
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3449
        // each of the nodes.
3450
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
×
3451
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
×
3452
                tx kvdb.RTx,
×
3453
                chanInfo *models.ChannelEdgeInfo,
×
3454
                policy, _ *models.ChannelEdgePolicy) error {
×
3455

×
3456
                // If the remote party has announced the channel to us, but we
×
3457
                // haven't yet, then we won't have a policy. However, we don't
×
3458
                // need this to connect to the peer, so we'll log it and move on.
×
3459
                if policy == nil {
×
3460
                        srvrLog.Warnf("No channel policy found for "+
×
3461
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3462
                }
×
3463

3464
                // We'll now fetch the peer opposite from us within this
3465
                // channel so we can queue up a direct connection to them.
3466
                channelPeer, err := s.graphDB.FetchOtherNode(
×
3467
                        tx, chanInfo, selfPub,
×
3468
                )
×
3469
                if err != nil {
×
3470
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3471
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3472
                                err)
×
3473
                }
×
3474

3475
                pubStr := string(channelPeer.PubKeyBytes[:])
×
3476

×
3477
                // Add all unique addresses from channel
×
3478
                // graph/NodeAnnouncements to the list of addresses we'll
×
3479
                // connect to for this peer.
×
3480
                addrSet := make(map[string]net.Addr)
×
3481
                for _, addr := range channelPeer.Addresses {
×
3482
                        switch addr.(type) {
×
3483
                        case *net.TCPAddr:
×
3484
                                addrSet[addr.String()] = addr
×
3485

3486
                        // We'll only attempt to connect to Tor addresses if Tor
3487
                        // outbound support is enabled.
3488
                        case *tor.OnionAddr:
×
3489
                                if s.cfg.Tor.Active {
×
3490
                                        addrSet[addr.String()] = addr
×
3491
                                }
×
3492
                        }
3493
                }
3494

3495
                // If this peer is also recorded as a link node, we'll add any
3496
                // additional addresses that have not already been selected.
3497
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
×
3498
                if ok {
×
3499
                        for _, lnAddress := range linkNodeAddrs.addresses {
×
3500
                                switch lnAddress.(type) {
×
3501
                                case *net.TCPAddr:
×
3502
                                        addrSet[lnAddress.String()] = lnAddress
×
3503

3504
                                // We'll only attempt to connect to Tor
3505
                                // addresses if Tor outbound support is enabled.
3506
                                case *tor.OnionAddr:
×
3507
                                        if s.cfg.Tor.Active {
×
3508
                                                addrSet[lnAddress.String()] = lnAddress
×
3509
                                        }
×
3510
                                }
3511
                        }
3512
                }
3513

3514
                // Construct a slice of the deduped addresses.
3515
                var addrs []net.Addr
×
3516
                for _, addr := range addrSet {
×
3517
                        addrs = append(addrs, addr)
×
3518
                }
×
3519

3520
                n := &nodeAddresses{
×
3521
                        addresses: addrs,
×
3522
                }
×
3523
                n.pubKey, err = channelPeer.PubKey()
×
3524
                if err != nil {
×
3525
                        return err
×
3526
                }
×
3527

3528
                nodeAddrsMap[pubStr] = n
×
3529
                return nil
×
3530
        })
3531
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
×
3532
                return err
×
3533
        }
×
3534

3535
        srvrLog.Debugf("Establishing %v persistent connections on start",
×
3536
                len(nodeAddrsMap))
×
3537

×
3538
        // Acquire and hold server lock until all persistent connection requests
×
3539
        // have been recorded and sent to the connection manager.
×
3540
        s.mu.Lock()
×
3541
        defer s.mu.Unlock()
×
3542

×
3543
        // Iterate through the combined list of addresses from prior links and
×
3544
        // node announcements and attempt to reconnect to each node.
×
3545
        var numOutboundConns int
×
3546
        for pubStr, nodeAddr := range nodeAddrsMap {
×
3547
                // Add this peer to the set of peers we should maintain a
×
3548
                // persistent connection with. We set the value to false to
×
3549
                // indicate that we should not continue to reconnect if the
×
3550
                // number of channels returns to zero, since this peer has not
×
3551
                // been requested as perm by the user.
×
3552
                s.persistentPeers[pubStr] = false
×
3553
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
×
3554
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
×
3555
                }
×
3556

3557
                for _, address := range nodeAddr.addresses {
×
3558
                        // Create a wrapper address which couples the IP and
×
3559
                        // the pubkey so the brontide authenticated connection
×
3560
                        // can be established.
×
3561
                        lnAddr := &lnwire.NetAddress{
×
3562
                                IdentityKey: nodeAddr.pubKey,
×
3563
                                Address:     address,
×
3564
                        }
×
3565

×
3566
                        s.persistentPeerAddrs[pubStr] = append(
×
3567
                                s.persistentPeerAddrs[pubStr], lnAddr)
×
3568
                }
×
3569

3570
                // We'll connect to the first 10 peers immediately, then
3571
                // randomly stagger any remaining connections if the
3572
                // stagger initial reconnect flag is set. This ensures
3573
                // that mobile nodes or nodes with a small number of
3574
                // channels obtain connectivity quickly, but larger
3575
                // nodes are able to disperse the costs of connecting to
3576
                // all peers at once.
3577
                if numOutboundConns < numInstantInitReconnect ||
×
3578
                        !s.cfg.StaggerInitialReconnect {
×
3579

×
3580
                        go s.connectToPersistentPeer(pubStr)
×
3581
                } else {
×
3582
                        go s.delayInitialReconnect(pubStr)
×
3583
                }
×
3584

3585
                numOutboundConns++
×
3586
        }
3587

3588
        return nil
×
3589
}
3590

3591
// delayInitialReconnect will attempt a reconnection to the given peer after
3592
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3593
//
3594
// NOTE: This method MUST be run as a goroutine.
3595
func (s *server) delayInitialReconnect(pubStr string) {
×
3596
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3597
        select {
×
3598
        case <-time.After(delay):
×
3599
                s.connectToPersistentPeer(pubStr)
×
3600
        case <-s.quit:
×
3601
        }
3602
}
3603

3604
// prunePersistentPeerConnection removes all internal state related to
3605
// persistent connections to a peer within the server. This is used to avoid
3606
// persistent connection retries to peers we do not have any open channels with.
3607
func (s *server) prunePersistentPeerConnection(compressedPubKey [33]byte) {
×
3608
        pubKeyStr := string(compressedPubKey[:])
×
3609

×
3610
        s.mu.Lock()
×
3611
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
×
3612
                delete(s.persistentPeers, pubKeyStr)
×
3613
                delete(s.persistentPeersBackoff, pubKeyStr)
×
3614
                delete(s.persistentPeerAddrs, pubKeyStr)
×
3615
                s.cancelConnReqs(pubKeyStr, nil)
×
3616
                s.mu.Unlock()
×
3617

×
3618
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
×
3619
                        "peer has no open channels", compressedPubKey)
×
3620

×
3621
                return
×
3622
        }
×
3623
        s.mu.Unlock()
×
3624
}
3625

3626
// BroadcastMessage sends a request to the server to broadcast a set of
3627
// messages to all peers other than the one specified by the `skips` parameter.
3628
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3629
// the target peers.
3630
//
3631
// NOTE: This function is safe for concurrent access.
3632
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3633
        msgs ...lnwire.Message) error {
×
3634

×
3635
        // Filter out peers found in the skips map. We synchronize access to
×
3636
        // peersByPub throughout this process to ensure we deliver messages to
×
3637
        // exact set of peers present at the time of invocation.
×
3638
        s.mu.RLock()
×
3639
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
3640
        for pubStr, sPeer := range s.peersByPub {
×
3641
                if skips != nil {
×
3642
                        if _, ok := skips[sPeer.PubKey()]; ok {
×
3643
                                srvrLog.Tracef("Skipping %x in broadcast with "+
×
3644
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
×
3645
                                continue
×
3646
                        }
3647
                }
3648

3649
                peers = append(peers, sPeer)
×
3650
        }
3651
        s.mu.RUnlock()
×
3652

×
3653
        // Iterate over all known peers, dispatching a go routine to enqueue
×
3654
        // all messages to each of peers.
×
3655
        var wg sync.WaitGroup
×
3656
        for _, sPeer := range peers {
×
3657
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
×
3658
                        sPeer.PubKey())
×
3659

×
3660
                // Dispatch a go routine to enqueue all messages to this peer.
×
3661
                wg.Add(1)
×
3662
                s.wg.Add(1)
×
3663
                go func(p lnpeer.Peer) {
×
3664
                        defer s.wg.Done()
×
3665
                        defer wg.Done()
×
3666

×
3667
                        p.SendMessageLazy(false, msgs...)
×
3668
                }(sPeer)
×
3669
        }
3670

3671
        // Wait for all messages to have been dispatched before returning to
3672
        // caller.
3673
        wg.Wait()
×
3674

×
3675
        return nil
×
3676
}
3677

3678
// NotifyWhenOnline can be called by other subsystems to get notified when a
3679
// particular peer comes online. The peer itself is sent across the peerChan.
3680
//
3681
// NOTE: This function is safe for concurrent access.
3682
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3683
        peerChan chan<- lnpeer.Peer) {
×
3684

×
3685
        s.mu.Lock()
×
3686

×
3687
        // Compute the target peer's identifier.
×
3688
        pubStr := string(peerKey[:])
×
3689

×
3690
        // Check if peer is connected.
×
3691
        peer, ok := s.peersByPub[pubStr]
×
3692
        if ok {
×
3693
                // Unlock here so that the mutex isn't held while we are
×
3694
                // waiting for the peer to become active.
×
3695
                s.mu.Unlock()
×
3696

×
3697
                // Wait until the peer signals that it is actually active
×
3698
                // rather than only in the server's maps.
×
3699
                select {
×
3700
                case <-peer.ActiveSignal():
×
3701
                case <-peer.QuitSignal():
×
3702
                        // The peer quit, so we'll add the channel to the slice
×
3703
                        // and return.
×
3704
                        s.mu.Lock()
×
3705
                        s.peerConnectedListeners[pubStr] = append(
×
3706
                                s.peerConnectedListeners[pubStr], peerChan,
×
3707
                        )
×
3708
                        s.mu.Unlock()
×
3709
                        return
×
3710
                }
3711

3712
                // Connected, can return early.
3713
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
×
3714

×
3715
                select {
×
3716
                case peerChan <- peer:
×
3717
                case <-s.quit:
×
3718
                }
3719

3720
                return
×
3721
        }
3722

3723
        // Not connected, store this listener such that it can be notified when
3724
        // the peer comes online.
3725
        s.peerConnectedListeners[pubStr] = append(
×
3726
                s.peerConnectedListeners[pubStr], peerChan,
×
3727
        )
×
3728
        s.mu.Unlock()
×
3729
}
3730

3731
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3732
// the given public key has been disconnected. The notification is signaled by
3733
// closing the channel returned.
3734
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
×
3735
        s.mu.Lock()
×
3736
        defer s.mu.Unlock()
×
3737

×
3738
        c := make(chan struct{})
×
3739

×
3740
        // If the peer is already offline, we can immediately trigger the
×
3741
        // notification.
×
3742
        peerPubKeyStr := string(peerPubKey[:])
×
3743
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
×
3744
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3745
                close(c)
×
3746
                return c
×
3747
        }
×
3748

3749
        // Otherwise, the peer is online, so we'll keep track of the channel to
3750
        // trigger the notification once the server detects the peer
3751
        // disconnects.
3752
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
×
3753
                s.peerDisconnectedListeners[peerPubKeyStr], c,
×
3754
        )
×
3755

×
3756
        return c
×
3757
}
3758

3759
// FindPeer will return the peer that corresponds to the passed in public key.
3760
// This function is used by the funding manager, allowing it to update the
3761
// daemon's local representation of the remote peer.
3762
//
3763
// NOTE: This function is safe for concurrent access.
3764
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
×
3765
        s.mu.RLock()
×
3766
        defer s.mu.RUnlock()
×
3767

×
3768
        pubStr := string(peerKey.SerializeCompressed())
×
3769

×
3770
        return s.findPeerByPubStr(pubStr)
×
3771
}
×
3772

3773
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3774
// which should be a string representation of the peer's serialized, compressed
3775
// public key.
3776
//
3777
// NOTE: This function is safe for concurrent access.
3778
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
3779
        s.mu.RLock()
×
3780
        defer s.mu.RUnlock()
×
3781

×
3782
        return s.findPeerByPubStr(pubStr)
×
3783
}
×
3784

3785
// findPeerByPubStr is an internal method that retrieves the specified peer from
3786
// the server's internal state using.
3787
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
3788
        peer, ok := s.peersByPub[pubStr]
×
3789
        if !ok {
×
3790
                return nil, ErrPeerNotConnected
×
3791
        }
×
3792

3793
        return peer, nil
×
3794
}
3795

3796
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3797
// exponential backoff. If no previous backoff was known, the default is
3798
// returned.
3799
func (s *server) nextPeerBackoff(pubStr string,
3800
        startTime time.Time) time.Duration {
×
3801

×
3802
        // Now, determine the appropriate backoff to use for the retry.
×
3803
        backoff, ok := s.persistentPeersBackoff[pubStr]
×
3804
        if !ok {
×
3805
                // If an existing backoff was unknown, use the default.
×
3806
                return s.cfg.MinBackoff
×
3807
        }
×
3808

3809
        // If the peer failed to start properly, we'll just use the previous
3810
        // backoff to compute the subsequent randomized exponential backoff
3811
        // duration. This will roughly double on average.
3812
        if startTime.IsZero() {
×
3813
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3814
        }
×
3815

3816
        // The peer succeeded in starting. If the connection didn't last long
3817
        // enough to be considered stable, we'll continue to back off retries
3818
        // with this peer.
3819
        connDuration := time.Since(startTime)
×
3820
        if connDuration < defaultStableConnDuration {
×
3821
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3822
        }
×
3823

3824
        // The peer succeed in starting and this was stable peer, so we'll
3825
        // reduce the timeout duration by the length of the connection after
3826
        // applying randomized exponential backoff. We'll only apply this in the
3827
        // case that:
3828
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3829
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3830
        if relaxedBackoff > s.cfg.MinBackoff {
×
3831
                return relaxedBackoff
×
3832
        }
×
3833

3834
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3835
        // the stable connection lasted much longer than our previous backoff.
3836
        // To reward such good behavior, we'll reconnect after the default
3837
        // timeout.
3838
        return s.cfg.MinBackoff
×
3839
}
3840

3841
// shouldDropLocalConnection determines if our local connection to a remote peer
3842
// should be dropped in the case of concurrent connection establishment. In
3843
// order to deterministically decide which connection should be dropped, we'll
3844
// utilize the ordering of the local and remote public key. If we didn't use
3845
// such a tie breaker, then we risk _both_ connections erroneously being
3846
// dropped.
3847
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3848
        localPubBytes := local.SerializeCompressed()
×
3849
        remotePubPbytes := remote.SerializeCompressed()
×
3850

×
3851
        // The connection that comes from the node with a "smaller" pubkey
×
3852
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3853
        // should drop our established connection.
×
3854
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3855
}
×
3856

3857
// InboundPeerConnected initializes a new peer in response to a new inbound
3858
// connection.
3859
//
3860
// NOTE: This function is safe for concurrent access.
3861
func (s *server) InboundPeerConnected(conn net.Conn) {
×
3862
        // Exit early if we have already been instructed to shutdown, this
×
3863
        // prevents any delayed callbacks from accidentally registering peers.
×
3864
        if s.Stopped() {
×
3865
                return
×
3866
        }
×
3867

3868
        nodePub := conn.(*brontide.Conn).RemotePub()
×
3869
        pubSer := nodePub.SerializeCompressed()
×
3870
        pubStr := string(pubSer)
×
3871

×
3872
        var pubBytes [33]byte
×
3873
        copy(pubBytes[:], pubSer)
×
3874

×
3875
        s.mu.Lock()
×
3876
        defer s.mu.Unlock()
×
3877

×
3878
        // If the remote node's public key is banned, drop the connection.
×
3879
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
×
3880
        if dcErr != nil {
×
3881
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3882
                        "peer: %v", dcErr)
×
3883
                conn.Close()
×
3884

×
3885
                return
×
3886
        }
×
3887

3888
        if shouldDc {
×
3889
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3890
                        "banned.", pubSer)
×
3891

×
3892
                conn.Close()
×
3893

×
3894
                return
×
3895
        }
×
3896

3897
        // If we already have an outbound connection to this peer, then ignore
3898
        // this new connection.
3899
        if p, ok := s.outboundPeers[pubStr]; ok {
×
3900
                srvrLog.Debugf("Already have outbound connection for %v, "+
×
3901
                        "ignoring inbound connection from local=%v, remote=%v",
×
3902
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
3903

×
3904
                conn.Close()
×
3905
                return
×
3906
        }
×
3907

3908
        // If we already have a valid connection that is scheduled to take
3909
        // precedence once the prior peer has finished disconnecting, we'll
3910
        // ignore this connection.
3911
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
×
3912
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3913
                        "scheduled", conn.RemoteAddr(), p)
×
3914
                conn.Close()
×
3915
                return
×
3916
        }
×
3917

3918
        srvrLog.Infof("New inbound connection from %v", conn.RemoteAddr())
×
3919

×
3920
        // Check to see if we already have a connection with this peer. If so,
×
3921
        // we may need to drop our existing connection. This prevents us from
×
3922
        // having duplicate connections to the same peer. We forgo adding a
×
3923
        // default case as we expect these to be the only error values returned
×
3924
        // from findPeerByPubStr.
×
3925
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
3926
        switch err {
×
3927
        case ErrPeerNotConnected:
×
3928
                // We were unable to locate an existing connection with the
×
3929
                // target peer, proceed to connect.
×
3930
                s.cancelConnReqs(pubStr, nil)
×
3931
                s.peerConnected(conn, nil, true)
×
3932

3933
        case nil:
×
3934
                // We already have a connection with the incoming peer. If the
×
3935
                // connection we've already established should be kept and is
×
3936
                // not of the same type of the new connection (inbound), then
×
3937
                // we'll close out the new connection s.t there's only a single
×
3938
                // connection between us.
×
3939
                localPub := s.identityECDH.PubKey()
×
3940
                if !connectedPeer.Inbound() &&
×
3941
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3942

×
3943
                        srvrLog.Warnf("Received inbound connection from "+
×
3944
                                "peer %v, but already have outbound "+
×
3945
                                "connection, dropping conn", connectedPeer)
×
3946
                        conn.Close()
×
3947
                        return
×
3948
                }
×
3949

3950
                // Otherwise, if we should drop the connection, then we'll
3951
                // disconnect our already connected peer.
3952
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3953
                        connectedPeer)
×
3954

×
3955
                s.cancelConnReqs(pubStr, nil)
×
3956

×
3957
                // Remove the current peer from the server's internal state and
×
3958
                // signal that the peer termination watcher does not need to
×
3959
                // execute for this peer.
×
3960
                s.removePeer(connectedPeer)
×
3961
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3962
                s.scheduledPeerConnection[pubStr] = func() {
×
3963
                        s.peerConnected(conn, nil, true)
×
3964
                }
×
3965
        }
3966
}
3967

3968
// OutboundPeerConnected initializes a new peer in response to a new outbound
3969
// connection.
3970
// NOTE: This function is safe for concurrent access.
3971
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
×
3972
        // Exit early if we have already been instructed to shutdown, this
×
3973
        // prevents any delayed callbacks from accidentally registering peers.
×
3974
        if s.Stopped() {
×
3975
                return
×
3976
        }
×
3977

3978
        nodePub := conn.(*brontide.Conn).RemotePub()
×
3979
        pubSer := nodePub.SerializeCompressed()
×
3980
        pubStr := string(pubSer)
×
3981

×
3982
        var pubBytes [33]byte
×
3983
        copy(pubBytes[:], pubSer)
×
3984

×
3985
        s.mu.Lock()
×
3986
        defer s.mu.Unlock()
×
3987

×
3988
        // If the remote node's public key is banned, drop the connection.
×
3989
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
×
3990
        if dcErr != nil {
×
3991
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3992
                        "peer: %v", dcErr)
×
3993
                conn.Close()
×
3994

×
3995
                return
×
3996
        }
×
3997

3998
        if shouldDc {
×
3999
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
4000
                        "banned.", pubSer)
×
4001

×
4002
                if connReq != nil {
×
4003
                        s.connMgr.Remove(connReq.ID())
×
4004
                }
×
4005

4006
                conn.Close()
×
4007

×
4008
                return
×
4009
        }
4010

4011
        // If we already have an inbound connection to this peer, then ignore
4012
        // this new connection.
4013
        if p, ok := s.inboundPeers[pubStr]; ok {
×
4014
                srvrLog.Debugf("Already have inbound connection for %v, "+
×
4015
                        "ignoring outbound connection from local=%v, remote=%v",
×
4016
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
4017

×
4018
                if connReq != nil {
×
4019
                        s.connMgr.Remove(connReq.ID())
×
4020
                }
×
4021
                conn.Close()
×
4022
                return
×
4023
        }
4024
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
×
4025
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4026
                s.connMgr.Remove(connReq.ID())
×
4027
                conn.Close()
×
4028
                return
×
4029
        }
×
4030

4031
        // If we already have a valid connection that is scheduled to take
4032
        // precedence once the prior peer has finished disconnecting, we'll
4033
        // ignore this connection.
4034
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
×
4035
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
4036

×
4037
                if connReq != nil {
×
4038
                        s.connMgr.Remove(connReq.ID())
×
4039
                }
×
4040

4041
                conn.Close()
×
4042
                return
×
4043
        }
4044

4045
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
×
4046
                conn.RemoteAddr())
×
4047

×
4048
        if connReq != nil {
×
4049
                // A successful connection was returned by the connmgr.
×
4050
                // Immediately cancel all pending requests, excluding the
×
4051
                // outbound connection we just established.
×
4052
                ignore := connReq.ID()
×
4053
                s.cancelConnReqs(pubStr, &ignore)
×
4054
        } else {
×
4055
                // This was a successful connection made by some other
×
4056
                // subsystem. Remove all requests being managed by the connmgr.
×
4057
                s.cancelConnReqs(pubStr, nil)
×
4058
        }
×
4059

4060
        // If we already have a connection with this peer, decide whether or not
4061
        // we need to drop the stale connection. We forgo adding a default case
4062
        // as we expect these to be the only error values returned from
4063
        // findPeerByPubStr.
4064
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
4065
        switch err {
×
4066
        case ErrPeerNotConnected:
×
4067
                // We were unable to locate an existing connection with the
×
4068
                // target peer, proceed to connect.
×
4069
                s.peerConnected(conn, connReq, false)
×
4070

4071
        case nil:
×
4072
                // We already have a connection with the incoming peer. If the
×
4073
                // connection we've already established should be kept and is
×
4074
                // not of the same type of the new connection (outbound), then
×
4075
                // we'll close out the new connection s.t there's only a single
×
4076
                // connection between us.
×
4077
                localPub := s.identityECDH.PubKey()
×
4078
                if connectedPeer.Inbound() &&
×
4079
                        shouldDropLocalConnection(localPub, nodePub) {
×
4080

×
4081
                        srvrLog.Warnf("Established outbound connection to "+
×
4082
                                "peer %v, but already have inbound "+
×
4083
                                "connection, dropping conn", connectedPeer)
×
4084
                        if connReq != nil {
×
4085
                                s.connMgr.Remove(connReq.ID())
×
4086
                        }
×
4087
                        conn.Close()
×
4088
                        return
×
4089
                }
4090

4091
                // Otherwise, _their_ connection should be dropped. So we'll
4092
                // disconnect the peer and send the now obsolete peer to the
4093
                // server for garbage collection.
4094
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4095
                        connectedPeer)
×
4096

×
4097
                // Remove the current peer from the server's internal state and
×
4098
                // signal that the peer termination watcher does not need to
×
4099
                // execute for this peer.
×
4100
                s.removePeer(connectedPeer)
×
4101
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4102
                s.scheduledPeerConnection[pubStr] = func() {
×
4103
                        s.peerConnected(conn, connReq, false)
×
4104
                }
×
4105
        }
4106
}
4107

4108
// UnassignedConnID is the default connection ID that a request can have before
4109
// it actually is submitted to the connmgr.
4110
// TODO(conner): move into connmgr package, or better, add connmgr method for
4111
// generating atomic IDs
4112
const UnassignedConnID uint64 = 0
4113

4114
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4115
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4116
// Afterwards, each connection request removed from the connmgr. The caller can
4117
// optionally specify a connection ID to ignore, which prevents us from
4118
// canceling a successful request. All persistent connreqs for the provided
4119
// pubkey are discarded after the operationjw.
4120
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
×
4121
        // First, cancel any lingering persistent retry attempts, which will
×
4122
        // prevent retries for any with backoffs that are still maturing.
×
4123
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
×
4124
                close(cancelChan)
×
4125
                delete(s.persistentRetryCancels, pubStr)
×
4126
        }
×
4127

4128
        // Next, check to see if we have any outstanding persistent connection
4129
        // requests to this peer. If so, then we'll remove all of these
4130
        // connection requests, and also delete the entry from the map.
4131
        connReqs, ok := s.persistentConnReqs[pubStr]
×
4132
        if !ok {
×
4133
                return
×
4134
        }
×
4135

4136
        for _, connReq := range connReqs {
×
4137
                srvrLog.Tracef("Canceling %s:", connReqs)
×
4138

×
4139
                // Atomically capture the current request identifier.
×
4140
                connID := connReq.ID()
×
4141

×
4142
                // Skip any zero IDs, this indicates the request has not
×
4143
                // yet been schedule.
×
4144
                if connID == UnassignedConnID {
×
4145
                        continue
×
4146
                }
4147

4148
                // Skip a particular connection ID if instructed.
4149
                if skip != nil && connID == *skip {
×
4150
                        continue
×
4151
                }
4152

4153
                s.connMgr.Remove(connID)
×
4154
        }
4155

4156
        delete(s.persistentConnReqs, pubStr)
×
4157
}
4158

4159
// handleCustomMessage dispatches an incoming custom peers message to
4160
// subscribers.
4161
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
×
4162
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
×
4163
                peer, msg.Type)
×
4164

×
4165
        return s.customMessageServer.SendUpdate(&CustomMessage{
×
4166
                Peer: peer,
×
4167
                Msg:  msg,
×
4168
        })
×
4169
}
×
4170

4171
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4172
// messages.
4173
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
×
4174
        return s.customMessageServer.Subscribe()
×
4175
}
×
4176

4177
// peerConnected is a function that handles initialization a newly connected
4178
// peer by adding it to the server's global list of all active peers, and
4179
// starting all the goroutines the peer needs to function properly. The inbound
4180
// boolean should be true if the peer initiated the connection to us.
4181
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4182
        inbound bool) {
×
4183

×
4184
        brontideConn := conn.(*brontide.Conn)
×
4185
        addr := conn.RemoteAddr()
×
4186
        pubKey := brontideConn.RemotePub()
×
4187

×
4188
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
×
4189
                pubKey.SerializeCompressed(), addr, inbound)
×
4190

×
4191
        peerAddr := &lnwire.NetAddress{
×
4192
                IdentityKey: pubKey,
×
4193
                Address:     addr,
×
4194
                ChainNet:    s.cfg.ActiveNetParams.Net,
×
4195
        }
×
4196

×
4197
        // With the brontide connection established, we'll now craft the feature
×
4198
        // vectors to advertise to the remote node.
×
4199
        initFeatures := s.featureMgr.Get(feature.SetInit)
×
4200
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
×
4201

×
4202
        // Lookup past error caches for the peer in the server. If no buffer is
×
4203
        // found, create a fresh buffer.
×
4204
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
×
4205
        errBuffer, ok := s.peerErrors[pkStr]
×
4206
        if !ok {
×
4207
                var err error
×
4208
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
×
4209
                if err != nil {
×
4210
                        srvrLog.Errorf("unable to create peer %v", err)
×
4211
                        return
×
4212
                }
×
4213
        }
4214

4215
        // If we directly set the peer.Config TowerClient member to the
4216
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4217
        // the peer.Config's TowerClient member will not evaluate to nil even
4218
        // though the underlying value is nil. To avoid this gotcha which can
4219
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4220
        // TowerClient if needed.
4221
        var towerClient wtclient.ClientManager
×
4222
        if s.towerClientMgr != nil {
×
4223
                towerClient = s.towerClientMgr
×
4224
        }
×
4225

4226
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
×
4227
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
4228

×
4229
        // Now that we've established a connection, create a peer, and it to the
×
4230
        // set of currently active peers. Configure the peer with the incoming
×
4231
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
×
4232
        // offered that would trigger channel closure. In case of outgoing
×
4233
        // htlcs, an extra block is added to prevent the channel from being
×
4234
        // closed when the htlc is outstanding and a new block comes in.
×
4235
        pCfg := peer.Config{
×
4236
                Conn:                    brontideConn,
×
4237
                ConnReq:                 connReq,
×
4238
                Addr:                    peerAddr,
×
4239
                Inbound:                 inbound,
×
4240
                Features:                initFeatures,
×
4241
                LegacyFeatures:          legacyFeatures,
×
4242
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
×
4243
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
×
4244
                ErrorBuffer:             errBuffer,
×
4245
                WritePool:               s.writePool,
×
4246
                ReadPool:                s.readPool,
×
4247
                Switch:                  s.htlcSwitch,
×
4248
                InterceptSwitch:         s.interceptableSwitch,
×
4249
                ChannelDB:               s.chanStateDB,
×
4250
                ChannelGraph:            s.graphDB,
×
4251
                ChainArb:                s.chainArb,
×
4252
                AuthGossiper:            s.authGossiper,
×
4253
                ChanStatusMgr:           s.chanStatusMgr,
×
4254
                ChainIO:                 s.cc.ChainIO,
×
4255
                FeeEstimator:            s.cc.FeeEstimator,
×
4256
                Signer:                  s.cc.Wallet.Cfg.Signer,
×
4257
                SigPool:                 s.sigPool,
×
4258
                Wallet:                  s.cc.Wallet,
×
4259
                ChainNotifier:           s.cc.ChainNotifier,
×
4260
                BestBlockView:           s.cc.BestBlockTracker,
×
4261
                RoutingPolicy:           s.cc.RoutingPolicy,
×
4262
                Sphinx:                  s.sphinx,
×
4263
                WitnessBeacon:           s.witnessBeacon,
×
4264
                Invoices:                s.invoices,
×
4265
                ChannelNotifier:         s.channelNotifier,
×
4266
                HtlcNotifier:            s.htlcNotifier,
×
4267
                TowerClient:             towerClient,
×
4268
                DisconnectPeer:          s.DisconnectPeer,
×
4269
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
×
4270
                        lnwire.NodeAnnouncement, error) {
×
4271

×
4272
                        return s.genNodeAnnouncement(nil)
×
4273
                },
×
4274

4275
                PongBuf: s.pongBuf,
4276

4277
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4278

4279
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4280

4281
                FundingManager: s.fundingMgr,
4282

4283
                Hodl:                    s.cfg.Hodl,
4284
                UnsafeReplay:            s.cfg.UnsafeReplay,
4285
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4286
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4287
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4288
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4289
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4290
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4291
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4292
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4293
                HandleCustomMessage:    s.handleCustomMessage,
4294
                GetAliases:             s.aliasMgr.GetAliases,
4295
                RequestAlias:           s.aliasMgr.RequestAlias,
4296
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4297
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4298
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4299
                MaxFeeExposure:         thresholdMSats,
4300
                Quit:                   s.quit,
4301
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4302
                AuxSigner:              s.implCfg.AuxSigner,
4303
                MsgRouter:              s.implCfg.MsgRouter,
4304
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4305
                AuxResolver:            s.implCfg.AuxContractResolver,
4306
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4307
                ShouldFwdExpEndorsement: func() bool {
×
4308
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
×
4309
                                return false
×
4310
                        }
×
4311

4312
                        return clock.NewDefaultClock().Now().Before(
×
4313
                                EndorsementExperimentEnd,
×
4314
                        )
×
4315
                },
4316
        }
4317

4318
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
×
4319
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
×
4320

×
4321
        p := peer.NewBrontide(pCfg)
×
4322

×
4323
        // TODO(roasbeef): update IP address for link-node
×
4324
        //  * also mark last-seen, do it one single transaction?
×
4325

×
4326
        s.addPeer(p)
×
4327

×
4328
        // Once we have successfully added the peer to the server, we can
×
4329
        // delete the previous error buffer from the server's map of error
×
4330
        // buffers.
×
4331
        delete(s.peerErrors, pkStr)
×
4332

×
4333
        // Dispatch a goroutine to asynchronously start the peer. This process
×
4334
        // includes sending and receiving Init messages, which would be a DOS
×
4335
        // vector if we held the server's mutex throughout the procedure.
×
4336
        s.wg.Add(1)
×
4337
        go s.peerInitializer(p)
×
4338
}
4339

4340
// addPeer adds the passed peer to the server's global state of all active
4341
// peers.
4342
func (s *server) addPeer(p *peer.Brontide) {
×
4343
        if p == nil {
×
4344
                return
×
4345
        }
×
4346

4347
        pubBytes := p.IdentityKey().SerializeCompressed()
×
4348

×
4349
        // Ignore new peers if we're shutting down.
×
4350
        if s.Stopped() {
×
4351
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4352
                        pubBytes)
×
4353
                p.Disconnect(ErrServerShuttingDown)
×
4354

×
4355
                return
×
4356
        }
×
4357

4358
        // Track the new peer in our indexes so we can quickly look it up either
4359
        // according to its public key, or its peer ID.
4360
        // TODO(roasbeef): pipe all requests through to the
4361
        // queryHandler/peerManager
4362

4363
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4364
        // be human-readable.
4365
        pubStr := string(pubBytes)
×
4366

×
4367
        s.peersByPub[pubStr] = p
×
4368

×
4369
        if p.Inbound() {
×
4370
                s.inboundPeers[pubStr] = p
×
4371
        } else {
×
4372
                s.outboundPeers[pubStr] = p
×
4373
        }
×
4374

4375
        // Inform the peer notifier of a peer online event so that it can be reported
4376
        // to clients listening for peer events.
4377
        var pubKey [33]byte
×
4378
        copy(pubKey[:], pubBytes)
×
4379

×
4380
        s.peerNotifier.NotifyPeerOnline(pubKey)
×
4381
}
4382

4383
// peerInitializer asynchronously starts a newly connected peer after it has
4384
// been added to the server's peer map. This method sets up a
4385
// peerTerminationWatcher for the given peer, and ensures that it executes even
4386
// if the peer failed to start. In the event of a successful connection, this
4387
// method reads the negotiated, local feature-bits and spawns the appropriate
4388
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4389
// be signaled of the new peer once the method returns.
4390
//
4391
// NOTE: This MUST be launched as a goroutine.
4392
func (s *server) peerInitializer(p *peer.Brontide) {
×
4393
        defer s.wg.Done()
×
4394

×
4395
        pubBytes := p.IdentityKey().SerializeCompressed()
×
4396

×
4397
        // Avoid initializing peers while the server is exiting.
×
4398
        if s.Stopped() {
×
4399
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4400
                        pubBytes)
×
4401
                return
×
4402
        }
×
4403

4404
        // Create a channel that will be used to signal a successful start of
4405
        // the link. This prevents the peer termination watcher from beginning
4406
        // its duty too early.
4407
        ready := make(chan struct{})
×
4408

×
4409
        // Before starting the peer, launch a goroutine to watch for the
×
4410
        // unexpected termination of this peer, which will ensure all resources
×
4411
        // are properly cleaned up, and re-establish persistent connections when
×
4412
        // necessary. The peer termination watcher will be short circuited if
×
4413
        // the peer is ever added to the ignorePeerTermination map, indicating
×
4414
        // that the server has already handled the removal of this peer.
×
4415
        s.wg.Add(1)
×
4416
        go s.peerTerminationWatcher(p, ready)
×
4417

×
4418
        // Start the peer! If an error occurs, we Disconnect the peer, which
×
4419
        // will unblock the peerTerminationWatcher.
×
4420
        if err := p.Start(); err != nil {
×
4421
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
×
4422

×
4423
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
4424
                return
×
4425
        }
×
4426

4427
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4428
        // was successful, and to begin watching the peer's wait group.
4429
        close(ready)
×
4430

×
4431
        s.mu.Lock()
×
4432
        defer s.mu.Unlock()
×
4433

×
4434
        // Check if there are listeners waiting for this peer to come online.
×
4435
        srvrLog.Debugf("Notifying that peer %v is online", p)
×
4436

×
4437
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
×
4438
        // route.Vertex as the key type of peerConnectedListeners.
×
4439
        pubStr := string(pubBytes)
×
4440
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
×
4441
                select {
×
4442
                case peerChan <- p:
×
4443
                case <-s.quit:
×
4444
                        return
×
4445
                }
4446
        }
4447
        delete(s.peerConnectedListeners, pubStr)
×
4448
}
4449

4450
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4451
// and then cleans up all resources allocated to the peer, notifies relevant
4452
// sub-systems of its demise, and finally handles re-connecting to the peer if
4453
// it's persistent. If the server intentionally disconnects a peer, it should
4454
// have a corresponding entry in the ignorePeerTermination map which will cause
4455
// the cleanup routine to exit early. The passed `ready` chan is used to
4456
// synchronize when WaitForDisconnect should begin watching on the peer's
4457
// waitgroup. The ready chan should only be signaled if the peer starts
4458
// successfully, otherwise the peer should be disconnected instead.
4459
//
4460
// NOTE: This MUST be launched as a goroutine.
4461
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
×
4462
        defer s.wg.Done()
×
4463

×
4464
        p.WaitForDisconnect(ready)
×
4465

×
4466
        srvrLog.Debugf("Peer %v has been disconnected", p)
×
4467

×
4468
        // If the server is exiting then we can bail out early ourselves as all
×
4469
        // the other sub-systems will already be shutting down.
×
4470
        if s.Stopped() {
×
4471
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
×
4472
                return
×
4473
        }
×
4474

4475
        // Next, we'll cancel all pending funding reservations with this node.
4476
        // If we tried to initiate any funding flows that haven't yet finished,
4477
        // then we need to unlock those committed outputs so they're still
4478
        // available for use.
4479
        s.fundingMgr.CancelPeerReservations(p.PubKey())
×
4480

×
4481
        pubKey := p.IdentityKey()
×
4482

×
4483
        // We'll also inform the gossiper that this peer is no longer active,
×
4484
        // so we don't need to maintain sync state for it any longer.
×
4485
        s.authGossiper.PruneSyncState(p.PubKey())
×
4486

×
4487
        // Tell the switch to remove all links associated with this peer.
×
4488
        // Passing nil as the target link indicates that all links associated
×
4489
        // with this interface should be closed.
×
4490
        //
×
4491
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
×
4492
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
×
4493
        if err != nil && err != htlcswitch.ErrNoLinksFound {
×
4494
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4495
        }
×
4496

4497
        for _, link := range links {
×
4498
                s.htlcSwitch.RemoveLink(link.ChanID())
×
4499
        }
×
4500

4501
        s.mu.Lock()
×
4502
        defer s.mu.Unlock()
×
4503

×
4504
        // If there were any notification requests for when this peer
×
4505
        // disconnected, we can trigger them now.
×
4506
        srvrLog.Debugf("Notifying that peer %v is offline", p)
×
4507
        pubStr := string(pubKey.SerializeCompressed())
×
4508
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
×
4509
                close(offlineChan)
×
4510
        }
×
4511
        delete(s.peerDisconnectedListeners, pubStr)
×
4512

×
4513
        // If the server has already removed this peer, we can short circuit the
×
4514
        // peer termination watcher and skip cleanup.
×
4515
        if _, ok := s.ignorePeerTermination[p]; ok {
×
4516
                delete(s.ignorePeerTermination, p)
×
4517

×
4518
                pubKey := p.PubKey()
×
4519
                pubStr := string(pubKey[:])
×
4520

×
4521
                // If a connection callback is present, we'll go ahead and
×
4522
                // execute it now that previous peer has fully disconnected. If
×
4523
                // the callback is not present, this likely implies the peer was
×
4524
                // purposefully disconnected via RPC, and that no reconnect
×
4525
                // should be attempted.
×
4526
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4527
                if ok {
×
4528
                        delete(s.scheduledPeerConnection, pubStr)
×
4529
                        connCallback()
×
4530
                }
×
4531
                return
×
4532
        }
4533

4534
        // First, cleanup any remaining state the server has regarding the peer
4535
        // in question.
4536
        s.removePeer(p)
×
4537

×
4538
        // Next, check to see if this is a persistent peer or not.
×
4539
        if _, ok := s.persistentPeers[pubStr]; !ok {
×
4540
                return
×
4541
        }
×
4542

4543
        // Get the last address that we used to connect to the peer.
4544
        addrs := []net.Addr{
×
4545
                p.NetAddress().Address,
×
4546
        }
×
4547

×
4548
        // We'll ensure that we locate all the peers advertised addresses for
×
4549
        // reconnection purposes.
×
4550
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
×
4551
        switch {
×
4552
        // We found advertised addresses, so use them.
4553
        case err == nil:
×
4554
                addrs = advertisedAddrs
×
4555

4556
        // The peer doesn't have an advertised address.
4557
        case err == errNoAdvertisedAddr:
×
4558
                // If it is an outbound peer then we fall back to the existing
×
4559
                // peer address.
×
4560
                if !p.Inbound() {
×
4561
                        break
×
4562
                }
4563

4564
                // Fall back to the existing peer address if
4565
                // we're not accepting connections over Tor.
4566
                if s.torController == nil {
×
4567
                        break
×
4568
                }
4569

4570
                // If we are, the peer's address won't be known
4571
                // to us (we'll see a private address, which is
4572
                // the address used by our onion service to dial
4573
                // to lnd), so we don't have enough information
4574
                // to attempt a reconnect.
4575
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4576
                        "to inbound peer %v without "+
×
4577
                        "advertised address", p)
×
4578
                return
×
4579

4580
        // We came across an error retrieving an advertised
4581
        // address, log it, and fall back to the existing peer
4582
        // address.
4583
        default:
×
4584
                srvrLog.Errorf("Unable to retrieve advertised "+
×
4585
                        "address for node %x: %v", p.PubKey(),
×
4586
                        err)
×
4587
        }
4588

4589
        // Make an easy lookup map so that we can check if an address
4590
        // is already in the address list that we have stored for this peer.
4591
        existingAddrs := make(map[string]bool)
×
4592
        for _, addr := range s.persistentPeerAddrs[pubStr] {
×
4593
                existingAddrs[addr.String()] = true
×
4594
        }
×
4595

4596
        // Add any missing addresses for this peer to persistentPeerAddr.
4597
        for _, addr := range addrs {
×
4598
                if existingAddrs[addr.String()] {
×
4599
                        continue
×
4600
                }
4601

4602
                s.persistentPeerAddrs[pubStr] = append(
×
4603
                        s.persistentPeerAddrs[pubStr],
×
4604
                        &lnwire.NetAddress{
×
4605
                                IdentityKey: p.IdentityKey(),
×
4606
                                Address:     addr,
×
4607
                                ChainNet:    p.NetAddress().ChainNet,
×
4608
                        },
×
4609
                )
×
4610
        }
4611

4612
        // Record the computed backoff in the backoff map.
4613
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
×
4614
        s.persistentPeersBackoff[pubStr] = backoff
×
4615

×
4616
        // Initialize a retry canceller for this peer if one does not
×
4617
        // exist.
×
4618
        cancelChan, ok := s.persistentRetryCancels[pubStr]
×
4619
        if !ok {
×
4620
                cancelChan = make(chan struct{})
×
4621
                s.persistentRetryCancels[pubStr] = cancelChan
×
4622
        }
×
4623

4624
        // We choose not to wait group this go routine since the Connect
4625
        // call can stall for arbitrarily long if we shutdown while an
4626
        // outbound connection attempt is being made.
4627
        go func() {
×
4628
                srvrLog.Debugf("Scheduling connection re-establishment to "+
×
4629
                        "persistent peer %x in %s",
×
4630
                        p.IdentityKey().SerializeCompressed(), backoff)
×
4631

×
4632
                select {
×
4633
                case <-time.After(backoff):
×
4634
                case <-cancelChan:
×
4635
                        return
×
4636
                case <-s.quit:
×
4637
                        return
×
4638
                }
4639

4640
                srvrLog.Debugf("Attempting to re-establish persistent "+
×
4641
                        "connection to peer %x",
×
4642
                        p.IdentityKey().SerializeCompressed())
×
4643

×
4644
                s.connectToPersistentPeer(pubStr)
×
4645
        }()
4646
}
4647

4648
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4649
// to connect to the peer. It creates connection requests if there are
4650
// currently none for a given address and it removes old connection requests
4651
// if the associated address is no longer in the latest address list for the
4652
// peer.
4653
func (s *server) connectToPersistentPeer(pubKeyStr string) {
×
4654
        s.mu.Lock()
×
4655
        defer s.mu.Unlock()
×
4656

×
4657
        // Create an easy lookup map of the addresses we have stored for the
×
4658
        // peer. We will remove entries from this map if we have existing
×
4659
        // connection requests for the associated address and then any leftover
×
4660
        // entries will indicate which addresses we should create new
×
4661
        // connection requests for.
×
4662
        addrMap := make(map[string]*lnwire.NetAddress)
×
4663
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
×
4664
                addrMap[addr.String()] = addr
×
4665
        }
×
4666

4667
        // Go through each of the existing connection requests and
4668
        // check if they correspond to the latest set of addresses. If
4669
        // there is a connection requests that does not use one of the latest
4670
        // advertised addresses then remove that connection request.
4671
        var updatedConnReqs []*connmgr.ConnReq
×
4672
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
×
4673
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
×
4674

×
4675
                switch _, ok := addrMap[lnAddr]; ok {
×
4676
                // If the existing connection request is using one of the
4677
                // latest advertised addresses for the peer then we add it to
4678
                // updatedConnReqs and remove the associated address from
4679
                // addrMap so that we don't recreate this connReq later on.
4680
                case true:
×
4681
                        updatedConnReqs = append(
×
4682
                                updatedConnReqs, connReq,
×
4683
                        )
×
4684
                        delete(addrMap, lnAddr)
×
4685

4686
                // If the existing connection request is using an address that
4687
                // is not one of the latest advertised addresses for the peer
4688
                // then we remove the connecting request from the connection
4689
                // manager.
4690
                case false:
×
4691
                        srvrLog.Info(
×
4692
                                "Removing conn req:", connReq.Addr.String(),
×
4693
                        )
×
4694
                        s.connMgr.Remove(connReq.ID())
×
4695
                }
4696
        }
4697

4698
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
×
4699

×
4700
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
×
4701
        if !ok {
×
4702
                cancelChan = make(chan struct{})
×
4703
                s.persistentRetryCancels[pubKeyStr] = cancelChan
×
4704
        }
×
4705

4706
        // Any addresses left in addrMap are new ones that we have not made
4707
        // connection requests for. So create new connection requests for those.
4708
        // If there is more than one address in the address map, stagger the
4709
        // creation of the connection requests for those.
4710
        go func() {
×
4711
                ticker := time.NewTicker(multiAddrConnectionStagger)
×
4712
                defer ticker.Stop()
×
4713

×
4714
                for _, addr := range addrMap {
×
4715
                        // Send the persistent connection request to the
×
4716
                        // connection manager, saving the request itself so we
×
4717
                        // can cancel/restart the process as needed.
×
4718
                        connReq := &connmgr.ConnReq{
×
4719
                                Addr:      addr,
×
4720
                                Permanent: true,
×
4721
                        }
×
4722

×
4723
                        s.mu.Lock()
×
4724
                        s.persistentConnReqs[pubKeyStr] = append(
×
4725
                                s.persistentConnReqs[pubKeyStr], connReq,
×
4726
                        )
×
4727
                        s.mu.Unlock()
×
4728

×
4729
                        srvrLog.Debugf("Attempting persistent connection to "+
×
4730
                                "channel peer %v", addr)
×
4731

×
4732
                        go s.connMgr.Connect(connReq)
×
4733

×
4734
                        select {
×
4735
                        case <-s.quit:
×
4736
                                return
×
4737
                        case <-cancelChan:
×
4738
                                return
×
4739
                        case <-ticker.C:
×
4740
                        }
4741
                }
4742
        }()
4743
}
4744

4745
// removePeer removes the passed peer from the server's state of all active
4746
// peers.
4747
func (s *server) removePeer(p *peer.Brontide) {
×
4748
        if p == nil {
×
4749
                return
×
4750
        }
×
4751

4752
        srvrLog.Debugf("removing peer %v", p)
×
4753

×
4754
        // As the peer is now finished, ensure that the TCP connection is
×
4755
        // closed and all of its related goroutines have exited.
×
4756
        p.Disconnect(fmt.Errorf("server: disconnecting peer %v", p))
×
4757

×
4758
        // If this peer had an active persistent connection request, remove it.
×
4759
        if p.ConnReq() != nil {
×
4760
                s.connMgr.Remove(p.ConnReq().ID())
×
4761
        }
×
4762

4763
        // Ignore deleting peers if we're shutting down.
4764
        if s.Stopped() {
×
4765
                return
×
4766
        }
×
4767

4768
        pKey := p.PubKey()
×
4769
        pubSer := pKey[:]
×
4770
        pubStr := string(pubSer)
×
4771

×
4772
        delete(s.peersByPub, pubStr)
×
4773

×
4774
        if p.Inbound() {
×
4775
                delete(s.inboundPeers, pubStr)
×
4776
        } else {
×
4777
                delete(s.outboundPeers, pubStr)
×
4778
        }
×
4779

4780
        // Copy the peer's error buffer across to the server if it has any items
4781
        // in it so that we can restore peer errors across connections.
4782
        if p.ErrorBuffer().Total() > 0 {
×
4783
                s.peerErrors[pubStr] = p.ErrorBuffer()
×
4784
        }
×
4785

4786
        // Inform the peer notifier of a peer offline event so that it can be
4787
        // reported to clients listening for peer events.
4788
        var pubKey [33]byte
×
4789
        copy(pubKey[:], pubSer)
×
4790

×
4791
        s.peerNotifier.NotifyPeerOffline(pubKey)
×
4792
}
4793

4794
// ConnectToPeer requests that the server connect to a Lightning Network peer
4795
// at the specified address. This function will *block* until either a
4796
// connection is established, or the initial handshake process fails.
4797
//
4798
// NOTE: This function is safe for concurrent access.
4799
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4800
        perm bool, timeout time.Duration) error {
×
4801

×
4802
        targetPub := string(addr.IdentityKey.SerializeCompressed())
×
4803

×
4804
        // Acquire mutex, but use explicit unlocking instead of defer for
×
4805
        // better granularity.  In certain conditions, this method requires
×
4806
        // making an outbound connection to a remote peer, which requires the
×
4807
        // lock to be released, and subsequently reacquired.
×
4808
        s.mu.Lock()
×
4809

×
4810
        // Ensure we're not already connected to this peer.
×
4811
        peer, err := s.findPeerByPubStr(targetPub)
×
4812
        if err == nil {
×
4813
                s.mu.Unlock()
×
4814
                return &errPeerAlreadyConnected{peer: peer}
×
4815
        }
×
4816

4817
        // Peer was not found, continue to pursue connection with peer.
4818

4819
        // If there's already a pending connection request for this pubkey,
4820
        // then we ignore this request to ensure we don't create a redundant
4821
        // connection.
4822
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
×
4823
                srvrLog.Warnf("Already have %d persistent connection "+
×
4824
                        "requests for %v, connecting anyway.", len(reqs), addr)
×
4825
        }
×
4826

4827
        // If there's not already a pending or active connection to this node,
4828
        // then instruct the connection manager to attempt to establish a
4829
        // persistent connection to the peer.
4830
        srvrLog.Debugf("Connecting to %v", addr)
×
4831
        if perm {
×
4832
                connReq := &connmgr.ConnReq{
×
4833
                        Addr:      addr,
×
4834
                        Permanent: true,
×
4835
                }
×
4836

×
4837
                // Since the user requested a permanent connection, we'll set
×
4838
                // the entry to true which will tell the server to continue
×
4839
                // reconnecting even if the number of channels with this peer is
×
4840
                // zero.
×
4841
                s.persistentPeers[targetPub] = true
×
4842
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
×
4843
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
×
4844
                }
×
4845
                s.persistentConnReqs[targetPub] = append(
×
4846
                        s.persistentConnReqs[targetPub], connReq,
×
4847
                )
×
4848
                s.mu.Unlock()
×
4849

×
4850
                go s.connMgr.Connect(connReq)
×
4851

×
4852
                return nil
×
4853
        }
4854
        s.mu.Unlock()
×
4855

×
4856
        // If we're not making a persistent connection, then we'll attempt to
×
4857
        // connect to the target peer. If the we can't make the connection, or
×
4858
        // the crypto negotiation breaks down, then return an error to the
×
4859
        // caller.
×
4860
        errChan := make(chan error, 1)
×
4861
        s.connectToPeer(addr, errChan, timeout)
×
4862

×
4863
        select {
×
4864
        case err := <-errChan:
×
4865
                return err
×
4866
        case <-s.quit:
×
4867
                return ErrServerShuttingDown
×
4868
        }
4869
}
4870

4871
// connectToPeer establishes a connection to a remote peer. errChan is used to
4872
// notify the caller if the connection attempt has failed. Otherwise, it will be
4873
// closed.
4874
func (s *server) connectToPeer(addr *lnwire.NetAddress,
4875
        errChan chan<- error, timeout time.Duration) {
×
4876

×
4877
        conn, err := brontide.Dial(
×
4878
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
×
4879
        )
×
4880
        if err != nil {
×
4881
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
×
4882
                select {
×
4883
                case errChan <- err:
×
4884
                case <-s.quit:
×
4885
                }
4886
                return
×
4887
        }
4888

4889
        close(errChan)
×
4890

×
4891
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
×
4892
                conn.LocalAddr(), conn.RemoteAddr())
×
4893

×
4894
        s.OutboundPeerConnected(nil, conn)
×
4895
}
4896

4897
// DisconnectPeer sends the request to server to close the connection with peer
4898
// identified by public key.
4899
//
4900
// NOTE: This function is safe for concurrent access.
4901
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
×
4902
        pubBytes := pubKey.SerializeCompressed()
×
4903
        pubStr := string(pubBytes)
×
4904

×
4905
        s.mu.Lock()
×
4906
        defer s.mu.Unlock()
×
4907

×
4908
        // Check that were actually connected to this peer. If not, then we'll
×
4909
        // exit in an error as we can't disconnect from a peer that we're not
×
4910
        // currently connected to.
×
4911
        peer, err := s.findPeerByPubStr(pubStr)
×
4912
        if err == ErrPeerNotConnected {
×
4913
                return fmt.Errorf("peer %x is not connected", pubBytes)
×
4914
        }
×
4915

4916
        srvrLog.Infof("Disconnecting from %v", peer)
×
4917

×
4918
        s.cancelConnReqs(pubStr, nil)
×
4919

×
4920
        // If this peer was formerly a persistent connection, then we'll remove
×
4921
        // them from this map so we don't attempt to re-connect after we
×
4922
        // disconnect.
×
4923
        delete(s.persistentPeers, pubStr)
×
4924
        delete(s.persistentPeersBackoff, pubStr)
×
4925

×
4926
        // Remove the peer by calling Disconnect. Previously this was done with
×
4927
        // removePeer, which bypassed the peerTerminationWatcher.
×
4928
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
×
4929

×
4930
        return nil
×
4931
}
4932

4933
// OpenChannel sends a request to the server to open a channel to the specified
4934
// peer identified by nodeKey with the passed channel funding parameters.
4935
//
4936
// NOTE: This function is safe for concurrent access.
4937
func (s *server) OpenChannel(
4938
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
×
4939

×
4940
        // The updateChan will have a buffer of 2, since we expect a ChanPending
×
4941
        // + a ChanOpen update, and we want to make sure the funding process is
×
4942
        // not blocked if the caller is not reading the updates.
×
4943
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
×
4944
        req.Err = make(chan error, 1)
×
4945

×
4946
        // First attempt to locate the target peer to open a channel with, if
×
4947
        // we're unable to locate the peer then this request will fail.
×
4948
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
×
4949
        s.mu.RLock()
×
4950
        peer, ok := s.peersByPub[string(pubKeyBytes)]
×
4951
        if !ok {
×
4952
                s.mu.RUnlock()
×
4953

×
4954
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4955
                return req.Updates, req.Err
×
4956
        }
×
4957
        req.Peer = peer
×
4958
        s.mu.RUnlock()
×
4959

×
4960
        // We'll wait until the peer is active before beginning the channel
×
4961
        // opening process.
×
4962
        select {
×
4963
        case <-peer.ActiveSignal():
×
4964
        case <-peer.QuitSignal():
×
4965
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
4966
                return req.Updates, req.Err
×
4967
        case <-s.quit:
×
4968
                req.Err <- ErrServerShuttingDown
×
4969
                return req.Updates, req.Err
×
4970
        }
4971

4972
        // If the fee rate wasn't specified at this point we fail the funding
4973
        // because of the missing fee rate information. The caller of the
4974
        // `OpenChannel` method needs to make sure that default values for the
4975
        // fee rate are set beforehand.
4976
        if req.FundingFeePerKw == 0 {
×
4977
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
4978
                        "the channel opening transaction")
×
4979

×
4980
                return req.Updates, req.Err
×
4981
        }
×
4982

4983
        // Spawn a goroutine to send the funding workflow request to the funding
4984
        // manager. This allows the server to continue handling queries instead
4985
        // of blocking on this request which is exported as a synchronous
4986
        // request to the outside world.
4987
        go s.fundingMgr.InitFundingWorkflow(req)
×
4988

×
4989
        return req.Updates, req.Err
×
4990
}
4991

4992
// Peers returns a slice of all active peers.
4993
//
4994
// NOTE: This function is safe for concurrent access.
4995
func (s *server) Peers() []*peer.Brontide {
×
4996
        s.mu.RLock()
×
4997
        defer s.mu.RUnlock()
×
4998

×
4999
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
5000
        for _, peer := range s.peersByPub {
×
5001
                peers = append(peers, peer)
×
5002
        }
×
5003

5004
        return peers
×
5005
}
5006

5007
// computeNextBackoff uses a truncated exponential backoff to compute the next
5008
// backoff using the value of the exiting backoff. The returned duration is
5009
// randomized in either direction by 1/20 to prevent tight loops from
5010
// stabilizing.
5011
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
×
5012
        // Double the current backoff, truncating if it exceeds our maximum.
×
5013
        nextBackoff := 2 * currBackoff
×
5014
        if nextBackoff > maxBackoff {
×
5015
                nextBackoff = maxBackoff
×
5016
        }
×
5017

5018
        // Using 1/10 of our duration as a margin, compute a random offset to
5019
        // avoid the nodes entering connection cycles.
5020
        margin := nextBackoff / 10
×
5021

×
5022
        var wiggle big.Int
×
5023
        wiggle.SetUint64(uint64(margin))
×
5024
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
×
5025
                // Randomizing is not mission critical, so we'll just return the
×
5026
                // current backoff.
×
5027
                return nextBackoff
×
5028
        }
×
5029

5030
        // Otherwise add in our wiggle, but subtract out half of the margin so
5031
        // that the backoff can tweaked by 1/20 in either direction.
5032
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
×
5033
}
5034

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

5039
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
5040
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
×
5041
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
×
5042
        if err != nil {
×
5043
                return nil, err
×
5044
        }
×
5045

5046
        node, err := s.graphDB.FetchLightningNode(vertex)
×
5047
        if err != nil {
×
5048
                return nil, err
×
5049
        }
×
5050

5051
        if len(node.Addresses) == 0 {
×
5052
                return nil, errNoAdvertisedAddr
×
5053
        }
×
5054

5055
        return node.Addresses, nil
×
5056
}
5057

5058
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5059
// channel update for a target channel.
5060
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5061
        *lnwire.ChannelUpdate1, error) {
×
5062

×
5063
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
×
5064
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
×
5065
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
×
5066
                if err != nil {
×
5067
                        return nil, err
×
5068
                }
×
5069

5070
                return netann.ExtractChannelUpdate(
×
5071
                        ourPubKey[:], info, edge1, edge2,
×
5072
                )
×
5073
        }
5074
}
5075

5076
// applyChannelUpdate applies the channel update to the different sub-systems of
5077
// the server. The useAlias boolean denotes whether or not to send an alias in
5078
// place of the real SCID.
5079
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5080
        op *wire.OutPoint, useAlias bool) error {
×
5081

×
5082
        var (
×
5083
                peerAlias    *lnwire.ShortChannelID
×
5084
                defaultAlias lnwire.ShortChannelID
×
5085
        )
×
5086

×
5087
        chanID := lnwire.NewChanIDFromOutPoint(*op)
×
5088

×
5089
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
×
5090
        // in the ChannelUpdate if it hasn't been announced yet.
×
5091
        if useAlias {
×
5092
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
×
5093
                if foundAlias != defaultAlias {
×
5094
                        peerAlias = &foundAlias
×
5095
                }
×
5096
        }
5097

5098
        errChan := s.authGossiper.ProcessLocalAnnouncement(
×
5099
                update, discovery.RemoteAlias(peerAlias),
×
5100
        )
×
5101
        select {
×
5102
        case err := <-errChan:
×
5103
                return err
×
5104
        case <-s.quit:
×
5105
                return ErrServerShuttingDown
×
5106
        }
5107
}
5108

5109
// SendCustomMessage sends a custom message to the peer with the specified
5110
// pubkey.
5111
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5112
        data []byte) error {
×
5113

×
5114
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
×
5115
        if err != nil {
×
5116
                return err
×
5117
        }
×
5118

5119
        // We'll wait until the peer is active.
5120
        select {
×
5121
        case <-peer.ActiveSignal():
×
5122
        case <-peer.QuitSignal():
×
5123
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5124
        case <-s.quit:
×
5125
                return ErrServerShuttingDown
×
5126
        }
5127

5128
        msg, err := lnwire.NewCustom(msgType, data)
×
5129
        if err != nil {
×
5130
                return err
×
5131
        }
×
5132

5133
        // Send the message as low-priority. For now we assume that all
5134
        // application-defined message are low priority.
5135
        return peer.SendMessageLazy(true, msg)
×
5136
}
5137

5138
// newSweepPkScriptGen creates closure that generates a new public key script
5139
// which should be used to sweep any funds into the on-chain wallet.
5140
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5141
// (p2wkh) output.
5142
func newSweepPkScriptGen(
5143
        wallet lnwallet.WalletController,
5144
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
×
5145

×
5146
        return func() fn.Result[lnwallet.AddrWithKey] {
×
5147
                sweepAddr, err := wallet.NewAddress(
×
5148
                        lnwallet.TaprootPubkey, false,
×
5149
                        lnwallet.DefaultAccountName,
×
5150
                )
×
5151
                if err != nil {
×
5152
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5153
                }
×
5154

5155
                addr, err := txscript.PayToAddrScript(sweepAddr)
×
5156
                if err != nil {
×
5157
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5158
                }
×
5159

5160
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
×
5161
                        wallet, netParams, addr,
×
5162
                )
×
5163
                if err != nil {
×
5164
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5165
                }
×
5166

5167
                return fn.Ok(lnwallet.AddrWithKey{
×
5168
                        DeliveryAddress: addr,
×
5169
                        InternalKey:     internalKeyDesc,
×
5170
                })
×
5171
        }
5172
}
5173

5174
// shouldPeerBootstrap returns true if we should attempt to perform peer
5175
// bootstrapping to actively seek our peers using the set of active network
5176
// bootstrappers.
5177
func shouldPeerBootstrap(cfg *Config) bool {
6✔
5178
        isSimnet := cfg.Bitcoin.SimNet
6✔
5179
        isSignet := cfg.Bitcoin.SigNet
6✔
5180
        isRegtest := cfg.Bitcoin.RegTest
6✔
5181
        isDevNetwork := isSimnet || isSignet || isRegtest
6✔
5182

6✔
5183
        // TODO(yy): remove the check on simnet/regtest such that the itest is
6✔
5184
        // covering the bootstrapping process.
6✔
5185
        return !cfg.NoNetBootstrap && !isDevNetwork
6✔
5186
}
6✔
5187

5188
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5189
// finished.
5190
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
×
5191
        // Get a list of closed channels.
×
5192
        channels, err := s.chanStateDB.FetchClosedChannels(false)
×
5193
        if err != nil {
×
5194
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5195
                return nil
×
5196
        }
×
5197

5198
        // Save the SCIDs in a map.
5199
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
×
5200
        for _, c := range channels {
×
5201
                // If the channel is not pending, its FC has been finalized.
×
5202
                if !c.IsPending {
×
5203
                        closedSCIDs[c.ShortChanID] = struct{}{}
×
5204
                }
×
5205
        }
5206

5207
        // Double check whether the reported closed channel has indeed finished
5208
        // closing.
5209
        //
5210
        // NOTE: There are misalignments regarding when a channel's FC is
5211
        // marked as finalized. We double check the pending channels to make
5212
        // sure the returned SCIDs are indeed terminated.
5213
        //
5214
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5215
        pendings, err := s.chanStateDB.FetchPendingChannels()
×
5216
        if err != nil {
×
5217
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5218
                return nil
×
5219
        }
×
5220

5221
        for _, c := range pendings {
×
5222
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
×
5223
                        continue
×
5224
                }
5225

5226
                // If the channel is still reported as pending, remove it from
5227
                // the map.
5228
                delete(closedSCIDs, c.ShortChannelID)
×
5229

×
5230
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5231
                        c.ShortChannelID)
×
5232
        }
5233

5234
        return closedSCIDs
×
5235
}
5236

5237
// getStartingBeat returns the current beat. This is used during the startup to
5238
// initialize blockbeat consumers.
5239
func (s *server) getStartingBeat() (*chainio.Beat, error) {
×
5240
        // beat is the current blockbeat.
×
5241
        var beat *chainio.Beat
×
5242

×
5243
        // We should get a notification with the current best block immediately
×
5244
        // by passing a nil block.
×
5245
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
×
5246
        if err != nil {
×
5247
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5248
        }
×
5249
        defer blockEpochs.Cancel()
×
5250

×
5251
        // We registered for the block epochs with a nil request. The notifier
×
5252
        // should send us the current best block immediately. So we need to
×
5253
        // wait for it here because we need to know the current best height.
×
5254
        select {
×
5255
        case bestBlock := <-blockEpochs.Epochs:
×
5256
                srvrLog.Infof("Received initial block %v at height %d",
×
5257
                        bestBlock.Hash, bestBlock.Height)
×
5258

×
5259
                // Update the current blockbeat.
×
5260
                beat = chainio.NewBeat(*bestBlock)
×
5261

5262
        case <-s.quit:
×
5263
                srvrLog.Debug("LND shutting down")
×
5264
        }
5265

5266
        return beat, nil
×
5267
}
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