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

lightningnetwork / lnd / 11126734513

01 Oct 2024 01:47PM UTC coverage: 58.772% (-0.04%) from 58.814%
11126734513

Pull #9147

github

ziggie1984
docs: add release-notes.
Pull Request #9147: [Part 1|3] Introduce SQL Payment schema into LND

130208 of 221548 relevant lines covered (58.77%)

28210.45 hits per line

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

63.68
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

158
        start sync.Once
159
        stop  sync.Once
160

161
        cfg *Config
162

163
        implCfg *ImplementationCfg
164

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

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

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

176
        chanStatusMgr *netann.ChanStatusManager
177

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

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

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

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

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

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

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

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

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

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

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

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

242
        cc *chainreg.ChainControl
243

244
        fundingMgr *funding.Manager
245

246
        graphDB *channeldb.ChannelGraph
247

248
        chanStateDB *channeldb.ChannelStateDB
249

250
        addrSource chanbackup.AddressSource
251

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

256
        invoicesDB invoices.InvoiceDB
257

258
        aliasMgr *aliasmgr.Manager
259

260
        htlcSwitch *htlcswitch.Switch
261

262
        interceptableSwitch *htlcswitch.InterceptableSwitch
263

264
        invoices *invoices.InvoiceRegistry
265

266
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
267

268
        channelNotifier *channelnotifier.ChannelNotifier
269

270
        peerNotifier *peernotifier.PeerNotifier
271

272
        htlcNotifier *htlcswitch.HtlcNotifier
273

274
        witnessBeacon contractcourt.WitnessBeacon
275

276
        breachArbitrator *contractcourt.BreachArbitrator
277

278
        missionControl *routing.MissionControl
279

280
        graphBuilder *graph.Builder
281

282
        chanRouter *routing.ChannelRouter
283

284
        controlTower routing.ControlTower
285

286
        authGossiper *discovery.AuthenticatedGossiper
287

288
        localChanMgr *localchans.Manager
289

290
        utxoNursery *contractcourt.UtxoNursery
291

292
        sweeper *sweep.UtxoSweeper
293

294
        chainArb *contractcourt.ChainArbitrator
295

296
        sphinx *hop.OnionProcessor
297

298
        towerClientMgr *wtclient.Manager
299

300
        connMgr *connmgr.ConnManager
301

302
        sigPool *lnwallet.SigPool
303

304
        writePool *pool.Write
305

306
        readPool *pool.Read
307

308
        tlsManager *TLSManager
309

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

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

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

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

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

332
        hostAnn *netann.HostAnnouncer
333

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

337
        customMessageServer *subscribe.Server
338

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

342
        quit chan struct{}
343

344
        wg sync.WaitGroup
345
}
346

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

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

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

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

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

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

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

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

402
                                        s.mu.Lock()
3✔
403

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

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

418
                                        s.mu.Unlock()
3✔
419

3✔
420
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
421
                                }
422
                        }
423
                }
424
        }()
425

426
        return nil
3✔
427
}
428

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
593
                channelNotifier: channelnotifier.New(
3✔
594
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
595
                ),
3✔
596

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

3✔
601
                listenAddrs: listenAddrs,
3✔
602

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

3✔
607
                torController: torController,
3✔
608

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

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

3✔
625
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
626

3✔
627
                customMessageServer: subscribe.NewServer(),
3✔
628

3✔
629
                tlsManager: tlsManager,
3✔
630

3✔
631
                featureMgr: featureMgr,
3✔
632
                quit:       make(chan struct{}),
3✔
633
        }
3✔
634

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

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

3✔
648
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
649

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

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

659
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
660

3✔
661
                return nil
3✔
662
        }
663

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

951
        mcCfg := &routing.MissionControlConfig{
3✔
952
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
953
                Estimator:               estimator,
3✔
954
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
955
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
956
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
957
        }
3✔
958
        s.missionControl, err = routing.NewMissionControl(
3✔
959
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
3✔
960
        )
3✔
961
        if err != nil {
3✔
962
                return nil, fmt.Errorf("can't create mission control: %w", err)
×
963
        }
×
964

965
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
966
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
967
                int64(routingConfig.AttemptCost),
3✔
968
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
969
                routingConfig.MinRouteProbability)
3✔
970

3✔
971
        pathFindingConfig := routing.PathFindingConfig{
3✔
972
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
973
                        routingConfig.AttemptCost,
3✔
974
                ),
3✔
975
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
976
                MinProbability: routingConfig.MinRouteProbability,
3✔
977
        }
3✔
978

3✔
979
        sourceNode, err := chanGraph.SourceNode()
3✔
980
        if err != nil {
3✔
981
                return nil, fmt.Errorf("error getting source node: %w", err)
×
982
        }
×
983
        paymentSessionSource := &routing.SessionSource{
3✔
984
                GraphSessionFactory: graphsession.NewGraphSessionFactory(
3✔
985
                        chanGraph,
3✔
986
                ),
3✔
987
                SourceNode:        sourceNode,
3✔
988
                MissionControl:    s.missionControl,
3✔
989
                GetLink:           s.htlcSwitch.GetLinkByShortID,
3✔
990
                PathFindingConfig: pathFindingConfig,
3✔
991
        }
3✔
992

3✔
993
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
994

3✔
995
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
996

3✔
997
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
998
                cfg.Routing.StrictZombiePruning
3✔
999

3✔
1000
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
1001
                SelfNode:            selfNode.PubKeyBytes,
3✔
1002
                Graph:               chanGraph,
3✔
1003
                Chain:               cc.ChainIO,
3✔
1004
                ChainView:           cc.ChainView,
3✔
1005
                Notifier:            cc.ChainNotifier,
3✔
1006
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
1007
                GraphPruneInterval:  time.Hour,
3✔
1008
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
1009
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
1010
                StrictZombiePruning: strictPruning,
3✔
1011
                IsAlias:             aliasmgr.IsAlias,
3✔
1012
        })
3✔
1013
        if err != nil {
3✔
1014
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1015
        }
×
1016

1017
        s.chanRouter, err = routing.New(routing.Config{
3✔
1018
                SelfNode:           selfNode.PubKeyBytes,
3✔
1019
                RoutingGraph:       graphsession.NewRoutingGraph(chanGraph),
3✔
1020
                Chain:              cc.ChainIO,
3✔
1021
                Payer:              s.htlcSwitch,
3✔
1022
                Control:            s.controlTower,
3✔
1023
                MissionControl:     s.missionControl,
3✔
1024
                SessionSource:      paymentSessionSource,
3✔
1025
                GetLink:            s.htlcSwitch.GetLinkByShortID,
3✔
1026
                NextPaymentID:      sequencer.NextID,
3✔
1027
                PathFindingConfig:  pathFindingConfig,
3✔
1028
                Clock:              clock.NewDefaultClock(),
3✔
1029
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
3✔
1030
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
3✔
1031
                TrafficShaper:      implCfg.TrafficShaper,
3✔
1032
        })
3✔
1033
        if err != nil {
3✔
1034
                return nil, fmt.Errorf("can't create router: %w", err)
×
1035
        }
×
1036

1037
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1038
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1039
        if err != nil {
3✔
1040
                return nil, err
×
1041
        }
×
1042
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1043
        if err != nil {
3✔
1044
                return nil, err
×
1045
        }
×
1046

1047
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1048

3✔
1049
        s.authGossiper = discovery.New(discovery.Config{
3✔
1050
                Graph:                 s.graphBuilder,
3✔
1051
                ChainIO:               s.cc.ChainIO,
3✔
1052
                Notifier:              s.cc.ChainNotifier,
3✔
1053
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1054
                Broadcast:             s.BroadcastMessage,
3✔
1055
                ChanSeries:            chanSeries,
3✔
1056
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1057
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1058
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1059
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1060
                        error) {
3✔
1061

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

1090
        //nolint:lll
1091
        s.localChanMgr = &localchans.Manager{
3✔
1092
                ForAllOutgoingChannels:    s.graphBuilder.ForAllOutgoingChannels,
3✔
1093
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
3✔
1094
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
3✔
1095
                FetchChannel:              s.chanStateDB.FetchChannel,
3✔
1096
        }
3✔
1097

3✔
1098
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1099
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1100
        )
3✔
1101
        if err != nil {
3✔
1102
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1103
                return nil, err
×
1104
        }
×
1105

1106
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1107
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1108
        )
3✔
1109
        if err != nil {
3✔
1110
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1111
                return nil, err
×
1112
        }
×
1113

1114
        aggregator := sweep.NewBudgetAggregator(
3✔
1115
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1116
        )
3✔
1117

3✔
1118
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1119
                Signer:    cc.Wallet.Cfg.Signer,
3✔
1120
                Wallet:    cc.Wallet,
3✔
1121
                Estimator: cc.FeeEstimator,
3✔
1122
                Notifier:  cc.ChainNotifier,
3✔
1123
        })
3✔
1124

3✔
1125
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1126
                FeeEstimator:         cc.FeeEstimator,
3✔
1127
                GenSweepScript:       newSweepPkScriptGen(cc.Wallet),
3✔
1128
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1129
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1130
                Mempool:              cc.MempoolNotifier,
3✔
1131
                Notifier:             cc.ChainNotifier,
3✔
1132
                Store:                sweeperStore,
3✔
1133
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1134
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1135
                Aggregator:           aggregator,
3✔
1136
                Publisher:            s.txPublisher,
3✔
1137
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1138
        })
3✔
1139

3✔
1140
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1141
                ChainIO:             cc.ChainIO,
3✔
1142
                ConfDepth:           1,
3✔
1143
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1144
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1145
                Notifier:            cc.ChainNotifier,
3✔
1146
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1147
                Store:               utxnStore,
3✔
1148
                SweepInput:          s.sweeper.SweepInput,
3✔
1149
                Budget:              s.cfg.Sweeper.Budget,
3✔
1150
        })
3✔
1151

3✔
1152
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1153
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1154
                closureType contractcourt.ChannelCloseType) {
6✔
1155
                // TODO(conner): Properly respect the update and error channels
3✔
1156
                // returned by CloseLink.
3✔
1157

3✔
1158
                // Instruct the switch to close the channel.  Provide no close out
3✔
1159
                // delivery script or target fee per kw because user input is not
3✔
1160
                // available when the remote peer closes the channel.
3✔
1161
                s.htlcSwitch.CloseLink(chanPoint, closureType, 0, 0, nil)
3✔
1162
        }
3✔
1163

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

3✔
1168
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1169
                &contractcourt.BreachConfig{
3✔
1170
                        CloseLink:          closeLink,
3✔
1171
                        DB:                 s.chanStateDB,
3✔
1172
                        Estimator:          s.cc.FeeEstimator,
3✔
1173
                        GenSweepScript:     newSweepPkScriptGen(cc.Wallet),
3✔
1174
                        Notifier:           cc.ChainNotifier,
3✔
1175
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1176
                        ContractBreaches:   contractBreaches,
3✔
1177
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1178
                        Store: contractcourt.NewRetributionStore(
3✔
1179
                                dbs.ChanStateDB,
3✔
1180
                        ),
3✔
1181
                },
3✔
1182
        )
3✔
1183

3✔
1184
        //nolint:lll
3✔
1185
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1186
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1187
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1188
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1189
                NewSweepAddr:           newSweepPkScriptGen(cc.Wallet),
3✔
1190
                PublishTx:              cc.Wallet.PublishTransaction,
3✔
1191
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
6✔
1192
                        for _, msg := range msgs {
6✔
1193
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1194
                                if err != nil {
3✔
1195
                                        return err
×
1196
                                }
×
1197
                        }
1198
                        return nil
3✔
1199
                },
1200
                IncubateOutputs: func(chanPoint wire.OutPoint,
1201
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1202
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1203
                        broadcastHeight uint32,
1204
                        deadlineHeight fn.Option[int32]) error {
3✔
1205

3✔
1206
                        return s.utxoNursery.IncubateOutputs(
3✔
1207
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1208
                                broadcastHeight, deadlineHeight,
3✔
1209
                        )
3✔
1210
                },
3✔
1211
                PreimageDB:   s.witnessBeacon,
1212
                Notifier:     cc.ChainNotifier,
1213
                Mempool:      cc.MempoolNotifier,
1214
                Signer:       cc.Wallet.Cfg.Signer,
1215
                FeeEstimator: cc.FeeEstimator,
1216
                ChainIO:      cc.ChainIO,
1217
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1218
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1219
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1220
                        return nil
3✔
1221
                },
3✔
1222
                IsOurAddress: cc.Wallet.IsOurAddress,
1223
                ContractBreach: func(chanPoint wire.OutPoint,
1224
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1225

3✔
1226
                        // processACK will handle the BreachArbitrator ACKing
3✔
1227
                        // the event.
3✔
1228
                        finalErr := make(chan error, 1)
3✔
1229
                        processACK := func(brarErr error) {
6✔
1230
                                if brarErr != nil {
3✔
1231
                                        finalErr <- brarErr
×
1232
                                        return
×
1233
                                }
×
1234

1235
                                // If the BreachArbitrator successfully handled
1236
                                // the event, we can signal that the handoff
1237
                                // was successful.
1238
                                finalErr <- nil
3✔
1239
                        }
1240

1241
                        event := &contractcourt.ContractBreachEvent{
3✔
1242
                                ChanPoint:         chanPoint,
3✔
1243
                                ProcessACK:        processACK,
3✔
1244
                                BreachRetribution: breachRet,
3✔
1245
                        }
3✔
1246

3✔
1247
                        // Send the contract breach event to the
3✔
1248
                        // BreachArbitrator.
3✔
1249
                        select {
3✔
1250
                        case contractBreaches <- event:
3✔
1251
                        case <-s.quit:
×
1252
                                return ErrServerShuttingDown
×
1253
                        }
1254

1255
                        // We'll wait for a final error to be available from
1256
                        // the BreachArbitrator.
1257
                        select {
3✔
1258
                        case err := <-finalErr:
3✔
1259
                                return err
3✔
1260
                        case <-s.quit:
×
1261
                                return ErrServerShuttingDown
×
1262
                        }
1263
                },
1264
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1265
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1266
                },
3✔
1267
                Sweeper:                       s.sweeper,
1268
                Registry:                      s.invoices,
1269
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1270
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1271
                OnionProcessor:                s.sphinx,
1272
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1273
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1274
                Clock:                         clock.NewDefaultClock(),
1275
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1276
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1277
                HtlcNotifier:                  s.htlcNotifier,
1278
                Budget:                        *s.cfg.Sweeper.Budget,
1279

1280
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1281
                QueryIncomingCircuit: func(
1282
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1283

3✔
1284
                        // Get the circuit map.
3✔
1285
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1286

3✔
1287
                        // Lookup the outgoing circuit.
3✔
1288
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1289
                        if pc == nil {
6✔
1290
                                return nil
3✔
1291
                        }
3✔
1292

1293
                        return &pc.Incoming
3✔
1294
                },
1295
                AuxLeafStore: implCfg.AuxLeafStore,
1296
                AuxSigner:    implCfg.AuxSigner,
1297
        }, dbs.ChanStateDB)
1298

1299
        // Select the configuration and funding parameters for Bitcoin.
1300
        chainCfg := cfg.Bitcoin
3✔
1301
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1302
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1303

3✔
1304
        var chanIDSeed [32]byte
3✔
1305
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1306
                return nil, err
×
1307
        }
×
1308

1309
        // Wrap the DeleteChannelEdges method so that the funding manager can
1310
        // use it without depending on several layers of indirection.
1311
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1312
                *models.ChannelEdgePolicy, error) {
6✔
1313

3✔
1314
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1315
                        scid.ToUint64(),
3✔
1316
                )
3✔
1317
                if errors.Is(err, channeldb.ErrEdgeNotFound) {
3✔
1318
                        // This is unlikely but there is a slim chance of this
×
1319
                        // being hit if lnd was killed via SIGKILL and the
×
1320
                        // funding manager was stepping through the delete
×
1321
                        // alias edge logic.
×
1322
                        return nil, nil
×
1323
                } else if err != nil {
3✔
1324
                        return nil, err
×
1325
                }
×
1326

1327
                // Grab our key to find our policy.
1328
                var ourKey [33]byte
3✔
1329
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1330

3✔
1331
                var ourPolicy *models.ChannelEdgePolicy
3✔
1332
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1333
                        ourPolicy = e1
