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

lightningnetwork / lnd / 10426952143

16 Aug 2024 10:17PM UTC coverage: 49.856% (+0.01%) from 49.843%
10426952143

Pull #8512

github

Roasbeef
lnwallet/chancloser: add unit tests for new rbf coop close
Pull Request #8512: [3/4] - lnwallet/chancloser: add new protofsm based RBF chan closer

6 of 1064 new or added lines in 6 files covered. (0.56%)

159 existing lines in 21 files now uncovered.

96167 of 192890 relevant lines covered (49.86%)

1.55 hits per line

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

63.82
/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
        channelNotifier *channelnotifier.ChannelNotifier
267

268
        peerNotifier *peernotifier.PeerNotifier
269

270
        htlcNotifier *htlcswitch.HtlcNotifier
271

272
        witnessBeacon contractcourt.WitnessBeacon
273

274
        breachArbitrator *contractcourt.BreachArbitrator
275

276
        missionControl *routing.MissionControl
277

278
        graphBuilder *graph.Builder
279

280
        chanRouter *routing.ChannelRouter
281

282
        controlTower routing.ControlTower
283

284
        authGossiper *discovery.AuthenticatedGossiper
285

286
        localChanMgr *localchans.Manager
287

288
        utxoNursery *contractcourt.UtxoNursery
289

290
        sweeper *sweep.UtxoSweeper
291

292
        chainArb *contractcourt.ChainArbitrator
293

294
        sphinx *hop.OnionProcessor
295

296
        towerClientMgr *wtclient.Manager
297

298
        connMgr *connmgr.ConnManager
299

300
        sigPool *lnwallet.SigPool
301

302
        writePool *pool.Write
303

304
        readPool *pool.Read
305

306
        tlsManager *TLSManager
307

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

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

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

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

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

330
        hostAnn *netann.HostAnnouncer
331

332
        // livenessMonitor monitors that lnd has access to critical resources.
333
        livenessMonitor *healthcheck.Monitor
334

335
        customMessageServer *subscribe.Server
336

337
        // txPublisher is a publisher with fee-bumping capability.
338
        txPublisher *sweep.TxPublisher
339

340
        quit chan struct{}
341

342
        wg sync.WaitGroup
343
}
344

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

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

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

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

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

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

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

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

400
                                        s.mu.Lock()
3✔
401

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

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

416
                                        s.mu.Unlock()
3✔
417

3✔
418
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
419
                                }
420
                        }
421
                }
422
        }()
423

424
        return nil
3✔
425
}
426

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

432
        // Msg is the custom wire message.
433
        Msg *lnwire.Custom
434
}
435

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
589
                channelNotifier: channelnotifier.New(
3✔
590
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
591
                ),
3✔
592

3✔
593
                identityECDH:   nodeKeyECDH,
3✔
594
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
595
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
596

3✔
597
                listenAddrs: listenAddrs,
3✔
598

3✔
599
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
600
                // schedule
3✔
601
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
602

3✔
603
                torController: torController,
3✔
604

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

3✔
615
                peersByPub:                make(map[string]*peer.Brontide),
3✔
616
                inboundPeers:              make(map[string]*peer.Brontide),
3✔
617
                outboundPeers:             make(map[string]*peer.Brontide),
3✔
618
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
3✔
619
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
3✔
620

3✔
621
                customMessageServer: subscribe.NewServer(),
3✔
622

3✔
623
                tlsManager: tlsManager,
3✔
624

3✔
625
                featureMgr: featureMgr,
3✔
626
                quit:       make(chan struct{}),
3✔
627
        }
3✔
628

3✔
629
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
630
        if err != nil {
3✔
631
                return nil, err
×
632
        }
×
633

634
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
635
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
636
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
637
        )
3✔
638
        s.invoices = invoices.NewRegistry(
3✔
639
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
640
        )
3✔
641

3✔
642
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
643

3✔
644
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
645
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
646

3✔
647
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB)
3✔
648
        if err != nil {
3✔
649
                return nil, err
×
650
        }
×
651

652
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
653
                DB:                   dbs.ChanStateDB,
3✔
654
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
655
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
656
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
657
                LocalChannelClose: func(pubKey []byte,
3✔
658
                        request *htlcswitch.ChanClose) {
6✔
659

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

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

704
        s.witnessBeacon = newPreimageBeacon(
3✔
705
                dbs.ChanStateDB.NewWitnessCache(),
3✔
706
                s.interceptableSwitch.ForwardPacket,
3✔
707
        )
3✔
708

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

3✔
722
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
723
        if err != nil {
3✔
724
                return nil, err
×
725
        }
×
726
        s.chanStatusMgr = chanStatusMgr
3✔
727

3✔
728
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
729
        // port forwarding for users behind a NAT.
3✔
730
        if cfg.NAT {
3✔
731
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
732

×
733
                discoveryTimeout := time.Duration(10 * time.Second)
×
734

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

×
749
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
750
                                "enabled device")
×
751

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

761
                        s.natTraversal = pmp
×
762
                }
763
        }
764

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

×
780
                        listenPorts = append(listenPorts, uint16(port))
×
781
                }
×
782

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

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

806
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
3✔
807
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
808

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

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

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

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

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

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

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

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

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

3✔
904
                        estimator, err = routing.NewAprioriEstimator(
3✔
905
                                aprioriConfig,
3✔
906
                        )
3✔
907
                        if err != nil {
3✔
908
                                return nil, err
×
909
                        }
×
910

911
                case routing.BimodalEstimatorName:
×
912
                        bCfg := routingConfig.BimodalConfig
×
913
                        bimodalConfig := routing.BimodalConfig{
×
914
                                BimodalNodeWeight: bCfg.NodeWeight,
×
915
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
916
                                        bCfg.Scale,
×
917
                                ),
×
918
                                BimodalDecayTime: bCfg.DecayTime,
×
919
                        }
×
920

×
921
                        estimator, err = routing.NewBimodalEstimator(
×
922
                                bimodalConfig,
×
923
                        )
×
924
                        if err != nil {
×
925
                                return nil, err
×
926
                        }
×
927

928
                default:
×
929
                        return nil, fmt.Errorf("unknown estimator type %v",
×
930
                                routingConfig.ProbabilityEstimatorType)
×
931
                }
932
        }
933

934
        mcCfg := &routing.MissionControlConfig{
3✔
935
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
936
                Estimator:               estimator,
3✔
937
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
938
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
939
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
940
        }
3✔
941
        s.missionControl, err = routing.NewMissionControl(
3✔
942
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
3✔
943
        )
3✔
944
        if err != nil {
3✔
945
                return nil, fmt.Errorf("can't create mission control: %w", err)
×
946
        }
×
947

948
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
949
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
950
                int64(routingConfig.AttemptCost),
3✔
951
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
952
                routingConfig.MinRouteProbability)
3✔
953

3✔
954
        pathFindingConfig := routing.PathFindingConfig{
3✔
955
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
956
                        routingConfig.AttemptCost,
3✔
957
                ),
3✔
958
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
959
                MinProbability: routingConfig.MinRouteProbability,
3✔
960
        }
3✔
961

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

3✔
976
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
977

3✔
978
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
979

3✔
980
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
981
                cfg.Routing.StrictZombiePruning
3✔
982

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

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

1019
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1020
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1021
        if err != nil {
3✔
1022
                return nil, err
×
1023
        }
×
1024
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1025
        if err != nil {
3✔
1026
                return nil, err
×
1027
        }
×
1028

1029
        s.authGossiper = discovery.New(discovery.Config{
3✔
1030
                Graph:                 s.graphBuilder,
3✔
1031
                Notifier:              s.cc.ChainNotifier,
3✔
1032
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1033
                Broadcast:             s.BroadcastMessage,
3✔
1034
                ChanSeries:            chanSeries,
3✔
1035
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1036
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1037
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1038
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1039
                        error) {
3✔
1040

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

1068
        //nolint:lll
1069
        s.localChanMgr = &localchans.Manager{
3✔
1070
                ForAllOutgoingChannels:    s.graphBuilder.ForAllOutgoingChannels,
3✔
1071
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
3✔
1072
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
3✔
1073
                FetchChannel:              s.chanStateDB.FetchChannel,
3✔
1074
        }
3✔
1075

3✔
1076
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1077
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1078
        )
3✔
1079
        if err != nil {
3✔
1080
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1081
                return nil, err
×
1082
        }
×
1083

1084
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1085
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1086
        )
3✔
1087
        if err != nil {
3✔
1088
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1089
                return nil, err
×
1090
        }
×
1091

1092
        aggregator := sweep.NewBudgetAggregator(
3✔
1093
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1094
        )
3✔
1095

3✔
1096
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1097
                Signer:    cc.Wallet.Cfg.Signer,
3✔
1098
                Wallet:    cc.Wallet,
3✔
1099
                Estimator: cc.FeeEstimator,
3✔
1100
                Notifier:  cc.ChainNotifier,
3✔
1101
        })
3✔
1102

3✔
1103
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1104
                FeeEstimator:         cc.FeeEstimator,
3✔
1105
                GenSweepScript:       newSweepPkScriptGen(cc.Wallet),
3✔
1106
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1107
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1108
                Mempool:              cc.MempoolNotifier,
3✔
1109
                Notifier:             cc.ChainNotifier,
3✔
1110
                Store:                sweeperStore,
3✔
1111
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1112
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1113
                Aggregator:           aggregator,
3✔
1114
                Publisher:            s.txPublisher,
3✔
1115
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1116
        })
3✔
1117

3✔
1118
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1119
                ChainIO:             cc.ChainIO,
3✔
1120
                ConfDepth:           1,
3✔
1121
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1122
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1123
                Notifier:            cc.ChainNotifier,
3✔
1124
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1125
                Store:               utxnStore,
3✔
1126
                SweepInput:          s.sweeper.SweepInput,
3✔
1127
                Budget:              s.cfg.Sweeper.Budget,
3✔
1128
        })
3✔
1129

3✔
1130
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1131
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1132
                closureType contractcourt.ChannelCloseType) {
6✔
1133
                // TODO(conner): Properly respect the update and error channels
3✔
1134
                // returned by CloseLink.
3✔
1135

3✔
1136
                // Instruct the switch to close the channel.  Provide no close out
3✔
1137
                // delivery script or target fee per kw because user input is not
3✔
1138
                // available when the remote peer closes the channel.
3✔
1139
                s.htlcSwitch.CloseLink(chanPoint, closureType, 0, 0, nil)
3✔
1140
        }
3✔
1141

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

3✔
1146
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1147
                &contractcourt.BreachConfig{
3✔
1148
                        CloseLink:          closeLink,
3✔
1149
                        DB:                 s.chanStateDB,
3✔
1150
                        Estimator:          s.cc.FeeEstimator,
3✔
1151
                        GenSweepScript:     newSweepPkScriptGen(cc.Wallet),
3✔
1152
                        Notifier:           cc.ChainNotifier,
3✔
1153
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1154
                        ContractBreaches:   contractBreaches,
3✔
1155
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1156
                        Store: contractcourt.NewRetributionStore(
3✔
1157
                                dbs.ChanStateDB,
3✔
1158
                        ),
3✔
1159
                },
3✔
1160
        )
3✔
1161

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

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

3✔
1204
                        // processACK will handle the BreachArbitrator ACKing
3✔
1205
                        // the event.
3✔
1206
                        finalErr := make(chan error, 1)
3✔
1207
                        processACK := func(brarErr error) {
6✔
1208
                                if brarErr != nil {
3✔
1209
                                        finalErr <- brarErr
×
1210
                                        return
×
1211
                                }
×
1212

1213
                                // If the BreachArbitrator successfully handled
1214
                                // the event, we can signal that the handoff
1215
                                // was successful.
1216
                                finalErr <- nil
3✔
1217
                        }
1218

1219
                        event := &contractcourt.ContractBreachEvent{
3✔
1220
                                ChanPoint:         chanPoint,
3✔
1221
                                ProcessACK:        processACK,
3✔
1222
                                BreachRetribution: breachRet,
3✔
1223
                        }
3✔
1224

3✔
1225
                        // Send the contract breach event to the
3✔
1226
                        // BreachArbitrator.
3✔
1227
                        select {
3✔
1228
                        case contractBreaches <- event:
3✔
1229
                        case <-s.quit:
×
1230
                                return ErrServerShuttingDown
×
1231
                        }
1232

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

1258
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1259
                QueryIncomingCircuit: func(
1260
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1261

3✔
1262
                        // Get the circuit map.
3✔
1263
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1264

3✔
1265
                        // Lookup the outgoing circuit.
3✔
1266
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1267
                        if pc == nil {
6✔
1268
                                return nil
3✔
1269
                        }
3✔
1270

1271
                        return &pc.Incoming
3✔
1272
                },
1273
        }, dbs.ChanStateDB)
1274

1275
        // Select the configuration and funding parameters for Bitcoin.
1276
        chainCfg := cfg.Bitcoin
3✔
1277
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1278
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1279

3✔
1280
        var chanIDSeed [32]byte
3✔
1281
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1282
                return nil, err
×
1283
        }
×
1284

1285
        // Wrap the DeleteChannelEdges method so that the funding manager can
1286
        // use it without depending on several layers of indirection.
1287
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1288
                *models.ChannelEdgePolicy, error) {
6✔
1289

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

1303
                // Grab our key to find our policy.
1304
                var ourKey [33]byte
3✔
1305
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1306

3✔
1307
                var ourPolicy *models.ChannelEdgePolicy
3✔
1308
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1309
                        ourPolicy = e1
3✔
1310
                } else {
6✔
1311
                        ourPolicy = e2
3✔
1312
                }
3✔
1313

1314
                if ourPolicy == nil {
3✔
1315
                        // Something is wrong, so return an error.
×
1316
                        return nil, fmt.Errorf("we don't have an edge")
×
1317
                }
×
1318

1319
                err = s.graphDB.DeleteChannelEdges(
3✔
1320
                        false, false, scid.ToUint64(),
3✔
1321
                )
3✔
1322
                return ourPolicy, err
3✔
1323
        }
1324

1325
        // For the reservationTimeout and the zombieSweeperInterval different
1326
        // values are set in case we are in a dev environment so enhance test
1327
        // capacilities.
1328
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1329
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1330

3✔
1331
        // Get the development config for funding manager. If we are not in
3✔
1332
        // development mode, this would be nil.
3✔
1333
        var devCfg *funding.DevConfig
3✔
1334
        if lncfg.IsDevBuild() {
6✔
1335
                devCfg = &funding.DevConfig{
3✔
1336
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1337
                }
3✔
1338

3✔
1339
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1340
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1341

3✔
1342
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1343
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1344
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1345
        }
3✔
1346

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

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

3✔
1385
                        // In case the user has explicitly specified
3✔
1386
                        // a default value for the number of
3✔
1387
                        // confirmations, we use it.
3✔
1388
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1389
                        if defaultConf != 0 {
6✔
1390
                                return defaultConf
3✔
1391
                        }
3✔
1392

1393
                        minConf := uint64(3)
×
1394
                        maxConf := uint64(6)
×
1395

×
1396
                        // If this is a wumbo channel, then we'll require the
×
1397
                        // max amount of confirmations.
×
1398
                        if chanAmt > MaxFundingAmount {
×
1399
                                return uint16(maxConf)
×
1400
                        }
×
1401

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

3✔
1424
                        // In case the user has explicitly specified
3✔
1425
                        // a default value for the remote delay, we
3✔
1426
                        // use it.
3✔
1427
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1428
                        if defaultDelay > 0 {
6✔
1429
                                return defaultDelay
3✔
1430
                        }
3✔
1431

1432
                        // If this is a wumbo channel, then we'll require the
1433
                        // max value.
1434
                        if chanAmt > MaxFundingAmount {
×
1435
                                return maxRemoteDelay
×
1436
                        }
×
1437

1438
                        // If not we scale according to channel size.
1439
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1440
                                chanAmt / MaxFundingAmount)
×
1441
                        if delay < minRemoteDelay {
×
1442
                                delay = minRemoteDelay
×
1443
                        }
