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

lightningnetwork / lnd / 11219354629

07 Oct 2024 03:56PM UTC coverage: 58.585% (-0.2%) from 58.814%
11219354629

Pull #9147

github

ziggie1984
fixup! sqlc: migration up script for payments.
Pull Request #9147: [Part 1|3] Introduce SQL Payment schema into LND

130227 of 222287 relevant lines covered (58.59%)

29106.19 hits per line

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

63.61
/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 {
147
        return fmt.Sprintf("already connected to peer: %v", e.peer)
2✔
148
}
2✔
149

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

158
        start sync.Once
159
        stop  sync.Once
160

161
        cfg *Config
162

163
        implCfg *ImplementationCfg
164

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

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

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

176
        chanStatusMgr *netann.ChanStatusManager
177

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

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

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

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

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

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

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

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

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

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

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

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

242
        cc *chainreg.ChainControl
243

244
        fundingMgr *funding.Manager
245

246
        graphDB *channeldb.ChannelGraph
247

248
        chanStateDB *channeldb.ChannelStateDB
249

250
        addrSource chanbackup.AddressSource
251

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

256
        invoicesDB invoices.InvoiceDB
257

258
        aliasMgr *aliasmgr.Manager
259

260
        htlcSwitch *htlcswitch.Switch
261

262
        interceptableSwitch *htlcswitch.InterceptableSwitch
263

264
        invoices *invoices.InvoiceRegistry
265

266
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
267

268
        channelNotifier *channelnotifier.ChannelNotifier
269

270
        peerNotifier *peernotifier.PeerNotifier
271

272
        htlcNotifier *htlcswitch.HtlcNotifier
273

274
        witnessBeacon contractcourt.WitnessBeacon
275

276
        breachArbitrator *contractcourt.BreachArbitrator
277

278
        missionControl *routing.MissionControl
279

280
        graphBuilder *graph.Builder
281

282
        chanRouter *routing.ChannelRouter
283

284
        controlTower routing.ControlTower
285

286
        authGossiper *discovery.AuthenticatedGossiper
287

288
        localChanMgr *localchans.Manager
289

290
        utxoNursery *contractcourt.UtxoNursery
291

292
        sweeper *sweep.UtxoSweeper
293

294
        chainArb *contractcourt.ChainArbitrator
295

296
        sphinx *hop.OnionProcessor
297

298
        towerClientMgr *wtclient.Manager
299

300
        connMgr *connmgr.ConnManager
301

302
        sigPool *lnwallet.SigPool
303

304
        writePool *pool.Write
305

306
        readPool *pool.Read
307

308
        tlsManager *TLSManager
309

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

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

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

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

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

332
        hostAnn *netann.HostAnnouncer
333

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

337
        customMessageServer *subscribe.Server
338

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

342
        quit chan struct{}
343

344
        wg sync.WaitGroup
345
}
346

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

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

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

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

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

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

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

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

2✔
402
                                        s.mu.Lock()
2✔
403

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

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

2✔
418
                                        s.mu.Unlock()
419

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

426
        return nil
427
}
428

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2✔
601
                listenAddrs: listenAddrs,
2✔
602

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

2✔
607
                torController: torController,
2✔
608

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

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

2✔
625
                invoiceHtlcModifier: invoiceHtlcModifier,
2✔
626

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

2✔
629
                tlsManager: tlsManager,
2✔
630

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

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

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

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

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

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

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

2✔
661
                return nil
2✔
662
        }
2✔
663

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1731
        return s, nil
×
1732
}
1733

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

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

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

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

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

1760
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
1761
}
1762

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

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

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

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

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

2✔
1795
                chainBackendAttempts = 0
2✔
1796
        }
2✔
1797

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2✔
1945
                checks = append(checks, leaderCheck)
2✔
1946
        }
2✔
1947

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2396
                close(s.quit)
×
2397

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

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

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

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

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

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

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

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

×
2519
        return nil
×
2520
}
×
2521

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

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

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

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

×
2551
        return externalIPs, nil
2552
}
2553

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2711
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2712

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

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

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

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

2741
        return bootStrappers, nil
×
2742
}
×
2743

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

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

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

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

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

×
2774
        return ignore
×
2775
}
×
2776

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

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

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

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

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

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

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

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

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

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

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

×
2838
                                sampleTicker.Stop()
×
2839

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3098
        return nil
×
3099
}
×
3100

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

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

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

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

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

3126
        return *s.currentNodeAnn
×
3127
}
×
3128

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

×
3135
        s.mu.Lock()
×
3136
        defer s.mu.Unlock()
×
3137

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

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

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

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

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

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

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

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

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

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

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

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

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

2✔
3220
        return nil
2✔
3221
}
2✔
3222

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
3399
                numOutboundConns++
3400
        }
2✔
3401

2✔
3402
        return nil
2✔
3403
}
2✔
3404

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

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

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

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

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

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

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

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

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

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

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

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

2✔
3489
        return nil
3490
}
3491

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

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

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

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

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

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

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

2✔
3534
                return
3535
        }
3536

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

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

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

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

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

×
3570
        return c
×
3571
}
×
3572

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

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

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

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

3596
        return s.findPeerByPubStr(pubStr)
3597
}
3598

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

2✔
3607
        return peer, nil
2✔
3608
}
2✔
3609

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

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

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

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

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

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

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

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

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

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

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

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

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

3699
                return
3700
        }
3701

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

3706
                conn.Close()
3707

3708
                return
3709
        }
3710

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

×
3718
                conn.Close()
×
3719
                return
×
3720
        }
×
3721

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

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

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

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

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

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

2✔
3769
                s.cancelConnReqs(pubStr, nil)
2✔
3770

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

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

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

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

×
3799
        s.mu.Lock()
×
3800
        defer s.mu.Unlock()
×
3801

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

×
3809
                return
×
3810
        }
×
3811

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

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

×
3820
                conn.Close()
×
3821

×
3822
                return
×
3823
        }
×
3824

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
3967
                s.connMgr.Remove(connID)
×
3968
        }
×
3969

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2✔
4089
                PongBuf: s.pongBuf,
2✔
4090

4091
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
2✔
4092

2✔
4093
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
2✔
4094

2✔
4095
                FundingManager: s.fundingMgr,
2✔
4096

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

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

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

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

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

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

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

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

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

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

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

4163
        s.peersByPub[pubStr] = p
4164

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4492
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
4493

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

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

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

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

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

4526
                        go s.connMgr.Connect(connReq)
×
4527

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4644
                go s.connMgr.Connect(connReq)
4645

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

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

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

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

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

2✔
4683
        close(errChan)
2✔
4684

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

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

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

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

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

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

2✔
4712
        s.cancelConnReqs(pubStr, nil)
×
4713

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

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

2✔
4724
        return nil
2✔
4725
}
2✔
4726

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

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

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

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

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

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

2✔
4774
                return req.Updates, req.Err
2✔
4775
        }
2✔
4776

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

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

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

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

2✔
4798
        return peers
×
4799
}
×
4800

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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