3✔
1334
                } else {
6✔
1335
                        ourPolicy = e2
3✔
1336
                }
3✔
1337

1338
                if ourPolicy == nil {
3✔
1339
                        // Something is wrong, so return an error.
×
1340
                        return nil, fmt.Errorf("we don't have an edge")
×
1341
                }
×
1342

1343
                err = s.graphDB.DeleteChannelEdges(
3✔
1344
                        false, false, scid.ToUint64(),
3✔
1345
                )
3✔
1346
                return ourPolicy, err
3✔
1347
        }
1348

1349
        // For the reservationTimeout and the zombieSweeperInterval different
1350
        // values are set in case we are in a dev environment so enhance test
1351
        // capacilities.
1352
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1353
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1354

3✔
1355
        // Get the development config for funding manager. If we are not in
3✔
1356
        // development mode, this would be nil.
3✔
1357
        var devCfg *funding.DevConfig
3✔
1358
        if lncfg.IsDevBuild() {
6✔
1359
                devCfg = &funding.DevConfig{
3✔
1360
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1361
                }
3✔
1362

3✔
1363
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1364
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1365

3✔
1366
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1367
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1368
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1369
        }
3✔
1370

1371
        //nolint:lll
1372
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1373
                Dev:                devCfg,
3✔
1374
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1375
                IDKey:              nodeKeyDesc.PubKey,
3✔
1376
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1377
                Wallet:             cc.Wallet,
3✔
1378
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1379
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1380
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1381
                },
3✔
1382
                Notifier:     cc.ChainNotifier,
1383
                ChannelDB:    s.chanStateDB,
1384
                FeeEstimator: cc.FeeEstimator,
1385
                SignMessage:  cc.MsgSigner.SignMessage,
1386
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1387
                        error) {
3✔
1388

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

3✔
1409
                        // In case the user has explicitly specified
3✔
1410
                        // a default value for the number of
3✔
1411
                        // confirmations, we use it.
3✔
1412
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1413
                        if defaultConf != 0 {
6✔
1414
                                return defaultConf
3✔
1415
                        }
3✔
1416

1417
                        minConf := uint64(3)
×
1418
                        maxConf := uint64(6)
×
1419

×
1420
                        // If this is a wumbo channel, then we'll require the
×
1421
                        // max amount of confirmations.
×
1422
                        if chanAmt > MaxFundingAmount {
×
1423
                                return uint16(maxConf)
×
1424
                        }
×
1425

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

3✔
1448
                        // In case the user has explicitly specified
3✔
1449
                        // a default value for the remote delay, we
3✔
1450
                        // use it.
3✔
1451
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1452
                        if defaultDelay > 0 {
6✔
1453
                                return defaultDelay
3✔
1454
                        }
3✔
1455

1456
                        // If this is a wumbo channel, then we'll require the
1457
                        // max value.
1458
                        if chanAmt > MaxFundingAmount {
×
1459
                                return maxRemoteDelay
×
1460
                        }
×
1461

1462
                        // If not we scale according to channel size.
1463
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1464
                                chanAmt / MaxFundingAmount)
×
1465
                        if delay < minRemoteDelay {
×
1466
                                delay = minRemoteDelay
×
1467
                        }
×
1468
                        if delay > maxRemoteDelay {
×
1469
                                delay = maxRemoteDelay
×
1470
                        }
×
1471
                        return delay
×
1472
                },
1473
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1474
                        peerKey *btcec.PublicKey) error {
3✔
1475

3✔
1476
                        // First, we'll mark this new peer as a persistent peer
3✔
1477
                        // for re-connection purposes. If the peer is not yet
3✔
1478
                        // tracked or the user hasn't requested it to be perm,
3✔
1479
                        // we'll set false to prevent the server from continuing
3✔
1480
                        // to connect to this peer even if the number of
3✔
1481
                        // channels with this peer is zero.
3✔
1482
                        s.mu.Lock()
3✔
1483
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1484
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1485
                                s.persistentPeers[pubStr] = false
3✔
1486
                        }
3✔
1487
                        s.mu.Unlock()
3✔
1488

3✔
1489
                        // With that taken care of, we'll send this channel to
3✔
1490
                        // the chain arb so it can react to on-chain events.
3✔
1491
                        return s.chainArb.WatchNewChannel(channel)
3✔
1492
                },
1493
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1494
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1495
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1496
                },
3✔
1497
                RequiredRemoteChanReserve: func(chanAmt,
1498
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1499

3✔
1500
                        // By default, we'll require the remote peer to maintain
3✔
1501
                        // at least 1% of the total channel capacity at all
3✔
1502
                        // times. If this value ends up dipping below the dust
3✔
1503
                        // limit, then we'll use the dust limit itself as the
3✔
1504
                        // reserve as required by BOLT #2.
3✔
1505
                        reserve := chanAmt / 100
3✔
1506
                        if reserve < dustLimit {
6✔
1507
                                reserve = dustLimit
3✔
1508
                        }
3✔
1509

1510
                        return reserve
3✔
1511
                },
1512
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1513
                        // By default, we'll allow the remote peer to fully
3✔
1514
                        // utilize the full bandwidth of the channel, minus our
3✔
1515
                        // required reserve.
3✔
1516
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1517
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1518
                },
3✔
1519
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1520
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1521
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1522
                        }
3✔
1523

1524
                        // By default, we'll permit them to utilize the full
1525
                        // channel bandwidth.
1526
                        return uint16(input.MaxHTLCNumber / 2)
×
1527
                },
1528
                ZombieSweeperInterval:         zombieSweeperInterval,
1529
                ReservationTimeout:            reservationTimeout,
1530
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1531
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1532
                MaxPendingChannels:            cfg.MaxPendingChannels,
1533
                RejectPush:                    cfg.RejectPush,
1534
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1535
                NotifyOpenChannelEvent:        s.channelNotifier.NotifyOpenChannelEvent,
1536
                OpenChannelPredicate:          chanPredicate,
1537
                NotifyPendingOpenChannelEvent: s.channelNotifier.NotifyPendingOpenChannelEvent,
1538
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1539
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1540
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1541
                DeleteAliasEdge:      deleteAliasEdge,
1542
                AliasManager:         s.aliasMgr,
1543
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1544
                AuxFundingController: implCfg.AuxFundingController,
1545
                AuxSigner:            implCfg.AuxSigner,
1546
        })
1547
        if err != nil {
3✔
1548
                return nil, err
×
1549
        }
×
1550

1551
        // Next, we'll assemble the sub-system that will maintain an on-disk
1552
        // static backup of the latest channel state.
1553
        chanNotifier := &channelNotifier{
3✔
1554
                chanNotifier: s.channelNotifier,
3✔
1555
                addrs:        dbs.ChanStateDB,
3✔
1556
        }
3✔
1557
        backupFile := chanbackup.NewMultiFile(cfg.BackupFilePath)
3✔
1558
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1559
                s.chanStateDB, s.addrSource,
3✔
1560
        )
3✔
1561
        if err != nil {
3✔
1562
                return nil, err
×
1563
        }
×
1564
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1565
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1566
        )
3✔
1567
        if err != nil {
3✔
1568
                return nil, err
×
1569
        }
×
1570

1571
        // Assemble a peer notifier which will provide clients with subscriptions
1572
        // to peer online and offline events.
1573
        s.peerNotifier = peernotifier.New()
3✔
1574

3✔
1575
        // Create a channel event store which monitors all open channels.
3✔
1576
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1577
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1578
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1579
                },
3✔
1580
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1581
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1582
                },
3✔
1583
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1584
                Clock:           clock.NewDefaultClock(),
1585
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1586
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1587
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1588
        })
1589

1590
        if cfg.WtClient.Active {
6✔
1591
                policy := wtpolicy.DefaultPolicy()
3✔
1592
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1593

3✔
1594
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1595
                // protocol operations on sat/kw.
3✔
1596
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1597
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1598
                )
3✔
1599

3✔
1600
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1601

3✔
1602
                if err := policy.Validate(); err != nil {
3✔
1603
                        return nil, err
×
1604
                }
×
1605

1606
                // authDial is the wrapper around the btrontide.Dial for the
1607
                // watchtower.
1608
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1609
                        netAddr *lnwire.NetAddress,
3✔
1610
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1611

3✔
1612
                        return brontide.Dial(
3✔
1613
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1614
                        )
3✔
1615
                }
3✔
1616

1617
                // buildBreachRetribution is a call-back that can be used to
1618
                // query the BreachRetribution info and channel type given a
1619
                // channel ID and commitment height.
1620
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1621
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1622
                        channeldb.ChannelType, error) {
6✔
1623

3✔
1624
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1625
                                nil, chanID,
3✔
1626
                        )
3✔
1627
                        if err != nil {
3✔
1628
                                return nil, 0, err
×
1629
                        }
×
1630

1631
                        br, err := lnwallet.NewBreachRetribution(
3✔
1632
                                channel, commitHeight, 0, nil,
3✔
1633
                                implCfg.AuxLeafStore,
3✔
1634
                        )
3✔
1635
                        if err != nil {
3✔
1636
                                return nil, 0, err
×
1637
                        }
×
1638

1639
                        return br, channel.ChanType, nil
3✔
1640
                }
1641

1642
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1643

3✔
1644
                // Copy the policy for legacy channels and set the blob flag
3✔
1645
                // signalling support for anchor channels.
3✔
1646
                anchorPolicy := policy
3✔
1647
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1648

3✔
1649
                // Copy the policy for legacy channels and set the blob flag
3✔
1650
                // signalling support for taproot channels.
3✔
1651
                taprootPolicy := policy
3✔
1652
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1653
                        blob.FlagTaprootChannel,
3✔
1654
                )
3✔
1655

3✔
1656
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1657
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1658
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1659
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1660
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1661
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1662
                                error) {
6✔
1663

3✔
1664
                                return s.channelNotifier.
3✔
1665
                                        SubscribeChannelEvents()
3✔
1666
                        },
3✔
1667
                        Signer:             cc.Wallet.Cfg.Signer,
1668
                        NewAddress:         newSweepPkScriptGen(cc.Wallet),
1669
                        SecretKeyRing:      s.cc.KeyRing,
1670
                        Dial:               cfg.net.Dial,
1671
                        AuthDial:           authDial,
1672
                        DB:                 dbs.TowerClientDB,
1673
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1674
                        MinBackoff:         10 * time.Second,
1675
                        MaxBackoff:         5 * time.Minute,
1676
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1677
                }, policy, anchorPolicy, taprootPolicy)
1678
                if err != nil {
3✔
1679
                        return nil, err
×
1680
                }
×
1681
        }
1682

1683
        if len(cfg.ExternalHosts) != 0 {
3✔
1684
                advertisedIPs := make(map[string]struct{})
×
1685
                for _, addr := range s.currentNodeAnn.Addresses {
×
1686
                        advertisedIPs[addr.String()] = struct{}{}
×
1687
                }
×
1688

1689
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1690
                        Hosts:         cfg.ExternalHosts,
×
1691
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1692
                        LookupHost: func(host string) (net.Addr, error) {
×
1693
                                return lncfg.ParseAddressString(
×
1694
                                        host, strconv.Itoa(defaultPeerPort),
×
1695
                                        cfg.net.ResolveTCPAddr,
×
1696
                                )
×
1697
                        },
×
1698
                        AdvertisedIPs: advertisedIPs,
1699
                        AnnounceNewIPs: netann.IPAnnouncer(
1700
                                func(modifier ...netann.NodeAnnModifier) (
1701
                                        lnwire.NodeAnnouncement, error) {
×
1702

×
1703
                                        return s.genNodeAnnouncement(
×
1704
                                                nil, modifier...,
×
1705
                                        )
×
1706
                                }),
×
1707
                })
1708
        }
1709

1710
        // Create liveness monitor.
1711
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1712

3✔
1713
        // Create the connection manager which will be responsible for
3✔
1714
        // maintaining persistent outbound connections and also accepting new
3✔
1715
        // incoming connections
3✔
1716
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1717
                Listeners:      listeners,
3✔
1718
                OnAccept:       s.InboundPeerConnected,
3✔
1719
                RetryDuration:  time.Second * 5,
3✔
1720
                TargetOutbound: 100,
3✔
1721
                Dial: noiseDial(
3✔
1722
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1723
                ),
3✔
1724
                OnConnection: s.OutboundPeerConnected,
3✔
1725
        })
3✔
1726
        if err != nil {
3✔
1727
                return nil, err
×
1728
        }
×
1729
        s.connMgr = cmgr
3✔
1730

3✔
1731
        return s, nil
3✔
1732
}
1733

1734
// UpdateRoutingConfig is a callback function to update the routing config
1735
// values in the main cfg.
1736
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1737
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1738

3✔
1739
        switch c := cfg.Estimator.Config().(type) {
3✔
1740
        case routing.AprioriConfig:
3✔
1741
                routerCfg.ProbabilityEstimatorType =
3✔
1742
                        routing.AprioriEstimatorName
3✔
1743

3✔
1744
                targetCfg := routerCfg.AprioriConfig
3✔
1745
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1746
                targetCfg.Weight = c.AprioriWeight
3✔
1747
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1748
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1749

1750
        case routing.BimodalConfig:
3✔
1751
                routerCfg.ProbabilityEstimatorType =
3✔
1752
                        routing.BimodalEstimatorName
3✔
1753

3✔
1754
                targetCfg := routerCfg.BimodalConfig
3✔
1755
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1756
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1757
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1758
        }
1759

1760
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1761
}
1762

1763
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1764
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1765
// may differ from what is on disk.
1766
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1767
        error) {
3✔
1768

3✔
1769
        data, err := u.DataToSign()
3✔
1770
        if err != nil {
3✔
1771
                return nil, err
×
1772
        }
×
1773

1774
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1775
}
1776

1777
// createLivenessMonitor creates a set of health checks using our configured
1778
// values and uses these checks to create a liveness monitor. Available
1779
// health checks,
1780
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1781
//   - diskCheck
1782
//   - tlsHealthCheck
1783
//   - torController, only created when tor is enabled.
1784
//
1785
// If a health check has been disabled by setting attempts to 0, our monitor
1786
// will not run it.
1787
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1788
        leaderElector cluster.LeaderElector) {
3✔
1789

3✔
1790
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
1791
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
1792
                srvrLog.Info("Disabling chain backend checks for " +
×
1793
                        "nochainbackend mode")
×
1794

×
1795
                chainBackendAttempts = 0
×
1796
        }
×
1797

1798
        chainHealthCheck := healthcheck.NewObservation(
3✔
1799
                "chain backend",
3✔
1800
                cc.HealthCheck,
3✔
1801
                cfg.HealthChecks.ChainCheck.Interval,
3✔
1802
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
1803
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
1804
                chainBackendAttempts,
3✔
1805
        )
3✔
1806

3✔
1807
        diskCheck := healthcheck.NewObservation(
3✔
1808
                "disk space",
3✔
1809
                func() error {
3✔
1810
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1811
                                cfg.LndDir,
×
1812
                        )
×
1813
                        if err != nil {
×
1814
                                return err
×
1815
                        }
×
1816

1817
                        // If we have more free space than we require,
1818
                        // we return a nil error.
1819
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1820
                                return nil
×
1821
                        }
×
1822

1823
                        return fmt.Errorf("require: %v free space, got: %v",
×
1824
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1825
                                free)
×
1826
                },
1827
                cfg.HealthChecks.DiskCheck.Interval,
1828
                cfg.HealthChecks.DiskCheck.Timeout,
1829
                cfg.HealthChecks.DiskCheck.Backoff,
1830
                cfg.HealthChecks.DiskCheck.Attempts,
1831
        )
1832

1833
        tlsHealthCheck := healthcheck.NewObservation(
3✔
1834
                "tls",
3✔
1835
                func() error {
3✔
1836
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1837
                                s.cc.KeyRing,
×
1838
                        )
×
1839
                        if err != nil {
×
1840
                                return err
×
1841
                        }
×
1842
                        if expired {
×
1843
                                return fmt.Errorf("TLS certificate is "+
×
1844
                                        "expired as of %v", expTime)
×
1845
                        }
×
1846

1847
                        // If the certificate is not outdated, no error needs
1848
                        // to be returned
1849
                        return nil
×
1850
                },
1851
                cfg.HealthChecks.TLSCheck.Interval,