×
1444
                        if delay > maxRemoteDelay {
×
1445
                                delay = maxRemoteDelay
×
1446
                        }
×
1447
                        return delay
×
1448
                },
1449
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1450
                        peerKey *btcec.PublicKey) error {
3✔
1451

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

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

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

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

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

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

1545
        // Assemble a peer notifier which will provide clients with subscriptions
1546
        // to peer online and offline events.
1547
        s.peerNotifier = peernotifier.New()
3✔
1548

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

1564
        if cfg.WtClient.Active {
6✔
1565
                policy := wtpolicy.DefaultPolicy()
3✔
1566
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1567

3✔
1568
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1569
                // protocol operations on sat/kw.
3✔
1570
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1571
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1572
                )
3✔
1573

3✔
1574
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1575

3✔
1576
                if err := policy.Validate(); err != nil {
3✔
1577
                        return nil, err
×
1578
                }
×
1579

1580
                // authDial is the wrapper around the btrontide.Dial for the
1581
                // watchtower.
1582
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1583
                        netAddr *lnwire.NetAddress,
3✔
1584
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1585

3✔
1586
                        return brontide.Dial(
3✔
1587
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1588
                        )
3✔
1589
                }
3✔
1590

1591
                // buildBreachRetribution is a call-back that can be used to
1592
                // query the BreachRetribution info and channel type given a
1593
                // channel ID and commitment height.
1594
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1595
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1596
                        channeldb.ChannelType, error) {
6✔
1597

3✔
1598
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1599
                                nil, chanID,
3✔
1600
                        )
3✔
1601
                        if err != nil {
3✔
1602
                                return nil, 0, err
×
1603
                        }
×
1604

1605
                        br, err := lnwallet.NewBreachRetribution(
3✔
1606
                                channel, commitHeight, 0, nil,
3✔
1607
                        )
3✔
1608
                        if err != nil {
3✔
1609
                                return nil, 0, err
×
1610
                        }
×
1611

1612
                        return br, channel.ChanType, nil
3✔
1613
                }
1614

1615
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1616

3✔
1617
                // Copy the policy for legacy channels and set the blob flag
3✔
1618
                // signalling support for anchor channels.
3✔
1619
                anchorPolicy := policy
3✔
1620
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1621

3✔
1622
                // Copy the policy for legacy channels and set the blob flag
3✔
1623
                // signalling support for taproot channels.
3✔
1624
                taprootPolicy := policy
3✔
1625
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1626
                        blob.FlagTaprootChannel,
3✔
1627
                )
3✔
1628

3✔
1629
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1630
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1631
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1632
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1633
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1634
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1635
                                error) {
6✔
1636

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

1656
        if len(cfg.ExternalHosts) != 0 {
3✔
1657
                advertisedIPs := make(map[string]struct{})
×
1658
                for _, addr := range s.currentNodeAnn.Addresses {
×
1659
                        advertisedIPs[addr.String()] = struct{}{}
×
1660
                }
×
1661

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

×
1676
                                        return s.genNodeAnnouncement(
×
1677
                                                nil, modifier...,
×
1678
                                        )
×
1679
                                }),
×
1680
                })
1681
        }
1682

1683
        // Create liveness monitor.
1684
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1685

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

3✔
1704
        return s, nil
3✔
1705
}
1706

1707
// UpdateRoutingConfig is a callback function to update the routing config
1708
// values in the main cfg.
1709
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1710
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1711

3✔
1712
        switch c := cfg.Estimator.Config().(type) {
3✔
1713
        case routing.AprioriConfig:
3✔
1714
                routerCfg.ProbabilityEstimatorType =
3✔
1715
                        routing.AprioriEstimatorName
3✔
1716

3✔
1717
                targetCfg := routerCfg.AprioriConfig
3✔
1718
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1719
                targetCfg.Weight = c.AprioriWeight
3✔
1720
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1721
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1722

1723
        case routing.BimodalConfig:
3✔
1724
                routerCfg.ProbabilityEstimatorType =
3✔
1725
                        routing.BimodalEstimatorName
3✔
1726

3✔
1727
                targetCfg := routerCfg.BimodalConfig
3✔
1728
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1729
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1730
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1731
        }
1732

1733
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1734
}
1735

1736
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1737
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1738
// may differ from what is on disk.
1739
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate) (*ecdsa.Signature,
1740
        error) {
3✔
1741

3✔
1742
        data, err := u.DataToSign()
3✔
1743
        if err != nil {
3✔
1744
                return nil, err
×
1745
        }
×
1746

1747
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1748
}
1749

1750
// createLivenessMonitor creates a set of health checks using our configured
1751
// values and uses these checks to create a liveness monitor. Available
1752
// health checks,
1753
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1754
//   - diskCheck
1755
//   - tlsHealthCheck
1756
//   - torController, only created when tor is enabled.
1757
//
1758
// If a health check has been disabled by setting attempts to 0, our monitor
1759
// will not run it.
1760
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1761
        leaderElector cluster.LeaderElector) {
3✔
1762

3✔
1763
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
1764
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
1765
                srvrLog.Info("Disabling chain backend checks for " +
×
1766
                        "nochainbackend mode")
×
1767

×
1768
                chainBackendAttempts = 0
×
1769
        }
×
1770

1771
        chainHealthCheck := healthcheck.NewObservation(
3✔
1772
                "chain backend",
3✔
1773
                cc.HealthCheck,
3✔
1774
                cfg.HealthChecks.ChainCheck.Interval,
3✔
1775
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
1776
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
1777
                chainBackendAttempts,
3✔
1778
        )
3✔
1779

3✔
1780
        diskCheck := healthcheck.NewObservation(
3✔
1781
                "disk space",
3✔
1782
                func() error {
3✔
1783
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1784
                                cfg.LndDir,
×
1785
                        )
×
1786
                        if err != nil {
×
1787
                                return err
×
1788
                        }
×
1789

1790
                        // If we have more free space than we require,
1791
                        // we return a nil error.
1792
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1793
                                return nil
×
1794
                        }
×
1795

1796
                        return fmt.Errorf("require: %v free space, got: %v",
×
1797
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1798
                                free)
×
1799
                },
1800
                cfg.HealthChecks.DiskCheck.Interval,
1801
                cfg.HealthChecks.DiskCheck.Timeout,
1802
                cfg.HealthChecks.DiskCheck.Backoff,
1803
                cfg.HealthChecks.DiskCheck.Attempts,
1804
        )
1805

1806
        tlsHealthCheck := healthcheck.NewObservation(
3✔
1807
                "tls",
3✔
1808
                func() error {
3✔
1809
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1810
                                s.cc.KeyRing,
×
1811
                        )
×
1812
                        if err != nil {
×
1813
                                return err
×
1814
                        }
×
1815
                        if expired {
×
1816
                                return fmt.Errorf("TLS certificate is "+
×
1817
                                        "expired as of %v", expTime)
×
1818
                        }
×
1819

1820
                        // If the certificate is not outdated, no error needs
1821
                        // to be returned
1822
                        return nil
×
1823
                },
1824
                cfg.HealthChecks.TLSCheck.Interval,
1825
                cfg.HealthChecks.TLSCheck.Timeout,
1826
                cfg.HealthChecks.TLSCheck.Backoff,
1827
                cfg.HealthChecks.TLSCheck.Attempts,
1828
        )
1829

1830
        checks := []*healthcheck.Observation{
3✔
1831
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
1832
        }
3✔
1833

3✔
1834
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
1835
        if s.torController != nil {
3✔
1836
                torConnectionCheck := healthcheck.NewObservation(
×
1837
                        "tor connection",
×
1838
                        func() error {
×
1839
                                return healthcheck.CheckTorServiceStatus(
×
1840
                                        s.torController,
×
1841
                                        s.createNewHiddenService,
×
1842
                                )
×
1843
                        },
×
1844
                        cfg.HealthChecks.TorConnection.Interval,
1845
                        cfg.HealthChecks.TorConnection.Timeout,
1846
                        cfg.HealthChecks.TorConnection.Backoff,
1847
                        cfg.HealthChecks.TorConnection.Attempts,
1848
                )
1849
                checks = append(checks, torConnectionCheck)
×
1850
        }
1851

1852
        // If remote signing is enabled, add the healthcheck for the remote
1853
        // signing RPC interface.
1854
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
1855
                // Because we have two cascading timeouts here, we need to add
3✔
1856
                // some slack to the "outer" one of them in case the "inner"
3✔
1857
                // returns exactly on time.
3✔
1858
                overhead := time.Millisecond * 10
3✔
1859

3✔
1860
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
1861
                        "remote signer connection",
3✔
1862
                        rpcwallet.HealthCheck(
3✔
1863
                                s.cfg.RemoteSigner,
3✔
1864

3✔
1865
                                // For the health check we might to be even
3✔
1866
                                // stricter than the initial/normal connect, so
3✔
1867
                                // we use the health check timeout here.
3✔
1868
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
1869
                        ),
3✔
1870
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
1871
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
1872
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
1873
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
1874
                )
3✔
1875
                checks = append(checks, remoteSignerConnectionCheck)
3✔
1876
        }
3✔
1877

1878
        // If we have a leader elector, we add a health check to ensure we are
1879
        // still the leader. During normal operation, we should always be the
1880
        // leader, but there are circumstances where this may change, such as
1881
        // when we lose network connectivity for long enough expiring out lease.
1882
        if leaderElector != nil {
3✔
1883
                leaderCheck := healthcheck.NewObservation(
×
1884
                        "leader status",
×
1885
                        func() error {
×
1886
                                // Check if we are still the leader. Note that
×
1887
                                // we don't need to use a timeout context here
×
1888
                                // as the healthcheck observer will handle the
×
1889
                                // timeout case for us.
×
1890
                                timeoutCtx, cancel := context.WithTimeout(
×
1891
                                        context.Background(),
×
1892
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
1893
                                )
×
1894
                                defer cancel()
×
1895

×
1896
                                leader, err := leaderElector.IsLeader(
×
1897
                                        timeoutCtx,
×
1898
                                )
×
1899
                                if err != nil {
×
1900
                                        return fmt.Errorf("unable to check if "+
×
1901
                                                "still leader: %v", err)
×
1902
                                }
×
1903

1904
                                if !leader {
×
1905
                                        srvrLog.Debug("Not the current leader")
×
1906
                                        return fmt.Errorf("not the current " +
×
1907
                                                "leader")
×
1908
                                }
×
1909

1910
                                return nil
×
1911
                        },
1912
                        cfg.HealthChecks.LeaderCheck.Interval,
1913
                        cfg.HealthChecks.LeaderCheck.Timeout,
1914
                        cfg.HealthChecks.LeaderCheck.Backoff,
1915
                        cfg.HealthChecks.LeaderCheck.Attempts,
1916
                )
1917

1918
                checks = append(checks, leaderCheck)
×
1919
        }
1920

1921
        // If we have not disabled all of our health checks, we create a
1922
        // liveness monitor with our configured checks.
1923
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
1924
                &healthcheck.Config{
3✔
1925
                        Checks:   checks,
3✔
1926
                        Shutdown: srvrLog.Criticalf,
3✔
1927
                },
3✔
1928
        )
3✔
1929
}
1930

1931
// Started returns true if the server has been started, and false otherwise.
1932
// NOTE: This function is safe for concurrent access.
1933
func (s *server) Started() bool {
3✔
1934
        return atomic.LoadInt32(&s.active) != 0
3✔
1935
}
3✔
1936

1937
// cleaner is used to aggregate "cleanup" functions during an operation that
1938
// starts several subsystems. In case one of the subsystem fails to start
1939
// and a proper resource cleanup is required, the "run" method achieves this
1940
// by running all these added "cleanup" functions.
1941
type cleaner []func() error
1942

1943
// add is used to add a cleanup function to be called when
1944
// the run function is executed.
1945
func (c cleaner) add(cleanup func() error) cleaner {
3✔
1946
        return append(c, cleanup)
3✔
1947
}
3✔
1948

1949
// run is used to run all the previousely added cleanup functions.
1950
func (c cleaner) run() {
×
1951
        for i := len(c) - 1; i >= 0; i-- {
×
1952
                if err := c[i](); err != nil {
×
1953
                        srvrLog.Infof("Cleanup failed: %v", err)
×
1954
                }
×
1955
        }
1956
}
1957

1958
// Start starts the main daemon server, all requested listeners, and any helper
1959
// goroutines.
1960
// NOTE: This function is safe for concurrent access.
1961
//
1962
//nolint:funlen
1963
func (s *server) Start() error {
3✔
1964
        var startErr error
3✔
1965

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

3✔
1971
        s.start.Do(func() {
6✔
1972
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
1973
                if err := s.customMessageServer.Start(); err != nil {
3✔
1974
                        startErr = err
×
1975
                        return
×
1976
                }
×
1977

1978
                if s.hostAnn != nil {
3✔
1979
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
1980
                        if err := s.hostAnn.Start(); err != nil {
×
1981
                                startErr = err
×
1982
                                return
×
1983
                        }
×
1984
                }
1985

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

1994
                // Start the notification server. This is used so channel
1995
                // management goroutines can be notified when a funding
1996
                // transaction reaches a sufficient number of confirmations, or
1997
                // when the input for the funding transaction is spent in an
1998
                // attempt at an uncooperative close by the counterparty.
1999
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2000
                if err := s.sigPool.Start(); err != nil {
3✔
2001
                        startErr = err
×
2002
                        return
×
2003
                }
×
2004

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

2011
                cleanup = cleanup.add(s.readPool.Stop)
3✔
2012
                if err := s.readPool.Start(); err != nil {
3✔
2013
                        startErr = err
×
2014
                        return
×
2015
                }
×
2016

2017
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2018
                if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2019
                        startErr = err
×
2020
                        return
×
2021
                }
×
2022

2023
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
3✔
2024
                if err := s.cc.BestBlockTracker.Start(); err != nil {
3✔
2025
                        startErr = err
×
2026
                        return
×
2027
                }
×
2028

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

2035
                cleanup = cleanup.add(func() error {
3✔
2036
                        return s.peerNotifier.Stop()
×
2037
                })
×
2038
                if err := s.peerNotifier.Start(); err != nil {
3✔
2039
                        startErr = err
×
2040
                        return
×
2041
                }
×
2042

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

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

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

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

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

2075
                cleanup = cleanup.add(s.breachArbitrator.Stop)
3✔
2076
                if err := s.breachArbitrator.Start(); err != nil {
3✔
2077
                        startErr = err
×
2078
                        return
×
2079
                }
×
2080

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

2087
                // htlcSwitch must be started before chainArb since the latter
2088
                // relies on htlcSwitch to deliver resolution message upon
2089
                // start.
2090
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2091
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2092
                        startErr = err
×
2093
                        return
×
2094
                }
×
2095

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

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

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

2114
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2115
                if err := s.chanRouter.Start(); err != nil {
3✔
2116
                        startErr = err
×
2117
                        return
×
2118
                }
×
2119
                // The authGossiper depends on the chanRouter and therefore
2120
                // should be started after it.
2121
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2122
                if err := s.authGossiper.Start(); err != nil {
3✔
2123
                        startErr = err
×
2124
                        return
×
2125
                }
×
2126

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

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

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

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

2151
                cleanup.add(func() error {
3✔
2152
                        s.missionControl.StopStoreTicker()
×
2153
                        return nil
×
2154
                })
×
2155
                s.missionControl.RunStoreTicker()
3✔
2156

3✔
2157
                // Before we start the connMgr, we'll check to see if we have
3✔
2158
                // any backups to recover. We do this now as we want to ensure
3✔
2159
                // that have all the information we need to handle channel
3✔
2160
                // recovery _before_ we even accept connections from any peers.
3✔
2161
                chanRestorer := &chanDBRestorer{
3✔
2162
                        db:         s.chanStateDB,
3✔
2163
                        secretKeys: s.cc.KeyRing,
3✔
2164
                        chainArb:   s.chainArb,
3✔
2165
                }
3✔
2166
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2167
                        err := chanbackup.UnpackAndRecoverSingles(
×
2168
                                s.chansToRestore.PackedSingleChanBackups,
×
2169
                                s.cc.KeyRing, chanRestorer, s,
×
2170
                        )
×
2171
                        if err != nil {
×
2172
                                startErr = fmt.Errorf("unable to unpack single "+
×
2173
                                        "backups: %v", err)
×
2174
                                return
×
2175
                        }
×
2176
                }