1852
                cfg.HealthChecks.TLSCheck.Timeout,
1853
                cfg.HealthChecks.TLSCheck.Backoff,
1854
                cfg.HealthChecks.TLSCheck.Attempts,
1855
        )
1856

1857
        checks := []*healthcheck.Observation{
3✔
1858
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
1859
        }
3✔
1860

3✔
1861
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
1862
        if s.torController != nil {
3✔
1863
                torConnectionCheck := healthcheck.NewObservation(
×
1864
                        "tor connection",
×
1865
                        func() error {
×
1866
                                return healthcheck.CheckTorServiceStatus(
×
1867
                                        s.torController,
×
1868
                                        s.createNewHiddenService,
×
1869
                                )
×
1870
                        },
×
1871
                        cfg.HealthChecks.TorConnection.Interval,
1872
                        cfg.HealthChecks.TorConnection.Timeout,
1873
                        cfg.HealthChecks.TorConnection.Backoff,
1874
                        cfg.HealthChecks.TorConnection.Attempts,
1875
                )
1876
                checks = append(checks, torConnectionCheck)
×
1877
        }
1878

1879
        // If remote signing is enabled, add the healthcheck for the remote
1880
        // signing RPC interface.
1881
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
1882
                // Because we have two cascading timeouts here, we need to add
3✔
1883
                // some slack to the "outer" one of them in case the "inner"
3✔
1884
                // returns exactly on time.
3✔
1885
                overhead := time.Millisecond * 10
3✔
1886

3✔
1887
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
1888
                        "remote signer connection",
3✔
1889
                        rpcwallet.HealthCheck(
3✔
1890
                                s.cfg.RemoteSigner,
3✔
1891

3✔
1892
                                // For the health check we might to be even
3✔
1893
                                // stricter than the initial/normal connect, so
3✔
1894
                                // we use the health check timeout here.
3✔
1895
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
1896
                        ),
3✔
1897
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
1898
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
1899
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
1900
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
1901
                )
3✔
1902
                checks = append(checks, remoteSignerConnectionCheck)
3✔
1903
        }
3✔
1904

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

×
1923
                                leader, err := leaderElector.IsLeader(
×
1924
                                        timeoutCtx,
×
1925
                                )
×
1926
                                if err != nil {
×
1927
                                        return fmt.Errorf("unable to check if "+
×
1928
                                                "still leader: %v", err)
×
1929
                                }
×
1930

1931
                                if !leader {
×
1932
                                        srvrLog.Debug("Not the current leader")
×
1933
                                        return fmt.Errorf("not the current " +
×
1934
                                                "leader")
×
1935
                                }
×
1936

1937
                                return nil
×
1938
                        },
1939
                        cfg.HealthChecks.LeaderCheck.Interval,
1940
                        cfg.HealthChecks.LeaderCheck.Timeout,
1941
                        cfg.HealthChecks.LeaderCheck.Backoff,
1942
                        cfg.HealthChecks.LeaderCheck.Attempts,
1943
                )
1944

1945
                checks = append(checks, leaderCheck)
×
1946
        }
1947

1948
        // If we have not disabled all of our health checks, we create a
1949
        // liveness monitor with our configured checks.
1950
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
1951
                &healthcheck.Config{
3✔
1952
                        Checks:   checks,
3✔
1953
                        Shutdown: srvrLog.Criticalf,
3✔
1954
                },
3✔
1955
        )
3✔
1956
}
1957

1958
// Started returns true if the server has been started, and false otherwise.
1959
// NOTE: This function is safe for concurrent access.
1960
func (s *server) Started() bool {
3✔
1961
        return atomic.LoadInt32(&s.active) != 0
3✔
1962
}
3✔
1963

1964
// cleaner is used to aggregate "cleanup" functions during an operation that
1965
// starts several subsystems. In case one of the subsystem fails to start
1966
// and a proper resource cleanup is required, the "run" method achieves this
1967
// by running all these added "cleanup" functions.
1968
type cleaner []func() error
1969

1970
// add is used to add a cleanup function to be called when
1971
// the run function is executed.
1972
func (c cleaner) add(cleanup func() error) cleaner {
3✔
1973
        return append(c, cleanup)
3✔
1974
}
3✔
1975

1976
// run is used to run all the previousely added cleanup functions.
1977
func (c cleaner) run() {
×
1978
        for i := len(c) - 1; i >= 0; i-- {
×
1979
                if err := c[i](); err != nil {
×
1980
                        srvrLog.Infof("Cleanup failed: %v", err)
×
1981
                }
×
1982
        }
1983
}
1984

1985
// Start starts the main daemon server, all requested listeners, and any helper
1986
// goroutines.
1987
// NOTE: This function is safe for concurrent access.
1988
//
1989
//nolint:funlen
1990
func (s *server) Start() error {
3✔
1991
        var startErr error
3✔
1992

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

3✔
1998
        s.start.Do(func() {
6✔
1999
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2000
                if err := s.customMessageServer.Start(); err != nil {
3✔
2001
                        startErr = err
×
2002
                        return
×
2003
                }
×
2004

2005
                if s.hostAnn != nil {
3✔
2006
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2007
                        if err := s.hostAnn.Start(); err != nil {
×
2008
                                startErr = err
×
2009
                                return
×
2010
                        }
×
2011
                }
2012

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

2021
                // Start the notification server. This is used so channel
2022
                // management goroutines can be notified when a funding
2023
                // transaction reaches a sufficient number of confirmations, or
2024
                // when the input for the funding transaction is spent in an
2025
                // attempt at an uncooperative close by the counterparty.
2026
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2027
                if err := s.sigPool.Start(); err != nil {
3✔
2028
                        startErr = err
×
2029
                        return
×
2030
                }
×
2031

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

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

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

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

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

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

2070
                cleanup = cleanup.add(s.htlcNotifier.Stop)
3✔
2071
                if err := s.htlcNotifier.Start(); err != nil {
3✔
2072
                        startErr = err
×
2073
                        return
×
2074
                }
×
2075

2076
                if s.towerClientMgr != nil {
6✔
2077
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
3✔
2078
                        if err := s.towerClientMgr.Start(); err != nil {
3✔
2079
                                startErr = err
×
2080
                                return
×
2081
                        }
×
2082
                }
2083

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

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

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

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

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

2114
                // htlcSwitch must be started before chainArb since the latter
2115
                // relies on htlcSwitch to deliver resolution message upon
2116
                // start.
2117
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2118
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2119
                        startErr = err
×
2120
                        return
×
2121
                }
×
2122

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

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

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

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

2147
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2148
                if err := s.chanRouter.Start(); err != nil {
3✔
2149
                        startErr = err
×
2150
                        return
×
2151
                }
×
2152
                // The authGossiper depends on the chanRouter and therefore
2153
                // should be started after it.
2154
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2155
                if err := s.authGossiper.Start(); err != nil {
3✔
2156
                        startErr = err
×
2157
                        return
×
2158
                }
×
2159

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

2166
                cleanup = cleanup.add(s.sphinx.Stop)
3✔
2167
                if err := s.sphinx.Start(); err != nil {
3✔
2168
                        startErr = err
×
2169
                        return
×
2170
                }
×
2171

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

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

2184
                cleanup.add(func() error {
3✔
2185
                        s.missionControl.StopStoreTicker()
×
2186
                        return nil
×
2187
                })
×
2188
                s.missionControl.RunStoreTicker()
3✔
2189

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

2222
                // chanSubSwapper must be started after the `channelNotifier`
2223
                // because it depends on channel events as a synchronization
2224
                // point.
2225
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2226
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2227
                        startErr = err
×
2228
                        return
×
2229
                }
×
2230

2231
                if s.torController != nil {
3✔
2232
                        cleanup = cleanup.add(s.torController.Stop)
×
2233
                        if err := s.createNewHiddenService(); err != nil {
×
2234
                                startErr = err
×
2235
                                return
×
2236
                        }
×
2237
                }
2238

2239
                if s.natTraversal != nil {
3✔
2240
                        s.wg.Add(1)
×
2241
                        go s.watchExternalIP()
×
2242
                }
×
2243

2244
                // Start connmgr last to prevent connections before init.
2245
                cleanup = cleanup.add(func() error {
3✔
2246
                        s.connMgr.Stop()
×
2247
                        return nil
×
2248
                })
×
2249
                s.connMgr.Start()
3✔
2250

3✔
2251
                // If peers are specified as a config option, we'll add those
3✔
2252
                // peers first.
3✔
2253
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2254
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2255
                                peerAddrCfg,
3✔
2256
                        )
3✔
2257
                        if err != nil {
3✔
2258
                                startErr = fmt.Errorf("unable to parse peer "+
×
2259
                                        "pubkey from config: %v", err)
×
2260
                                return
×
2261
                        }
×
2262
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2263
                        if err != nil {
3✔
2264
                                startErr = fmt.Errorf("unable to parse peer "+
×
2265
                                        "address provided as a config option: "+
×
2266
                                        "%v", err)
×
2267
                                return
×
2268
                        }
×
2269

2270
                        peerAddr := &lnwire.NetAddress{
3✔
2271
                                IdentityKey: parsedPubkey,
3✔
2272
                                Address:     addr,
3✔
2273
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2274
                        }
3✔
2275

3✔
2276
                        err = s.ConnectToPeer(
3✔
2277
                                peerAddr, true,
3✔
2278
                                s.cfg.ConnectionTimeout,
3✔
2279
                        )
3✔
2280
                        if err != nil {
3✔
2281
                                startErr = fmt.Errorf("unable to connect to "+
×
2282
                                        "peer address provided as a config "+
×
2283
                                        "option: %v", err)
×
2284
                                return
×
2285
                        }
×
2286
                }
2287

2288
                // Subscribe to NodeAnnouncements that advertise new addresses
2289
                // our persistent peers.
2290
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2291
                        startErr = err
×
2292
                        return
×
2293
                }
×
2294

2295
                // With all the relevant sub-systems started, we'll now attempt
2296
                // to establish persistent connections to our direct channel
2297
                // collaborators within the network. Before doing so however,
2298
                // we'll prune our set of link nodes found within the database
2299
                // to ensure we don't reconnect to any nodes we no longer have
2300
                // open channels with.
2301
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2302
                        startErr = err
×
2303
                        return
×
2304
                }
×
2305
                if err := s.establishPersistentConnections(); err != nil {
3✔
2306
                        startErr = err
×
2307
                        return
×
2308
                }
×
2309

2310
                // setSeedList is a helper function that turns multiple DNS seed
2311
                // server tuples from the command line or config file into the
2312
                // data structure we need and does a basic formal sanity check
2313
                // in the process.
2314
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2315
                        if len(tuples) == 0 {
×
2316
                                return
×
2317
                        }
×
2318

2319
                        result := make([][2]string, len(tuples))
×
2320
                        for idx, tuple := range tuples {
×
2321
                                tuple = strings.TrimSpace(tuple)
×
2322
                                if len(tuple) == 0 {
×
2323
                                        return
×
2324
                                }
×
2325

2326
                                servers := strings.Split(tuple, ",")
×
2327
                                if len(servers) > 2 || len(servers) == 0 {
×
2328
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2329
                                                "seed tuple: %v", servers)
×
2330
                                        return
×
2331
                                }
×
2332

2333
                                copy(result[idx][:], servers)
×
2334
                        }
2335

2336
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2337
                }
2338

2339
                // Let users overwrite the DNS seed nodes. We only allow them
2340
                // for bitcoin mainnet/testnet/signet.
2341
                if s.cfg.Bitcoin.MainNet {
3✔
2342
                        setSeedList(
×
2343
                                s.cfg.Bitcoin.DNSSeeds,
×
2344
                                chainreg.BitcoinMainnetGenesis,
×
2345
                        )
×
2346
                }
×
2347
                if s.cfg.Bitcoin.TestNet3 {
3✔
2348
                        setSeedList(
×
2349
                                s.cfg.Bitcoin.DNSSeeds,
×
2350
                                chainreg.BitcoinTestnetGenesis,
×
2351
                        )
×
2352
                }
×
2353
                if s.cfg.Bitcoin.SigNet {
3✔
2354
                        setSeedList(
×
2355
                                s.cfg.Bitcoin.DNSSeeds,
×
2356
                                chainreg.BitcoinSignetGenesis,
×
2357
                        )
×
2358
                }
×
2359

2360
                // If network bootstrapping hasn't been disabled, then we'll
2361
                // configure the set of active bootstrappers, and launch a
2362
                // dedicated goroutine to maintain a set of persistent
2363
                // connections.
2364
                if shouldPeerBootstrap(s.cfg) {
3✔
2365
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2366
                        if err != nil {
×
2367
                                startErr = err
×
2368
                                return
×
2369
                        }
×
2370

2371
                        s.wg.Add(1)
×
2372
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2373
                } else {
3✔
2374
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2375
                }
3✔
2376

2377
                // Set the active flag now that we've completed the full
2378
                // startup.
2379
                atomic.StoreInt32(&s.active, 1)
3✔
2380
        })
2381

2382
        if startErr != nil {
3✔
2383
                cleanup.run()
×
2384
        }
×
2385
        return startErr
3✔
2386
}
2387

2388
// Stop gracefully shutsdown the main daemon server. This function will signal
2389
// any active goroutines, or helper objects to exit, then blocks until they've
2390
// all successfully exited. Additionally, any/all listeners are closed.
2391
// NOTE: This function is safe for concurrent access.
2392
func (s *server) Stop() error {
3✔
2393
        s.stop.Do(func() {
6✔
2394
                atomic.StoreInt32(&s.stopping, 1)
3✔
2395

3✔
2396
                close(s.quit)
3✔
2397

3✔
2398
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2399
                s.connMgr.Stop()
3✔
2400

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

3✔
2472
                // Disconnect from each active peers to ensure that
3✔
2473
                // peerTerminationWatchers signal completion to each peer.
3✔
2474
                for _, peer := range s.Peers() {
6✔
2475
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2476
                        if err != nil {
3✔
2477
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2478
                                        "received error: %v", peer.IdentityKey(),
×
2479
                                        err,
×
2480
                                )
×
2481
                        }
×
2482
                }
2483

2484
                // Now that all connections have been torn down, stop the tower
2485
                // client which will reliably flush all queued states to the
2486
                // tower. If this is halted for any reason, the force quit timer
2487
                // will kick in and abort to allow this method to return.
2488
                if s.towerClientMgr != nil {
6✔
2489
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2490
                                srvrLog.Warnf("Unable to shut down tower "+
×
2491
                                        "client manager: %v", err)
×
2492
                        }
×
2493
                }
2494

2495
                if s.hostAnn != nil {
3✔
2496
                        if err := s.hostAnn.Stop(); err != nil {
×
2497
                                srvrLog.Warnf("unable to shut down host "+
×
2498
                                        "annoucner: %v", err)
×
2499
                        }
×
2500
                }
2501

2502
                if s.livenessMonitor != nil {
6✔
2503
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2504
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2505
                                        "monitor: %v", err)
×
2506
                        }
×
2507
                }
2508

2509
                // Wait for all lingering goroutines to quit.
2510
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2511
                s.wg.Wait()
3✔
2512

3✔
2513
                srvrLog.Debug("Stopping buffer pools...")
3✔
2514
                s.sigPool.Stop()
3✔
2515
                s.writePool.Stop()
3✔
2516
                s.readPool.Stop()
3✔
2517
        })
2518

2519
        return nil
3✔
2520
}
2521

2522
// Stopped returns true if the server has been instructed to shutdown.
2523
// NOTE: This function is safe for concurrent access.
2524
func (s *server) Stopped() bool {
3✔
2525
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2526
}
3✔
2527

2528
// configurePortForwarding attempts to set up port forwarding for the different
2529
// ports that the server will be listening on.
2530
//
2531
// NOTE: This should only be used when using some kind of NAT traversal to
2532
// automatically set up forwarding rules.
2533
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2534
        ip, err := s.natTraversal.ExternalIP()
×
2535
        if err != nil {
×
2536
                return nil, err
×
2537
        }
×
2538
        s.lastDetectedIP = ip
×
2539

×
2540
        externalIPs := make([]string, 0, len(ports))
×
2541
        for _, port := range ports {
×
2542
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2543
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2544
                        continue
×
2545
                }
2546

2547
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2548
                externalIPs = append(externalIPs, hostIP)