2177
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2178
                        err := chanbackup.UnpackAndRecoverMulti(
3✔
2179
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2180
                                s.cc.KeyRing, chanRestorer, s,
3✔
2181
                        )
3✔
2182
                        if err != nil {
3✔
2183
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2184
                                        "backup: %v", err)
×
2185
                                return
×
2186
                        }
×
2187
                }
2188

2189
                // chanSubSwapper must be started after the `channelNotifier`
2190
                // because it depends on channel events as a synchronization
2191
                // point.
2192
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2193
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2194
                        startErr = err
×
2195
                        return
×
2196
                }
×
2197

2198
                if s.torController != nil {
3✔
2199
                        cleanup = cleanup.add(s.torController.Stop)
×
2200
                        if err := s.createNewHiddenService(); err != nil {
×
2201
                                startErr = err
×
2202
                                return
×
2203
                        }
×
2204
                }
2205

2206
                if s.natTraversal != nil {
3✔
2207
                        s.wg.Add(1)
×
2208
                        go s.watchExternalIP()
×
2209
                }
×
2210

2211
                // Start connmgr last to prevent connections before init.
2212
                cleanup = cleanup.add(func() error {
3✔
2213
                        s.connMgr.Stop()
×
2214
                        return nil
×
2215
                })
×
2216
                s.connMgr.Start()
3✔
2217

3✔
2218
                // If peers are specified as a config option, we'll add those
3✔
2219
                // peers first.
3✔
2220
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2221
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2222
                                peerAddrCfg,
3✔
2223
                        )
3✔
2224
                        if err != nil {
3✔
2225
                                startErr = fmt.Errorf("unable to parse peer "+
×
2226
                                        "pubkey from config: %v", err)
×
2227
                                return
×
2228
                        }
×
2229
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2230
                        if err != nil {
3✔
2231
                                startErr = fmt.Errorf("unable to parse peer "+
×
2232
                                        "address provided as a config option: "+
×
2233
                                        "%v", err)
×
2234
                                return
×
2235
                        }
×
2236

2237
                        peerAddr := &lnwire.NetAddress{
3✔
2238
                                IdentityKey: parsedPubkey,
3✔
2239
                                Address:     addr,
3✔
2240
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2241
                        }
3✔
2242

3✔
2243
                        err = s.ConnectToPeer(
3✔
2244
                                peerAddr, true,
3✔
2245
                                s.cfg.ConnectionTimeout,
3✔
2246
                        )
3✔
2247
                        if err != nil {
3✔
2248
                                startErr = fmt.Errorf("unable to connect to "+
×
2249
                                        "peer address provided as a config "+
×
2250
                                        "option: %v", err)
×
2251
                                return
×
2252
                        }
×
2253
                }
2254

2255
                // Subscribe to NodeAnnouncements that advertise new addresses
2256
                // our persistent peers.
2257
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2258
                        startErr = err
×
2259
                        return
×
2260
                }
×
2261

2262
                // With all the relevant sub-systems started, we'll now attempt
2263
                // to establish persistent connections to our direct channel
2264
                // collaborators within the network. Before doing so however,
2265
                // we'll prune our set of link nodes found within the database
2266
                // to ensure we don't reconnect to any nodes we no longer have
2267
                // open channels with.
2268
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2269
                        startErr = err
×
2270
                        return
×
2271
                }
×
2272
                if err := s.establishPersistentConnections(); err != nil {
3✔
2273
                        startErr = err
×
2274
                        return
×
2275
                }
×
2276

2277
                // setSeedList is a helper function that turns multiple DNS seed
2278
                // server tuples from the command line or config file into the
2279
                // data structure we need and does a basic formal sanity check
2280
                // in the process.
2281
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2282
                        if len(tuples) == 0 {
×
2283
                                return
×
2284
                        }
×
2285

2286
                        result := make([][2]string, len(tuples))
×
2287
                        for idx, tuple := range tuples {
×
2288
                                tuple = strings.TrimSpace(tuple)
×
2289
                                if len(tuple) == 0 {
×
2290
                                        return
×
2291
                                }
×
2292

2293
                                servers := strings.Split(tuple, ",")
×
2294
                                if len(servers) > 2 || len(servers) == 0 {
×
2295
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2296
                                                "seed tuple: %v", servers)
×
2297
                                        return
×
2298
                                }
×
2299

2300
                                copy(result[idx][:], servers)
×
2301
                        }
2302

2303
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2304
                }
2305

2306
                // Let users overwrite the DNS seed nodes. We only allow them
2307
                // for bitcoin mainnet/testnet/signet.
2308
                if s.cfg.Bitcoin.MainNet {
3✔
2309
                        setSeedList(
×
2310
                                s.cfg.Bitcoin.DNSSeeds,
×
2311
                                chainreg.BitcoinMainnetGenesis,
×
2312
                        )
×
2313
                }
×
2314
                if s.cfg.Bitcoin.TestNet3 {
3✔
2315
                        setSeedList(
×
2316
                                s.cfg.Bitcoin.DNSSeeds,
×
2317
                                chainreg.BitcoinTestnetGenesis,
×
2318
                        )
×
2319
                }
×
2320
                if s.cfg.Bitcoin.SigNet {
3✔
2321
                        setSeedList(
×
2322
                                s.cfg.Bitcoin.DNSSeeds,
×
2323
                                chainreg.BitcoinSignetGenesis,
×
2324
                        )
×
2325
                }
×
2326

2327
                // If network bootstrapping hasn't been disabled, then we'll
2328
                // configure the set of active bootstrappers, and launch a
2329
                // dedicated goroutine to maintain a set of persistent
2330
                // connections.
2331
                if shouldPeerBootstrap(s.cfg) {
3✔
2332
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2333
                        if err != nil {
×
2334
                                startErr = err
×
2335
                                return
×
2336
                        }
×
2337

2338
                        s.wg.Add(1)
×
2339
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2340
                } else {
3✔
2341
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2342
                }
3✔
2343

2344
                // Set the active flag now that we've completed the full
2345
                // startup.
2346
                atomic.StoreInt32(&s.active, 1)
3✔
2347
        })
2348

2349
        if startErr != nil {
3✔
2350
                cleanup.run()
×
2351
        }
×
2352
        return startErr
3✔
2353
}
2354

2355
// Stop gracefully shutsdown the main daemon server. This function will signal
2356
// any active goroutines, or helper objects to exit, then blocks until they've
2357
// all successfully exited. Additionally, any/all listeners are closed.
2358
// NOTE: This function is safe for concurrent access.
2359
func (s *server) Stop() error {
3✔
2360
        s.stop.Do(func() {
6✔
2361
                atomic.StoreInt32(&s.stopping, 1)
3✔
2362

3✔
2363
                close(s.quit)
3✔
2364

3✔
2365
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2366
                s.connMgr.Stop()
3✔
2367

3✔
2368
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2369
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2370
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2371
                }
×
2372
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2373
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2374
                }
×
2375
                if err := s.sphinx.Stop(); err != nil {
3✔
2376
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2377
                }
×
2378
                if err := s.invoices.Stop(); err != nil {
3✔
2379
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2380
                }
×
2381
                if err := s.chanRouter.Stop(); err != nil {
3✔
2382
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2383
                }
×
2384
                if err := s.chainArb.Stop(); err != nil {
3✔
2385
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2386
                }
×
2387
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2388
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2389
                }
×
2390
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2391
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2392
                                err)
×
2393
                }
×
2394
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2395
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2396
                }
×
2397
                if err := s.authGossiper.Stop(); err != nil {
3✔
2398
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2399
                }
×
2400
                if err := s.sweeper.Stop(); err != nil {
3✔
2401
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2402
                }
×
2403
                if err := s.txPublisher.Stop(); err != nil {
3✔
2404
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2405
                }
×
2406
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2407
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2408
                }
×
2409
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2410
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2411
                }
×
2412
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2413
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2414
                }
×
2415
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2416
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2417
                }
×
2418
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2419
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2420
                }
×
2421
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2422
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2423
                                err)
×
2424
                }
×
2425
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2426
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2427
                                err)
×
2428
                }
×
2429
                s.missionControl.StopStoreTicker()
3✔
2430

3✔
2431
                // Disconnect from each active peers to ensure that
3✔
2432
                // peerTerminationWatchers signal completion to each peer.
3✔
2433
                for _, peer := range s.Peers() {
6✔
2434
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2435
                        if err != nil {
3✔
2436
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2437
                                        "received error: %v", peer.IdentityKey(),
×
2438
                                        err,
×
2439
                                )
×
2440
                        }
×
2441
                }
2442

2443
                // Now that all connections have been torn down, stop the tower
2444
                // client which will reliably flush all queued states to the
2445
                // tower. If this is halted for any reason, the force quit timer
2446
                // will kick in and abort to allow this method to return.
2447
                if s.towerClientMgr != nil {
6✔
2448
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2449
                                srvrLog.Warnf("Unable to shut down tower "+
×
2450
                                        "client manager: %v", err)
×
2451
                        }
×
2452
                }
2453

2454
                if s.hostAnn != nil {
3✔
2455
                        if err := s.hostAnn.Stop(); err != nil {
×
2456
                                srvrLog.Warnf("unable to shut down host "+
×
2457
                                        "annoucner: %v", err)
×
2458
                        }
×
2459
                }
2460

2461
                if s.livenessMonitor != nil {
6✔
2462
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2463
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2464
                                        "monitor: %v", err)
×
2465
                        }
×
2466
                }
2467

2468
                // Wait for all lingering goroutines to quit.
2469
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2470
                s.wg.Wait()
3✔
2471

3✔
2472
                srvrLog.Debug("Stopping buffer pools...")
3✔
2473
                s.sigPool.Stop()
3✔
2474
                s.writePool.Stop()
3✔
2475
                s.readPool.Stop()
3✔
2476
        })
2477

2478
        return nil
3✔
2479
}
2480

2481
// Stopped returns true if the server has been instructed to shutdown.
2482
// NOTE: This function is safe for concurrent access.
2483
func (s *server) Stopped() bool {
3✔
2484
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2485
}
3✔
2486

2487
// configurePortForwarding attempts to set up port forwarding for the different
2488
// ports that the server will be listening on.
2489
//
2490
// NOTE: This should only be used when using some kind of NAT traversal to
2491
// automatically set up forwarding rules.
2492
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2493
        ip, err := s.natTraversal.ExternalIP()
×
2494
        if err != nil {
×
2495
                return nil, err
×
2496
        }
×
2497
        s.lastDetectedIP = ip
×
2498

×
2499
        externalIPs := make([]string, 0, len(ports))
×
2500
        for _, port := range ports {
×
2501
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2502
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2503
                        continue
×
2504
                }
2505

2506
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2507
                externalIPs = append(externalIPs, hostIP)
×
2508
        }
2509

2510
        return externalIPs, nil
×
2511
}
2512

2513
// removePortForwarding attempts to clear the forwarding rules for the different
2514
// ports the server is currently listening on.
2515
//
2516
// NOTE: This should only be used when using some kind of NAT traversal to
2517
// automatically set up forwarding rules.
2518
func (s *server) removePortForwarding() {
×
2519
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2520
        for _, port := range forwardedPorts {
×
2521
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2522
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2523
                                "port %d: %v", port, err)
×
2524
                }
×
2525
        }
2526
}
2527

2528
// watchExternalIP continuously checks for an updated external IP address every
2529
// 15 minutes. Once a new IP address has been detected, it will automatically
2530
// handle port forwarding rules and send updated node announcements to the
2531
// currently connected peers.
2532
//
2533
// NOTE: This MUST be run as a goroutine.
2534
func (s *server) watchExternalIP() {
×
2535
        defer s.wg.Done()
×
2536

×
2537
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2538
        // up by the server.
×
2539
        defer s.removePortForwarding()
×
2540

×
2541
        // Keep track of the external IPs set by the user to avoid replacing
×
2542
        // them when detecting a new IP.
×
2543
        ipsSetByUser := make(map[string]struct{})
×
2544
        for _, ip := range s.cfg.ExternalIPs {
×
2545
                ipsSetByUser[ip.String()] = struct{}{}
×
2546
        }
×
2547

2548
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2549

×
2550
        ticker := time.NewTicker(15 * time.Minute)
×
2551
        defer ticker.Stop()
×
2552
out:
×
2553
        for {
×
2554
                select {
×
2555
                case <-ticker.C:
×
2556
                        // We'll start off by making sure a new IP address has
×
2557
                        // been detected.
×
2558
                        ip, err := s.natTraversal.ExternalIP()
×
2559
                        if err != nil {
×
2560
                                srvrLog.Debugf("Unable to retrieve the "+
×
2561
                                        "external IP address: %v", err)
×
2562
                                continue
×
2563
                        }
2564

2565
                        // Periodically renew the NAT port forwarding.
2566
                        for _, port := range forwardedPorts {
×
2567
                                err := s.natTraversal.AddPortMapping(port)
×
2568
                                if err != nil {
×
2569
                                        srvrLog.Warnf("Unable to automatically "+
×
2570
                                                "re-create port forwarding using %s: %v",
×
2571
                                                s.natTraversal.Name(), err)
×
2572
                                } else {
×
2573
                                        srvrLog.Debugf("Automatically re-created "+
×
2574
                                                "forwarding for port %d using %s to "+
×
2575
                                                "advertise external IP",
×
2576
                                                port, s.natTraversal.Name())
×
2577
                                }
×
2578
                        }
2579

2580
                        if ip.Equal(s.lastDetectedIP) {
×
2581
                                continue
×
2582
                        }
2583

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

×
2586
                        // Next, we'll craft the new addresses that will be
×
2587
                        // included in the new node announcement and advertised
×
2588
                        // to the network. Each address will consist of the new
×
2589
                        // IP detected and one of the currently advertised
×
2590
                        // ports.
×
2591
                        var newAddrs []net.Addr
×
2592
                        for _, port := range forwardedPorts {
×
2593
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2594
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2595
                                if err != nil {
×
2596
                                        srvrLog.Debugf("Unable to resolve "+
×
2597
                                                "host %v: %v", addr, err)
×
2598
                                        continue
×
2599
                                }
2600

2601
                                newAddrs = append(newAddrs, addr)
×
2602
                        }
2603

2604
                        // Skip the update if we weren't able to resolve any of
2605
                        // the new addresses.
2606
                        if len(newAddrs) == 0 {
×
2607
                                srvrLog.Debug("Skipping node announcement " +
×
2608
                                        "update due to not being able to " +
×
2609
                                        "resolve any new addresses")
×
2610
                                continue
×
2611
                        }
2612

2613
                        // Now, we'll need to update the addresses in our node's
2614
                        // announcement in order to propagate the update
2615
                        // throughout the network. We'll only include addresses
2616
                        // that have a different IP from the previous one, as
2617
                        // the previous IP is no longer valid.
2618
                        currentNodeAnn := s.getNodeAnnouncement()
×
2619

×
2620
                        for _, addr := range currentNodeAnn.Addresses {
×
2621
                                host, _, err := net.SplitHostPort(addr.String())
×
2622
                                if err != nil {
×
2623
                                        srvrLog.Debugf("Unable to determine "+
×
2624
                                                "host from address %v: %v",
×
2625
                                                addr, err)
×
2626
                                        continue
×
2627
                                }
2628

2629
                                // We'll also make sure to include external IPs
2630
                                // set manually by the user.
2631
                                _, setByUser := ipsSetByUser[addr.String()]
×
2632
                                if setByUser || host != s.lastDetectedIP.String() {
×
2633
                                        newAddrs = append(newAddrs, addr)
×
2634
                                }
×
2635
                        }
2636

2637
                        // Then, we'll generate a new timestamped node
2638
                        // announcement with the updated addresses and broadcast
2639
                        // it to our peers.
2640
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2641
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2642
                        )
×
2643
                        if err != nil {
×
2644
                                srvrLog.Debugf("Unable to generate new node "+
×
2645
                                        "announcement: %v", err)
×
2646
                                continue
×
2647
                        }
2648

2649
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2650
                        if err != nil {
×
2651
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2652
                                        "announcement to peers: %v", err)
×
2653
                                continue
×
2654
                        }
2655

2656
                        // Finally, update the last IP seen to the current one.
2657
                        s.lastDetectedIP = ip
×
2658
                case <-s.quit:
×
2659
                        break out
×
2660
                }