×
2549
        }
2550

2551
        return externalIPs, nil
×
2552
}
2553

2554
// removePortForwarding attempts to clear the forwarding rules for the different
2555
// ports the server is currently listening on.
2556
//
2557
// NOTE: This should only be used when using some kind of NAT traversal to
2558
// automatically set up forwarding rules.
2559
func (s *server) removePortForwarding() {
×
2560
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2561
        for _, port := range forwardedPorts {
×
2562
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2563
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2564
                                "port %d: %v", port, err)
×
2565
                }
×
2566
        }
2567
}
2568

2569
// watchExternalIP continuously checks for an updated external IP address every
2570
// 15 minutes. Once a new IP address has been detected, it will automatically
2571
// handle port forwarding rules and send updated node announcements to the
2572
// currently connected peers.
2573
//
2574
// NOTE: This MUST be run as a goroutine.
2575
func (s *server) watchExternalIP() {
×
2576
        defer s.wg.Done()
×
2577

×
2578
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2579
        // up by the server.
×
2580
        defer s.removePortForwarding()
×
2581

×
2582
        // Keep track of the external IPs set by the user to avoid replacing
×
2583
        // them when detecting a new IP.
×
2584
        ipsSetByUser := make(map[string]struct{})
×
2585
        for _, ip := range s.cfg.ExternalIPs {
×
2586
                ipsSetByUser[ip.String()] = struct{}{}
×
2587
        }
×
2588

2589
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2590

×
2591
        ticker := time.NewTicker(15 * time.Minute)
×
2592
        defer ticker.Stop()
×
2593
out:
×
2594
        for {
×
2595
                select {
×
2596
                case <-ticker.C:
×
2597
                        // We'll start off by making sure a new IP address has
×
2598
                        // been detected.
×
2599
                        ip, err := s.natTraversal.ExternalIP()
×
2600
                        if err != nil {
×
2601
                                srvrLog.Debugf("Unable to retrieve the "+
×
2602
                                        "external IP address: %v", err)
×
2603
                                continue
×
2604
                        }
2605

2606
                        // Periodically renew the NAT port forwarding.
2607
                        for _, port := range forwardedPorts {
×
2608
                                err := s.natTraversal.AddPortMapping(port)
×
2609
                                if err != nil {
×
2610
                                        srvrLog.Warnf("Unable to automatically "+
×
2611
                                                "re-create port forwarding using %s: %v",
×
2612
                                                s.natTraversal.Name(), err)
×
2613
                                } else {
×
2614
                                        srvrLog.Debugf("Automatically re-created "+
×
2615
                                                "forwarding for port %d using %s to "+
×
2616
                                                "advertise external IP",
×
2617
                                                port, s.natTraversal.Name())
×
2618
                                }
×
2619
                        }
2620

2621
                        if ip.Equal(s.lastDetectedIP) {
×
2622
                                continue
×
2623
                        }
2624

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

×
2627
                        // Next, we'll craft the new addresses that will be
×
2628
                        // included in the new node announcement and advertised
×
2629
                        // to the network. Each address will consist of the new
×
2630
                        // IP detected and one of the currently advertised
×
2631
                        // ports.
×
2632
                        var newAddrs []net.Addr
×
2633
                        for _, port := range forwardedPorts {
×
2634
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2635
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2636
                                if err != nil {
×
2637
                                        srvrLog.Debugf("Unable to resolve "+
×
2638
                                                "host %v: %v", addr, err)
×
2639
                                        continue
×
2640
                                }
2641

2642
                                newAddrs = append(newAddrs, addr)
×
2643
                        }
2644

2645
                        // Skip the update if we weren't able to resolve any of
2646
                        // the new addresses.
2647
                        if len(newAddrs) == 0 {
×
2648
                                srvrLog.Debug("Skipping node announcement " +
×
2649
                                        "update due to not being able to " +
×
2650
                                        "resolve any new addresses")
×
2651
                                continue
×
2652
                        }
2653

2654
                        // Now, we'll need to update the addresses in our node's
2655
                        // announcement in order to propagate the update
2656
                        // throughout the network. We'll only include addresses
2657
                        // that have a different IP from the previous one, as
2658
                        // the previous IP is no longer valid.
2659
                        currentNodeAnn := s.getNodeAnnouncement()
×
2660

×
2661
                        for _, addr := range currentNodeAnn.Addresses {
×
2662
                                host, _, err := net.SplitHostPort(addr.String())
×
2663
                                if err != nil {
×
2664
                                        srvrLog.Debugf("Unable to determine "+
×
2665
                                                "host from address %v: %v",
×
2666
                                                addr, err)
×
2667
                                        continue
×
2668
                                }
2669

2670
                                // We'll also make sure to include external IPs
2671
                                // set manually by the user.
2672
                                _, setByUser := ipsSetByUser[addr.String()]
×
2673
                                if setByUser || host != s.lastDetectedIP.String() {
×
2674
                                        newAddrs = append(newAddrs, addr)
×
2675
                                }
×
2676
                        }
2677

2678
                        // Then, we'll generate a new timestamped node
2679
                        // announcement with the updated addresses and broadcast
2680
                        // it to our peers.
2681
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2682
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2683
                        )
×
2684
                        if err != nil {
×
2685
                                srvrLog.Debugf("Unable to generate new node "+
×
2686
                                        "announcement: %v", err)
×
2687
                                continue
×
2688
                        }
2689

2690
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2691
                        if err != nil {
×
2692
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2693
                                        "announcement to peers: %v", err)
×
2694
                                continue
×
2695
                        }
2696

2697
                        // Finally, update the last IP seen to the current one.
2698
                        s.lastDetectedIP = ip
×
2699
                case <-s.quit:
×
2700
                        break out
×
2701
                }
2702
        }
2703
}
2704

2705
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2706
// based on the server, and currently active bootstrap mechanisms as defined
2707
// within the current configuration.
2708
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2709
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2710

×
2711
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2712

×
2713
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2714
        // this can be used by default if we've already partially seeded the
×
2715
        // network.
×
2716
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2717
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
2718
        if err != nil {
×
2719
                return nil, err
×
2720
        }
×
2721
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2722

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

×
2728
                // If we have a set of DNS seeds for this chain, then we'll add
×
2729
                // it as an additional bootstrapping source.
×
2730
                if ok {
×
2731
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2732
                                "seeds: %v", dnsSeeds)
×
2733

×
2734
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2735
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2736
                        )
×
2737
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2738
                }
×
2739
        }
2740

2741
        return bootStrappers, nil
×
2742
}
2743

2744
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2745
// needs to ignore, which is made of three parts,
2746
//   - the node itself needs to be skipped as it doesn't make sense to connect
2747
//     to itself.
2748
//   - the peers that already have connections with, as in s.peersByPub.
2749
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2750
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2751
        s.mu.RLock()
×
2752
        defer s.mu.RUnlock()
×
2753

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

×
2756
        // We should ignore ourselves from bootstrapping.
×
2757
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2758
        ignore[selfKey] = struct{}{}
×
2759

×
2760
        // Ignore all connected peers.
×
2761
        for _, peer := range s.peersByPub {
×
2762
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2763
                ignore[nID] = struct{}{}
×
2764
        }
×
2765

2766
        // Ignore all persistent peers as they have a dedicated reconnecting
2767
        // process.
2768
        for pubKeyStr := range s.persistentPeers {
×
2769
                var nID autopilot.NodeID
×
2770
                copy(nID[:], []byte(pubKeyStr))
×
2771
                ignore[nID] = struct{}{}
×
2772
        }
×
2773

2774
        return ignore
×
2775
}
2776

2777
// peerBootstrapper is a goroutine which is tasked with attempting to establish
2778
// and maintain a target minimum number of outbound connections. With this
2779
// invariant, we ensure that our node is connected to a diverse set of peers
2780
// and that nodes newly joining the network receive an up to date network view
2781
// as soon as possible.
2782
func (s *server) peerBootstrapper(numTargetPeers uint32,
2783
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2784

×
2785
        defer s.wg.Done()
×
2786

×
2787
        // Before we continue, init the ignore peers map.
×
2788
        ignoreList := s.createBootstrapIgnorePeers()
×
2789

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

×
2794
        // Once done, we'll attempt to maintain our target minimum number of
×
2795
        // peers.
×
2796
        //
×
2797
        // We'll use a 15 second backoff, and double the time every time an
×
2798
        // epoch fails up to a ceiling.
×
2799
        backOff := time.Second * 15
×
2800

×
2801
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2802
        // see if we've reached our minimum number of peers.
×
2803
        sampleTicker := time.NewTicker(backOff)
×
2804
        defer sampleTicker.Stop()
×
2805

×
2806
        // We'll use the number of attempts and errors to determine if we need
×
2807
        // to increase the time between discovery epochs.
×
2808
        var epochErrors uint32 // To be used atomically.
×
2809
        var epochAttempts uint32
×
2810

×
2811
        for {
×
2812
                select {
×
2813
                // The ticker has just woken us up, so we'll need to check if
2814
                // we need to attempt to connect our to any more peers.
2815
                case <-sampleTicker.C:
×
2816
                        // Obtain the current number of peers, so we can gauge
×
2817
                        // if we need to sample more peers or not.
×
2818
                        s.mu.RLock()
×
2819
                        numActivePeers := uint32(len(s.peersByPub))
×
2820
                        s.mu.RUnlock()
×
2821

×
2822
                        // If we have enough peers, then we can loop back
×
2823
                        // around to the next round as we're done here.
×
2824
                        if numActivePeers >= numTargetPeers {
×
2825
                                continue
×
2826
                        }
2827

2828
                        // If all of our attempts failed during this last back
2829
                        // off period, then will increase our backoff to 5
2830
                        // minute ceiling to avoid an excessive number of
2831
                        // queries
2832
                        //
2833
                        // TODO(roasbeef): add reverse policy too?
2834

2835
                        if epochAttempts > 0 &&
×
2836
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
2837

×
2838
                                sampleTicker.Stop()
×
2839

×
2840
                                backOff *= 2
×
2841
                                if backOff > bootstrapBackOffCeiling {
×
2842
                                        backOff = bootstrapBackOffCeiling
×
2843
                                }
×
2844

2845
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
2846
                                        "%v", backOff)
×
2847
                                sampleTicker = time.NewTicker(backOff)
×
2848
                                continue
×
2849
                        }
2850

2851
                        atomic.StoreUint32(&epochErrors, 0)
×
2852
                        epochAttempts = 0
×
2853

×
2854
                        // Since we know need more peers, we'll compute the
×
2855
                        // exact number we need to reach our threshold.
×
2856
                        numNeeded := numTargetPeers - numActivePeers
×
2857

×
2858
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
2859
                                "peers", numNeeded)
×
2860

×
2861
                        // With the number of peers we need calculated, we'll
×
2862
                        // query the network bootstrappers to sample a set of
×
2863
                        // random addrs for us.
×
2864
                        //
×
2865
                        // Before we continue, get a copy of the ignore peers
×
2866
                        // map.
×
2867
                        ignoreList = s.createBootstrapIgnorePeers()
×
2868

×
2869
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
2870
                                ignoreList, numNeeded*2, bootstrappers...,
×
2871
                        )
×
2872
                        if err != nil {
×
2873
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
2874
                                        "peers: %v", err)
×
2875
                                continue
×
2876
                        }
2877

2878
                        // Finally, we'll launch a new goroutine for each
2879
                        // prospective peer candidates.
2880
                        for _, addr := range peerAddrs {
×
2881
                                epochAttempts++
×
2882

×
2883
                                go func(a *lnwire.NetAddress) {
×
2884
                                        // TODO(roasbeef): can do AS, subnet,
×
2885
                                        // country diversity, etc
×
2886
                                        errChan := make(chan error, 1)
×
2887
                                        s.connectToPeer(
×
2888
                                                a, errChan,
×
2889
                                                s.cfg.ConnectionTimeout,
×
2890
                                        )
×
2891
                                        select {
×
2892
                                        case err := <-errChan:
×
2893
                                                if err == nil {
×
2894
                                                        return
×
2895
                                                }
×
2896

2897
                                                srvrLog.Errorf("Unable to "+
×
2898
                                                        "connect to %v: %v",
×
2899
                                                        a, err)
×
2900
                                                atomic.AddUint32(&epochErrors, 1)
×
2901
                                        case <-s.quit:
×
2902
                                        }
2903
                                }(addr)
2904
                        }
2905
                case <-s.quit:
×
2906
                        return
×
2907
                }
2908
        }
2909
}
2910

2911
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
2912
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
2913
// query back off each time we encounter a failure.
2914
const bootstrapBackOffCeiling = time.Minute * 5
2915

2916
// initialPeerBootstrap attempts to continuously connect to peers on startup
2917
// until the target number of peers has been reached. This ensures that nodes
2918
// receive an up to date network view as soon as possible.
2919
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
2920
        numTargetPeers uint32,
2921
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2922

×
2923
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
2924
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
2925

×
2926
        // We'll start off by waiting 2 seconds between failed attempts, then
×
2927
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
2928
        var delaySignal <-chan time.Time
×
2929
        delayTime := time.Second * 2
×
2930

×
2931
        // As want to be more aggressive, we'll use a lower back off celling
×
2932
        // then the main peer bootstrap logic.
×
2933
        backOffCeiling := bootstrapBackOffCeiling / 5
×
2934

×
2935
        for attempts := 0; ; attempts++ {
×
2936
                // Check if the server has been requested to shut down in order
×
2937
                // to prevent blocking.
×
2938
                if s.Stopped() {
×
2939
                        return
×
2940
                }
×
2941

2942
                // We can exit our aggressive initial peer bootstrapping stage
2943
                // if we've reached out target number of peers.
2944
                s.mu.RLock()
×
2945
                numActivePeers := uint32(len(s.peersByPub))
×
2946
                s.mu.RUnlock()
×
2947

×
2948
                if numActivePeers >= numTargetPeers {
×
2949
                        return
×
2950
                }
×
2951

2952
                if attempts > 0 {
×
2953
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
2954
                                "bootstrap peers (attempt #%v)", delayTime,
×
2955
                                attempts)
×
2956

×
2957
                        // We've completed at least one iterating and haven't
×
2958
                        // finished, so we'll start to insert a delay period
×
2959
                        // between each attempt.
×
2960
                        delaySignal = time.After(delayTime)
×
2961
                        select {
×
2962
                        case <-delaySignal:
×
2963
                        case <-s.quit:
×
2964
                                return
×
2965
                        }
2966

2967
                        // After our delay, we'll double the time we wait up to
2968
                        // the max back off period.
2969
                        delayTime *= 2
×
2970
                        if delayTime > backOffCeiling {
×
2971
                                delayTime = backOffCeiling
×
2972
                        }
×
2973
                }
2974

2975
                // Otherwise, we'll request for the remaining number of peers
2976
                // in order to reach our target.
2977
                peersNeeded := numTargetPeers - numActivePeers
×
2978
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
2979
                        ignore, peersNeeded, bootstrappers...,
×
2980
                )
×
2981
                if err != nil {
×
2982
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
2983
                                "peers: %v", err)
×
2984
                        continue
×
2985
                }
2986

2987
                // Then, we'll attempt to establish a connection to the
2988
                // different peer addresses retrieved by our bootstrappers.
2989
                var wg sync.WaitGroup
×
2990
                for _, bootstrapAddr := range bootstrapAddrs {
×
2991
                        wg.Add(1)
×
2992
                        go func(addr *lnwire.NetAddress) {
×
2993
                                defer wg.Done()
×
2994

×
2995
                                errChan := make(chan error, 1)
×
2996
                                go s.connectToPeer(
×
2997
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
2998
                                )
×
2999

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

3023
                wg.Wait()
×
3024
        }
3025
}
3026