2661
        }
2662
}
2663

2664
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2665
// based on the server, and currently active bootstrap mechanisms as defined
2666
// within the current configuration.
2667
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2668
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2669

×
2670
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2671

×
2672
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2673
        // this can be used by default if we've already partially seeded the
×
2674
        // network.
×
2675
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2676
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
2677
        if err != nil {
×
2678
                return nil, err
×
2679
        }
×
2680
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2681

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

×
2687
                // If we have a set of DNS seeds for this chain, then we'll add
×
2688
                // it as an additional bootstrapping source.
×
2689
                if ok {
×
2690
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2691
                                "seeds: %v", dnsSeeds)
×
2692

×
2693
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2694
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2695
                        )
×
2696
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2697
                }
×
2698
        }
2699

2700
        return bootStrappers, nil
×
2701
}
2702

2703
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2704
// needs to ignore, which is made of three parts,
2705
//   - the node itself needs to be skipped as it doesn't make sense to connect
2706
//     to itself.
2707
//   - the peers that already have connections with, as in s.peersByPub.
2708
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2709
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2710
        s.mu.RLock()
×
2711
        defer s.mu.RUnlock()
×
2712

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

×
2715
        // We should ignore ourselves from bootstrapping.
×
2716
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2717
        ignore[selfKey] = struct{}{}
×
2718

×
2719
        // Ignore all connected peers.
×
2720
        for _, peer := range s.peersByPub {
×
2721
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2722
                ignore[nID] = struct{}{}
×
2723
        }
×
2724

2725
        // Ignore all persistent peers as they have a dedicated reconnecting
2726
        // process.
2727
        for pubKeyStr := range s.persistentPeers {
×
2728
                var nID autopilot.NodeID
×
2729
                copy(nID[:], []byte(pubKeyStr))
×
2730
                ignore[nID] = struct{}{}
×
2731
        }
×
2732

2733
        return ignore
×
2734
}
2735

2736
// peerBootstrapper is a goroutine which is tasked with attempting to establish
2737
// and maintain a target minimum number of outbound connections. With this
2738
// invariant, we ensure that our node is connected to a diverse set of peers
2739
// and that nodes newly joining the network receive an up to date network view
2740
// as soon as possible.
2741
func (s *server) peerBootstrapper(numTargetPeers uint32,
2742
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2743

×
2744
        defer s.wg.Done()
×
2745

×
2746
        // Before we continue, init the ignore peers map.
×
2747
        ignoreList := s.createBootstrapIgnorePeers()
×
2748

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

×
2753
        // Once done, we'll attempt to maintain our target minimum number of
×
2754
        // peers.
×
2755
        //
×
2756
        // We'll use a 15 second backoff, and double the time every time an
×
2757
        // epoch fails up to a ceiling.
×
2758
        backOff := time.Second * 15
×
2759

×
2760
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2761
        // see if we've reached our minimum number of peers.
×
2762
        sampleTicker := time.NewTicker(backOff)
×
2763
        defer sampleTicker.Stop()
×
2764

×
2765
        // We'll use the number of attempts and errors to determine if we need
×
2766
        // to increase the time between discovery epochs.
×
2767
        var epochErrors uint32 // To be used atomically.
×
2768
        var epochAttempts uint32
×
2769

×
2770
        for {
×
2771
                select {
×
2772
                // The ticker has just woken us up, so we'll need to check if
2773
                // we need to attempt to connect our to any more peers.
2774
                case <-sampleTicker.C:
×
2775
                        // Obtain the current number of peers, so we can gauge
×
2776
                        // if we need to sample more peers or not.
×
2777
                        s.mu.RLock()
×
2778
                        numActivePeers := uint32(len(s.peersByPub))
×
2779
                        s.mu.RUnlock()
×
2780

×
2781
                        // If we have enough peers, then we can loop back
×
2782
                        // around to the next round as we're done here.
×
2783
                        if numActivePeers >= numTargetPeers {
×
2784
                                continue
×
2785
                        }
2786

2787
                        // If all of our attempts failed during this last back
2788
                        // off period, then will increase our backoff to 5
2789
                        // minute ceiling to avoid an excessive number of
2790
                        // queries
2791
                        //
2792
                        // TODO(roasbeef): add reverse policy too?
2793

2794
                        if epochAttempts > 0 &&
×
2795
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
2796

×
2797
                                sampleTicker.Stop()
×
2798

×
2799
                                backOff *= 2
×
2800
                                if backOff > bootstrapBackOffCeiling {
×
2801
                                        backOff = bootstrapBackOffCeiling
×
2802
                                }
×
2803

2804
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
2805
                                        "%v", backOff)
×
2806
                                sampleTicker = time.NewTicker(backOff)
×
2807
                                continue
×
2808
                        }
2809

2810
                        atomic.StoreUint32(&epochErrors, 0)
×
2811
                        epochAttempts = 0
×
2812

×
2813
                        // Since we know need more peers, we'll compute the
×
2814
                        // exact number we need to reach our threshold.
×
2815
                        numNeeded := numTargetPeers - numActivePeers
×
2816

×
2817
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
2818
                                "peers", numNeeded)
×
2819

×
2820
                        // With the number of peers we need calculated, we'll
×
2821
                        // query the network bootstrappers to sample a set of
×
2822
                        // random addrs for us.
×
2823
                        //
×
2824
                        // Before we continue, get a copy of the ignore peers
×
2825
                        // map.
×
2826
                        ignoreList = s.createBootstrapIgnorePeers()
×
2827

×
2828
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
2829
                                ignoreList, numNeeded*2, bootstrappers...,
×
2830
                        )
×
2831
                        if err != nil {
×
2832
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
2833
                                        "peers: %v", err)
×
2834
                                continue
×
2835
                        }
2836

2837
                        // Finally, we'll launch a new goroutine for each
2838
                        // prospective peer candidates.
2839
                        for _, addr := range peerAddrs {
×
2840
                                epochAttempts++
×
2841

×
2842
                                go func(a *lnwire.NetAddress) {
×
2843
                                        // TODO(roasbeef): can do AS, subnet,
×
2844
                                        // country diversity, etc
×
2845
                                        errChan := make(chan error, 1)
×
2846
                                        s.connectToPeer(
×
2847
                                                a, errChan,
×
2848
                                                s.cfg.ConnectionTimeout,
×
2849
                                        )
×
2850
                                        select {
×
2851
                                        case err := <-errChan:
×
2852
                                                if err == nil {
×
2853
                                                        return
×
2854
                                                }
×
2855

2856
                                                srvrLog.Errorf("Unable to "+
×
2857
                                                        "connect to %v: %v",
×
2858
                                                        a, err)
×
2859
                                                atomic.AddUint32(&epochErrors, 1)
×
2860
                                        case <-s.quit:
×
2861
                                        }
2862
                                }(addr)
2863
                        }
2864
                case <-s.quit:
×
2865
                        return
×
2866
                }
2867
        }
2868
}
2869

2870
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
2871
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
2872
// query back off each time we encounter a failure.
2873
const bootstrapBackOffCeiling = time.Minute * 5
2874

2875
// initialPeerBootstrap attempts to continuously connect to peers on startup
2876
// until the target number of peers has been reached. This ensures that nodes
2877
// receive an up to date network view as soon as possible.
2878
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
2879
        numTargetPeers uint32,
2880
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2881

×
2882
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
2883
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
2884

×
2885
        // We'll start off by waiting 2 seconds between failed attempts, then
×
2886
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
2887
        var delaySignal <-chan time.Time
×
2888
        delayTime := time.Second * 2
×
2889

×
2890
        // As want to be more aggressive, we'll use a lower back off celling
×
2891
        // then the main peer bootstrap logic.
×
2892
        backOffCeiling := bootstrapBackOffCeiling / 5
×
2893

×
2894
        for attempts := 0; ; attempts++ {
×
2895
                // Check if the server has been requested to shut down in order
×
2896
                // to prevent blocking.
×
2897
                if s.Stopped() {
×
2898
                        return
×
2899
                }
×
2900

2901
                // We can exit our aggressive initial peer bootstrapping stage
2902
                // if we've reached out target number of peers.
2903
                s.mu.RLock()
×
2904
                numActivePeers := uint32(len(s.peersByPub))
×
2905
                s.mu.RUnlock()
×
2906

×
2907
                if numActivePeers >= numTargetPeers {
×
2908
                        return
×
2909
                }
×
2910

2911
                if attempts > 0 {
×
2912
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
2913
                                "bootstrap peers (attempt #%v)", delayTime,
×
2914
                                attempts)
×
2915

×
2916
                        // We've completed at least one iterating and haven't
×
2917
                        // finished, so we'll start to insert a delay period
×
2918
                        // between each attempt.
×
2919
                        delaySignal = time.After(delayTime)
×
2920
                        select {
×
2921
                        case <-delaySignal:
×
2922
                        case <-s.quit:
×
2923
                                return
×
2924
                        }
2925

2926
                        // After our delay, we'll double the time we wait up to
2927
                        // the max back off period.
2928
                        delayTime *= 2
×
2929
                        if delayTime > backOffCeiling {
×
2930
                                delayTime = backOffCeiling
×
2931
                        }
×
2932
                }
2933

2934
                // Otherwise, we'll request for the remaining number of peers
2935
                // in order to reach our target.
2936
                peersNeeded := numTargetPeers - numActivePeers
×
2937
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
2938
                        ignore, peersNeeded, bootstrappers...,
×
2939
                )
×
2940
                if err != nil {
×
2941
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
2942
                                "peers: %v", err)
×
2943
                        continue
×
2944
                }
2945

2946
                // Then, we'll attempt to establish a connection to the
2947
                // different peer addresses retrieved by our bootstrappers.
2948
                var wg sync.WaitGroup
×
2949
                for _, bootstrapAddr := range bootstrapAddrs {
×
2950
                        wg.Add(1)
×
2951
                        go func(addr *lnwire.NetAddress) {
×
2952
                                defer wg.Done()
×
2953

×
2954
                                errChan := make(chan error, 1)
×
2955
                                go s.connectToPeer(
×
2956
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
2957
                                )
×
2958

×
2959
                                // We'll only allow this connection attempt to
×
2960
                                // take up to 3 seconds. This allows us to move
×
2961
                                // quickly by discarding peers that are slowing
×
2962
                                // us down.
×
2963
                                select {
×
2964
                                case err := <-errChan:
×
2965
                                        if err == nil {
×
2966
                                                return
×
2967
                                        }
×
2968
                                        srvrLog.Errorf("Unable to connect to "+
×
2969
                                                "%v: %v", addr, err)
×
2970
                                // TODO: tune timeout? 3 seconds might be *too*
2971
                                // aggressive but works well.
2972
                                case <-time.After(3 * time.Second):
×
2973
                                        srvrLog.Tracef("Skipping peer %v due "+
×
2974
                                                "to not establishing a "+
×
2975
                                                "connection within 3 seconds",
×
2976
                                                addr)
×
2977
                                case <-s.quit:
×
2978
                                }
2979
                        }(bootstrapAddr)
2980
                }
2981

2982
                wg.Wait()
×
2983
        }
2984
}
2985

2986
// createNewHiddenService automatically sets up a v2 or v3 onion service in
2987
// order to listen for inbound connections over Tor.
2988
func (s *server) createNewHiddenService() error {
×
2989
        // Determine the different ports the server is listening on. The onion
×
2990
        // service's virtual port will map to these ports and one will be picked
×
2991
        // at random when the onion service is being accessed.
×
2992
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
2993
        for _, listenAddr := range s.listenAddrs {
×
2994
                port := listenAddr.(*net.TCPAddr).Port
×
2995
                listenPorts = append(listenPorts, port)
×
2996
        }
×
2997

2998
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
2999
        if err != nil {
×
3000
                return err
×
3001
        }
×
3002

3003
        // Once the port mapping has been set, we can go ahead and automatically
3004
        // create our onion service. The service's private key will be saved to
3005
        // disk in order to regain access to this service when restarting `lnd`.
3006
        onionCfg := tor.AddOnionConfig{
×
3007
                VirtualPort: defaultPeerPort,
×
3008
                TargetPorts: listenPorts,
×
3009
                Store: tor.NewOnionFile(
×
3010
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3011
                        encrypter,
×
3012
                ),
×
3013
        }
×
3014

×
3015
        switch {
×
3016
        case s.cfg.Tor.V2:
×
3017
                onionCfg.Type = tor.V2
×
3018
        case s.cfg.Tor.V3:
×
3019
                onionCfg.Type = tor.V3
×
3020
        }
3021

3022
        addr, err := s.torController.AddOnion(onionCfg)
×
3023
        if err != nil {
×
3024
                return err
×
3025
        }
×
3026

3027
        // Now that the onion service has been created, we'll add the onion
3028
        // address it can be reached at to our list of advertised addresses.
3029
        newNodeAnn, err := s.genNodeAnnouncement(
×
3030
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3031
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3032
                },
×
3033
        )
3034
        if err != nil {
×
3035
                return fmt.Errorf("unable to generate new node "+
×
3036
                        "announcement: %v", err)
×
3037
        }
×
3038

3039
        // Finally, we'll update the on-disk version of our announcement so it
3040
        // will eventually propagate to nodes in the network.
3041
        selfNode := &channeldb.LightningNode{
×
3042
                HaveNodeAnnouncement: true,
×
3043
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3044
                Addresses:            newNodeAnn.Addresses,
×
3045
                Alias:                newNodeAnn.Alias.String(),
×
3046
                Features: lnwire.NewFeatureVector(
×
3047
                        newNodeAnn.Features, lnwire.Features,
×
3048
                ),
×
3049
                Color:        newNodeAnn.RGBColor,
×
3050
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3051
        }
×
3052
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3053
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3054
                return fmt.Errorf("can't set self node: %w", err)
×
3055
        }
×
3056

3057
        return nil
×
3058
}
3059

3060
// findChannel finds a channel given a public key and ChannelID. It is an
3061
// optimization that is quicker than seeking for a channel given only the
3062
// ChannelID.
3063
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3064
        *channeldb.OpenChannel, error) {
3✔
3065

3✔
3066
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3067
        if err != nil {
3✔
3068
                return nil, err
×
3069
        }
×
3070

3071
        for _, channel := range nodeChans {
6✔
3072
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3073
                        return channel, nil
3✔
3074
                }
3✔
3075
        }
3076

3077
        return nil, fmt.Errorf("unable to find channel")
3✔
3078
}
3079

3080
// getNodeAnnouncement fetches the current, fully signed node announcement.
3081
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3082
        s.mu.Lock()
3✔
3083
        defer s.mu.Unlock()
3✔
3084

3✔
3085
        return *s.currentNodeAnn
3✔
3086
}
3✔
3087

3088
// genNodeAnnouncement generates and returns the current fully signed node
3089
// announcement. The time stamp of the announcement will be updated in order
3090
// to ensure it propagates through the network.
3091
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3092
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3093

3✔
3094
        s.mu.Lock()
3✔
3095
        defer s.mu.Unlock()
3✔
3096

3✔
3097
        // First, try to update our feature manager with the updated set of
3✔
3098
        // features.
3✔
3099
        if features != nil {
6✔
3100
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3101
                        feature.SetNodeAnn: features,
3✔
3102
                }
3✔
3103
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3104
                if err != nil {
6✔
3105
                        return lnwire.NodeAnnouncement{}, err
3✔
3106
                }
3✔
3107