3027
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3028
// order to listen for inbound connections over Tor.
3029
func (s *server) createNewHiddenService() error {
×
3030
        // Determine the different ports the server is listening on. The onion
×
3031
        // service's virtual port will map to these ports and one will be picked
×
3032
        // at random when the onion service is being accessed.
×
3033
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3034
        for _, listenAddr := range s.listenAddrs {
×
3035
                port := listenAddr.(*net.TCPAddr).Port
×
3036
                listenPorts = append(listenPorts, port)
×
3037
        }
×
3038

3039
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3040
        if err != nil {
×
3041
                return err
×
3042
        }
×
3043

3044
        // Once the port mapping has been set, we can go ahead and automatically
3045
        // create our onion service. The service's private key will be saved to
3046
        // disk in order to regain access to this service when restarting `lnd`.
3047
        onionCfg := tor.AddOnionConfig{
×
3048
                VirtualPort: defaultPeerPort,
×
3049
                TargetPorts: listenPorts,
×
3050
                Store: tor.NewOnionFile(
×
3051
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3052
                        encrypter,
×
3053
                ),
×
3054
        }
×
3055

×
3056
        switch {
×
3057
        case s.cfg.Tor.V2:
×
3058
                onionCfg.Type = tor.V2
×
3059
        case s.cfg.Tor.V3:
×
3060
                onionCfg.Type = tor.V3
×
3061
        }
3062

3063
        addr, err := s.torController.AddOnion(onionCfg)
×
3064
        if err != nil {
×
3065
                return err
×
3066
        }
×
3067

3068
        // Now that the onion service has been created, we'll add the onion
3069
        // address it can be reached at to our list of advertised addresses.
3070
        newNodeAnn, err := s.genNodeAnnouncement(
×
3071
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3072
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3073
                },
×
3074
        )
3075
        if err != nil {
×
3076
                return fmt.Errorf("unable to generate new node "+
×
3077
                        "announcement: %v", err)
×
3078
        }
×
3079

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

3098
        return nil
×
3099
}
3100

3101
// findChannel finds a channel given a public key and ChannelID. It is an
3102
// optimization that is quicker than seeking for a channel given only the
3103
// ChannelID.
3104
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3105
        *channeldb.OpenChannel, error) {
3✔
3106

3✔
3107
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3108
        if err != nil {
3✔
3109
                return nil, err
×
3110
        }
×
3111

3112
        for _, channel := range nodeChans {
6✔
3113
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3114
                        return channel, nil
3✔
3115
                }
3✔
3116
        }
3117

3118
        return nil, fmt.Errorf("unable to find channel")
3✔
3119
}
3120

3121
// getNodeAnnouncement fetches the current, fully signed node announcement.
3122
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3123
        s.mu.Lock()
3✔
3124
        defer s.mu.Unlock()
3✔
3125

3✔
3126
        return *s.currentNodeAnn
3✔
3127
}
3✔
3128

3129
// genNodeAnnouncement generates and returns the current fully signed node
3130
// announcement. The time stamp of the announcement will be updated in order
3131
// to ensure it propagates through the network.
3132
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3133
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3134

3✔
3135
        s.mu.Lock()
3✔
3136
        defer s.mu.Unlock()
3✔
3137

3✔
3138
        // First, try to update our feature manager with the updated set of
3✔
3139
        // features.
3✔
3140
        if features != nil {
6✔
3141
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3142
                        feature.SetNodeAnn: features,
3✔
3143
                }
3✔
3144
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3145
                if err != nil {
6✔
3146
                        return lnwire.NodeAnnouncement{}, err
3✔
3147
                }
3✔
3148

3149
                // If we could successfully update our feature manager, add
3150
                // an update modifier to include these new features to our
3151
                // set.
3152
                modifiers = append(
3✔
3153
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3154
                )
3✔
3155
        }
3156

3157
        // Always update the timestamp when refreshing to ensure the update
3158
        // propagates.
3159
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3160

3✔
3161
        // Apply the requested changes to the node announcement.
3✔
3162
        for _, modifier := range modifiers {
6✔
3163
                modifier(s.currentNodeAnn)
3✔
3164
        }
3✔
3165

3166
        // Sign a new update after applying all of the passed modifiers.
3167
        err := netann.SignNodeAnnouncement(
3✔
3168
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
3✔
3169
        )
3✔
3170
        if err != nil {
3✔
3171
                return lnwire.NodeAnnouncement{}, err
×
3172
        }
×
3173

3174
        return *s.currentNodeAnn, nil
3✔
3175
}
3176

3177
// updateAndBrodcastSelfNode generates a new node announcement
3178
// applying the giving modifiers and updating the time stamp
3179
// to ensure it propagates through the network. Then it brodcasts
3180
// it to the network.
3181
func (s *server) updateAndBrodcastSelfNode(features *lnwire.RawFeatureVector,
3182
        modifiers ...netann.NodeAnnModifier) error {
3✔
3183

3✔
3184
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3185
        if err != nil {
6✔
3186
                return fmt.Errorf("unable to generate new node "+
3✔
3187
                        "announcement: %v", err)
3✔
3188
        }
3✔
3189

3190
        // Update the on-disk version of our announcement.
3191
        // Load and modify self node istead of creating anew instance so we
3192
        // don't risk overwriting any existing values.
3193
        selfNode, err := s.graphDB.SourceNode()
3✔
3194
        if err != nil {
3✔
3195
                return fmt.Errorf("unable to get current source node: %w", err)
×
3196
        }
×
3197

3198
        selfNode.HaveNodeAnnouncement = true
3✔
3199
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3200
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3201
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3202
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3203
        selfNode.Color = newNodeAnn.RGBColor
3✔
3204
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3205

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

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

3212
        // Finally, propagate it to the nodes in the network.
3213
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3214
        if err != nil {
3✔
3215
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3216
                        "announcement to peers: %v", err)
×
3217
                return err
×
3218
        }
×
3219

3220
        return nil
3✔
3221
}
3222

3223
type nodeAddresses struct {
3224
        pubKey    *btcec.PublicKey
3225
        addresses []net.Addr
3226
}
3227

3228
// establishPersistentConnections attempts to establish persistent connections
3229
// to all our direct channel collaborators. In order to promote liveness of our
3230
// active channels, we instruct the connection manager to attempt to establish
3231
// and maintain persistent connections to all our direct channel counterparties.
3232
func (s *server) establishPersistentConnections() error {
3✔
3233
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3234
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3235
        // since other PubKey forms can't be compared.
3✔
3236
        nodeAddrsMap := map[string]*nodeAddresses{}
3✔
3237

3✔
3238
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3239
        // attempt to connect to based on our set of previous connections. Set
3✔
3240
        // the reconnection port to the default peer port.
3✔
3241
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3242
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
3✔
3243
                return err
×
3244
        }
×
3245
        for _, node := range linkNodes {
6✔
3246
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3247
                nodeAddrs := &nodeAddresses{
3✔
3248
                        pubKey:    node.IdentityPub,
3✔
3249
                        addresses: node.Addresses,
3✔
3250
                }
3✔
3251
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3252
        }
3✔
3253

3254
        // After checking our previous connections for addresses to connect to,
3255
        // iterate through the nodes in our channel graph to find addresses
3256
        // that have been added via NodeAnnouncement messages.
3257
        sourceNode, err := s.graphDB.SourceNode()
3✔
3258
        if err != nil {
3✔
3259
                return err
×
3260
        }
×
3261

3262
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3263
        // each of the nodes.
3264
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
3✔
3265
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
3✔
3266
                tx kvdb.RTx,
3✔
3267
                chanInfo *models.ChannelEdgeInfo,
3✔
3268
                policy, _ *models.ChannelEdgePolicy) error {
6✔
3269

3✔
3270
                // If the remote party has announced the channel to us, but we
3✔
3271
                // haven't yet, then we won't have a policy. However, we don't
3✔
3272
                // need this to connect to the peer, so we'll log it and move on.
3✔
3273
                if policy == nil {
3✔
3274
                        srvrLog.Warnf("No channel policy found for "+
×
3275
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3276
                }
×
3277

3278
                // We'll now fetch the peer opposite from us within this
3279
                // channel so we can queue up a direct connection to them.
3280
                channelPeer, err := s.graphDB.FetchOtherNode(
3✔
3281
                        tx, chanInfo, selfPub,
3✔
3282
                )
3✔
3283
                if err != nil {
3✔
3284
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3285
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3286
                                err)
×
3287
                }
×
3288

3289
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3290

3✔
3291
                // Add all unique addresses from channel
3✔
3292
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3293
                // connect to for this peer.
3✔
3294
                addrSet := make(map[string]net.Addr)
3✔
3295
                for _, addr := range channelPeer.Addresses {
6✔
3296
                        switch addr.(type) {
3✔
3297
                        case *net.TCPAddr:
3✔
3298
                                addrSet[addr.String()] = addr
3✔
3299

3300
                        // We'll only attempt to connect to Tor addresses if Tor
3301
                        // outbound support is enabled.
3302
                        case *tor.OnionAddr:
×
3303
                                if s.cfg.Tor.Active {
×
3304
                                        addrSet[addr.String()] = addr
×
3305
                                }
×
3306
                        }
3307
                }
3308

3309
                // If this peer is also recorded as a link node, we'll add any
3310
                // additional addresses that have not already been selected.
3311
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3312
                if ok {
6✔
3313
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3314
                                switch lnAddress.(type) {
3✔
3315
                                case *net.TCPAddr:
3✔
3316
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3317

3318
                                // We'll only attempt to connect to Tor
3319
                                // addresses if Tor outbound support is enabled.
3320
                                case *tor.OnionAddr:
×
3321
                                        if s.cfg.Tor.Active {
×
3322
                                                addrSet[lnAddress.String()] = lnAddress
×
3323
                                        }
×
3324
                                }
3325
                        }
3326
                }
3327

3328
                // Construct a slice of the deduped addresses.
3329
                var addrs []net.Addr
3✔
3330
                for _, addr := range addrSet {
6✔
3331
                        addrs = append(addrs, addr)
3✔
3332
                }
3✔
3333

3334
                n := &nodeAddresses{
3✔
3335
                        addresses: addrs,
3✔
3336
                }
3✔
3337
                n.pubKey, err = channelPeer.PubKey()
3✔
3338
                if err != nil {
3✔
3339
                        return err
×
3340
                }
×
3341

3342
                nodeAddrsMap[pubStr] = n
3✔
3343
                return nil
3✔
3344
        })
3345
        if err != nil && err != channeldb.ErrGraphNoEdgesFound {
3✔
3346
                return err
×
3347
        }
×
3348

3349
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3350
                len(nodeAddrsMap))
3✔
3351

3✔
3352
        // Acquire and hold server lock until all persistent connection requests
3✔
3353
        // have been recorded and sent to the connection manager.
3✔
3354
        s.mu.Lock()
3✔
3355
        defer s.mu.Unlock()
3✔
3356

3✔
3357
        // Iterate through the combined list of addresses from prior links and
3✔
3358
        // node announcements and attempt to reconnect to each node.
3✔
3359
        var numOutboundConns int
3✔
3360
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3361
                // Add this peer to the set of peers we should maintain a
3✔
3362
                // persistent connection with. We set the value to false to
3✔
3363
                // indicate that we should not continue to reconnect if the
3✔
3364
                // number of channels returns to zero, since this peer has not
3✔
3365
                // been requested as perm by the user.
3✔
3366
                s.persistentPeers[pubStr] = false
3✔
3367
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3368
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3369
                }
3✔
3370

3371
                for _, address := range nodeAddr.addresses {
6✔
3372
                        // Create a wrapper address which couples the IP and
3✔
3373
                        // the pubkey so the brontide authenticated connection
3✔
3374
                        // can be established.
3✔
3375
                        lnAddr := &lnwire.NetAddress{
3✔
3376
                                IdentityKey: nodeAddr.pubKey,
3✔
3377
                                Address:     address,
3✔
3378
                        }
3✔
3379

3✔
3380
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3381
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3382
                }
3✔
3383

3384
                // We'll connect to the first 10 peers immediately, then
3385
                // randomly stagger any remaining connections if the
3386
                // stagger initial reconnect flag is set. This ensures
3387
                // that mobile nodes or nodes with a small number of
3388
                // channels obtain connectivity quickly, but larger
3389
                // nodes are able to disperse the costs of connecting to
3390
                // all peers at once.
3391
                if numOutboundConns < numInstantInitReconnect ||
3✔
3392
                        !s.cfg.StaggerInitialReconnect {
6✔
3393

3✔
3394
                        go s.connectToPersistentPeer(pubStr)
3✔
3395
                } else {
3✔
3396
                        go s.delayInitialReconnect(pubStr)
×
3397
                }
×
3398

3399
                numOutboundConns++
3✔
3400
        }
3401

3402
        return nil
3✔
3403
}
3404

3405
// delayInitialReconnect will attempt a reconnection to the given peer after
3406
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3407
//
3408
// NOTE: This method MUST be run as a goroutine.
3409
func (s *server) delayInitialReconnect(pubStr string) {
×
3410
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3411
        select {
×
3412
        case <-time.After(delay):
×
3413
                s.connectToPersistentPeer(pubStr)
×
3414
        case <-s.quit:
×
3415
        }
3416
}
3417

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

3✔
3424
        s.mu.Lock()
3✔
3425
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3426
                delete(s.persistentPeers, pubKeyStr)
3✔
3427
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3428
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3429
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3430
                s.mu.Unlock()
3✔
3431

3✔
3432
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3433
                        "peer has no open channels", compressedPubKey)
3✔
3434

3✔
3435
                return
3✔
3436
        }
3✔
3437
        s.mu.Unlock()
3✔
3438
}
3439

3440
// BroadcastMessage sends a request to the server to broadcast a set of
3441
// messages to all peers other than the one specified by the `skips` parameter.
3442
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3443
// the target peers.
3444
//
3445
// NOTE: This function is safe for concurrent access.
3446
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3447
        msgs ...lnwire.Message) error {
3✔
3448

3✔
3449
        // Filter out peers found in the skips map. We synchronize access to
3✔
3450
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3451
        // exact set of peers present at the time of invocation.
3✔
3452
        s.mu.RLock()
3✔
3453
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3454
        for pubStr, sPeer := range s.peersByPub {
6✔
3455
                if skips != nil {
6✔
3456
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3457
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3458
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3459
                                continue
3✔
3460
                        }
3461
                }
3462

3463
                peers = append(peers, sPeer)
3✔
3464
        }
3465
        s.mu.RUnlock()
3✔
3466

3✔
3467
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3468
        // all messages to each of peers.
3✔
3469
        var wg sync.WaitGroup
3✔
3470
        for _, sPeer := range peers {
6✔
3471
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3472
                        sPeer.PubKey())
3✔
3473

3✔
3474
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3475
                wg.Add(1)
3✔
3476
                s.wg.Add(1)
3✔
3477
                go func(p lnpeer.Peer) {
6✔
3478
                        defer s.wg.Done()
3✔
3479
                        defer wg.Done()
3✔
3480

3✔
3481
                        p.SendMessageLazy(false, msgs...)
3✔
3482
                }(sPeer)
3✔
3483
        }
3484

3485
        // Wait for all messages to have been dispatched before returning to
3486
        // caller.
3487
        wg.Wait()
3✔
3488

3✔
3489
        return nil
3✔
3490
}
3491

3492
// NotifyWhenOnline can be called by other subsystems to get notified when a
3493
// particular peer comes online. The peer itself is sent across the peerChan.
3494
//
3495
// NOTE: This function is safe for concurrent access.
3496
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3497
        peerChan chan<- lnpeer.Peer) {
3✔
3498

3✔
3499
        s.mu.Lock()
3✔
3500

3✔
3501
        // Compute the target peer's identifier.
3✔
3502
        pubStr := string(peerKey[:])
3✔
3503

3✔
3504
        // Check if peer is connected.
3✔
3505
        peer, ok := s.peersByPub[pubStr]
3✔
3506
        if ok {
6✔
3507
                // Unlock here so that the mutex isn't held while we are
3✔
3508
                // waiting for the peer to become active.
3✔
3509
                s.mu.Unlock()
3✔
3510

3✔
3511
                // Wait until the peer signals that it is actually active
3✔
3512
                // rather than only in the server's maps.
3✔
3513
                select {
3✔
3514
                case <-peer.ActiveSignal():
3✔
3515
                case <-peer.QuitSignal():
×
3516
                        // The peer quit, so we'll add the channel to the slice
×
3517
                        // and return.
×
3518
                        s.mu.Lock()
×
3519
                        s.peerConnectedListeners[pubStr] = append(
×
3520
                                s.peerConnectedListeners[pubStr], peerChan,
×
3521
                        )
×
3522
                        s.mu.Unlock()
×
3523
                        return
×
3524
                }
3525

3526
                // Connected, can return early.
3527
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3528

3✔
3529
                select {
3✔
3530
                case peerChan <- peer:
3✔
3531
                case <-s.quit:
×
3532
                }
3533

3534
                return
3✔
3535
        }
3536

3537
        // Not connected, store this listener such that it can be notified when
3538
        // the peer comes online.
3539
        s.peerConnectedListeners[pubStr] = append(
3✔
3540
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3541
        )
3✔
3542
        s.mu.Unlock()
3✔
3543
}
3544

3545
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3546
// the given public key has been disconnected. The notification is signaled by
3547
// closing the channel returned.
3548
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3549
        s.mu.Lock()
3✔
3550
        defer s.mu.Unlock()
3✔
3551

3✔
3552
        c := make(chan struct{})
3✔
3553

3✔
3554
        // If the peer is already offline, we can immediately trigger the
3✔
3555
        // notification.
3✔
3556
        peerPubKeyStr := string(peerPubKey[:])
3✔
3557
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3558
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3559
                close(c)
×
3560
                return c
×
3561
        }
×
3562

3563
        // Otherwise, the peer is online, so we'll keep track of the channel to
3564
        // trigger the notification once the server detects the peer
3565
        // disconnects.
3566
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3567
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3568
        )
3✔
3569

3✔
3570
        return c
3✔
3571
}
3572

3573
// FindPeer will return the peer that corresponds to the passed in public key.
3574
// This function is used by the funding manager, allowing it to update the
3575
// daemon's local representation of the remote peer.
3576
//
3577
// NOTE: This function is safe for concurrent access.
3578
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3579
        s.mu.RLock()
3✔
3580
        defer s.mu.RUnlock()
3✔
3581

3✔
3582
        pubStr := string(peerKey.SerializeCompressed())
3✔
3583

3✔
3584
        return s.findPeerByPubStr(pubStr)
3✔
3585
}
3✔
3586

3587
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3588
// which should be a string representation of the peer's serialized, compressed
3589
// public key.
3590
//
3591
// NOTE: This function is safe for concurrent access.
3592
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3593
        s.mu.RLock()
3✔
3594
        defer s.mu.RUnlock()
3✔
3595

3✔
3596
        return s.findPeerByPubStr(pubStr)
3✔
3597
}
3✔
3598

3599
// findPeerByPubStr is an internal method that retrieves the specified peer from
3600
// the server's internal state using.
3601
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3602
        peer, ok := s.peersByPub[pubStr]
3✔
3603
        if !ok {
6✔
3604
                return nil, ErrPeerNotConnected
3✔
3605
        }
3✔
3606

3607
        return peer, nil
3✔
3608
}
3609

3610
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3611
// exponential backoff. If no previous backoff was known, the default is
3612
// returned.
3613
func (s *server) nextPeerBackoff(pubStr string,
3614
        startTime time.Time) time.Duration {
3✔
3615

3✔
3616
        // Now, determine the appropriate backoff to use for the retry.
3✔
3617
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3618
        if !ok {
6✔
3619
                // If an existing backoff was unknown, use the default.
3✔
3620
                return s.cfg.MinBackoff
3✔
3621
        }
3✔
3622

3623
        // If the peer failed to start properly, we'll just use the previous
3624
        // backoff to compute the subsequent randomized exponential backoff
3625
        // duration. This will roughly double on average.
3626
        if startTime.IsZero() {
3✔
3627
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3628
        }
×
3629

3630
        // The peer succeeded in starting. If the connection didn't last long
3631
        // enough to be considered stable, we'll continue to back off retries
3632
        // with this peer.
3633
        connDuration := time.Since(startTime)
3✔
3634
        if connDuration < defaultStableConnDuration {
6✔
3635
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3636
        }
3✔
3637

3638
        // The peer succeed in starting and this was stable peer, so we'll
3639
        // reduce the timeout duration by the length of the connection after
3640
        // applying randomized exponential backoff. We'll only apply this in the
3641
        // case that:
3642
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3643
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3644
        if relaxedBackoff > s.cfg.MinBackoff {
×
3645
                return relaxedBackoff
×
3646
        }
×
3647

3648
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3649
        // the stable connection lasted much longer than our previous backoff.
3650
        // To reward such good behavior, we'll reconnect after the default
3651
        // timeout.
3652
        return s.cfg.MinBackoff
×
3653
}
3654

3655
// shouldDropLocalConnection determines if our local connection to a remote peer
3656
// should be dropped in the case of concurrent connection establishment. In
3657
// order to deterministically decide which connection should be dropped, we'll
3658
// utilize the ordering of the local and remote public key. If we didn't use
3659
// such a tie breaker, then we risk _both_ connections erroneously being
3660
// dropped.
3661
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3662
        localPubBytes := local.SerializeCompressed()
×
3663
        remotePubPbytes := remote.SerializeCompressed()
×
3664

×
3665
        // The connection that comes from the node with a "smaller" pubkey
×
3666
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3667
        // should drop our established connection.
×
3668
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3669
}
×
3670

3671
// InboundPeerConnected initializes a new peer in response to a new inbound
3672
// connection.
3673
//
3674
// NOTE: This function is safe for concurrent access.
3675
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
3676
        // Exit early if we have already been instructed to shutdown, this
3✔
3677
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3678
        if s.Stopped() {
3✔
3679
                return
×
3680
        }
×
3681

3682
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3683
        pubSer := nodePub.SerializeCompressed()
3✔
3684
        pubStr := string(pubSer)
3✔
3685

3✔
3686
        var pubBytes [33]byte
3✔
3687
        copy(pubBytes[:], pubSer)
3✔
3688

3✔
3689
        s.mu.Lock()
3✔
3690
        defer s.mu.Unlock()
3✔
3691

3✔
3692
        // If the remote node's public key is banned, drop the connection.
3✔
3693
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
3✔
3694
        if dcErr != nil {
3✔
3695
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3696
                        "peer: %v", dcErr)
×
3697
                conn.Close()
×
3698

×
3699
                return
×
3700
        }
×
3701

3702
        if shouldDc {
3✔
3703
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3704
                        "banned.", pubSer)
×
3705

×
3706
                conn.Close()
×
3707

×
3708
                return
×
3709
        }
×
3710

3711
        // If we already have an outbound connection to this peer, then ignore
3712
        // this new connection.
3713
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
3714
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
3715
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
3716
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3717

3✔
3718
                conn.Close()
3✔
3719
                return
3✔
3720
        }
3✔
3721

3722
        // If we already have a valid connection that is scheduled to take
3723
        // precedence once the prior peer has finished disconnecting, we'll
3724
        // ignore this connection.
3725
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
3726
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3727
                        "scheduled", conn.RemoteAddr(), p)
×
3728
                conn.Close()
×
3729
                return
×
3730
        }
×
3731

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

3✔
3734
        // Check to see if we already have a connection with this peer. If so,
3✔
3735
        // we may need to drop our existing connection. This prevents us from
3✔
3736
        // having duplicate connections to the same peer. We forgo adding a
3✔
3737
        // default case as we expect these to be the only error values returned
3✔
3738
        // from findPeerByPubStr.
3✔
3739
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
3740
        switch err {
3✔
3741
        case ErrPeerNotConnected:
3✔
3742
                // We were unable to locate an existing connection with the
3✔
3743
                // target peer, proceed to connect.
3✔
3744
                s.cancelConnReqs(pubStr, nil)
3✔
3745
                s.peerConnected(conn, nil, true)
3✔
3746

3747
        case nil:
×
3748
                // We already have a connection with the incoming peer. If the
×
3749
                // connection we've already established should be kept and is
×
3750
                // not of the same type of the new connection (inbound), then
×
3751
                // we'll close out the new connection s.t there's only a single
×
3752
                // connection between us.
×
3753
                localPub := s.identityECDH.PubKey()
×
3754
                if !connectedPeer.Inbound() &&
×
3755
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3756

×
3757
                        srvrLog.Warnf("Received inbound connection from "+
×
3758
                                "peer %v, but already have outbound "+
×
3759
                                "connection, dropping conn", connectedPeer)
×
3760
                        conn.Close()
×
3761
                        return
×
3762
                }
×
3763

3764
                // Otherwise, if we should drop the connection, then we'll
3765
                // disconnect our already connected peer.
3766
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3767
                        connectedPeer)
×
3768

×
3769
                s.cancelConnReqs(pubStr, nil)
×
3770

×
3771
                // Remove the current peer from the server's internal state and
×
3772
                // signal that the peer termination watcher does not need to
×
3773
                // execute for this peer.
×
3774
                s.removePeer(connectedPeer)
×
3775
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3776
                s.scheduledPeerConnection[pubStr] = func() {
×
3777
                        s.peerConnected(conn, nil, true)
×
3778
                }
×
3779
        }
3780
}
3781

3782
// OutboundPeerConnected initializes a new peer in response to a new outbound
3783
// connection.
3784
// NOTE: This function is safe for concurrent access.
3785
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
3786
        // Exit early if we have already been instructed to shutdown, this
3✔
3787
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3788
        if s.Stopped() {
3✔
3789
                return
×
3790
        }
×
3791

3792
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3793
        pubSer := nodePub.SerializeCompressed()
3✔
3794
        pubStr := string(pubSer)
3✔
3795

3✔
3796
        var pubBytes [33]byte
3✔
3797
        copy(pubBytes[:], pubSer)
3✔
3798

3✔
3799
        s.mu.Lock()
3✔
3800
        defer s.mu.Unlock()
3✔
3801

3✔
3802
        // If the remote node's public key is banned, drop the connection.
3✔
3803
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
3✔
3804
        if dcErr != nil {
3✔
3805
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3806
                        "peer: %v", dcErr)
×
3807
                conn.Close()
×
3808

×
3809
                return
×
3810
        }
×
3811

3812
        if shouldDc {
3✔
3813
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3814
                        "banned.", pubSer)
×
3815

×
3816
                if connReq != nil {
×
3817
                        s.connMgr.Remove(connReq.ID())
×
3818
                }
×
3819

3820
                conn.Close()
×
3821

×
3822
                return
×
3823
        }
3824

3825
        // If we already have an inbound connection to this peer, then ignore
3826
        // this new connection.
3827
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
3828
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
3829
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
3830
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3831

3✔
3832
                if connReq != nil {
6✔
3833
                        s.connMgr.Remove(connReq.ID())
3✔
3834
                }
3✔
3835
                conn.Close()
3✔
3836
                return
3✔
3837
        }
3838
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
3839
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
3840
                s.connMgr.Remove(connReq.ID())
×
3841
                conn.Close()
×
3842
                return
×
3843
        }
×
3844

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

×
3851
                if connReq != nil {
×
3852
                        s.connMgr.Remove(connReq.ID())
×
3853
                }
×
3854

3855
                conn.Close()
×
3856
                return
×
3857
        }
3858

3859
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
3✔
3860
                conn.RemoteAddr())
3✔
3861

3✔
3862
        if connReq != nil {
6✔
3863
                // A successful connection was returned by the connmgr.
3✔
3864
                // Immediately cancel all pending requests, excluding the
3✔
3865
                // outbound connection we just established.
3✔
3866
                ignore := connReq.ID()
3✔
3867
                s.cancelConnReqs(pubStr, &ignore)
3✔
3868
        } else {
6✔
3869
                // This was a successful connection made by some other
3✔
3870
                // subsystem. Remove all requests being managed by the connmgr.
3✔
3871
                s.cancelConnReqs(pubStr, nil)
3✔
3872
        }
3✔
3873

3874
        // If we already have a connection with this peer, decide whether or not
3875
        // we need to drop the stale connection. We forgo adding a default case
3876
        // as we expect these to be the only error values returned from
3877
        // findPeerByPubStr.
3878
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
3879
        switch err {
3✔
3880
        case ErrPeerNotConnected:
3✔
3881
                // We were unable to locate an existing connection with the
3✔
3882
                // target peer, proceed to connect.
3✔
3883
                s.peerConnected(conn, connReq, false)
3✔
3884

3885
        case nil:
×
3886
                // We already have a connection with the incoming peer. If the
×
3887
                // connection we've already established should be kept and is
×
3888
                // not of the same type of the new connection (outbound), then
×
3889
                // we'll close out the new connection s.t there's only a single
×
3890
                // connection between us.
×
3891
                localPub := s.identityECDH.PubKey()
×
3892
                if connectedPeer.Inbound() &&
×
3893
                        shouldDropLocalConnection(localPub, nodePub) {
×
3894

×
3895
                        srvrLog.Warnf("Established outbound connection to "+
×
3896
                                "peer %v, but already have inbound "+
×
3897
                                "connection, dropping conn", connectedPeer)
×
3898
                        if connReq != nil {
×
3899
                                s.connMgr.Remove(connReq.ID())
×
3900
                        }
×
3901
                        conn.Close()
×
3902
                        return
×
3903
                }
3904

3905
                // Otherwise, _their_ connection should be dropped. So we'll
3906
                // disconnect the peer and send the now obsolete peer to the
3907
                // server for garbage collection.
3908
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3909
                        connectedPeer)
×
3910

×
3911
                // Remove the current peer from the server's internal state and
×
3912
                // signal that the peer termination watcher does not need to
×
3913
                // execute for this peer.
×
3914
                s.removePeer(connectedPeer)
×
3915
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3916
                s.scheduledPeerConnection[pubStr] = func() {
×
3917
                        s.peerConnected(conn, connReq, false)
×
3918
                }
×
3919
        }
3920
}
3921

3922
// UnassignedConnID is the default connection ID that a request can have before
3923
// it actually is submitted to the connmgr.
3924
// TODO(conner): move into connmgr package, or better, add connmgr method for
3925
// generating atomic IDs
3926
const UnassignedConnID uint64 = 0
3927

3928
// cancelConnReqs stops all persistent connection requests for a given pubkey.
3929
// Any attempts initiated by the peerTerminationWatcher are canceled first.
3930
// Afterwards, each connection request removed from the connmgr. The caller can
3931
// optionally specify a connection ID to ignore, which prevents us from
3932
// canceling a successful request. All persistent connreqs for the provided
3933
// pubkey are discarded after the operationjw.
3934
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
3935
        // First, cancel any lingering persistent retry attempts, which will
3✔
3936
        // prevent retries for any with backoffs that are still maturing.
3✔
3937
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
3938
                close(cancelChan)
3✔
3939
                delete(s.persistentRetryCancels, pubStr)
3✔
3940
        }
3✔
3941

3942
        // Next, check to see if we have any outstanding persistent connection
3943
        // requests to this peer. If so, then we'll remove all of these
3944
        // connection requests, and also delete the entry from the map.
3945
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
3946
        if !ok {
6✔
3947
                return
3✔
3948
        }
3✔
3949

3950
        for _, connReq := range connReqs {
6✔
3951
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
3952

3✔
3953
                // Atomically capture the current request identifier.
3✔
3954
                connID := connReq.ID()
3✔
3955

3✔
3956
                // Skip any zero IDs, this indicates the request has not
3✔
3957
                // yet been schedule.
3✔
3958
                if connID == UnassignedConnID {
3✔
3959
                        continue
×
3960
                }
3961

3962
                // Skip a particular connection ID if instructed.
3963
                if skip != nil && connID == *skip {
6✔
3964
                        continue
3✔
3965
                }
3966

3967
                s.connMgr.Remove(connID)
3✔
3968
        }
3969

3970
        delete(s.persistentConnReqs, pubStr)
3✔
3971
}
3972

3973
// handleCustomMessage dispatches an incoming custom peers message to
3974
// subscribers.
3975
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
3976
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
3977
                peer, msg.Type)
3✔
3978

3✔
3979
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
3980
                Peer: peer,
3✔
3981
                Msg:  msg,
3✔
3982
        })
3✔
3983
}
3✔
3984

3985
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
3986
// messages.
3987
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
3988
        return s.customMessageServer.Subscribe()
3✔
3989
}
3✔
3990

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

3✔
3998
        brontideConn := conn.(*brontide.Conn)
3✔
3999
        addr := conn.RemoteAddr()
3✔
4000
        pubKey := brontideConn.RemotePub()
3✔
4001

3✔
4002
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4003
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4004

3✔
4005
        peerAddr := &lnwire.NetAddress{
3✔
4006
                IdentityKey: pubKey,
3✔
4007
                Address:     addr,
3✔
4008
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4009
        }
3✔
4010