3108
                // If we could successfully update our feature manager, add
3109
                // an update modifier to include these new features to our
3110
                // set.
3111
                modifiers = append(
3✔
3112
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3113
                )
3✔
3114
        }
3115

3116
        // Always update the timestamp when refreshing to ensure the update
3117
        // propagates.
3118
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3119

3✔
3120
        // Apply the requested changes to the node announcement.
3✔
3121
        for _, modifier := range modifiers {
6✔
3122
                modifier(s.currentNodeAnn)
3✔
3123
        }
3✔
3124

3125
        // Sign a new update after applying all of the passed modifiers.
3126
        err := netann.SignNodeAnnouncement(
3✔
3127
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
3✔
3128
        )
3✔
3129
        if err != nil {
3✔
3130
                return lnwire.NodeAnnouncement{}, err
×
3131
        }
×
3132

3133
        return *s.currentNodeAnn, nil
3✔
3134
}
3135

3136
// updateAndBrodcastSelfNode generates a new node announcement
3137
// applying the giving modifiers and updating the time stamp
3138
// to ensure it propagates through the network. Then it brodcasts
3139
// it to the network.
3140
func (s *server) updateAndBrodcastSelfNode(features *lnwire.RawFeatureVector,
3141
        modifiers ...netann.NodeAnnModifier) error {
3✔
3142

3✔
3143
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3144
        if err != nil {
6✔
3145
                return fmt.Errorf("unable to generate new node "+
3✔
3146
                        "announcement: %v", err)
3✔
3147
        }
3✔
3148

3149
        // Update the on-disk version of our announcement.
3150
        // Load and modify self node istead of creating anew instance so we
3151
        // don't risk overwriting any existing values.
3152
        selfNode, err := s.graphDB.SourceNode()
3✔
3153
        if err != nil {
3✔
3154
                return fmt.Errorf("unable to get current source node: %w", err)
×
3155
        }
×
3156

3157
        selfNode.HaveNodeAnnouncement = true
3✔
3158
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3159
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3160
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3161
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3162
        selfNode.Color = newNodeAnn.RGBColor
3✔
3163
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3164

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

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

3171
        // Finally, propagate it to the nodes in the network.
3172
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3173
        if err != nil {
3✔
3174
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3175
                        "announcement to peers: %v", err)
×
3176
                return err
×
3177
        }
×
3178

3179
        return nil
3✔
3180
}
3181

3182
type nodeAddresses struct {
3183
        pubKey    *btcec.PublicKey
3184
        addresses []net.Addr
3185
}
3186

3187
// establishPersistentConnections attempts to establish persistent connections
3188
// to all our direct channel collaborators. In order to promote liveness of our
3189
// active channels, we instruct the connection manager to attempt to establish
3190
// and maintain persistent connections to all our direct channel counterparties.
3191
func (s *server) establishPersistentConnections() error {
3✔
3192
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3193
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3194
        // since other PubKey forms can't be compared.
3✔
3195
        nodeAddrsMap := map[string]*nodeAddresses{}
3✔
3196

3✔
3197
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3198
        // attempt to connect to based on our set of previous connections. Set
3✔
3199
        // the reconnection port to the default peer port.
3✔
3200
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3201
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
3✔
3202
                return err
×
3203
        }
×
3204
        for _, node := range linkNodes {
6✔
3205
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3206
                nodeAddrs := &nodeAddresses{
3✔
3207
                        pubKey:    node.IdentityPub,
3✔
3208
                        addresses: node.Addresses,
3✔
3209
                }
3✔
3210
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3211
        }
3✔
3212

3213
        // After checking our previous connections for addresses to connect to,
3214
        // iterate through the nodes in our channel graph to find addresses
3215
        // that have been added via NodeAnnouncement messages.
3216
        sourceNode, err := s.graphDB.SourceNode()
3✔
3217
        if err != nil {
3✔
3218
                return err
×
3219
        }
×
3220

3221
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3222
        // each of the nodes.
3223
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
3✔
3224
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
3✔
3225
                tx kvdb.RTx,
3✔
3226
                chanInfo *models.ChannelEdgeInfo,
3✔
3227
                policy, _ *models.ChannelEdgePolicy) error {
6✔
3228

3✔
3229
                // If the remote party has announced the channel to us, but we
3✔
3230
                // haven't yet, then we won't have a policy. However, we don't
3✔
3231
                // need this to connect to the peer, so we'll log it and move on.
3✔
3232
                if policy == nil {
3✔
3233
                        srvrLog.Warnf("No channel policy found for "+
×
3234
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3235
                }
×
3236

3237
                // We'll now fetch the peer opposite from us within this
3238
                // channel so we can queue up a direct connection to them.
3239
                channelPeer, err := s.graphDB.FetchOtherNode(
3✔
3240
                        tx, chanInfo, selfPub,
3✔
3241
                )
3✔
3242
                if err != nil {
3✔
3243
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3244
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3245
                                err)
×
3246
                }
×
3247

3248
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3249

3✔
3250
                // Add all unique addresses from channel
3✔
3251
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3252
                // connect to for this peer.
3✔
3253
                addrSet := make(map[string]net.Addr)
3✔
3254
                for _, addr := range channelPeer.Addresses {
6✔
3255
                        switch addr.(type) {
3✔
3256
                        case *net.TCPAddr:
3✔
3257
                                addrSet[addr.String()] = addr
3✔
3258

3259
                        // We'll only attempt to connect to Tor addresses if Tor
3260
                        // outbound support is enabled.
3261
                        case *tor.OnionAddr:
×
3262
                                if s.cfg.Tor.Active {
×
3263
                                        addrSet[addr.String()] = addr
×
3264
                                }
×
3265
                        }
3266
                }
3267

3268
                // If this peer is also recorded as a link node, we'll add any
3269
                // additional addresses that have not already been selected.
3270
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3271
                if ok {
6✔
3272
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3273
                                switch lnAddress.(type) {
3✔
3274
                                case *net.TCPAddr:
3✔
3275
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3276

3277
                                // We'll only attempt to connect to Tor
3278
                                // addresses if Tor outbound support is enabled.
3279
                                case *tor.OnionAddr:
×
3280
                                        if s.cfg.Tor.Active {
×
3281
                                                addrSet[lnAddress.String()] = lnAddress
×
3282
                                        }
×
3283
                                }
3284
                        }
3285
                }
3286

3287
                // Construct a slice of the deduped addresses.
3288
                var addrs []net.Addr
3✔
3289
                for _, addr := range addrSet {
6✔
3290
                        addrs = append(addrs, addr)
3✔
3291
                }
3✔
3292

3293
                n := &nodeAddresses{
3✔
3294
                        addresses: addrs,
3✔
3295
                }
3✔
3296
                n.pubKey, err = channelPeer.PubKey()
3✔
3297
                if err != nil {
3✔
3298
                        return err
×
3299
                }
×
3300

3301
                nodeAddrsMap[pubStr] = n
3✔
3302
                return nil
3✔
3303
        })
3304
        if err != nil && err != channeldb.ErrGraphNoEdgesFound {
3✔
3305
                return err
×
3306
        }
×
3307

3308
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3309
                len(nodeAddrsMap))
3✔
3310

3✔
3311
        // Acquire and hold server lock until all persistent connection requests
3✔
3312
        // have been recorded and sent to the connection manager.
3✔
3313
        s.mu.Lock()
3✔
3314
        defer s.mu.Unlock()
3✔
3315

3✔
3316
        // Iterate through the combined list of addresses from prior links and
3✔
3317
        // node announcements and attempt to reconnect to each node.
3✔
3318
        var numOutboundConns int
3✔
3319
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3320
                // Add this peer to the set of peers we should maintain a
3✔
3321
                // persistent connection with. We set the value to false to
3✔
3322
                // indicate that we should not continue to reconnect if the
3✔
3323
                // number of channels returns to zero, since this peer has not
3✔
3324
                // been requested as perm by the user.
3✔
3325
                s.persistentPeers[pubStr] = false
3✔
3326
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3327
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3328
                }
3✔
3329

3330
                for _, address := range nodeAddr.addresses {
6✔
3331
                        // Create a wrapper address which couples the IP and
3✔
3332
                        // the pubkey so the brontide authenticated connection
3✔
3333
                        // can be established.
3✔
3334
                        lnAddr := &lnwire.NetAddress{
3✔
3335
                                IdentityKey: nodeAddr.pubKey,
3✔
3336
                                Address:     address,
3✔
3337
                        }
3✔
3338

3✔
3339
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3340
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3341
                }
3✔
3342

3343
                // We'll connect to the first 10 peers immediately, then
3344
                // randomly stagger any remaining connections if the
3345
                // stagger initial reconnect flag is set. This ensures
3346
                // that mobile nodes or nodes with a small number of
3347
                // channels obtain connectivity quickly, but larger
3348
                // nodes are able to disperse the costs of connecting to
3349
                // all peers at once.
3350
                if numOutboundConns < numInstantInitReconnect ||
3✔
3351
                        !s.cfg.StaggerInitialReconnect {
6✔
3352

3✔
3353
                        go s.connectToPersistentPeer(pubStr)
3✔
3354
                } else {
3✔
3355
                        go s.delayInitialReconnect(pubStr)
×
3356
                }
×
3357

3358
                numOutboundConns++
3✔
3359
        }
3360

3361
        return nil
3✔
3362
}
3363

3364
// delayInitialReconnect will attempt a reconnection to the given peer after
3365
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3366
//
3367
// NOTE: This method MUST be run as a goroutine.
3368
func (s *server) delayInitialReconnect(pubStr string) {
×
3369
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3370
        select {
×
3371
        case <-time.After(delay):
×
3372
                s.connectToPersistentPeer(pubStr)
×
3373
        case <-s.quit:
×
3374
        }
3375
}
3376

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

3✔
3383
        s.mu.Lock()
3✔
3384
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3385
                delete(s.persistentPeers, pubKeyStr)
3✔
3386
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3387
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3388
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3389
                s.mu.Unlock()
3✔
3390

3✔
3391
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3392
                        "peer has no open channels", compressedPubKey)
3✔
3393

3✔
3394
                return
3✔
3395
        }
3✔
3396
        s.mu.Unlock()
3✔
3397
}
3398

3399
// BroadcastMessage sends a request to the server to broadcast a set of
3400
// messages to all peers other than the one specified by the `skips` parameter.
3401
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3402
// the target peers.
3403
//
3404
// NOTE: This function is safe for concurrent access.
3405
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3406
        msgs ...lnwire.Message) error {
3✔
3407

3✔
3408
        // Filter out peers found in the skips map. We synchronize access to
3✔
3409
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3410
        // exact set of peers present at the time of invocation.
3✔
3411
        s.mu.RLock()
3✔
3412
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3413
        for pubStr, sPeer := range s.peersByPub {
6✔
3414
                if skips != nil {
6✔
3415
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3416
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3417
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3418
                                continue
3✔
3419
                        }
3420
                }
3421

3422
                peers = append(peers, sPeer)
3✔
3423
        }
3424
        s.mu.RUnlock()
3✔
3425

3✔
3426
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3427
        // all messages to each of peers.
3✔
3428
        var wg sync.WaitGroup
3✔
3429
        for _, sPeer := range peers {
6✔
3430
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3431
                        sPeer.PubKey())
3✔
3432

3✔
3433
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3434
                wg.Add(1)
3✔
3435
                s.wg.Add(1)
3✔
3436
                go func(p lnpeer.Peer) {
6✔
3437
                        defer s.wg.Done()
3✔
3438
                        defer wg.Done()
3✔
3439

3✔
3440
                        p.SendMessageLazy(false, msgs...)
3✔
3441
                }(sPeer)
3✔
3442
        }
3443

3444
        // Wait for all messages to have been dispatched before returning to
3445
        // caller.
3446
        wg.Wait()
3✔
3447

3✔
3448
        return nil
3✔
3449
}
3450

3451
// NotifyWhenOnline can be called by other subsystems to get notified when a
3452
// particular peer comes online. The peer itself is sent across the peerChan.
3453
//
3454
// NOTE: This function is safe for concurrent access.
3455
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3456
        peerChan chan<- lnpeer.Peer) {
3✔
3457

3✔
3458
        s.mu.Lock()
3✔
3459

3✔
3460
        // Compute the target peer's identifier.
3✔
3461
        pubStr := string(peerKey[:])
3✔
3462

3✔
3463
        // Check if peer is connected.
3✔
3464
        peer, ok := s.peersByPub[pubStr]
3✔
3465
        if ok {
6✔
3466
                // Unlock here so that the mutex isn't held while we are
3✔
3467
                // waiting for the peer to become active.
3✔
3468
                s.mu.Unlock()
3✔
3469

3✔
3470
                // Wait until the peer signals that it is actually active
3✔
3471
                // rather than only in the server's maps.
3✔
3472
                select {
3✔
3473
                case <-peer.ActiveSignal():
3✔
3474
                case <-peer.QuitSignal():
×
3475
                        // The peer quit, so we'll add the channel to the slice
×
3476
                        // and return.
×
3477
                        s.mu.Lock()
×
3478
                        s.peerConnectedListeners[pubStr] = append(
×
3479
                                s.peerConnectedListeners[pubStr], peerChan,
×
3480
                        )
×
3481
                        s.mu.Unlock()
×
3482
                        return
×
3483
                }
3484

3485
                // Connected, can return early.
3486
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3487

3✔
3488
                select {
3✔
3489
                case peerChan <- peer:
3✔
3490
                case <-s.quit:
×
3491
                }
3492

3493
                return
3✔
3494
        }
3495

3496
        // Not connected, store this listener such that it can be notified when
3497
        // the peer comes online.
3498
        s.peerConnectedListeners[pubStr] = append(
3✔
3499
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3500
        )
3✔
3501
        s.mu.Unlock()
3✔
3502
}
3503

3504
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3505
// the given public key has been disconnected. The notification is signaled by
3506
// closing the channel returned.
3507
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3508
        s.mu.Lock()
3✔
3509
        defer s.mu.Unlock()
3✔
3510

3✔
3511
        c := make(chan struct{})
3✔
3512

3✔
3513
        // If the peer is already offline, we can immediately trigger the
3✔
3514
        // notification.
3✔
3515
        peerPubKeyStr := string(peerPubKey[:])
3✔
3516
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3517
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3518
                close(c)
×
3519
                return c
×
3520
        }
×
3521

3522
        // Otherwise, the peer is online, so we'll keep track of the channel to
3523
        // trigger the notification once the server detects the peer
3524
        // disconnects.
3525
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3526
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3527
        )
3✔
3528

3✔
3529
        return c
3✔
3530
}
3531

3532
// FindPeer will return the peer that corresponds to the passed in public key.
3533
// This function is used by the funding manager, allowing it to update the
3534
// daemon's local representation of the remote peer.
3535
//
3536
// NOTE: This function is safe for concurrent access.
3537
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3538
        s.mu.RLock()
3✔
3539
        defer s.mu.RUnlock()
3✔
3540

3✔
3541
        pubStr := string(peerKey.SerializeCompressed())
3✔
3542

3✔
3543
        return s.findPeerByPubStr(pubStr)
3✔
3544
}
3✔
3545

3546
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3547
// which should be a string representation of the peer's serialized, compressed
3548
// public key.
3549
//
3550
// NOTE: This function is safe for concurrent access.
3551
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3552
        s.mu.RLock()
3✔
3553
        defer s.mu.RUnlock()
3✔
3554

3✔
3555
        return s.findPeerByPubStr(pubStr)
3✔
3556
}
3✔
3557

3558
// findPeerByPubStr is an internal method that retrieves the specified peer from
3559
// the server's internal state using.
3560
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3561
        peer, ok := s.peersByPub[pubStr]
3✔
3562
        if !ok {
6✔
3563
                return nil, ErrPeerNotConnected
3✔
3564
        }
3✔
3565

3566
        return peer, nil
3✔
3567
}
3568