3✔
4011
        // With the brontide connection established, we'll now craft the feature
3✔
4012
        // vectors to advertise to the remote node.
3✔
4013
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4014
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4015

3✔
4016
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4017
        // found, create a fresh buffer.
3✔
4018
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4019
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4020
        if !ok {
6✔
4021
                var err error
3✔
4022
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4023
                if err != nil {
3✔
4024
                        srvrLog.Errorf("unable to create peer %v", err)
×
4025
                        return
×
4026
                }
×
4027
        }
4028

4029
        // If we directly set the peer.Config TowerClient member to the
4030
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4031
        // the peer.Config's TowerClient member will not evaluate to nil even
4032
        // though the underlying value is nil. To avoid this gotcha which can
4033
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4034
        // TowerClient if needed.
4035
        var towerClient wtclient.ClientManager
3✔
4036
        if s.towerClientMgr != nil {
6✔
4037
                towerClient = s.towerClientMgr
3✔
4038
        }
3✔
4039

4040
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4041
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4042

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

3✔
4086
                        return s.genNodeAnnouncement(nil)
3✔
4087
                },
3✔
4088

4089
                PongBuf: s.pongBuf,
4090

4091
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4092

4093
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4094

4095
                FundingManager: s.fundingMgr,
4096

4097
                Hodl:                    s.cfg.Hodl,
4098
                UnsafeReplay:            s.cfg.UnsafeReplay,
4099
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4100
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4101
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4102
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4103
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4104
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4105
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4106
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4107
                HandleCustomMessage:    s.handleCustomMessage,
4108
                GetAliases:             s.aliasMgr.GetAliases,
4109
                RequestAlias:           s.aliasMgr.RequestAlias,
4110
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4111
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4112
                MaxFeeExposure:         thresholdMSats,
4113
                Quit:                   s.quit,
4114
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4115
                AuxSigner:              s.implCfg.AuxSigner,
4116
                MsgRouter:              s.implCfg.MsgRouter,
4117
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4118
        }
4119

4120
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4121
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4122

3✔
4123
        p := peer.NewBrontide(pCfg)
3✔
4124

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

3✔
4128
        s.addPeer(p)
3✔
4129

3✔
4130
        // Once we have successfully added the peer to the server, we can
3✔
4131
        // delete the previous error buffer from the server's map of error
3✔
4132
        // buffers.
3✔
4133
        delete(s.peerErrors, pkStr)
3✔
4134

3✔
4135
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4136
        // includes sending and receiving Init messages, which would be a DOS
3✔
4137
        // vector if we held the server's mutex throughout the procedure.
3✔
4138
        s.wg.Add(1)
3✔
4139
        go s.peerInitializer(p)
3✔
4140
}
4141

4142
// addPeer adds the passed peer to the server's global state of all active
4143
// peers.
4144
func (s *server) addPeer(p *peer.Brontide) {
3✔
4145
        if p == nil {
3✔
4146
                return
×
4147
        }
×
4148

4149
        // Ignore new peers if we're shutting down.
4150
        if s.Stopped() {
3✔
4151
                p.Disconnect(ErrServerShuttingDown)
×
4152
                return
×
4153
        }
×
4154

4155
        // Track the new peer in our indexes so we can quickly look it up either
4156
        // according to its public key, or its peer ID.
4157
        // TODO(roasbeef): pipe all requests through to the
4158
        // queryHandler/peerManager
4159

4160
        pubSer := p.IdentityKey().SerializeCompressed()
3✔
4161
        pubStr := string(pubSer)
3✔
4162

3✔
4163
        s.peersByPub[pubStr] = p
3✔
4164

3✔
4165
        if p.Inbound() {
6✔
4166
                s.inboundPeers[pubStr] = p
3✔
4167
        } else {
6✔
4168
                s.outboundPeers[pubStr] = p
3✔
4169
        }
3✔
4170

4171
        // Inform the peer notifier of a peer online event so that it can be reported
4172
        // to clients listening for peer events.
4173
        var pubKey [33]byte
3✔
4174
        copy(pubKey[:], pubSer)
3✔
4175

3✔
4176
        s.peerNotifier.NotifyPeerOnline(pubKey)
3✔
4177
}
4178

4179
// peerInitializer asynchronously starts a newly connected peer after it has
4180
// been added to the server's peer map. This method sets up a
4181
// peerTerminationWatcher for the given peer, and ensures that it executes even
4182
// if the peer failed to start. In the event of a successful connection, this
4183
// method reads the negotiated, local feature-bits and spawns the appropriate
4184
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4185
// be signaled of the new peer once the method returns.
4186
//
4187
// NOTE: This MUST be launched as a goroutine.
4188
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4189
        defer s.wg.Done()
3✔
4190

3✔
4191
        // Avoid initializing peers while the server is exiting.
3✔
4192
        if s.Stopped() {
3✔
4193
                return
×
4194
        }
×
4195

4196
        // Create a channel that will be used to signal a successful start of
4197
        // the link. This prevents the peer termination watcher from beginning
4198
        // its duty too early.
4199
        ready := make(chan struct{})
3✔
4200

3✔
4201
        // Before starting the peer, launch a goroutine to watch for the
3✔
4202
        // unexpected termination of this peer, which will ensure all resources
3✔
4203
        // are properly cleaned up, and re-establish persistent connections when
3✔
4204
        // necessary. The peer termination watcher will be short circuited if
3✔
4205
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4206
        // that the server has already handled the removal of this peer.
3✔
4207
        s.wg.Add(1)
3✔
4208
        go s.peerTerminationWatcher(p, ready)
3✔
4209

3✔
4210
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4211

3✔
4212
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4213
        // will unblock the peerTerminationWatcher.
3✔
4214
        if err := p.Start(); err != nil {
5✔
4215
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
2✔
4216

2✔
4217
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
2✔
4218
                return
2✔
4219
        }
2✔
4220

4221
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4222
        // was successful, and to begin watching the peer's wait group.
4223
        close(ready)
3✔
4224

3✔
4225
        s.mu.Lock()
3✔
4226
        defer s.mu.Unlock()
3✔
4227

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

3✔
4231
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4232
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4233
        pubStr := string(pubBytes)
3✔
4234
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4235
                select {
3✔
4236
                case peerChan <- p:
3✔
4237
                case <-s.quit:
1✔
4238
                        return
1✔
4239
                }
4240
        }
4241
        delete(s.peerConnectedListeners, pubStr)
3✔
4242
}
4243

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

3✔
4258
        p.WaitForDisconnect(ready)
3✔
4259

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

3✔
4262
        // If the server is exiting then we can bail out early ourselves as all
3✔
4263
        // the other sub-systems will already be shutting down.
3✔
4264
        if s.Stopped() {
6✔
4265
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
3✔
4266
                return
3✔
4267
        }
3✔
4268

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

3✔
4275
        pubKey := p.IdentityKey()
3✔
4276

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

3✔
4281
        // Tell the switch to remove all links associated with this peer.
3✔
4282
        // Passing nil as the target link indicates that all links associated
3✔
4283
        // with this interface should be closed.
3✔
4284
        //
3✔
4285
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4286
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4287
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4288
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4289
        }
×
4290

4291
        for _, link := range links {
6✔
4292
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4293
        }
3✔
4294

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

3✔
4298
        // If there were any notification requests for when this peer
3✔
4299
        // disconnected, we can trigger them now.
3✔
4300
        srvrLog.Debugf("Notifying that peer %v is offline", p)
3✔
4301
        pubStr := string(pubKey.SerializeCompressed())
3✔
4302
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4303
                close(offlineChan)
3✔
4304
        }
3✔
4305
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4306

3✔
4307
        // If the server has already removed this peer, we can short circuit the
3✔
4308
        // peer termination watcher and skip cleanup.
3✔
4309
        if _, ok := s.ignorePeerTermination[p]; ok {
3✔
4310
                delete(s.ignorePeerTermination, p)
×
4311

×
4312
                pubKey := p.PubKey()
×
4313
                pubStr := string(pubKey[:])
×
4314

×
4315
                // If a connection callback is present, we'll go ahead and
×
4316
                // execute it now that previous peer has fully disconnected. If
×
4317
                // the callback is not present, this likely implies the peer was
×
4318
                // purposefully disconnected via RPC, and that no reconnect
×
4319
                // should be attempted.
×
4320
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4321
                if ok {
×
4322
                        delete(s.scheduledPeerConnection, pubStr)
×
4323
                        connCallback()
×
4324
                }
×
4325
                return
×
4326
        }
4327

4328
        // First, cleanup any remaining state the server has regarding the peer
4329
        // in question.
4330
        s.removePeer(p)
3✔
4331

3✔
4332
        // Next, check to see if this is a persistent peer or not.
3✔
4333
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4334
                return
3✔
4335
        }
3✔
4336

4337
        // Get the last address that we used to connect to the peer.
4338
        addrs := []net.Addr{
3✔
4339
                p.NetAddress().Address,
3✔
4340
        }
3✔
4341

3✔
4342
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4343
        // reconnection purposes.
3✔
4344
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
3✔
4345
        switch {
3✔
4346
        // We found advertised addresses, so use them.
4347
        case err == nil:
3✔
4348
                addrs = advertisedAddrs
3✔
4349

4350
        // The peer doesn't have an advertised address.
4351
        case err == errNoAdvertisedAddr:
3✔
4352
                // If it is an outbound peer then we fall back to the existing
3✔
4353
                // peer address.
3✔
4354
                if !p.Inbound() {
6✔
4355
                        break
3✔
4356
                }
4357

4358
                // Fall back to the existing peer address if
4359
                // we're not accepting connections over Tor.
4360
                if s.torController == nil {
6✔
4361
                        break
3✔
4362
                }
4363

4364
                // If we are, the peer's address won't be known
4365
                // to us (we'll see a private address, which is
4366
                // the address used by our onion service to dial
4367
                // to lnd), so we don't have enough information
4368
                // to attempt a reconnect.
4369
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4370
                        "to inbound peer %v without "+
×
4371
                        "advertised address", p)
×
4372
                return
×
4373

4374
        // We came across an error retrieving an advertised
4375
        // address, log it, and fall back to the existing peer
4376
        // address.
4377
        default:
3✔
4378
                srvrLog.Errorf("Unable to retrieve advertised "+
3✔
4379
                        "address for node %x: %v", p.PubKey(),
3✔
4380
                        err)
3✔
4381
        }
4382

4383
        // Make an easy lookup map so that we can check if an address
4384
        // is already in the address list that we have stored for this peer.
4385
        existingAddrs := make(map[string]bool)
3✔
4386
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4387
                existingAddrs[addr.String()] = true
3✔
4388
        }
3✔
4389

4390
        // Add any missing addresses for this peer to persistentPeerAddr.
4391
        for _, addr := range addrs {
6✔
4392
                if existingAddrs[addr.String()] {
3✔
4393
                        continue
×
4394
                }
4395

4396
                s.persistentPeerAddrs[pubStr] = append(
3✔
4397
                        s.persistentPeerAddrs[pubStr],
3✔
4398
                        &lnwire.NetAddress{
3✔
4399
                                IdentityKey: p.IdentityKey(),
3✔
4400
                                Address:     addr,
3✔
4401
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4402
                        },
3✔
4403
                )
3✔
4404
        }
4405

4406
        // Record the computed backoff in the backoff map.
4407
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4408
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4409

3✔
4410
        // Initialize a retry canceller for this peer if one does not
3✔
4411
        // exist.
3✔
4412
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4413
        if !ok {
6✔
4414
                cancelChan = make(chan struct{})
3✔
4415
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4416
        }
3✔
4417

4418
        // We choose not to wait group this go routine since the Connect
4419
        // call can stall for arbitrarily long if we shutdown while an
4420
        // outbound connection attempt is being made.
4421
        go func() {
6✔
4422
                srvrLog.Debugf("Scheduling connection re-establishment to "+
3✔
4423
                        "persistent peer %x in %s",
3✔
4424
                        p.IdentityKey().SerializeCompressed(), backoff)
3✔
4425

3✔
4426
                select {
3✔
4427
                case <-time.After(backoff):
3✔
4428
                case <-cancelChan:
3✔
4429
                        return
3✔
4430
                case <-s.quit:
3✔
4431
                        return
3✔
4432
                }
4433

4434
                srvrLog.Debugf("Attempting to re-establish persistent "+
3✔
4435
                        "connection to peer %x",
3✔
4436
                        p.IdentityKey().SerializeCompressed())
3✔
4437

3✔
4438
                s.connectToPersistentPeer(pubStr)
3✔
4439
        }()
4440
}
4441

4442
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4443
// to connect to the peer. It creates connection requests if there are
4444
// currently none for a given address and it removes old connection requests
4445
// if the associated address is no longer in the latest address list for the
4446
// peer.
4447
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4448
        s.mu.Lock()
3✔
4449
        defer s.mu.Unlock()
3✔
4450

3✔
4451
        // Create an easy lookup map of the addresses we have stored for the
3✔
4452
        // peer. We will remove entries from this map if we have existing
3✔
4453
        // connection requests for the associated address and then any leftover
3✔
4454
        // entries will indicate which addresses we should create new
3✔
4455
        // connection requests for.
3✔
4456
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4457
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4458
                addrMap[addr.String()] = addr
3✔
4459
        }
3✔
4460

4461
        // Go through each of the existing connection requests and
4462
        // check if they correspond to the latest set of addresses. If
4463
        // there is a connection requests that does not use one of the latest
4464
        // advertised addresses then remove that connection request.
4465
        var updatedConnReqs []*connmgr.ConnReq
3✔
4466
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4467
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4468

3✔
4469
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4470
                // If the existing connection request is using one of the
4471
                // latest advertised addresses for the peer then we add it to
4472
                // updatedConnReqs and remove the associated address from
4473
                // addrMap so that we don't recreate this connReq later on.
4474
                case true:
×
4475
                        updatedConnReqs = append(
×
4476
                                updatedConnReqs, connReq,
×
4477
                        )
×
4478
                        delete(addrMap, lnAddr)
×
4479

4480
                // If the existing connection request is using an address that
4481
                // is not one of the latest advertised addresses for the peer
4482
                // then we remove the connecting request from the connection
4483
                // manager.
4484
                case false:
3✔
4485
                        srvrLog.Info(
3✔
4486
                                "Removing conn req:", connReq.Addr.String(),
3✔
4487
                        )
3✔
4488
                        s.connMgr.Remove(connReq.ID())
3✔
4489
                }
4490
        }
4491

4492
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4493

3✔
4494
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4495
        if !ok {
6✔
4496
                cancelChan = make(chan struct{})
3✔
4497
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4498
        }
3✔
4499

4500
        // Any addresses left in addrMap are new ones that we have not made
4501
        // connection requests for. So create new connection requests for those.
4502
        // If there is more than one address in the address map, stagger the
4503
        // creation of the connection requests for those.
4504
        go func() {
6✔
4505
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4506
                defer ticker.Stop()
3✔
4507

3✔
4508
                for _, addr := range addrMap {
6✔
4509
                        // Send the persistent connection request to the
3✔
4510
                        // connection manager, saving the request itself so we
3✔
4511
                        // can cancel/restart the process as needed.
3✔
4512
                        connReq := &connmgr.ConnReq{
3✔
4513
                                Addr:      addr,
3✔
4514
                                Permanent: true,
3✔
4515
                        }
3✔
4516

3✔
4517
                        s.mu.Lock()
3✔
4518
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4519
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4520
                        )
3✔
4521
                        s.mu.Unlock()
3✔
4522

3✔
4523
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4524
                                "channel peer %v", addr)
3✔
4525

3✔
4526
                        go s.connMgr.Connect(connReq)
3✔
4527

3✔
4528
                        select {
3✔
4529
                        case <-s.quit:
3✔
4530
                                return
3✔
4531
                        case <-cancelChan:
3✔
4532
                                return
3✔
4533
                        case <-ticker.C:
3✔
4534
                        }
4535
                }
4536
        }()
4537
}
4538