3569
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3570
// exponential backoff. If no previous backoff was known, the default is
3571
// returned.
3572
func (s *server) nextPeerBackoff(pubStr string,
3573
        startTime time.Time) time.Duration {
3✔
3574

3✔
3575
        // Now, determine the appropriate backoff to use for the retry.
3✔
3576
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3577
        if !ok {
6✔
3578
                // If an existing backoff was unknown, use the default.
3✔
3579
                return s.cfg.MinBackoff
3✔
3580
        }
3✔
3581

3582
        // If the peer failed to start properly, we'll just use the previous
3583
        // backoff to compute the subsequent randomized exponential backoff
3584
        // duration. This will roughly double on average.
3585
        if startTime.IsZero() {
3✔
3586
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3587
        }
×
3588

3589
        // The peer succeeded in starting. If the connection didn't last long
3590
        // enough to be considered stable, we'll continue to back off retries
3591
        // with this peer.
3592
        connDuration := time.Since(startTime)
3✔
3593
        if connDuration < defaultStableConnDuration {
6✔
3594
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3595
        }
3✔
3596

3597
        // The peer succeed in starting and this was stable peer, so we'll
3598
        // reduce the timeout duration by the length of the connection after
3599
        // applying randomized exponential backoff. We'll only apply this in the
3600
        // case that:
3601
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3602
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3603
        if relaxedBackoff > s.cfg.MinBackoff {
×
3604
                return relaxedBackoff
×
3605
        }
×
3606

3607
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3608
        // the stable connection lasted much longer than our previous backoff.
3609
        // To reward such good behavior, we'll reconnect after the default
3610
        // timeout.
3611
        return s.cfg.MinBackoff
×
3612
}
3613

3614
// shouldDropLocalConnection determines if our local connection to a remote peer
3615
// should be dropped in the case of concurrent connection establishment. In
3616
// order to deterministically decide which connection should be dropped, we'll
3617
// utilize the ordering of the local and remote public key. If we didn't use
3618
// such a tie breaker, then we risk _both_ connections erroneously being
3619
// dropped.
3620
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3621
        localPubBytes := local.SerializeCompressed()
×
3622
        remotePubPbytes := remote.SerializeCompressed()
×
3623

×
3624
        // The connection that comes from the node with a "smaller" pubkey
×
3625
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3626
        // should drop our established connection.
×
3627
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3628
}
×
3629

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

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

3✔
3644
        s.mu.Lock()
3✔
3645
        defer s.mu.Unlock()
3✔
3646

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

3✔
3654
                conn.Close()
3✔
3655
                return
3✔
3656
        }
3✔
3657

3658
        // If we already have a valid connection that is scheduled to take
3659
        // precedence once the prior peer has finished disconnecting, we'll
3660
        // ignore this connection.
3661
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
3662
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3663
                        "scheduled", conn.RemoteAddr(), p)
×
3664
                conn.Close()
×
3665
                return
×
3666
        }
×
3667

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

3✔
3670
        // Check to see if we already have a connection with this peer. If so,
3✔
3671
        // we may need to drop our existing connection. This prevents us from
3✔
3672
        // having duplicate connections to the same peer. We forgo adding a
3✔
3673
        // default case as we expect these to be the only error values returned
3✔
3674
        // from findPeerByPubStr.
3✔
3675
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
3676
        switch err {
3✔
3677
        case ErrPeerNotConnected:
3✔
3678
                // We were unable to locate an existing connection with the
3✔
3679
                // target peer, proceed to connect.
3✔
3680
                s.cancelConnReqs(pubStr, nil)
3✔
3681
                s.peerConnected(conn, nil, true)
3✔
3682

3683
        case nil:
×
3684
                // We already have a connection with the incoming peer. If the
×
3685
                // connection we've already established should be kept and is
×
3686
                // not of the same type of the new connection (inbound), then
×
3687
                // we'll close out the new connection s.t there's only a single
×
3688
                // connection between us.
×
3689
                localPub := s.identityECDH.PubKey()
×
3690
                if !connectedPeer.Inbound() &&
×
3691
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3692

×
3693
                        srvrLog.Warnf("Received inbound connection from "+
×
3694
                                "peer %v, but already have outbound "+
×
3695
                                "connection, dropping conn", connectedPeer)
×
3696
                        conn.Close()
×
3697
                        return
×
3698
                }
×
3699

3700
                // Otherwise, if we should drop the connection, then we'll
3701
                // disconnect our already connected peer.
3702
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3703
                        connectedPeer)
×
3704

×
3705
                s.cancelConnReqs(pubStr, nil)
×
3706

×
3707
                // Remove the current peer from the server's internal state and
×
3708
                // signal that the peer termination watcher does not need to
×
3709
                // execute for this peer.
×
3710
                s.removePeer(connectedPeer)
×
3711
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3712
                s.scheduledPeerConnection[pubStr] = func() {
×
3713
                        s.peerConnected(conn, nil, true)
×
3714
                }
×
3715
        }
3716
}
3717

3718
// OutboundPeerConnected initializes a new peer in response to a new outbound
3719
// connection.
3720
// NOTE: This function is safe for concurrent access.
3721
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
3722
        // Exit early if we have already been instructed to shutdown, this
3✔
3723
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3724
        if s.Stopped() {
3✔
3725
                return
×
3726
        }
×
3727

3728
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3729
        pubStr := string(nodePub.SerializeCompressed())
3✔
3730

3✔
3731
        s.mu.Lock()
3✔
3732
        defer s.mu.Unlock()
3✔
3733

3✔
3734
        // If we already have an inbound connection to this peer, then ignore
3✔
3735
        // this new connection.
3✔
3736
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
3737
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
3738
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
3739
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3740

3✔
3741
                if connReq != nil {
6✔
3742
                        s.connMgr.Remove(connReq.ID())
3✔
3743
                }
3✔
3744
                conn.Close()
3✔
3745
                return
3✔
3746
        }
3747
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
3748
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
3749
                s.connMgr.Remove(connReq.ID())
×
3750
                conn.Close()
×
3751
                return
×
3752
        }
×
3753

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

×
3760
                if connReq != nil {
×
3761
                        s.connMgr.Remove(connReq.ID())
×
3762
                }
×
3763

3764
                conn.Close()
×
3765
                return
×
3766
        }
3767

3768
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
3✔
3769
                conn.RemoteAddr())
3✔
3770

3✔
3771
        if connReq != nil {
6✔
3772
                // A successful connection was returned by the connmgr.
3✔
3773
                // Immediately cancel all pending requests, excluding the
3✔
3774
                // outbound connection we just established.
3✔
3775
                ignore := connReq.ID()
3✔
3776
                s.cancelConnReqs(pubStr, &ignore)
3✔
3777
        } else {
6✔
3778
                // This was a successful connection made by some other
3✔
3779
                // subsystem. Remove all requests being managed by the connmgr.
3✔
3780
                s.cancelConnReqs(pubStr, nil)
3✔
3781
        }
3✔
3782

3783
        // If we already have a connection with this peer, decide whether or not
3784
        // we need to drop the stale connection. We forgo adding a default case
3785
        // as we expect these to be the only error values returned from
3786
        // findPeerByPubStr.
3787
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
3788
        switch err {
3✔
3789
        case ErrPeerNotConnected:
3✔
3790
                // We were unable to locate an existing connection with the
3✔
3791
                // target peer, proceed to connect.
3✔
3792
                s.peerConnected(conn, connReq, false)
3✔
3793

3794
        case nil:
×
3795
                // We already have a connection with the incoming peer. If the
×
3796
                // connection we've already established should be kept and is
×
3797
                // not of the same type of the new connection (outbound), then
×
3798
                // we'll close out the new connection s.t there's only a single
×
3799
                // connection between us.
×
3800
                localPub := s.identityECDH.PubKey()
×
3801
                if connectedPeer.Inbound() &&
×
3802
                        shouldDropLocalConnection(localPub, nodePub) {
×
3803

×
3804
                        srvrLog.Warnf("Established outbound connection to "+
×
3805
                                "peer %v, but already have inbound "+
×
3806
                                "connection, dropping conn", connectedPeer)
×
3807
                        if connReq != nil {
×
3808
                                s.connMgr.Remove(connReq.ID())
×
3809
                        }
×
3810
                        conn.Close()
×
3811
                        return
×
3812
                }
3813

3814
                // Otherwise, _their_ connection should be dropped. So we'll
3815
                // disconnect the peer and send the now obsolete peer to the
3816
                // server for garbage collection.
3817
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3818
                        connectedPeer)
×
3819

×
3820
                // Remove the current peer from the server's internal state and
×
3821
                // signal that the peer termination watcher does not need to
×
3822
                // execute for this peer.
×
3823
                s.removePeer(connectedPeer)
×
3824
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3825
                s.scheduledPeerConnection[pubStr] = func() {
×
3826
                        s.peerConnected(conn, connReq, false)
×
3827
                }
×
3828
        }
3829
}
3830

3831
// UnassignedConnID is the default connection ID that a request can have before
3832
// it actually is submitted to the connmgr.
3833
// TODO(conner): move into connmgr package, or better, add connmgr method for
3834
// generating atomic IDs
3835
const UnassignedConnID uint64 = 0
3836

3837
// cancelConnReqs stops all persistent connection requests for a given pubkey.
3838
// Any attempts initiated by the peerTerminationWatcher are canceled first.
3839
// Afterwards, each connection request removed from the connmgr. The caller can
3840
// optionally specify a connection ID to ignore, which prevents us from
3841
// canceling a successful request. All persistent connreqs for the provided
3842
// pubkey are discarded after the operationjw.
3843
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
3844
        // First, cancel any lingering persistent retry attempts, which will
3✔
3845
        // prevent retries for any with backoffs that are still maturing.
3✔
3846
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
3847
                close(cancelChan)
3✔
3848
                delete(s.persistentRetryCancels, pubStr)
3✔
3849
        }
3✔
3850

3851
        // Next, check to see if we have any outstanding persistent connection
3852
        // requests to this peer. If so, then we'll remove all of these
3853
        // connection requests, and also delete the entry from the map.
3854
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
3855
        if !ok {
6✔
3856
                return
3✔
3857
        }
3✔
3858

3859
        for _, connReq := range connReqs {
6✔
3860
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
3861

3✔
3862
                // Atomically capture the current request identifier.
3✔
3863
                connID := connReq.ID()
3✔
3864

3✔
3865
                // Skip any zero IDs, this indicates the request has not
3✔
3866
                // yet been schedule.
3✔
3867
                if connID == UnassignedConnID {
3✔
3868
                        continue
×
3869
                }
3870

3871
                // Skip a particular connection ID if instructed.
3872
                if skip != nil && connID == *skip {
6✔
3873
                        continue
3✔
3874
                }
3875

3876
                s.connMgr.Remove(connID)
3✔
3877
        }
3878

3879
        delete(s.persistentConnReqs, pubStr)
3✔
3880
}
3881

3882
// handleCustomMessage dispatches an incoming custom peers message to
3883
// subscribers.
3884
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
3885
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
3886
                peer, msg.Type)
3✔
3887

3✔
3888
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
3889
                Peer: peer,
3✔
3890
                Msg:  msg,
3✔
3891
        })
3✔
3892
}
3✔
3893

3894
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
3895
// messages.
3896
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
3897
        return s.customMessageServer.Subscribe()
3✔
3898
}
3✔
3899

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

3✔
3907
        brontideConn := conn.(*brontide.Conn)
3✔
3908
        addr := conn.RemoteAddr()
3✔
3909
        pubKey := brontideConn.RemotePub()
3✔
3910

3✔
3911
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
3912
                pubKey.SerializeCompressed(), addr, inbound)
3✔
3913

3✔
3914
        peerAddr := &lnwire.NetAddress{
3✔
3915
                IdentityKey: pubKey,
3✔
3916
                Address:     addr,
3✔
3917
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
3918
        }
3✔
3919

3✔
3920
        // With the brontide connection established, we'll now craft the feature
3✔
3921
        // vectors to advertise to the remote node.
3✔
3922
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
3923
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
3924

3✔
3925
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
3926
        // found, create a fresh buffer.
3✔
3927
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
3928
        errBuffer, ok := s.peerErrors[pkStr]
3✔
3929
        if !ok {
6✔
3930
                var err error
3✔
3931
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
3932
                if err != nil {
3✔
3933
                        srvrLog.Errorf("unable to create peer %v", err)
×
3934
                        return
×
3935
                }
×
3936
        }
3937

3938
        // If we directly set the peer.Config TowerClient member to the
3939
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
3940
        // the peer.Config's TowerClient member will not evaluate to nil even
3941
        // though the underlying value is nil. To avoid this gotcha which can
3942
        // cause a panic, we need to explicitly pass nil to the peer.Config's
3943
        // TowerClient if needed.
3944
        var towerClient wtclient.ClientManager
3✔
3945
        if s.towerClientMgr != nil {
6✔
3946
                towerClient = s.towerClientMgr
3✔
3947
        }
3✔
3948

3949
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
3950
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
3951

3✔
3952
        // Now that we've established a connection, create a peer, and it to the
3✔
3953
        // set of currently active peers. Configure the peer with the incoming
3✔
3954
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
3✔
3955
        // offered that would trigger channel closure. In case of outgoing
3✔
3956
        // htlcs, an extra block is added to prevent the channel from being
3✔
3957
        // closed when the htlc is outstanding and a new block comes in.
3✔
3958
        pCfg := peer.Config{
3✔
3959
                Conn:                    brontideConn,
3✔
3960
                ConnReq:                 connReq,
3✔
3961
                Addr:                    peerAddr,
3✔
3962
                Inbound:                 inbound,
3✔
3963
                Features:                initFeatures,
3✔
3964
                LegacyFeatures:          legacyFeatures,
3✔
3965
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
3✔
3966
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
3✔
3967
                ErrorBuffer:             errBuffer,
3✔
3968
                WritePool:               s.writePool,
3✔
3969
                ReadPool:                s.readPool,
3✔
3970
                Switch:                  s.htlcSwitch,
3✔
3971
                InterceptSwitch:         s.interceptableSwitch,
3✔
3972
                ChannelDB:               s.chanStateDB,
3✔
3973
                ChannelGraph:            s.graphDB,
3✔
3974
                ChainArb:                s.chainArb,
3✔
3975
                AuthGossiper:            s.authGossiper,
3✔
3976
                ChanStatusMgr:           s.chanStatusMgr,
3✔
3977
                ChainIO:                 s.cc.ChainIO,
3✔
3978
                FeeEstimator:            s.cc.FeeEstimator,
3✔
3979
                Signer:                  s.cc.Wallet.Cfg.Signer,
3✔
3980
                SigPool:                 s.sigPool,
3✔
3981
                Wallet:                  s.cc.Wallet,
3✔
3982
                ChainNotifier:           s.cc.ChainNotifier,
3✔
3983
                BestBlockView:           s.cc.BestBlockTracker,
3✔
3984
                RoutingPolicy:           s.cc.RoutingPolicy,
3✔
3985
                Sphinx:                  s.sphinx,
3✔
3986
                WitnessBeacon:           s.witnessBeacon,
3✔
3987
                Invoices:                s.invoices,
3✔
3988
                ChannelNotifier:         s.channelNotifier,
3✔
3989
                HtlcNotifier:            s.htlcNotifier,
3✔
3990
                TowerClient:             towerClient,
3✔
3991
                DisconnectPeer:          s.DisconnectPeer,
3✔
3992
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
3✔
3993
                        lnwire.NodeAnnouncement, error) {
6✔
3994

3✔
3995
                        return s.genNodeAnnouncement(nil)
3✔
3996
                },
3✔
3997

3998
                PongBuf: s.pongBuf,
3999

4000
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4001

4002
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4003

4004
                FundingManager: s.fundingMgr,
4005

4006
                Hodl:                    s.cfg.Hodl,
4007
                UnsafeReplay:            s.cfg.UnsafeReplay,
4008
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4009
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4010
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4011
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4012
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4013
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4014
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4015
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4016
                HandleCustomMessage:    s.handleCustomMessage,
4017
                GetAliases:             s.aliasMgr.GetAliases,
4018
                RequestAlias:           s.aliasMgr.RequestAlias,