4539
// removePeer removes the passed peer from the server's state of all active
4540
// peers.
4541
func (s *server) removePeer(p *peer.Brontide) {
3✔
4542
        if p == nil {
3✔
4543
                return
×
4544
        }
×
4545

4546
        srvrLog.Debugf("removing peer %v", p)
3✔
4547

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

3✔
4552
        // If this peer had an active persistent connection request, remove it.
3✔
4553
        if p.ConnReq() != nil {
6✔
4554
                s.connMgr.Remove(p.ConnReq().ID())
3✔
4555
        }
3✔
4556

4557
        // Ignore deleting peers if we're shutting down.
4558
        if s.Stopped() {
3✔
4559
                return
×
4560
        }
×
4561

4562
        pKey := p.PubKey()
3✔
4563
        pubSer := pKey[:]
3✔
4564
        pubStr := string(pubSer)
3✔
4565

3✔
4566
        delete(s.peersByPub, pubStr)
3✔
4567

3✔
4568
        if p.Inbound() {
6✔
4569
                delete(s.inboundPeers, pubStr)
3✔
4570
        } else {
6✔
4571
                delete(s.outboundPeers, pubStr)
3✔
4572
        }
3✔
4573

4574
        // Copy the peer's error buffer across to the server if it has any items
4575
        // in it so that we can restore peer errors across connections.
4576
        if p.ErrorBuffer().Total() > 0 {
6✔
4577
                s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4578
        }
3✔
4579

4580
        // Inform the peer notifier of a peer offline event so that it can be
4581
        // reported to clients listening for peer events.
4582
        var pubKey [33]byte
3✔
4583
        copy(pubKey[:], pubSer)
3✔
4584

3✔
4585
        s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4586
}
4587

4588
// ConnectToPeer requests that the server connect to a Lightning Network peer
4589
// at the specified address. This function will *block* until either a
4590
// connection is established, or the initial handshake process fails.
4591
//
4592
// NOTE: This function is safe for concurrent access.
4593
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4594
        perm bool, timeout time.Duration) error {
3✔
4595

3✔
4596
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4597

3✔
4598
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
4599
        // better granularity.  In certain conditions, this method requires
3✔
4600
        // making an outbound connection to a remote peer, which requires the
3✔
4601
        // lock to be released, and subsequently reacquired.
3✔
4602
        s.mu.Lock()
3✔
4603

3✔
4604
        // Ensure we're not already connected to this peer.
3✔
4605
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4606
        if err == nil {
6✔
4607
                s.mu.Unlock()
3✔
4608
                return &errPeerAlreadyConnected{peer: peer}
3✔
4609
        }
3✔
4610

4611
        // Peer was not found, continue to pursue connection with peer.
4612

4613
        // If there's already a pending connection request for this pubkey,
4614
        // then we ignore this request to ensure we don't create a redundant
4615
        // connection.
4616
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
4617
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
4618
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
4619
        }
3✔
4620

4621
        // If there's not already a pending or active connection to this node,
4622
        // then instruct the connection manager to attempt to establish a
4623
        // persistent connection to the peer.
4624
        srvrLog.Debugf("Connecting to %v", addr)
3✔
4625
        if perm {
6✔
4626
                connReq := &connmgr.ConnReq{
3✔
4627
                        Addr:      addr,
3✔
4628
                        Permanent: true,
3✔
4629
                }
3✔
4630

3✔
4631
                // Since the user requested a permanent connection, we'll set
3✔
4632
                // the entry to true which will tell the server to continue
3✔
4633
                // reconnecting even if the number of channels with this peer is
3✔
4634
                // zero.
3✔
4635
                s.persistentPeers[targetPub] = true
3✔
4636
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
4637
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
4638
                }
3✔
4639
                s.persistentConnReqs[targetPub] = append(
3✔
4640
                        s.persistentConnReqs[targetPub], connReq,
3✔
4641
                )
3✔
4642
                s.mu.Unlock()
3✔
4643

3✔
4644
                go s.connMgr.Connect(connReq)
3✔
4645

3✔
4646
                return nil
3✔
4647
        }
4648
        s.mu.Unlock()
3✔
4649

3✔
4650
        // If we're not making a persistent connection, then we'll attempt to
3✔
4651
        // connect to the target peer. If the we can't make the connection, or
3✔
4652
        // the crypto negotiation breaks down, then return an error to the
3✔
4653
        // caller.
3✔
4654
        errChan := make(chan error, 1)
3✔
4655
        s.connectToPeer(addr, errChan, timeout)
3✔
4656

3✔
4657
        select {
3✔
4658
        case err := <-errChan:
3✔
4659
                return err
3✔
4660
        case <-s.quit:
×
4661
                return ErrServerShuttingDown
×
4662
        }
4663
}
4664

4665
// connectToPeer establishes a connection to a remote peer. errChan is used to
4666
// notify the caller if the connection attempt has failed. Otherwise, it will be
4667
// closed.
4668
func (s *server) connectToPeer(addr *lnwire.NetAddress,
4669
        errChan chan<- error, timeout time.Duration) {
3✔
4670

3✔
4671
        conn, err := brontide.Dial(
3✔
4672
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
4673
        )
3✔
4674
        if err != nil {
6✔
4675
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
4676
                select {
3✔
4677
                case errChan <- err:
3✔
4678
                case <-s.quit:
×
4679
                }
4680
                return
3✔
4681
        }
4682

4683
        close(errChan)
3✔
4684

3✔
4685
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
4686
                conn.LocalAddr(), conn.RemoteAddr())
3✔
4687

3✔
4688
        s.OutboundPeerConnected(nil, conn)
3✔
4689
}
4690

4691
// DisconnectPeer sends the request to server to close the connection with peer
4692
// identified by public key.
4693
//
4694
// NOTE: This function is safe for concurrent access.
4695
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
4696
        pubBytes := pubKey.SerializeCompressed()
3✔
4697
        pubStr := string(pubBytes)
3✔
4698

3✔
4699
        s.mu.Lock()
3✔
4700
        defer s.mu.Unlock()
3✔
4701

3✔
4702
        // Check that were actually connected to this peer. If not, then we'll
3✔
4703
        // exit in an error as we can't disconnect from a peer that we're not
3✔
4704
        // currently connected to.
3✔
4705
        peer, err := s.findPeerByPubStr(pubStr)
3✔
4706
        if err == ErrPeerNotConnected {
6✔
4707
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
4708
        }
3✔
4709

4710
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
4711

3✔
4712
        s.cancelConnReqs(pubStr, nil)
3✔
4713

3✔
4714
        // If this peer was formerly a persistent connection, then we'll remove
3✔
4715
        // them from this map so we don't attempt to re-connect after we
3✔
4716
        // disconnect.
3✔
4717
        delete(s.persistentPeers, pubStr)
3✔
4718
        delete(s.persistentPeersBackoff, pubStr)
3✔
4719

3✔
4720
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
4721
        // removePeer, which bypassed the peerTerminationWatcher.
3✔
4722
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
4723

3✔
4724
        return nil
3✔
4725
}
4726

4727
// OpenChannel sends a request to the server to open a channel to the specified
4728
// peer identified by nodeKey with the passed channel funding parameters.
4729
//
4730
// NOTE: This function is safe for concurrent access.
4731
func (s *server) OpenChannel(
4732
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
4733

3✔
4734
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
4735
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
4736
        // not blocked if the caller is not reading the updates.
3✔
4737
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
4738
        req.Err = make(chan error, 1)
3✔
4739

3✔
4740
        // First attempt to locate the target peer to open a channel with, if
3✔
4741
        // we're unable to locate the peer then this request will fail.
3✔
4742
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
4743
        s.mu.RLock()
3✔
4744
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
4745
        if !ok {
3✔
4746
                s.mu.RUnlock()
×
4747

×
4748
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4749
                return req.Updates, req.Err
×
4750
        }
×
4751
        req.Peer = peer
3✔
4752
        s.mu.RUnlock()
3✔
4753

3✔
4754
        // We'll wait until the peer is active before beginning the channel
3✔
4755
        // opening process.
3✔
4756
        select {
3✔
4757
        case <-peer.ActiveSignal():
3✔
4758
        case <-peer.QuitSignal():
×
4759
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
4760
                return req.Updates, req.Err
×
4761
        case <-s.quit:
×
4762
                req.Err <- ErrServerShuttingDown
×
4763
                return req.Updates, req.Err
×
4764
        }
4765

4766
        // If the fee rate wasn't specified at this point we fail the funding
4767
        // because of the missing fee rate information. The caller of the
4768
        // `OpenChannel` method needs to make sure that default values for the
4769
        // fee rate are set beforehand.
4770
        if req.FundingFeePerKw == 0 {
3✔
4771
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
4772
                        "the channel opening transaction")
×
4773

×
4774
                return req.Updates, req.Err
×
4775
        }
×
4776

4777
        // Spawn a goroutine to send the funding workflow request to the funding
4778
        // manager. This allows the server to continue handling queries instead
4779
        // of blocking on this request which is exported as a synchronous
4780
        // request to the outside world.
4781
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
4782

3✔
4783
        return req.Updates, req.Err
3✔
4784
}
4785

4786
// Peers returns a slice of all active peers.
4787
//
4788
// NOTE: This function is safe for concurrent access.
4789
func (s *server) Peers() []*peer.Brontide {
3✔
4790
        s.mu.RLock()
3✔
4791
        defer s.mu.RUnlock()
3✔
4792

3✔
4793
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
4794
        for _, peer := range s.peersByPub {
6✔
4795
                peers = append(peers, peer)
3✔
4796
        }
3✔
4797

4798
        return peers
3✔
4799
}
4800

4801
// computeNextBackoff uses a truncated exponential backoff to compute the next
4802
// backoff using the value of the exiting backoff. The returned duration is
4803
// randomized in either direction by 1/20 to prevent tight loops from
4804
// stabilizing.
4805
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
4806
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
4807
        nextBackoff := 2 * currBackoff
3✔
4808
        if nextBackoff > maxBackoff {
6✔
4809
                nextBackoff = maxBackoff
3✔
4810
        }
3✔
4811

4812
        // Using 1/10 of our duration as a margin, compute a random offset to
4813
        // avoid the nodes entering connection cycles.
4814
        margin := nextBackoff / 10
3✔
4815

3✔
4816
        var wiggle big.Int
3✔
4817
        wiggle.SetUint64(uint64(margin))
3✔
4818
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
4819
                // Randomizing is not mission critical, so we'll just return the
×
4820
                // current backoff.
×
4821
                return nextBackoff
×
4822
        }
×
4823

4824
        // Otherwise add in our wiggle, but subtract out half of the margin so
4825
        // that the backoff can tweaked by 1/20 in either direction.
4826
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
4827
}
4828

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

4833
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
4834
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
3✔
4835
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
4836
        if err != nil {
3✔
4837
                return nil, err
×
4838
        }
×
4839

4840
        node, err := s.graphDB.FetchLightningNode(vertex)
3✔
4841
        if err != nil {
6✔
4842
                return nil, err
3✔
4843
        }
3✔
4844

4845
        if len(node.Addresses) == 0 {
6✔
4846
                return nil, errNoAdvertisedAddr
3✔
4847
        }
3✔
4848

4849
        return node.Addresses, nil
3✔
4850
}
4851

4852
// fetchLastChanUpdate returns a function which is able to retrieve our latest
4853
// channel update for a target channel.
4854
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
4855
        *lnwire.ChannelUpdate1, error) {
3✔
4856

3✔
4857
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
4858
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
4859
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
4860
                if err != nil {
6✔
4861
                        return nil, err
3✔
4862
                }
3✔
4863

4864
                return netann.ExtractChannelUpdate(
3✔
4865
                        ourPubKey[:], info, edge1, edge2,
3✔
4866
                )
3✔
4867
        }
4868
}
4869

4870
// applyChannelUpdate applies the channel update to the different sub-systems of
4871
// the server. The useAlias boolean denotes whether or not to send an alias in
4872
// place of the real SCID.
4873
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
4874
        op *wire.OutPoint, useAlias bool) error {
3✔
4875

3✔
4876
        var (
3✔
4877
                peerAlias    *lnwire.ShortChannelID
3✔
4878
                defaultAlias lnwire.ShortChannelID
3✔
4879
        )
3✔
4880

3✔
4881
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
4882

3✔
4883
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
4884
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
4885
        if useAlias {
6✔
4886
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
4887
                if foundAlias != defaultAlias {
6✔
4888
                        peerAlias = &foundAlias
3✔
4889
                }
3✔
4890
        }
4891

4892
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
4893
                update, discovery.RemoteAlias(peerAlias),
3✔
4894
        )
3✔
4895
        select {
3✔
4896
        case err := <-errChan:
3✔
4897
                return err
3✔
4898
        case <-s.quit:
×
4899
                return ErrServerShuttingDown
×
4900
        }
4901
}
4902

4903
// SendCustomMessage sends a custom message to the peer with the specified
4904
// pubkey.
4905
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
4906
        data []byte) error {
3✔
4907

3✔
4908
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
4909
        if err != nil {
3✔
4910
                return err
×
4911
        }
×
4912

4913
        // We'll wait until the peer is active.
4914
        select {
3✔
4915
        case <-peer.ActiveSignal():
3✔
4916
        case <-peer.QuitSignal():
×
4917
                return fmt.Errorf("peer %x disconnected", peerPub)
×
4918
        case <-s.quit:
×
4919
                return ErrServerShuttingDown
×
4920
        }
4921

4922
        msg, err := lnwire.NewCustom(msgType, data)
3✔
4923
        if err != nil {
6✔
4924
                return err
3✔
4925
        }
3✔
4926

4927
        // Send the message as low-priority. For now we assume that all
4928
        // application-defined message are low priority.
4929
        return peer.SendMessageLazy(true, msg)
3✔
4930
}
4931

4932
// newSweepPkScriptGen creates closure that generates a new public key script
4933
// which should be used to sweep any funds into the on-chain wallet.
4934
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
4935
// (p2wkh) output.
4936
func newSweepPkScriptGen(
4937
        wallet lnwallet.WalletController) func() ([]byte, error) {
3✔
4938

3✔
4939
        return func() ([]byte, error) {
6✔
4940
                sweepAddr, err := wallet.NewAddress(
3✔
4941
                        lnwallet.TaprootPubkey, false,
3✔
4942
                        lnwallet.DefaultAccountName,
3✔
4943
                )
3✔
4944
                if err != nil {
3✔
4945
                        return nil, err
×
4946
                }
×
4947

4948
                return txscript.PayToAddrScript(sweepAddr)
3✔
4949
        }
4950
}
4951

4952
// shouldPeerBootstrap returns true if we should attempt to perform peer
4953
// bootstrapping to actively seek our peers using the set of active network
4954
// bootstrappers.
4955
func shouldPeerBootstrap(cfg *Config) bool {
9✔
4956
        isSimnet := cfg.Bitcoin.SimNet
9✔
4957
        isSignet := cfg.Bitcoin.SigNet
9✔
4958
        isRegtest := cfg.Bitcoin.RegTest
9✔
4959
        isDevNetwork := isSimnet || isSignet || isRegtest
9✔
4960

9✔
4961
        // TODO(yy): remove the check on simnet/regtest such that the itest is
9✔
4962
        // covering the bootstrapping process.
9✔
4963
        return !cfg.NoNetBootstrap && !isDevNetwork
9✔
4964
}
9✔
4965

4966
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
4967
// finished.
4968
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
4969
        // Get a list of closed channels.
3✔
4970
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
4971
        if err != nil {
3✔
4972
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
4973
                return nil
×
4974
        }
×
4975

4976
        // Save the SCIDs in a map.
4977
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
4978
        for _, c := range channels {
6✔
4979
                // If the channel is not pending, its FC has been finalized.
3✔
4980
                if !c.IsPending {
6✔
4981
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
4982
                }
3✔
4983
        }
4984

4985
        // Double check whether the reported closed channel has indeed finished
4986
        // closing.
4987
        //
4988
        // NOTE: There are misalignments regarding when a channel's FC is
4989
        // marked as finalized. We double check the pending channels to make
4990
        // sure the returned SCIDs are indeed terminated.
4991
        //
4992
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
4993
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
4994
        if err != nil {
3✔
4995
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
4996
                return nil
×
4997
        }
×
4998

4999
        for _, c := range pendings {
6✔
5000
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5001
                        continue
3✔
5002
                }
5003

5004
                // If the channel is still reported as pending, remove it from
5005
                // the map.
5006
                delete(closedSCIDs, c.ShortChannelID)
×
5007

×
5008
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5009
                        c.ShortChannelID)
×
5010
        }
5011

5012
        return closedSCIDs
3✔
5013
}
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