4019
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4020
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4021
                MaxFeeExposure:         thresholdMSats,
4022
                Quit:                   s.quit,
4023
                MsgRouter:              s.implCfg.MsgRouter,
4024
        }
4025

4026
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4027
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4028

3✔
4029
        p := peer.NewBrontide(pCfg)
3✔
4030

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

3✔
4034
        s.addPeer(p)
3✔
4035

3✔
4036
        // Once we have successfully added the peer to the server, we can
3✔
4037
        // delete the previous error buffer from the server's map of error
3✔
4038
        // buffers.
3✔
4039
        delete(s.peerErrors, pkStr)
3✔
4040

3✔
4041
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4042
        // includes sending and receiving Init messages, which would be a DOS
3✔
4043
        // vector if we held the server's mutex throughout the procedure.
3✔
4044
        s.wg.Add(1)
3✔
4045
        go s.peerInitializer(p)
3✔
4046
}
4047

4048
// addPeer adds the passed peer to the server's global state of all active
4049
// peers.
4050
func (s *server) addPeer(p *peer.Brontide) {
3✔
4051
        if p == nil {
3✔
4052
                return
×
4053
        }
×
4054

4055
        // Ignore new peers if we're shutting down.
4056
        if s.Stopped() {
3✔
4057
                p.Disconnect(ErrServerShuttingDown)
×
4058
                return
×
4059
        }
×
4060

4061
        // Track the new peer in our indexes so we can quickly look it up either
4062
        // according to its public key, or its peer ID.
4063
        // TODO(roasbeef): pipe all requests through to the
4064
        // queryHandler/peerManager
4065

4066
        pubSer := p.IdentityKey().SerializeCompressed()
3✔
4067
        pubStr := string(pubSer)
3✔
4068

3✔
4069
        s.peersByPub[pubStr] = p
3✔
4070

3✔
4071
        if p.Inbound() {
6✔
4072
                s.inboundPeers[pubStr] = p
3✔
4073
        } else {
6✔
4074
                s.outboundPeers[pubStr] = p
3✔
4075
        }
3✔
4076

4077
        // Inform the peer notifier of a peer online event so that it can be reported
4078
        // to clients listening for peer events.
4079
        var pubKey [33]byte
3✔
4080
        copy(pubKey[:], pubSer)
3✔
4081

3✔
4082
        s.peerNotifier.NotifyPeerOnline(pubKey)
3✔
4083
}
4084

4085
// peerInitializer asynchronously starts a newly connected peer after it has
4086
// been added to the server's peer map. This method sets up a
4087
// peerTerminationWatcher for the given peer, and ensures that it executes even
4088
// if the peer failed to start. In the event of a successful connection, this
4089
// method reads the negotiated, local feature-bits and spawns the appropriate
4090
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4091
// be signaled of the new peer once the method returns.
4092
//
4093
// NOTE: This MUST be launched as a goroutine.
4094
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4095
        defer s.wg.Done()
3✔
4096

3✔
4097
        // Avoid initializing peers while the server is exiting.
3✔
4098
        if s.Stopped() {
3✔
4099
                return
×
4100
        }
×
4101

4102
        // Create a channel that will be used to signal a successful start of
4103
        // the link. This prevents the peer termination watcher from beginning
4104
        // its duty too early.
4105
        ready := make(chan struct{})
3✔
4106

3✔
4107
        // Before starting the peer, launch a goroutine to watch for the
3✔
4108
        // unexpected termination of this peer, which will ensure all resources
3✔
4109
        // are properly cleaned up, and re-establish persistent connections when
3✔
4110
        // necessary. The peer termination watcher will be short circuited if
3✔
4111
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4112
        // that the server has already handled the removal of this peer.
3✔
4113
        s.wg.Add(1)
3✔
4114
        go s.peerTerminationWatcher(p, ready)
3✔
4115

3✔
4116
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4117
        // will unblock the peerTerminationWatcher.
3✔
4118
        if err := p.Start(); err != nil {
3✔
UNCOV
4119
                srvrLog.Warnf("Starting peer=%v got error: %v",
×
UNCOV
4120
                        p.IdentityKey(), err)
×
UNCOV
4121

×
UNCOV
4122
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
UNCOV
4123
                return
×
UNCOV
4124
        }
×
4125

4126
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4127
        // was successful, and to begin watching the peer's wait group.
4128
        close(ready)
3✔
4129

3✔
4130
        pubStr := string(p.IdentityKey().SerializeCompressed())
3✔
4131

3✔
4132
        s.mu.Lock()
3✔
4133
        defer s.mu.Unlock()
3✔
4134

3✔
4135
        // Check if there are listeners waiting for this peer to come online.
3✔
4136
        srvrLog.Debugf("Notifying that peer %v is online", p)
3✔
4137
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4138
                select {
3✔
4139
                case peerChan <- p:
3✔
UNCOV
4140
                case <-s.quit:
×
UNCOV
4141
                        return
×
4142
                }
4143
        }
4144
        delete(s.peerConnectedListeners, pubStr)
3✔
4145
}
4146

4147
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4148
// and then cleans up all resources allocated to the peer, notifies relevant
4149
// sub-systems of its demise, and finally handles re-connecting to the peer if
4150
// it's persistent. If the server intentionally disconnects a peer, it should
4151
// have a corresponding entry in the ignorePeerTermination map which will cause
4152
// the cleanup routine to exit early. The passed `ready` chan is used to
4153
// synchronize when WaitForDisconnect should begin watching on the peer's
4154
// waitgroup. The ready chan should only be signaled if the peer starts
4155
// successfully, otherwise the peer should be disconnected instead.
4156
//
4157
// NOTE: This MUST be launched as a goroutine.
4158
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4159
        defer s.wg.Done()
3✔
4160

3✔
4161
        p.WaitForDisconnect(ready)
3✔
4162

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

3✔
4165
        // If the server is exiting then we can bail out early ourselves as all
3✔
4166
        // the other sub-systems will already be shutting down.
3✔
4167
        if s.Stopped() {
6✔
4168
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
3✔
4169
                return
3✔
4170
        }
3✔
4171

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

3✔
4178
        pubKey := p.IdentityKey()
3✔
4179

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

3✔
4184
        // Tell the switch to remove all links associated with this peer.
3✔
4185
        // Passing nil as the target link indicates that all links associated
3✔
4186
        // with this interface should be closed.
3✔
4187
        //
3✔
4188
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4189
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4190
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4191
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4192
        }
×
4193

4194
        for _, link := range links {
6✔
4195
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4196
        }
3✔
4197

4198
        s.mu.Lock()
3✔
4199
        defer s.mu.Unlock()
3✔
4200

3✔
4201
        // If there were any notification requests for when this peer
3✔
4202
        // disconnected, we can trigger them now.
3✔
4203
        srvrLog.Debugf("Notifying that peer %v is offline", p)
3✔
4204
        pubStr := string(pubKey.SerializeCompressed())
3✔
4205
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4206
                close(offlineChan)
3✔
4207
        }
3✔
4208
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4209

3✔
4210
        // If the server has already removed this peer, we can short circuit the
3✔
4211
        // peer termination watcher and skip cleanup.
3✔
4212
        if _, ok := s.ignorePeerTermination[p]; ok {
3✔
4213
                delete(s.ignorePeerTermination, p)
×
4214

×
4215
                pubKey := p.PubKey()
×
4216
                pubStr := string(pubKey[:])
×
4217

×
4218
                // If a connection callback is present, we'll go ahead and
×
4219
                // execute it now that previous peer has fully disconnected. If
×
4220
                // the callback is not present, this likely implies the peer was
×
4221
                // purposefully disconnected via RPC, and that no reconnect
×
4222
                // should be attempted.
×
4223
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4224
                if ok {
×
4225
                        delete(s.scheduledPeerConnection, pubStr)
×
4226
                        connCallback()
×
4227
                }
×
4228
                return
×
4229
        }
4230

4231
        // First, cleanup any remaining state the server has regarding the peer
4232
        // in question.
4233
        s.removePeer(p)
3✔
4234

3✔
4235
        // Next, check to see if this is a persistent peer or not.
3✔
4236
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4237
                return
3✔
4238
        }
3✔
4239

4240
        // Get the last address that we used to connect to the peer.
4241
        addrs := []net.Addr{
3✔
4242
                p.NetAddress().Address,
3✔
4243
        }
3✔
4244

3✔
4245
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4246
        // reconnection purposes.
3✔
4247
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
3✔
4248
        switch {
3✔
4249
        // We found advertised addresses, so use them.
4250
        case err == nil:
3✔
4251
                addrs = advertisedAddrs
3✔
4252

4253
        // The peer doesn't have an advertised address.
4254
        case err == errNoAdvertisedAddr:
3✔
4255
                // If it is an outbound peer then we fall back to the existing
3✔
4256
                // peer address.
3✔
4257
                if !p.Inbound() {
6✔
4258
                        break
3✔
4259
                }
4260

4261
                // Fall back to the existing peer address if
4262
                // we're not accepting connections over Tor.
4263
                if s.torController == nil {
6✔
4264
                        break
3✔
4265
                }
4266

4267
                // If we are, the peer's address won't be known
4268
                // to us (we'll see a private address, which is
4269
                // the address used by our onion service to dial
4270
                // to lnd), so we don't have enough information
4271
                // to attempt a reconnect.
4272
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4273
                        "to inbound peer %v without "+
×
4274
                        "advertised address", p)
×
4275
                return
×
4276

4277
        // We came across an error retrieving an advertised
4278
        // address, log it, and fall back to the existing peer
4279
        // address.
4280
        default:
3✔
4281
                srvrLog.Errorf("Unable to retrieve advertised "+
3✔
4282
                        "address for node %x: %v", p.PubKey(),
3✔
4283
                        err)
3✔
4284
        }
4285

4286
        // Make an easy lookup map so that we can check if an address
4287
        // is already in the address list that we have stored for this peer.
4288
        existingAddrs := make(map[string]bool)
3✔
4289
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4290
                existingAddrs[addr.String()] = true
3✔
4291
        }
3✔
4292

4293
        // Add any missing addresses for this peer to persistentPeerAddr.
4294
        for _, addr := range addrs {
6✔
4295
                if existingAddrs[addr.String()] {
3✔
4296
                        continue
×
4297
                }
4298

4299
                s.persistentPeerAddrs[pubStr] = append(
3✔
4300
                        s.persistentPeerAddrs[pubStr],
3✔
4301
                        &lnwire.NetAddress{
3✔
4302
                                IdentityKey: p.IdentityKey(),
3✔
4303
                                Address:     addr,
3✔
4304
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4305
                        },
3✔
4306
                )
3✔
4307
        }
4308

4309
        // Record the computed backoff in the backoff map.
4310
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4311
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4312

3✔
4313
        // Initialize a retry canceller for this peer if one does not
3✔
4314
        // exist.
3✔
4315
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4316
        if !ok {
6✔
4317
                cancelChan = make(chan struct{})
3✔
4318
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4319
        }
3✔
4320

4321
        // We choose not to wait group this go routine since the Connect
4322
        // call can stall for arbitrarily long if we shutdown while an
4323
        // outbound connection attempt is being made.
4324
        go func() {
6✔
4325
                srvrLog.Debugf("Scheduling connection re-establishment to "+
3✔
4326
                        "persistent peer %x in %s",
3✔
4327
                        p.IdentityKey().SerializeCompressed(), backoff)
3✔
4328

3✔
4329
                select {
3✔
4330
                case <-time.After(backoff):
3✔
4331
                case <-cancelChan:
3✔
4332
                        return
3✔
4333
                case <-s.quit:
3✔
4334
                        return
3✔
4335
                }
4336

4337
                srvrLog.Debugf("Attempting to re-establish persistent "+
3✔
4338
                        "connection to peer %x",
3✔
4339
                        p.IdentityKey().SerializeCompressed())
3✔
4340

3✔
4341
                s.connectToPersistentPeer(pubStr)
3✔
4342
        }()
4343
}
4344

4345
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4346
// to connect to the peer. It creates connection requests if there are
4347
// currently none for a given address and it removes old connection requests
4348
// if the associated address is no longer in the latest address list for the
4349
// peer.
4350
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4351
        s.mu.Lock()
3✔
4352
        defer s.mu.Unlock()
3✔
4353

3✔
4354
        // Create an easy lookup map of the addresses we have stored for the
3✔
4355
        // peer. We will remove entries from this map if we have existing
3✔
4356
        // connection requests for the associated address and then any leftover
3✔
4357
        // entries will indicate which addresses we should create new
3✔
4358
        // connection requests for.
3✔
4359
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4360
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4361
                addrMap[addr.String()] = addr
3✔
4362
        }
3✔
4363

4364
        // Go through each of the existing connection requests and
4365
        // check if they correspond to the latest set of addresses. If
4366
        // there is a connection requests that does not use one of the latest
4367
        // advertised addresses then remove that connection request.
4368
        var updatedConnReqs []*connmgr.ConnReq
3✔
4369
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4370
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4371

3✔
4372
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4373
                // If the existing connection request is using one of the
4374
                // latest advertised addresses for the peer then we add it to
4375
                // updatedConnReqs and remove the associated address from
4376
                // addrMap so that we don't recreate this connReq later on.
4377
                case true:
×
4378
                        updatedConnReqs = append(
×
4379
                                updatedConnReqs, connReq,
×
4380
                        )
×
4381
                        delete(addrMap, lnAddr)
×
4382

4383
                // If the existing connection request is using an address that
4384
                // is not one of the latest advertised addresses for the peer
4385
                // then we remove the connecting request from the connection
4386
                // manager.
4387
                case false:
3✔
4388
                        srvrLog.Info(
3✔
4389
                                "Removing conn req:", connReq.Addr.String(),
3✔
4390
                        )
3✔
4391
                        s.connMgr.Remove(connReq.ID())
3✔
4392
                }
4393
        }
4394

4395
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4396

3✔
4397
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4398
        if !ok {
6✔
4399
                cancelChan = make(chan struct{})
3✔
4400
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4401
        }
3✔
4402

4403
        // Any addresses left in addrMap are new ones that we have not made
4404
        // connection requests for. So create new connection requests for those.
4405
        // If there is more than one address in the address map, stagger the
4406
        // creation of the connection requests for those.
4407
        go func() {
6✔
4408
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4409
                defer ticker.Stop()
3✔
4410

3✔
4411
                for _, addr := range addrMap {
6✔
4412
                        // Send the persistent connection request to the
3✔
4413
                        // connection manager, saving the request itself so we
3✔
4414
                        // can cancel/restart the process as needed.
3✔
4415
                        connReq := &connmgr.ConnReq{
3✔
4416
                                Addr:      addr,
3✔
4417
                                Permanent: true,
3✔
4418
                        }
3✔
4419

3✔
4420
                        s.mu.Lock()
3✔
4421
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4422
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4423
                        )
3✔
4424
                        s.mu.Unlock()
3✔
4425

3✔
4426
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4427
                                "channel peer %v", addr)
3✔
4428

3✔
4429
                        go s.connMgr.Connect(connReq)
3✔
4430

3✔
4431
                        select {
3✔
4432
                        case <-s.quit:
3✔
4433
                                return
3✔
4434
                        case <-cancelChan:
3✔
4435
                                return
3✔
4436
                        case <-ticker.C:
3✔
4437
                        }
4438
                }
4439
        }()
4440
}
4441

4442
// removePeer removes the passed peer from the server's state of all active
4443
// peers.
4444
func (s *server) removePeer(p *peer.Brontide) {
3✔
4445
        if p == nil {
3✔
4446
                return
×
4447
        }
×
4448

4449
        srvrLog.Debugf("removing peer %v", p)
3✔
4450

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

3✔
4455
        // If this peer had an active persistent connection request, remove it.
3✔
4456
        if p.ConnReq() != nil {
6✔
4457
                s.connMgr.Remove(p.ConnReq().ID())
3✔
4458
        }
3✔
4459

4460
        // Ignore deleting peers if we're shutting down.
4461
        if s.Stopped() {
3✔
4462
                return
×
4463
        }
×
4464

4465
        pKey := p.PubKey()
3✔
4466
        pubSer := pKey[:]
3✔
4467
        pubStr := string(pubSer)
3✔
4468

3✔
4469
        delete(s.peersByPub, pubStr)
3✔
4470

3✔
4471
        if p.Inbound() {
6✔
4472
                delete(s.inboundPeers, pubStr)
3✔
4473
        } else {
6✔
4474
                delete(s.outboundPeers, pubStr)
3✔
4475
        }
3✔
4476

4477
        // Copy the peer's error buffer across to the server if it has any items
4478
        // in it so that we can restore peer errors across connections.
4479
        if p.ErrorBuffer().Total() > 0 {
6✔
4480
                s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4481
        }
3✔
4482

4483
        // Inform the peer notifier of a peer offline event so that it can be
4484
        // reported to clients listening for peer events.
4485
        var pubKey [33]byte
3✔
4486
        copy(pubKey[:], pubSer)
3✔
4487

3✔
4488
        s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4489
}
4490

4491
// ConnectToPeer requests that the server connect to a Lightning Network peer
4492
// at the specified address. This function will *block* until either a
4493
// connection is established, or the initial handshake process fails.
4494
//
4495
// NOTE: This function is safe for concurrent access.
4496
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4497
        perm bool, timeout time.Duration) error {
3✔
4498

3✔
4499
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4500

3✔
4501
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
4502
        // better granularity.  In certain conditions, this method requires
3✔
4503
        // making an outbound connection to a remote peer, which requires the
3✔
4504
        // lock to be released, and subsequently reacquired.
3✔
4505
        s.mu.Lock()
3✔
4506

3✔
4507
        // Ensure we're not already connected to this peer.
3✔
4508
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4509
        if err == nil {
6✔
4510
                s.mu.Unlock()
3✔
4511
                return &errPeerAlreadyConnected{peer: peer}
3✔
4512
        }
3✔
4513

4514
        // Peer was not found, continue to pursue connection with peer.
4515

4516
        // If there's already a pending connection request for this pubkey,
4517
        // then we ignore this request to ensure we don't create a redundant
4518
        // connection.
4519
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
4520
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
4521
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
4522
        }
3✔
4523

4524
        // If there's not already a pending or active connection to this node,
4525
        // then instruct the connection manager to attempt to establish a
4526
        // persistent connection to the peer.
4527
        srvrLog.Debugf("Connecting to %v", addr)
3✔
4528
        if perm {
6✔
4529
                connReq := &connmgr.ConnReq{
3✔
4530
                        Addr:      addr,
3✔
4531
                        Permanent: true,
3✔
4532
                }
3✔
4533

3✔
4534
                // Since the user requested a permanent connection, we'll set
3✔
4535
                // the entry to true which will tell the server to continue
3✔
4536
                // reconnecting even if the number of channels with this peer is
3✔
4537
                // zero.
3✔
4538
                s.persistentPeers[targetPub] = true
3✔
4539
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
4540
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
4541
                }
3✔
4542
                s.persistentConnReqs[targetPub] = append(
3✔
4543
                        s.persistentConnReqs[targetPub], connReq,
3✔
4544
                )
3✔
4545
                s.mu.Unlock()
3✔
4546

3✔
4547
                go s.connMgr.Connect(connReq)
3✔
4548

3✔
4549
                return nil
3✔
4550
        }
4551
        s.mu.Unlock()
3✔
4552

3✔
4553
        // If we're not making a persistent connection, then we'll attempt to
3✔
4554
        // connect to the target peer. If the we can't make the connection, or
3✔
4555
        // the crypto negotiation breaks down, then return an error to the
3✔
4556
        // caller.
3✔
4557
        errChan := make(chan error, 1)
3✔
4558
        s.connectToPeer(addr, errChan, timeout)
3✔
4559

3✔
4560
        select {
3✔
4561
        case err := <-errChan:
3✔
4562
                return err
3✔
4563
        case <-s.quit:
×
4564
                return ErrServerShuttingDown
×
4565
        }
4566
}
4567

4568
// connectToPeer establishes a connection to a remote peer. errChan is used to
4569
// notify the caller if the connection attempt has failed. Otherwise, it will be
4570
// closed.
4571
func (s *server) connectToPeer(addr *lnwire.NetAddress,
4572
        errChan chan<- error, timeout time.Duration) {
3✔
4573

3✔
4574
        conn, err := brontide.Dial(
3✔
4575
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
4576
        )
3✔
4577
        if err != nil {
6✔
4578
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
4579
                select {
3✔
4580
                case errChan <- err:
3✔
4581
                case <-s.quit:
×
4582
                }
4583
                return
3✔
4584
        }
4585

4586
        close(errChan)
3✔
4587

3✔
4588
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
4589
                conn.LocalAddr(), conn.RemoteAddr())
3✔
4590

3✔
4591
        s.OutboundPeerConnected(nil, conn)
3✔
4592
}
4593

4594
// DisconnectPeer sends the request to server to close the connection with peer
4595
// identified by public key.
4596
//
4597
// NOTE: This function is safe for concurrent access.
4598
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
4599
        pubBytes := pubKey.SerializeCompressed()
3✔
4600
        pubStr := string(pubBytes)
3✔
4601

3✔
4602
        s.mu.Lock()
3✔
4603
        defer s.mu.Unlock()
3✔
4604

3✔
4605
        // Check that were actually connected to this peer. If not, then we'll
3✔
4606
        // exit in an error as we can't disconnect from a peer that we're not
3✔
4607
        // currently connected to.
3✔
4608
        peer, err := s.findPeerByPubStr(pubStr)
3✔
4609
        if err == ErrPeerNotConnected {
6✔
4610
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
4611
        }
3✔
4612

4613
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
4614

3✔
4615
        s.cancelConnReqs(pubStr, nil)
3✔
4616

3✔
4617
        // If this peer was formerly a persistent connection, then we'll remove
3✔
4618
        // them from this map so we don't attempt to re-connect after we
3✔
4619
        // disconnect.
3✔
4620
        delete(s.persistentPeers, pubStr)
3✔
4621
        delete(s.persistentPeersBackoff, pubStr)
3✔
4622

3✔
4623
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
4624
        // removePeer, which bypassed the peerTerminationWatcher.
3✔
4625
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
4626

3✔
4627
        return nil
3✔
4628
}
4629

4630
// OpenChannel sends a request to the server to open a channel to the specified
4631
// peer identified by nodeKey with the passed channel funding parameters.
4632
//
4633
// NOTE: This function is safe for concurrent access.
4634
func (s *server) OpenChannel(
4635
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
4636

3✔
4637
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
4638
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
4639
        // not blocked if the caller is not reading the updates.
3✔
4640
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
4641
        req.Err = make(chan error, 1)
3✔
4642

3✔
4643
        // First attempt to locate the target peer to open a channel with, if
3✔
4644
        // we're unable to locate the peer then this request will fail.
3✔
4645
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
4646
        s.mu.RLock()
3✔
4647
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
4648
        if !ok {
3✔
4649
                s.mu.RUnlock()
×
4650

×
4651
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4652
                return req.Updates, req.Err
×
4653
        }
×
4654
        req.Peer = peer
3✔
4655
        s.mu.RUnlock()
3✔
4656

3✔
4657
        // We'll wait until the peer is active before beginning the channel
3✔
4658
        // opening process.
3✔
4659
        select {
3✔
4660
        case <-peer.ActiveSignal():
3✔
4661
        case <-peer.QuitSignal():
×
4662
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
4663
                return req.Updates, req.Err
×
4664
        case <-s.quit:
×
4665
                req.Err <- ErrServerShuttingDown
×
4666
                return req.Updates, req.Err
×
4667
        }
4668

4669
        // If the fee rate wasn't specified at this point we fail the funding
4670
        // because of the missing fee rate information. The caller of the
4671
        // `OpenChannel` method needs to make sure that default values for the
4672
        // fee rate are set beforehand.
4673
        if req.FundingFeePerKw == 0 {
3✔
4674
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
4675
                        "the channel opening transaction")
×
4676

×
4677
                return req.Updates, req.Err
×
4678
        }
×
4679

4680
        // Spawn a goroutine to send the funding workflow request to the funding
4681
        // manager. This allows the server to continue handling queries instead
4682
        // of blocking on this request which is exported as a synchronous
4683
        // request to the outside world.
4684
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
4685

3✔
4686
        return req.Updates, req.Err
3✔
4687
}
4688

4689
// Peers returns a slice of all active peers.
4690
//
4691
// NOTE: This function is safe for concurrent access.
4692
func (s *server) Peers() []*peer.Brontide {
3✔
4693
        s.mu.RLock()
3✔
4694
        defer s.mu.RUnlock()
3✔
4695

3✔
4696
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
4697
        for _, peer := range s.peersByPub {
6✔
4698
                peers = append(peers, peer)
3✔
4699
        }
3✔
4700

4701
        return peers
3✔
4702
}
4703

4704
// computeNextBackoff uses a truncated exponential backoff to compute the next
4705
// backoff using the value of the exiting backoff. The returned duration is
4706
// randomized in either direction by 1/20 to prevent tight loops from
4707
// stabilizing.
4708
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
4709
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
4710
        nextBackoff := 2 * currBackoff
3✔
4711
        if nextBackoff > maxBackoff {
6✔
4712
                nextBackoff = maxBackoff
3✔
4713
        }
3✔
4714

4715
        // Using 1/10 of our duration as a margin, compute a random offset to
4716
        // avoid the nodes entering connection cycles.
4717
        margin := nextBackoff / 10
3✔
4718

3✔
4719
        var wiggle big.Int
3✔
4720
        wiggle.SetUint64(uint64(margin))
3✔
4721
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
4722
                // Randomizing is not mission critical, so we'll just return the
×
4723
                // current backoff.
×
4724
                return nextBackoff
×
4725
        }
×
4726

4727
        // Otherwise add in our wiggle, but subtract out half of the margin so
4728
        // that the backoff can tweaked by 1/20 in either direction.
4729
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
4730
}
4731

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

4736
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
4737
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
3✔
4738
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
4739
        if err != nil {
3✔
4740
                return nil, err
×
4741
        }
×
4742

4743
        node, err := s.graphDB.FetchLightningNode(vertex)
3✔
4744
        if err != nil {
6✔
4745
                return nil, err
3✔
4746
        }
3✔
4747

4748
        if len(node.Addresses) == 0 {
6✔
4749
                return nil, errNoAdvertisedAddr
3✔
4750
        }
3✔
4751

4752
        return node.Addresses, nil
3✔
4753
}
4754

4755
// fetchLastChanUpdate returns a function which is able to retrieve our latest
4756
// channel update for a target channel.
4757
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
4758
        *lnwire.ChannelUpdate, error) {
3✔
4759

3✔
4760
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
4761
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate, error) {
6✔
4762
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
4763
                if err != nil {
6✔
4764
                        return nil, err
3✔
4765
                }
3✔
4766

4767
                return netann.ExtractChannelUpdate(
3✔
4768
                        ourPubKey[:], info, edge1, edge2,
3✔
4769
                )
3✔
4770
        }
4771
}
4772

4773
// applyChannelUpdate applies the channel update to the different sub-systems of
4774
// the server. The useAlias boolean denotes whether or not to send an alias in
4775
// place of the real SCID.
4776
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate,
4777
        op *wire.OutPoint, useAlias bool) error {
3✔
4778

3✔
4779
        var (
3✔
4780
                peerAlias    *lnwire.ShortChannelID
3✔
4781
                defaultAlias lnwire.ShortChannelID
3✔
4782
        )
3✔
4783

3✔
4784
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
4785

3✔
4786
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
4787
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
4788
        if useAlias {
6✔
4789
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
4790
                if foundAlias != defaultAlias {
6✔
4791
                        peerAlias = &foundAlias
3✔
4792
                }
3✔
4793
        }
4794

4795
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
4796
                update, discovery.RemoteAlias(peerAlias),
3✔
4797
        )
3✔
4798
        select {
3✔
4799
        case err := <-errChan:
3✔
4800
                return err
3✔
4801
        case <-s.quit:
×
4802
                return ErrServerShuttingDown
×
4803
        }
4804
}
4805

4806
// SendCustomMessage sends a custom message to the peer with the specified
4807
// pubkey.
4808
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
4809
        data []byte) error {
3✔
4810

3✔
4811
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
4812
        if err != nil {
3✔
4813
                return err
×
4814
        }
×
4815

4816
        // We'll wait until the peer is active.
4817
        select {
3✔
4818
        case <-peer.ActiveSignal():
3✔
4819
        case <-peer.QuitSignal():
×
4820
                return fmt.Errorf("peer %x disconnected", peerPub)
×
4821
        case <-s.quit:
×
4822
                return ErrServerShuttingDown
×
4823
        }
4824

4825
        msg, err := lnwire.NewCustom(msgType, data)
3✔
4826
        if err != nil {
6✔
4827
                return err
3✔
4828
        }
3✔
4829

4830
        // Send the message as low-priority. For now we assume that all
4831
        // application-defined message are low priority.
4832
        return peer.SendMessageLazy(true, msg)
3✔
4833
}
4834

4835
// newSweepPkScriptGen creates closure that generates a new public key script
4836
// which should be used to sweep any funds into the on-chain wallet.
4837
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
4838
// (p2wkh) output.
4839
func newSweepPkScriptGen(
4840
        wallet lnwallet.WalletController) func() ([]byte, error) {
3✔
4841

3✔
4842
        return func() ([]byte, error) {
6✔
4843
                sweepAddr, err := wallet.NewAddress(
3✔
4844
                        lnwallet.TaprootPubkey, false,
3✔
4845
                        lnwallet.DefaultAccountName,
3✔
4846
                )
3✔
4847
                if err != nil {
3✔
4848
                        return nil, err
×
4849
                }
×
4850

4851
                return txscript.PayToAddrScript(sweepAddr)
3✔
4852
        }
4853
}
4854

4855
// shouldPeerBootstrap returns true if we should attempt to perform peer
4856
// bootstrapping to actively seek our peers using the set of active network
4857
// bootstrappers.
4858
func shouldPeerBootstrap(cfg *Config) bool {
3✔
4859
        isSimnet := cfg.Bitcoin.SimNet
3✔
4860
        isSignet := cfg.Bitcoin.SigNet
3✔
4861
        isRegtest := cfg.Bitcoin.RegTest
3✔
4862
        isDevNetwork := isSimnet || isSignet || isRegtest
3✔
4863

3✔
4864
        // TODO(yy): remove the check on simnet/regtest such that the itest is
3✔
4865
        // covering the bootstrapping process.
3✔
4866
        return !cfg.NoNetBootstrap && !isDevNetwork
3✔
4867
}
3✔
4868

4869
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
4870
// finished.
4871
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
4872
        // Get a list of closed channels.
3✔
4873
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
4874
        if err != nil {
3✔
4875
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
4876
                return nil
×
4877
        }
×
4878

4879
        // Save the SCIDs in a map.
4880
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
4881
        for _, c := range channels {
6✔
4882
                // If the channel is not pending, its FC has been finalized.
3✔
4883
                if !c.IsPending {
6✔
4884
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
4885
                }
3✔
4886
        }
4887

4888
        // Double check whether the reported closed channel has indeed finished
4889
        // closing.
4890
        //
4891
        // NOTE: There are misalignments regarding when a channel's FC is
4892
        // marked as finalized. We double check the pending channels to make
4893
        // sure the returned SCIDs are indeed terminated.
4894
        //
4895
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
4896
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
4897
        if err != nil {
3✔
4898
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
4899
                return nil
×
4900
        }
×
4901

4902
        for _, c := range pendings {
6✔
4903
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
4904
                        continue
3✔
4905
                }
4906

4907
                // If the channel is still reported as pending, remove it from
4908
                // the map.
4909
                delete(closedSCIDs, c.ShortChannelID)
×
4910

×
4911
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
4912
                        c.ShortChannelID)
×
4913
        }
4914

4915
        return closedSCIDs
3✔
4916
}
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