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

lightningnetwork / lnd / 10244606158

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

Pull #8959

github

guggero
mod: bump kvdb to v1.4.10

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

125469 of 213798 relevant lines covered (58.69%)

28246.55 hits per line

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

78.72
/peer/brontide.go
1
package peer
2

3
import (
4
        "bytes"
5
        "container/list"
6
        "errors"
7
        "fmt"
8
        "math/rand"
9
        "net"
10
        "strings"
11
        "sync"
12
        "sync/atomic"
13
        "time"
14

15
        "github.com/btcsuite/btcd/btcec/v2"
16
        "github.com/btcsuite/btcd/chaincfg/chainhash"
17
        "github.com/btcsuite/btcd/connmgr"
18
        "github.com/btcsuite/btcd/txscript"
19
        "github.com/btcsuite/btcd/wire"
20
        "github.com/btcsuite/btclog"
21
        "github.com/davecgh/go-spew/spew"
22
        "github.com/lightningnetwork/lnd/buffer"
23
        "github.com/lightningnetwork/lnd/build"
24
        "github.com/lightningnetwork/lnd/chainntnfs"
25
        "github.com/lightningnetwork/lnd/channeldb"
26
        "github.com/lightningnetwork/lnd/channeldb/models"
27
        "github.com/lightningnetwork/lnd/channelnotifier"
28
        "github.com/lightningnetwork/lnd/contractcourt"
29
        "github.com/lightningnetwork/lnd/discovery"
30
        "github.com/lightningnetwork/lnd/feature"
31
        "github.com/lightningnetwork/lnd/fn"
32
        "github.com/lightningnetwork/lnd/funding"
33
        "github.com/lightningnetwork/lnd/htlcswitch"
34
        "github.com/lightningnetwork/lnd/htlcswitch/hodl"
35
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
36
        "github.com/lightningnetwork/lnd/input"
37
        "github.com/lightningnetwork/lnd/invoices"
38
        "github.com/lightningnetwork/lnd/lnpeer"
39
        "github.com/lightningnetwork/lnd/lntypes"
40
        "github.com/lightningnetwork/lnd/lnutils"
41
        "github.com/lightningnetwork/lnd/lnwallet"
42
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
43
        "github.com/lightningnetwork/lnd/lnwallet/chancloser"
44
        "github.com/lightningnetwork/lnd/lnwire"
45
        "github.com/lightningnetwork/lnd/netann"
46
        "github.com/lightningnetwork/lnd/pool"
47
        "github.com/lightningnetwork/lnd/queue"
48
        "github.com/lightningnetwork/lnd/subscribe"
49
        "github.com/lightningnetwork/lnd/ticker"
50
        "github.com/lightningnetwork/lnd/tlv"
51
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
52
)
53

54
const (
55
        // pingInterval is the interval at which ping messages are sent.
56
        pingInterval = 1 * time.Minute
57

58
        // pingTimeout is the amount of time we will wait for a pong response
59
        // before considering the peer to be unresponsive.
60
        //
61
        // This MUST be a smaller value than the pingInterval.
62
        pingTimeout = 30 * time.Second
63

64
        // idleTimeout is the duration of inactivity before we time out a peer.
65
        idleTimeout = 5 * time.Minute
66

67
        // writeMessageTimeout is the timeout used when writing a message to the
68
        // peer.
69
        writeMessageTimeout = 5 * time.Second
70

71
        // readMessageTimeout is the timeout used when reading a message from a
72
        // peer.
73
        readMessageTimeout = 5 * time.Second
74

75
        // handshakeTimeout is the timeout used when waiting for the peer's init
76
        // message.
77
        handshakeTimeout = 15 * time.Second
78

79
        // ErrorBufferSize is the number of historic peer errors that we store.
80
        ErrorBufferSize = 10
81

82
        // pongSizeCeiling is the upper bound on a uniformly distributed random
83
        // variable that we use for requesting pong responses. We don't use the
84
        // MaxPongBytes (upper bound accepted by the protocol) because it is
85
        // needlessly wasteful of precious Tor bandwidth for little to no gain.
86
        pongSizeCeiling = 4096
87

88
        // torTimeoutMultiplier is the scaling factor we use on network timeouts
89
        // for Tor peers.
90
        torTimeoutMultiplier = 3
91
)
92

93
var (
94
        // ErrChannelNotFound is an error returned when a channel is queried and
95
        // either the Brontide doesn't know of it, or the channel in question
96
        // is pending.
97
        ErrChannelNotFound = fmt.Errorf("channel not found")
98
)
99

100
// outgoingMsg packages an lnwire.Message to be sent out on the wire, along with
101
// a buffered channel which will be sent upon once the write is complete. This
102
// buffered channel acts as a semaphore to be used for synchronization purposes.
103
type outgoingMsg struct {
104
        priority bool
105
        msg      lnwire.Message
106
        errChan  chan error // MUST be buffered.
107
}
108

109
// newChannelMsg packages a channeldb.OpenChannel with a channel that allows
110
// the receiver of the request to report when the channel creation process has
111
// completed.
112
type newChannelMsg struct {
113
        // channel is used when the pending channel becomes active.
114
        channel *lnpeer.NewChannel
115

116
        // channelID is used when there's a new pending channel.
117
        channelID lnwire.ChannelID
118

119
        err chan error
120
}
121

122
type customMsg struct {
123
        peer [33]byte
124
        msg  lnwire.Custom
125
}
126

127
// closeMsg is a wrapper struct around any wire messages that deal with the
128
// cooperative channel closure negotiation process. This struct includes the
129
// raw channel ID targeted along with the original message.
130
type closeMsg struct {
131
        cid lnwire.ChannelID
132
        msg lnwire.Message
133
}
134

135
// PendingUpdate describes the pending state of a closing channel.
136
type PendingUpdate struct {
137
        Txid        []byte
138
        OutputIndex uint32
139
}
140

141
// ChannelCloseUpdate contains the outcome of the close channel operation.
142
type ChannelCloseUpdate struct {
143
        ClosingTxid []byte
144
        Success     bool
145
}
146

147
// TimestampedError is a timestamped error that is used to store the most recent
148
// errors we have experienced with our peers.
149
type TimestampedError struct {
150
        Error     error
151
        Timestamp time.Time
152
}
153

154
// Config defines configuration fields that are necessary for a peer object
155
// to function.
156
type Config struct {
157
        // Conn is the underlying network connection for this peer.
158
        Conn MessageConn
159

160
        // ConnReq stores information related to the persistent connection request
161
        // for this peer.
162
        ConnReq *connmgr.ConnReq
163

164
        // PubKeyBytes is the serialized, compressed public key of this peer.
165
        PubKeyBytes [33]byte
166

167
        // Addr is the network address of the peer.
168
        Addr *lnwire.NetAddress
169

170
        // Inbound indicates whether or not the peer is an inbound peer.
171
        Inbound bool
172

173
        // Features is the set of features that we advertise to the remote party.
174
        Features *lnwire.FeatureVector
175

176
        // LegacyFeatures is the set of features that we advertise to the remote
177
        // peer for backwards compatibility. Nodes that have not implemented
178
        // flat features will still be able to read our feature bits from the
179
        // legacy global field, but we will also advertise everything in the
180
        // default features field.
181
        LegacyFeatures *lnwire.FeatureVector
182

183
        // OutgoingCltvRejectDelta defines the number of blocks before expiry of
184
        // an htlc where we don't offer it anymore.
185
        OutgoingCltvRejectDelta uint32
186

187
        // ChanActiveTimeout specifies the duration the peer will wait to request
188
        // a channel reenable, beginning from the time the peer was started.
189
        ChanActiveTimeout time.Duration
190

191
        // ErrorBuffer stores a set of errors related to a peer. It contains error
192
        // messages that our peer has recently sent us over the wire and records of
193
        // unknown messages that were sent to us so that we can have a full track
194
        // record of the communication errors we have had with our peer. If we
195
        // choose to disconnect from a peer, it also stores the reason we had for
196
        // disconnecting.
197
        ErrorBuffer *queue.CircularBuffer
198

199
        // WritePool is the task pool that manages reuse of write buffers. Write
200
        // tasks are submitted to the pool in order to conserve the total number of
201
        // write buffers allocated at any one time, and decouple write buffer
202
        // allocation from the peer life cycle.
203
        WritePool *pool.Write
204

205
        // ReadPool is the task pool that manages reuse of read buffers.
206
        ReadPool *pool.Read
207

208
        // Switch is a pointer to the htlcswitch. It is used to setup, get, and
209
        // tear-down ChannelLinks.
210
        Switch messageSwitch
211

212
        // InterceptSwitch is a pointer to the InterceptableSwitch, a wrapper around
213
        // the regular Switch. We only export it here to pass ForwardPackets to the
214
        // ChannelLinkConfig.
215
        InterceptSwitch *htlcswitch.InterceptableSwitch
216

217
        // ChannelDB is used to fetch opened channels, and closed channels.
218
        ChannelDB *channeldb.ChannelStateDB
219

220
        // ChannelGraph is a pointer to the channel graph which is used to
221
        // query information about the set of known active channels.
222
        ChannelGraph *channeldb.ChannelGraph
223

224
        // ChainArb is used to subscribe to channel events, update contract signals,
225
        // and force close channels.
226
        ChainArb *contractcourt.ChainArbitrator
227

228
        // AuthGossiper is needed so that the Brontide impl can register with the
229
        // gossiper and process remote channel announcements.
230
        AuthGossiper *discovery.AuthenticatedGossiper
231

232
        // ChanStatusMgr is used to set or un-set the disabled bit in channel
233
        // updates.
234
        ChanStatusMgr *netann.ChanStatusManager
235

236
        // ChainIO is used to retrieve the best block.
237
        ChainIO lnwallet.BlockChainIO
238

239
        // FeeEstimator is used to compute our target ideal fee-per-kw when
240
        // initializing the coop close process.
241
        FeeEstimator chainfee.Estimator
242

243
        // Signer is used when creating *lnwallet.LightningChannel instances.
244
        Signer input.Signer
245

246
        // SigPool is used when creating *lnwallet.LightningChannel instances.
247
        SigPool *lnwallet.SigPool
248

249
        // Wallet is used to publish transactions and generates delivery
250
        // scripts during the coop close process.
251
        Wallet *lnwallet.LightningWallet
252

253
        // ChainNotifier is used to receive confirmations of a coop close
254
        // transaction.
255
        ChainNotifier chainntnfs.ChainNotifier
256

257
        // BestBlockView is used to efficiently query for up-to-date
258
        // blockchain state information
259
        BestBlockView chainntnfs.BestBlockView
260

261
        // RoutingPolicy is used to set the forwarding policy for links created by
262
        // the Brontide.
263
        RoutingPolicy models.ForwardingPolicy
264

265
        // Sphinx is used when setting up ChannelLinks so they can decode sphinx
266
        // onion blobs.
267
        Sphinx *hop.OnionProcessor
268

269
        // WitnessBeacon is used when setting up ChannelLinks so they can add any
270
        // preimages that they learn.
271
        WitnessBeacon contractcourt.WitnessBeacon
272

273
        // Invoices is passed to the ChannelLink on creation and handles all
274
        // invoice-related logic.
275
        Invoices *invoices.InvoiceRegistry
276

277
        // ChannelNotifier is used by the link to notify other sub-systems about
278
        // channel-related events and by the Brontide to subscribe to
279
        // ActiveLinkEvents.
280
        ChannelNotifier *channelnotifier.ChannelNotifier
281

282
        // HtlcNotifier is used when creating a ChannelLink.
283
        HtlcNotifier *htlcswitch.HtlcNotifier
284

285
        // TowerClient is used to backup revoked states.
286
        TowerClient wtclient.ClientManager
287

288
        // DisconnectPeer is used to disconnect this peer if the cooperative close
289
        // process fails.
290
        DisconnectPeer func(*btcec.PublicKey) error
291

292
        // GenNodeAnnouncement is used to send our node announcement to the remote
293
        // on startup.
294
        GenNodeAnnouncement func(...netann.NodeAnnModifier) (
295
                lnwire.NodeAnnouncement, error)
296

297
        // PrunePersistentPeerConnection is used to remove all internal state
298
        // related to this peer in the server.
299
        PrunePersistentPeerConnection func([33]byte)
300

301
        // FetchLastChanUpdate fetches our latest channel update for a target
302
        // channel.
303
        FetchLastChanUpdate func(lnwire.ShortChannelID) (*lnwire.ChannelUpdate,
304
                error)
305

306
        // FundingManager is an implementation of the funding.Controller interface.
307
        FundingManager funding.Controller
308

309
        // Hodl is used when creating ChannelLinks to specify HodlFlags as
310
        // breakpoints in dev builds.
311
        Hodl *hodl.Config
312

313
        // UnsafeReplay is used when creating ChannelLinks to specify whether or
314
        // not to replay adds on its commitment tx.
315
        UnsafeReplay bool
316

317
        // MaxOutgoingCltvExpiry is used when creating ChannelLinks and is the max
318
        // number of blocks that funds could be locked up for when forwarding
319
        // payments.
320
        MaxOutgoingCltvExpiry uint32
321

322
        // MaxChannelFeeAllocation is used when creating ChannelLinks and is the
323
        // maximum percentage of total funds that can be allocated to a channel's
324
        // commitment fee. This only applies for the initiator of the channel.
325
        MaxChannelFeeAllocation float64
326

327
        // MaxAnchorsCommitFeeRate is the maximum fee rate we'll use as an
328
        // initiator for anchor channel commitments.
329
        MaxAnchorsCommitFeeRate chainfee.SatPerKWeight
330

331
        // CoopCloseTargetConfs is the confirmation target that will be used
332
        // to estimate the fee rate to use during a cooperative channel
333
        // closure initiated by the remote peer.
334
        CoopCloseTargetConfs uint32
335

336
        // ServerPubKey is the serialized, compressed public key of our lnd node.
337
        // It is used to determine which policy (channel edge) to pass to the
338
        // ChannelLink.
339
        ServerPubKey [33]byte
340

341
        // ChannelCommitInterval is the maximum time that is allowed to pass between
342
        // receiving a channel state update and signing the next commitment.
343
        // Setting this to a longer duration allows for more efficient channel
344
        // operations at the cost of latency.
345
        ChannelCommitInterval time.Duration
346

347
        // PendingCommitInterval is the maximum time that is allowed to pass
348
        // while waiting for the remote party to revoke a locally initiated
349
        // commitment state. Setting this to a longer duration if a slow
350
        // response is expected from the remote party or large number of
351
        // payments are attempted at the same time.
352
        PendingCommitInterval time.Duration
353

354
        // ChannelCommitBatchSize is the maximum number of channel state updates
355
        // that is accumulated before signing a new commitment.
356
        ChannelCommitBatchSize uint32
357

358
        // HandleCustomMessage is called whenever a custom message is received
359
        // from the peer.
360
        HandleCustomMessage func(peer [33]byte, msg *lnwire.Custom) error
361

362
        // GetAliases is passed to created links so the Switch and link can be
363
        // aware of the channel's aliases.
364
        GetAliases func(base lnwire.ShortChannelID) []lnwire.ShortChannelID
365

366
        // RequestAlias allows the Brontide struct to request an alias to send
367
        // to the peer.
368
        RequestAlias func() (lnwire.ShortChannelID, error)
369

370
        // AddLocalAlias persists an alias to an underlying alias store.
371
        AddLocalAlias func(alias, base lnwire.ShortChannelID,
372
                gossip bool) error
373

374
        // PongBuf is a slice we'll reuse instead of allocating memory on the
375
        // heap. Since only reads will occur and no writes, there is no need
376
        // for any synchronization primitives. As a result, it's safe to share
377
        // this across multiple Peer struct instances.
378
        PongBuf []byte
379

380
        // Adds the option to disable forwarding payments in blinded routes
381
        // by failing back any blinding-related payloads as if they were
382
        // invalid.
383
        DisallowRouteBlinding bool
384

385
        // MaxFeeExposure limits the number of outstanding fees in a channel.
386
        // This value will be passed to created links.
387
        MaxFeeExposure lnwire.MilliSatoshi
388

389
        // Quit is the server's quit channel. If this is closed, we halt operation.
390
        Quit chan struct{}
391
}
392

393
// Brontide is an active peer on the Lightning Network. This struct is responsible
394
// for managing any channel state related to this peer. To do so, it has
395
// several helper goroutines to handle events such as HTLC timeouts, new
396
// funding workflow, and detecting an uncooperative closure of any active
397
// channels.
398
// TODO(roasbeef): proper reconnection logic.
399
type Brontide struct {
400
        // MUST be used atomically.
401
        started    int32
402
        disconnect int32
403

404
        // MUST be used atomically.
405
        bytesReceived uint64
406
        bytesSent     uint64
407

408
        // isTorConnection is a flag that indicates whether or not we believe
409
        // the remote peer is a tor connection. It is not always possible to
410
        // know this with certainty but we have heuristics we use that should
411
        // catch most cases.
412
        //
413
        // NOTE: We judge the tor-ness of a connection by if the remote peer has
414
        // ".onion" in the address OR if it's connected over localhost.
415
        // This will miss cases where our peer is connected to our clearnet
416
        // address over the tor network (via exit nodes). It will also misjudge
417
        // actual localhost connections as tor. We need to include this because
418
        // inbound connections to our tor address will appear to come from the
419
        // local socks5 proxy. This heuristic is only used to expand the timeout
420
        // window for peers so it is OK to misjudge this. If you use this field
421
        // for any other purpose you should seriously consider whether or not
422
        // this heuristic is good enough for your use case.
423
        isTorConnection bool
424

425
        pingManager *PingManager
426

427
        // lastPingPayload stores an unsafe pointer wrapped as an atomic
428
        // variable which points to the last payload the remote party sent us
429
        // as their ping.
430
        //
431
        // MUST be used atomically.
432
        lastPingPayload atomic.Value
433

434
        cfg Config
435

436
        // activeSignal when closed signals that the peer is now active and
437
        // ready to process messages.
438
        activeSignal chan struct{}
439

440
        // startTime is the time this peer connection was successfully established.
441
        // It will be zero for peers that did not successfully call Start().
442
        startTime time.Time
443

444
        // sendQueue is the channel which is used to queue outgoing messages to be
445
        // written onto the wire. Note that this channel is unbuffered.
446
        sendQueue chan outgoingMsg
447

448
        // outgoingQueue is a buffered channel which allows second/third party
449
        // objects to queue messages to be sent out on the wire.
450
        outgoingQueue chan outgoingMsg
451

452
        // activeChannels is a map which stores the state machines of all
453
        // active channels. Channels are indexed into the map by the txid of
454
        // the funding transaction which opened the channel.
455
        //
456
        // NOTE: On startup, pending channels are stored as nil in this map.
457
        // Confirmed channels have channel data populated in the map. This means
458
        // that accesses to this map should nil-check the LightningChannel to
459
        // see if this is a pending channel or not. The tradeoff here is either
460
        // having two maps everywhere (one for pending, one for confirmed chans)
461
        // or having an extra nil-check per access.
462
        activeChannels *lnutils.SyncMap[
463
                lnwire.ChannelID, *lnwallet.LightningChannel]
464

465
        // addedChannels tracks any new channels opened during this peer's
466
        // lifecycle. We use this to filter out these new channels when the time
467
        // comes to request a reenable for active channels, since they will have
468
        // waited a shorter duration.
469
        addedChannels *lnutils.SyncMap[lnwire.ChannelID, struct{}]
470

471
        // newActiveChannel is used by the fundingManager to send fully opened
472
        // channels to the source peer which handled the funding workflow.
473
        newActiveChannel chan *newChannelMsg
474

475
        // newPendingChannel is used by the fundingManager to send pending open
476
        // channels to the source peer which handled the funding workflow.
477
        newPendingChannel chan *newChannelMsg
478

479
        // removePendingChannel is used by the fundingManager to cancel pending
480
        // open channels to the source peer when the funding flow is failed.
481
        removePendingChannel chan *newChannelMsg
482

483
        // activeMsgStreams is a map from channel id to the channel streams that
484
        // proxy messages to individual, active links.
485
        activeMsgStreams map[lnwire.ChannelID]*msgStream
486

487
        // activeChanCloses is a map that keeps track of all the active
488
        // cooperative channel closures. Any channel closing messages are directed
489
        // to one of these active state machines. Once the channel has been closed,
490
        // the state machine will be deleted from the map.
491
        activeChanCloses map[lnwire.ChannelID]*chancloser.ChanCloser
492

493
        // localCloseChanReqs is a channel in which any local requests to close
494
        // a particular channel are sent over.
495
        localCloseChanReqs chan *htlcswitch.ChanClose
496

497
        // linkFailures receives all reported channel failures from the switch,
498
        // and instructs the channelManager to clean remaining channel state.
499
        linkFailures chan linkFailureReport
500

501
        // chanCloseMsgs is a channel that any message related to channel
502
        // closures are sent over. This includes lnwire.Shutdown message as
503
        // well as lnwire.ClosingSigned messages.
504
        chanCloseMsgs chan *closeMsg
505

506
        // remoteFeatures is the feature vector received from the peer during
507
        // the connection handshake.
508
        remoteFeatures *lnwire.FeatureVector
509

510
        // resentChanSyncMsg is a set that keeps track of which channels we
511
        // have re-sent channel reestablishment messages for. This is done to
512
        // avoid getting into loop where both peers will respond to the other
513
        // peer's chansync message with its own over and over again.
514
        resentChanSyncMsg map[lnwire.ChannelID]struct{}
515

516
        // channelEventClient is the channel event subscription client that's
517
        // used to assist retry enabling the channels. This client is only
518
        // created when the reenableTimeout is no greater than 1 minute. Once
519
        // created, it is canceled once the reenabling has been finished.
520
        //
521
        // NOTE: we choose to create the client conditionally to avoid
522
        // potentially holding lots of un-consumed events.
523
        channelEventClient *subscribe.Client
524

525
        startReady chan struct{}
526
        quit       chan struct{}
527
        wg         sync.WaitGroup
528

529
        // log is a peer-specific logging instance.
530
        log btclog.Logger
531
}
532

533
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer interface.
534
var _ lnpeer.Peer = (*Brontide)(nil)
535

536
// NewBrontide creates a new Brontide from a peer.Config struct.
537
func NewBrontide(cfg Config) *Brontide {
28✔
538
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
28✔
539

28✔
540
        p := &Brontide{
28✔
541
                cfg:           cfg,
28✔
542
                activeSignal:  make(chan struct{}),
28✔
543
                sendQueue:     make(chan outgoingMsg),
28✔
544
                outgoingQueue: make(chan outgoingMsg),
28✔
545
                addedChannels: &lnutils.SyncMap[lnwire.ChannelID, struct{}]{},
28✔
546
                activeChannels: &lnutils.SyncMap[
28✔
547
                        lnwire.ChannelID, *lnwallet.LightningChannel,
28✔
548
                ]{},
28✔
549
                newActiveChannel:     make(chan *newChannelMsg, 1),
28✔
550
                newPendingChannel:    make(chan *newChannelMsg, 1),
28✔
551
                removePendingChannel: make(chan *newChannelMsg),
28✔
552

28✔
553
                activeMsgStreams:   make(map[lnwire.ChannelID]*msgStream),
28✔
554
                activeChanCloses:   make(map[lnwire.ChannelID]*chancloser.ChanCloser),
28✔
555
                localCloseChanReqs: make(chan *htlcswitch.ChanClose),
28✔
556
                linkFailures:       make(chan linkFailureReport),
28✔
557
                chanCloseMsgs:      make(chan *closeMsg),
28✔
558
                resentChanSyncMsg:  make(map[lnwire.ChannelID]struct{}),
28✔
559
                startReady:         make(chan struct{}),
28✔
560
                quit:               make(chan struct{}),
28✔
561
                log:                build.NewPrefixLog(logPrefix, peerLog),
28✔
562
        }
28✔
563

28✔
564
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
32✔
565
                remoteAddr := cfg.Conn.RemoteAddr().String()
4✔
566
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
4✔
567
                        strings.Contains(remoteAddr, "127.0.0.1")
4✔
568
        }
4✔
569

570
        var (
28✔
571
                lastBlockHeader           *wire.BlockHeader
28✔
572
                lastSerializedBlockHeader [wire.MaxBlockHeaderPayload]byte
28✔
573
        )
28✔
574
        newPingPayload := func() []byte {
31✔
575
                // We query the BestBlockHeader from our BestBlockView each time
3✔
576
                // this is called, and update our serialized block header if
3✔
577
                // they differ.  Over time, we'll use this to disseminate the
3✔
578
                // latest block header between all our peers, which can later be
3✔
579
                // used to cross-check our own view of the network to mitigate
3✔
580
                // various types of eclipse attacks.
3✔
581
                header, err := p.cfg.BestBlockView.BestBlockHeader()
3✔
582
                if err != nil && header == lastBlockHeader {
3✔
583
                        return lastSerializedBlockHeader[:]
×
584
                }
×
585

586
                buf := bytes.NewBuffer(lastSerializedBlockHeader[0:0])
3✔
587
                err = header.Serialize(buf)
3✔
588
                if err == nil {
6✔
589
                        lastBlockHeader = header
3✔
590
                } else {
3✔
591
                        p.log.Warn("unable to serialize current block" +
×
592
                                "header for ping payload generation." +
×
593
                                "This should be impossible and means" +
×
594
                                "there is an implementation bug.")
×
595
                }
×
596

597
                return lastSerializedBlockHeader[:]
3✔
598
        }
599

600
        // TODO(roasbeef): make dynamic in order to create fake cover traffic.
601
        //
602
        // NOTE(proofofkeags): this was changed to be dynamic to allow better
603
        // pong identification, however, more thought is needed to make this
604
        // actually usable as a traffic decoy.
605
        randPongSize := func() uint16 {
31✔
606
                return uint16(
3✔
607
                        // We don't need cryptographic randomness here.
3✔
608
                        /* #nosec */
3✔
609
                        rand.Intn(pongSizeCeiling) + 1,
3✔
610
                )
3✔
611
        }
3✔
612

613
        p.pingManager = NewPingManager(&PingManagerConfig{
28✔
614
                NewPingPayload:   newPingPayload,
28✔
615
                NewPongSize:      randPongSize,
28✔
616
                IntervalDuration: p.scaleTimeout(pingInterval),
28✔
617
                TimeoutDuration:  p.scaleTimeout(pingTimeout),
28✔
618
                SendPing: func(ping *lnwire.Ping) {
31✔
619
                        p.queueMsg(ping, nil)
3✔
620
                },
3✔
621
                OnPongFailure: func(err error) {
×
622
                        eStr := "pong response failure for %s: %v " +
×
623
                                "-- disconnecting"
×
624
                        p.log.Warnf(eStr, p, err)
×
625
                        go p.Disconnect(fmt.Errorf(eStr, p, err))
×
626
                },
×
627
        })
628

629
        return p
28✔
630
}
631

632
// Start starts all helper goroutines the peer needs for normal operations.  In
633
// the case this peer has already been started, then this function is a noop.
634
func (p *Brontide) Start() error {
6✔
635
        if atomic.AddInt32(&p.started, 1) != 1 {
6✔
636
                return nil
×
637
        }
×
638

639
        // Once we've finished starting up the peer, we'll signal to other
640
        // goroutines that the they can move forward to tear down the peer, or
641
        // carry out other relevant changes.
642
        defer close(p.startReady)
6✔
643

6✔
644
        p.log.Tracef("starting with conn[%v->%v]",
6✔
645
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
6✔
646

6✔
647
        // Fetch and then load all the active channels we have with this remote
6✔
648
        // peer from the database.
6✔
649
        activeChans, err := p.cfg.ChannelDB.FetchOpenChannels(
6✔
650
                p.cfg.Addr.IdentityKey,
6✔
651
        )
6✔
652
        if err != nil {
6✔
653
                p.log.Errorf("Unable to fetch active chans "+
×
654
                        "for peer: %v", err)
×
655
                return err
×
656
        }
×
657

658
        if len(activeChans) == 0 {
11✔
659
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
5✔
660
        }
5✔
661

662
        // Quickly check if we have any existing legacy channels with this
663
        // peer.
664
        haveLegacyChan := false
6✔
665
        for _, c := range activeChans {
11✔
666
                if c.ChanType.IsTweakless() {
10✔
667
                        continue
5✔
668
                }
669

670
                haveLegacyChan = true
4✔
671
                break
4✔
672
        }
673

674
        // Exchange local and global features, the init message should be very
675
        // first between two nodes.
676
        if err := p.sendInitMsg(haveLegacyChan); err != nil {
6✔
677
                return fmt.Errorf("unable to send init msg: %w", err)
×
678
        }
×
679

680
        // Before we launch any of the helper goroutines off the peer struct,
681
        // we'll first ensure proper adherence to the p2p protocol. The init
682
        // message MUST be sent before any other message.
683
        readErr := make(chan error, 1)
6✔
684
        msgChan := make(chan lnwire.Message, 1)
6✔
685
        p.wg.Add(1)
6✔
686
        go func() {
12✔
687
                defer p.wg.Done()
6✔
688

6✔
689
                msg, err := p.readNextMessage()
6✔
690
                if err != nil {
8✔
691
                        readErr <- err
2✔
692
                        msgChan <- nil
2✔
693
                        return
2✔
694
                }
2✔
695
                readErr <- nil
6✔
696
                msgChan <- msg
6✔
697
        }()
698

699
        select {
6✔
700
        // In order to avoid blocking indefinitely, we'll give the other peer
701
        // an upper timeout to respond before we bail out early.
702
        case <-time.After(handshakeTimeout):
×
703
                return fmt.Errorf("peer did not complete handshake within %v",
×
704
                        handshakeTimeout)
×
705
        case err := <-readErr:
6✔
706
                if err != nil {
8✔
707
                        return fmt.Errorf("unable to read init msg: %w", err)
2✔
708
                }
2✔
709
        }
710

711
        // Once the init message arrives, we can parse it so we can figure out
712
        // the negotiation of features for this session.
713
        msg := <-msgChan
6✔
714
        if msg, ok := msg.(*lnwire.Init); ok {
12✔
715
                if err := p.handleInitMsg(msg); err != nil {
6✔
716
                        p.storeError(err)
×
717
                        return err
×
718
                }
×
719
        } else {
×
720
                return errors.New("very first message between nodes " +
×
721
                        "must be init message")
×
722
        }
×
723

724
        // Next, load all the active channels we have with this peer,
725
        // registering them with the switch and launching the necessary
726
        // goroutines required to operate them.
727
        p.log.Debugf("Loaded %v active channels from database",
6✔
728
                len(activeChans))
6✔
729

6✔
730
        // Conditionally subscribe to channel events before loading channels so
6✔
731
        // we won't miss events. This subscription is used to listen to active
6✔
732
        // channel event when reenabling channels. Once the reenabling process
6✔
733
        // is finished, this subscription will be canceled.
6✔
734
        //
6✔
735
        // NOTE: ChannelNotifier must be started before subscribing events
6✔
736
        // otherwise we'd panic here.
6✔
737
        if err := p.attachChannelEventSubscription(); err != nil {
6✔
738
                return err
×
739
        }
×
740

741
        msgs, err := p.loadActiveChannels(activeChans)
6✔
742
        if err != nil {
6✔
743
                return fmt.Errorf("unable to load channels: %w", err)
×
744
        }
×
745

746
        p.startTime = time.Now()
6✔
747

6✔
748
        // Before launching the writeHandler goroutine, we send any channel
6✔
749
        // sync messages that must be resent for borked channels. We do this to
6✔
750
        // avoid data races with WriteMessage & Flush calls.
6✔
751
        if len(msgs) > 0 {
11✔
752
                p.log.Infof("Sending %d channel sync messages to peer after "+
5✔
753
                        "loading active channels", len(msgs))
5✔
754

5✔
755
                // Send the messages directly via writeMessage and bypass the
5✔
756
                // writeHandler goroutine.
5✔
757
                for _, msg := range msgs {
10✔
758
                        if err := p.writeMessage(msg); err != nil {
5✔
759
                                return fmt.Errorf("unable to send "+
×
760
                                        "reestablish msg: %v", err)
×
761
                        }
×
762
                }
763
        }
764

765
        err = p.pingManager.Start()
6✔
766
        if err != nil {
6✔
767
                return fmt.Errorf("could not start ping manager %w", err)
×
768
        }
×
769

770
        p.wg.Add(4)
6✔
771
        go p.queueHandler()
6✔
772
        go p.writeHandler()
6✔
773
        go p.channelManager()
6✔
774
        go p.readHandler()
6✔
775

6✔
776
        // Signal to any external processes that the peer is now active.
6✔
777
        close(p.activeSignal)
6✔
778

6✔
779
        // Node announcements don't propagate very well throughout the network
6✔
780
        // as there isn't a way to efficiently query for them through their
6✔
781
        // timestamp, mostly affecting nodes that were offline during the time
6✔
782
        // of broadcast. We'll resend our node announcement to the remote peer
6✔
783
        // as a best-effort delivery such that it can also propagate to their
6✔
784
        // peers. To ensure they can successfully process it in most cases,
6✔
785
        // we'll only resend it as long as we have at least one confirmed
6✔
786
        // advertised channel with the remote peer.
6✔
787
        //
6✔
788
        // TODO(wilmer): Remove this once we're able to query for node
6✔
789
        // announcements through their timestamps.
6✔
790
        go p.maybeSendNodeAnn(activeChans)
6✔
791

6✔
792
        return nil
6✔
793
}
794

795
// initGossipSync initializes either a gossip syncer or an initial routing
796
// dump, depending on the negotiated synchronization method.
797
func (p *Brontide) initGossipSync() {
6✔
798
        // If the remote peer knows of the new gossip queries feature, then
6✔
799
        // we'll create a new gossipSyncer in the AuthenticatedGossiper for it.
6✔
800
        if p.remoteFeatures.HasFeature(lnwire.GossipQueriesOptional) {
12✔
801
                p.log.Info("Negotiated chan series queries")
6✔
802

6✔
803
                if p.cfg.AuthGossiper == nil {
8✔
804
                        // This should only ever be hit in the unit tests.
2✔
805
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
2✔
806
                                "gossip sync.")
2✔
807
                        return
2✔
808
                }
2✔
809

810
                // Register the peer's gossip syncer with the gossiper.
811
                // This blocks synchronously to ensure the gossip syncer is
812
                // registered with the gossiper before attempting to read
813
                // messages from the remote peer.
814
                //
815
                // TODO(wilmer): Only sync updates from non-channel peers. This
816
                // requires an improved version of the current network
817
                // bootstrapper to ensure we can find and connect to non-channel
818
                // peers.
819
                p.cfg.AuthGossiper.InitSyncState(p)
4✔
820
        }
821
}
822

823
// taprootShutdownAllowed returns true if both parties have negotiated the
824
// shutdown-any-segwit feature.
825
func (p *Brontide) taprootShutdownAllowed() bool {
10✔
826
        return p.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
10✔
827
                p.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
10✔
828
}
10✔
829

830
// QuitSignal is a method that should return a channel which will be sent upon
831
// or closed once the backing peer exits. This allows callers using the
832
// interface to cancel any processing in the event the backing implementation
833
// exits.
834
//
835
// NOTE: Part of the lnpeer.Peer interface.
836
func (p *Brontide) QuitSignal() <-chan struct{} {
4✔
837
        return p.quit
4✔
838
}
4✔
839

840
// loadActiveChannels creates indexes within the peer for tracking all active
841
// channels returned by the database. It returns a slice of channel reestablish
842
// messages that should be sent to the peer immediately, in case we have borked
843
// channels that haven't been closed yet.
844
func (p *Brontide) loadActiveChannels(chans []*channeldb.OpenChannel) (
845
        []lnwire.Message, error) {
6✔
846

6✔
847
        // Return a slice of messages to send to the peers in case the channel
6✔
848
        // cannot be loaded normally.
6✔
849
        var msgs []lnwire.Message
6✔
850

6✔
851
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
6✔
852

6✔
853
        for _, dbChan := range chans {
11✔
854
                hasScidFeature := dbChan.ChanType.HasScidAliasFeature()
5✔
855
                if scidAliasNegotiated && !hasScidFeature {
9✔
856
                        // We'll request and store an alias, making sure that a
4✔
857
                        // gossiper mapping is not created for the alias to the
4✔
858
                        // real SCID. This is done because the peer and funding
4✔
859
                        // manager are not aware of each other's states and if
4✔
860
                        // we did not do this, we would accept alias channel
4✔
861
                        // updates after 6 confirmations, which would be buggy.
4✔
862
                        // We'll queue a channel_ready message with the new
4✔
863
                        // alias. This should technically be done *after* the
4✔
864
                        // reestablish, but this behavior is pre-existing since
4✔
865
                        // the funding manager may already queue a
4✔
866
                        // channel_ready before the channel_reestablish.
4✔
867
                        if !dbChan.IsPending {
8✔
868
                                aliasScid, err := p.cfg.RequestAlias()
4✔
869
                                if err != nil {
4✔
870
                                        return nil, err
×
871
                                }
×
872

873
                                err = p.cfg.AddLocalAlias(
4✔
874
                                        aliasScid, dbChan.ShortChanID(), false,
4✔
875
                                )
4✔
876
                                if err != nil {
4✔
877
                                        return nil, err
×
878
                                }
×
879

880
                                chanID := lnwire.NewChanIDFromOutPoint(
4✔
881
                                        dbChan.FundingOutpoint,
4✔
882
                                )
4✔
883

4✔
884
                                // Fetch the second commitment point to send in
4✔
885
                                // the channel_ready message.
4✔
886
                                second, err := dbChan.SecondCommitmentPoint()
4✔
887
                                if err != nil {
4✔
888
                                        return nil, err
×
889
                                }
×
890

891
                                channelReadyMsg := lnwire.NewChannelReady(
4✔
892
                                        chanID, second,
4✔
893
                                )
4✔
894
                                channelReadyMsg.AliasScid = &aliasScid
4✔
895

4✔
896
                                msgs = append(msgs, channelReadyMsg)
4✔
897
                        }
898

899
                        // If we've negotiated the option-scid-alias feature
900
                        // and this channel does not have ScidAliasFeature set
901
                        // to true due to an upgrade where the feature bit was
902
                        // turned on, we'll update the channel's database
903
                        // state.
904
                        err := dbChan.MarkScidAliasNegotiated()
4✔
905
                        if err != nil {
4✔
906
                                return nil, err
×
907
                        }
×
908
                }
909

910
                lnChan, err := lnwallet.NewLightningChannel(
5✔
911
                        p.cfg.Signer, dbChan, p.cfg.SigPool,
5✔
912
                )
5✔
913
                if err != nil {
5✔
914
                        return nil, err
×
915
                }
×
916

917
                chanPoint := dbChan.FundingOutpoint
5✔
918

5✔
919
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
5✔
920

5✔
921
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
5✔
922
                        chanPoint, lnChan.IsPending())
5✔
923

5✔
924
                // Skip adding any permanently irreconcilable channels to the
5✔
925
                // htlcswitch.
5✔
926
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
5✔
927
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
10✔
928

5✔
929
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
5✔
930
                                "start.", chanPoint, dbChan.ChanStatus())
5✔
931

5✔
932
                        // To help our peer recover from a potential data loss,
5✔
933
                        // we resend our channel reestablish message if the
5✔
934
                        // channel is in a borked state. We won't process any
5✔
935
                        // channel reestablish message sent from the peer, but
5✔
936
                        // that's okay since the assumption is that we did when
5✔
937
                        // marking the channel borked.
5✔
938
                        chanSync, err := dbChan.ChanSyncMsg()
5✔
939
                        if err != nil {
5✔
940
                                p.log.Errorf("Unable to create channel "+
×
941
                                        "reestablish message for channel %v: "+
×
942
                                        "%v", chanPoint, err)
×
943
                                continue
×
944
                        }
945

946
                        msgs = append(msgs, chanSync)
5✔
947

5✔
948
                        // Check if this channel needs to have the cooperative
5✔
949
                        // close process restarted. If so, we'll need to send
5✔
950
                        // the Shutdown message that is returned.
5✔
951
                        if dbChan.HasChanStatus(
5✔
952
                                channeldb.ChanStatusCoopBroadcasted,
5✔
953
                        ) {
5✔
954

×
955
                                shutdownMsg, err := p.restartCoopClose(lnChan)
×
956
                                if err != nil {
×
957
                                        p.log.Errorf("Unable to restart "+
×
958
                                                "coop close for channel: %v",
×
959
                                                err)
×
960
                                        continue
×
961
                                }
962

963
                                if shutdownMsg == nil {
×
964
                                        continue
×
965
                                }
966

967
                                // Append the message to the set of messages to
968
                                // send.
969
                                msgs = append(msgs, shutdownMsg)
×
970
                        }
971

972
                        continue
5✔
973
                }
974

975
                // Before we register this new link with the HTLC Switch, we'll
976
                // need to fetch its current link-layer forwarding policy from
977
                // the database.
978
                graph := p.cfg.ChannelGraph
4✔
979
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
4✔
980
                        &chanPoint,
4✔
981
                )
4✔
982
                if err != nil && !errors.Is(err, channeldb.ErrEdgeNotFound) {
4✔
983
                        return nil, err
×
984
                }
×
985

986
                // We'll filter out our policy from the directional channel
987
                // edges based whom the edge connects to. If it doesn't connect
988
                // to us, then we know that we were the one that advertised the
989
                // policy.
990
                //
991
                // TODO(roasbeef): can add helper method to get policy for
992
                // particular channel.
993
                var selfPolicy *models.ChannelEdgePolicy
4✔
994
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
4✔
995
                        p.cfg.ServerPubKey[:]) {
8✔
996

4✔
997
                        selfPolicy = p1
4✔
998
                } else {
8✔
999
                        selfPolicy = p2
4✔
1000
                }
4✔
1001

1002
                // If we don't yet have an advertised routing policy, then
1003
                // we'll use the current default, otherwise we'll translate the
1004
                // routing policy into a forwarding policy.
1005
                var forwardingPolicy *models.ForwardingPolicy
4✔
1006
                if selfPolicy != nil {
8✔
1007
                        var inboundWireFee lnwire.Fee
4✔
1008
                        _, err := selfPolicy.ExtraOpaqueData.ExtractRecords(
4✔
1009
                                &inboundWireFee,
4✔
1010
                        )
4✔
1011
                        if err != nil {
4✔
1012
                                return nil, err
×
1013
                        }
×
1014

1015
                        inboundFee := models.NewInboundFeeFromWire(
4✔
1016
                                inboundWireFee,
4✔
1017
                        )
4✔
1018

4✔
1019
                        forwardingPolicy = &models.ForwardingPolicy{
4✔
1020
                                MinHTLCOut:    selfPolicy.MinHTLC,
4✔
1021
                                MaxHTLC:       selfPolicy.MaxHTLC,
4✔
1022
                                BaseFee:       selfPolicy.FeeBaseMSat,
4✔
1023
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
4✔
1024
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
4✔
1025

4✔
1026
                                InboundFee: inboundFee,
4✔
1027
                        }
4✔
1028
                } else {
4✔
1029
                        p.log.Warnf("Unable to find our forwarding policy "+
4✔
1030
                                "for channel %v, using default values",
4✔
1031
                                chanPoint)
4✔
1032
                        forwardingPolicy = &p.cfg.RoutingPolicy
4✔
1033
                }
4✔
1034

1035
                p.log.Tracef("Using link policy of: %v",
4✔
1036
                        spew.Sdump(forwardingPolicy))
4✔
1037

4✔
1038
                // If the channel is pending, set the value to nil in the
4✔
1039
                // activeChannels map. This is done to signify that the channel
4✔
1040
                // is pending. We don't add the link to the switch here - it's
4✔
1041
                // the funding manager's responsibility to spin up pending
4✔
1042
                // channels. Adding them here would just be extra work as we'll
4✔
1043
                // tear them down when creating + adding the final link.
4✔
1044
                if lnChan.IsPending() {
8✔
1045
                        p.activeChannels.Store(chanID, nil)
4✔
1046

4✔
1047
                        continue
4✔
1048
                }
1049

1050
                shutdownInfo, err := lnChan.State().ShutdownInfo()
4✔
1051
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
4✔
1052
                        return nil, err
×
1053
                }
×
1054

1055
                var (
4✔
1056
                        shutdownMsg     fn.Option[lnwire.Shutdown]
4✔
1057
                        shutdownInfoErr error
4✔
1058
                )
4✔
1059
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
8✔
1060
                        // Compute an ideal fee.
4✔
1061
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
4✔
1062
                                p.cfg.CoopCloseTargetConfs,
4✔
1063
                        )
4✔
1064
                        if err != nil {
4✔
1065
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1066
                                        "estimate fee: %w", err)
×
1067

×
1068
                                return
×
1069
                        }
×
1070

1071
                        chanCloser, err := p.createChanCloser(
4✔
1072
                                lnChan, info.DeliveryScript.Val, feePerKw, nil,
4✔
1073
                                info.Closer(),
4✔
1074
                        )
4✔
1075
                        if err != nil {
4✔
1076
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1077
                                        "create chan closer: %w", err)
×
1078

×
1079
                                return
×
1080
                        }
×
1081

1082
                        chanID := lnwire.NewChanIDFromOutPoint(
4✔
1083
                                lnChan.State().FundingOutpoint,
4✔
1084
                        )
4✔
1085

4✔
1086
                        p.activeChanCloses[chanID] = chanCloser
4✔
1087

4✔
1088
                        // Create the Shutdown message.
4✔
1089
                        shutdown, err := chanCloser.ShutdownChan()
4✔
1090
                        if err != nil {
4✔
1091
                                delete(p.activeChanCloses, chanID)
×
1092
                                shutdownInfoErr = err
×
1093

×
1094
                                return
×
1095
                        }
×
1096

1097
                        shutdownMsg = fn.Some(*shutdown)
4✔
1098
                })
1099
                if shutdownInfoErr != nil {
4✔
1100
                        return nil, shutdownInfoErr
×
1101
                }
×
1102

1103
                // Subscribe to the set of on-chain events for this channel.
1104
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
4✔
1105
                        chanPoint,
4✔
1106
                )
4✔
1107
                if err != nil {
4✔
1108
                        return nil, err
×
1109
                }
×
1110

1111
                err = p.addLink(
4✔
1112
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
4✔
1113
                        true, shutdownMsg,
4✔
1114
                )
4✔
1115
                if err != nil {
4✔
1116
                        return nil, fmt.Errorf("unable to add link %v to "+
×
1117
                                "switch: %v", chanPoint, err)
×
1118
                }
×
1119

1120
                p.activeChannels.Store(chanID, lnChan)
4✔
1121
        }
1122

1123
        return msgs, nil
6✔
1124
}
1125

1126
// addLink creates and adds a new ChannelLink from the specified channel.
1127
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1128
        lnChan *lnwallet.LightningChannel,
1129
        forwardingPolicy *models.ForwardingPolicy,
1130
        chainEvents *contractcourt.ChainEventSubscription,
1131
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
4✔
1132

4✔
1133
        // onChannelFailure will be called by the link in case the channel
4✔
1134
        // fails for some reason.
4✔
1135
        onChannelFailure := func(chanID lnwire.ChannelID,
4✔
1136
                shortChanID lnwire.ShortChannelID,
4✔
1137
                linkErr htlcswitch.LinkFailureError) {
8✔
1138

4✔
1139
                failure := linkFailureReport{
4✔
1140
                        chanPoint:   *chanPoint,
4✔
1141
                        chanID:      chanID,
4✔
1142
                        shortChanID: shortChanID,
4✔
1143
                        linkErr:     linkErr,
4✔
1144
                }
4✔
1145

4✔
1146
                select {
4✔
1147
                case p.linkFailures <- failure:
4✔
1148
                case <-p.quit:
×
1149
                case <-p.cfg.Quit:
×
1150
                }
1151
        }
1152

1153
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
8✔
1154
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
4✔
1155
        }
4✔
1156

1157
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
8✔
1158
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
4✔
1159
        }
4✔
1160

1161
        //nolint:lll
1162
        linkCfg := htlcswitch.ChannelLinkConfig{
4✔
1163
                Peer:                   p,
4✔
1164
                DecodeHopIterators:     p.cfg.Sphinx.DecodeHopIterators,
4✔
1165
                ExtractErrorEncrypter:  p.cfg.Sphinx.ExtractErrorEncrypter,
4✔
1166
                FetchLastChannelUpdate: p.cfg.FetchLastChanUpdate,
4✔
1167
                HodlMask:               p.cfg.Hodl.Mask(),
4✔
1168
                Registry:               p.cfg.Invoices,
4✔
1169
                BestHeight:             p.cfg.Switch.BestHeight,
4✔
1170
                Circuits:               p.cfg.Switch.CircuitModifier(),
4✔
1171
                ForwardPackets:         p.cfg.InterceptSwitch.ForwardPackets,
4✔
1172
                FwrdingPolicy:          *forwardingPolicy,
4✔
1173
                FeeEstimator:           p.cfg.FeeEstimator,
4✔
1174
                PreimageCache:          p.cfg.WitnessBeacon,
4✔
1175
                ChainEvents:            chainEvents,
4✔
1176
                UpdateContractSignals:  updateContractSignals,
4✔
1177
                NotifyContractUpdate:   notifyContractUpdate,
4✔
1178
                OnChannelFailure:       onChannelFailure,
4✔
1179
                SyncStates:             syncStates,
4✔
1180
                BatchTicker:            ticker.New(p.cfg.ChannelCommitInterval),
4✔
1181
                FwdPkgGCTicker:         ticker.New(time.Hour),
4✔
1182
                PendingCommitTicker: ticker.New(
4✔
1183
                        p.cfg.PendingCommitInterval,
4✔
1184
                ),
4✔
1185
                BatchSize:               p.cfg.ChannelCommitBatchSize,
4✔
1186
                UnsafeReplay:            p.cfg.UnsafeReplay,
4✔
1187
                MinUpdateTimeout:        htlcswitch.DefaultMinLinkFeeUpdateTimeout,
4✔
1188
                MaxUpdateTimeout:        htlcswitch.DefaultMaxLinkFeeUpdateTimeout,
4✔
1189
                OutgoingCltvRejectDelta: p.cfg.OutgoingCltvRejectDelta,
4✔
1190
                TowerClient:             p.cfg.TowerClient,
4✔
1191
                MaxOutgoingCltvExpiry:   p.cfg.MaxOutgoingCltvExpiry,
4✔
1192
                MaxFeeAllocation:        p.cfg.MaxChannelFeeAllocation,
4✔
1193
                MaxAnchorsCommitFeeRate: p.cfg.MaxAnchorsCommitFeeRate,
4✔
1194
                NotifyActiveLink:        p.cfg.ChannelNotifier.NotifyActiveLinkEvent,
4✔
1195
                NotifyActiveChannel:     p.cfg.ChannelNotifier.NotifyActiveChannelEvent,
4✔
1196
                NotifyInactiveChannel:   p.cfg.ChannelNotifier.NotifyInactiveChannelEvent,
4✔
1197
                NotifyInactiveLinkEvent: p.cfg.ChannelNotifier.NotifyInactiveLinkEvent,
4✔
1198
                HtlcNotifier:            p.cfg.HtlcNotifier,
4✔
1199
                GetAliases:              p.cfg.GetAliases,
4✔
1200
                PreviouslySentShutdown:  shutdownMsg,
4✔
1201
                DisallowRouteBlinding:   p.cfg.DisallowRouteBlinding,
4✔
1202
                MaxFeeExposure:          p.cfg.MaxFeeExposure,
4✔
1203
        }
4✔
1204

4✔
1205
        // Before adding our new link, purge the switch of any pending or live
4✔
1206
        // links going by the same channel id. If one is found, we'll shut it
4✔
1207
        // down to ensure that the mailboxes are only ever under the control of
4✔
1208
        // one link.
4✔
1209
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
4✔
1210
        p.cfg.Switch.RemoveLink(chanID)
4✔
1211

4✔
1212
        // With the channel link created, we'll now notify the htlc switch so
4✔
1213
        // this channel can be used to dispatch local payments and also
4✔
1214
        // passively forward payments.
4✔
1215
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
4✔
1216
}
1217

1218
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1219
// one confirmed public channel exists with them.
1220
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
6✔
1221
        hasConfirmedPublicChan := false
6✔
1222
        for _, channel := range channels {
11✔
1223
                if channel.IsPending {
9✔
1224
                        continue
4✔
1225
                }
1226
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
10✔
1227
                        continue
5✔
1228
                }
1229

1230
                hasConfirmedPublicChan = true
4✔
1231
                break
4✔
1232
        }
1233
        if !hasConfirmedPublicChan {
12✔
1234
                return
6✔
1235
        }
6✔
1236

1237
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
4✔
1238
        if err != nil {
4✔
1239
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1240
                return
×
1241
        }
×
1242

1243
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
4✔
1244
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1245
        }
×
1246
}
1247

1248
// WaitForDisconnect waits until the peer has disconnected. A peer may be
1249
// disconnected if the local or remote side terminates the connection, or an
1250
// irrecoverable protocol error has been encountered. This method will only
1251
// begin watching the peer's waitgroup after the ready channel or the peer's
1252
// quit channel are signaled. The ready channel should only be signaled if a
1253
// call to Start returns no error. Otherwise, if the peer fails to start,
1254
// calling Disconnect will signal the quit channel and the method will not
1255
// block, since no goroutines were spawned.
1256
func (p *Brontide) WaitForDisconnect(ready chan struct{}) {
4✔
1257
        // Before we try to call the `Wait` goroutine, we'll make sure the main
4✔
1258
        // set of goroutines are already active.
4✔
1259
        select {
4✔
1260
        case <-p.startReady:
4✔
1261
        case <-p.quit:
×
1262
                return
×
1263
        }
1264

1265
        select {
4✔
1266
        case <-ready:
4✔
1267
        case <-p.quit:
2✔
1268
        }
1269

1270
        p.wg.Wait()
4✔
1271
}
1272

1273
// Disconnect terminates the connection with the remote peer. Additionally, a
1274
// signal is sent to the server and htlcSwitch indicating the resources
1275
// allocated to the peer can now be cleaned up.
1276
func (p *Brontide) Disconnect(reason error) {
4✔
1277
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
8✔
1278
                return
4✔
1279
        }
4✔
1280

1281
        // Make sure initialization has completed before we try to tear things
1282
        // down.
1283
        select {
4✔
1284
        case <-p.startReady:
4✔
1285
        case <-p.quit:
×
1286
                return
×
1287
        }
1288

1289
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
4✔
1290
        p.storeError(err)
4✔
1291

4✔
1292
        p.log.Infof(err.Error())
4✔
1293

4✔
1294
        // Stop PingManager before closing TCP connection.
4✔
1295
        p.pingManager.Stop()
4✔
1296

4✔
1297
        // Ensure that the TCP connection is properly closed before continuing.
4✔
1298
        p.cfg.Conn.Close()
4✔
1299

4✔
1300
        close(p.quit)
4✔
1301
}
1302

1303
// String returns the string representation of this peer.
1304
func (p *Brontide) String() string {
4✔
1305
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
4✔
1306
}
4✔
1307

1308
// readNextMessage reads, and returns the next message on the wire along with
1309
// any additional raw payload.
1310
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
9✔
1311
        noiseConn := p.cfg.Conn
9✔
1312
        err := noiseConn.SetReadDeadline(time.Time{})
9✔
1313
        if err != nil {
9✔
1314
                return nil, err
×
1315
        }
×
1316

1317
        pktLen, err := noiseConn.ReadNextHeader()
9✔
1318
        if err != nil {
13✔
1319
                return nil, fmt.Errorf("read next header: %w", err)
4✔
1320
        }
4✔
1321

1322
        // First we'll read the next _full_ message. We do this rather than
1323
        // reading incrementally from the stream as the Lightning wire protocol
1324
        // is message oriented and allows nodes to pad on additional data to
1325
        // the message stream.
1326
        var (
7✔
1327
                nextMsg lnwire.Message
7✔
1328
                msgLen  uint64
7✔
1329
        )
7✔
1330
        err = p.cfg.ReadPool.Submit(func(buf *buffer.Read) error {
14✔
1331
                // Before reading the body of the message, set the read timeout
7✔
1332
                // accordingly to ensure we don't block other readers using the
7✔
1333
                // pool. We do so only after the task has been scheduled to
7✔
1334
                // ensure the deadline doesn't expire while the message is in
7✔
1335
                // the process of being scheduled.
7✔
1336
                readDeadline := time.Now().Add(
7✔
1337
                        p.scaleTimeout(readMessageTimeout),
7✔
1338
                )
7✔
1339
                readErr := noiseConn.SetReadDeadline(readDeadline)
7✔
1340
                if readErr != nil {
7✔
1341
                        return readErr
×
1342
                }
×
1343

1344
                // The ReadNextBody method will actually end up re-using the
1345
                // buffer, so within this closure, we can continue to use
1346
                // rawMsg as it's just a slice into the buf from the buffer
1347
                // pool.
1348
                rawMsg, readErr := noiseConn.ReadNextBody(buf[:pktLen])
7✔
1349
                if readErr != nil {
7✔
1350
                        return fmt.Errorf("read next body: %w", readErr)
×
1351
                }
×
1352
                msgLen = uint64(len(rawMsg))
7✔
1353

7✔
1354
                // Next, create a new io.Reader implementation from the raw
7✔
1355
                // message, and use this to decode the message directly from.
7✔
1356
                msgReader := bytes.NewReader(rawMsg)
7✔
1357
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
7✔
1358
                if err != nil {
11✔
1359
                        return err
4✔
1360
                }
4✔
1361

1362
                // At this point, rawMsg and buf will be returned back to the
1363
                // buffer pool for re-use.
1364
                return nil
7✔
1365
        })
1366
        atomic.AddUint64(&p.bytesReceived, msgLen)
7✔
1367
        if err != nil {
11✔
1368
                return nil, err
4✔
1369
        }
4✔
1370

1371
        p.logWireMessage(nextMsg, true)
7✔
1372

7✔
1373
        return nextMsg, nil
7✔
1374
}
1375

1376
// msgStream implements a goroutine-safe, in-order stream of messages to be
1377
// delivered via closure to a receiver. These messages MUST be in order due to
1378
// the nature of the lightning channel commitment and gossiper state machines.
1379
// TODO(conner): use stream handler interface to abstract out stream
1380
// state/logging.
1381
type msgStream struct {
1382
        streamShutdown int32 // To be used atomically.
1383

1384
        peer *Brontide
1385

1386
        apply func(lnwire.Message)
1387

1388
        startMsg string
1389
        stopMsg  string
1390

1391
        msgCond *sync.Cond
1392
        msgs    []lnwire.Message
1393

1394
        mtx sync.Mutex
1395

1396
        producerSema chan struct{}
1397

1398
        wg   sync.WaitGroup
1399
        quit chan struct{}
1400
}
1401

1402
// newMsgStream creates a new instance of a chanMsgStream for a particular
1403
// channel identified by its channel ID. bufSize is the max number of messages
1404
// that should be buffered in the internal queue. Callers should set this to a
1405
// sane value that avoids blocking unnecessarily, but doesn't allow an
1406
// unbounded amount of memory to be allocated to buffer incoming messages.
1407
func newMsgStream(p *Brontide, startMsg, stopMsg string, bufSize uint32,
1408
        apply func(lnwire.Message)) *msgStream {
6✔
1409

6✔
1410
        stream := &msgStream{
6✔
1411
                peer:         p,
6✔
1412
                apply:        apply,
6✔
1413
                startMsg:     startMsg,
6✔
1414
                stopMsg:      stopMsg,
6✔
1415
                producerSema: make(chan struct{}, bufSize),
6✔
1416
                quit:         make(chan struct{}),
6✔
1417
        }
6✔
1418
        stream.msgCond = sync.NewCond(&stream.mtx)
6✔
1419

6✔
1420
        // Before we return the active stream, we'll populate the producer's
6✔
1421
        // semaphore channel. We'll use this to ensure that the producer won't
6✔
1422
        // attempt to allocate memory in the queue for an item until it has
6✔
1423
        // sufficient extra space.
6✔
1424
        for i := uint32(0); i < bufSize; i++ {
2,010✔
1425
                stream.producerSema <- struct{}{}
2,004✔
1426
        }
2,004✔
1427

1428
        return stream
6✔
1429
}
1430

1431
// Start starts the chanMsgStream.
1432
func (ms *msgStream) Start() {
6✔
1433
        ms.wg.Add(1)
6✔
1434
        go ms.msgConsumer()
6✔
1435
}
6✔
1436

1437
// Stop stops the chanMsgStream.
1438
func (ms *msgStream) Stop() {
4✔
1439
        // TODO(roasbeef): signal too?
4✔
1440

4✔
1441
        close(ms.quit)
4✔
1442

4✔
1443
        // Now that we've closed the channel, we'll repeatedly signal the msg
4✔
1444
        // consumer until we've detected that it has exited.
4✔
1445
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
8✔
1446
                ms.msgCond.Signal()
4✔
1447
                time.Sleep(time.Millisecond * 100)
4✔
1448
        }
4✔
1449

1450
        ms.wg.Wait()
4✔
1451
}
1452

1453
// msgConsumer is the main goroutine that streams messages from the peer's
1454
// readHandler directly to the target channel.
1455
func (ms *msgStream) msgConsumer() {
6✔
1456
        defer ms.wg.Done()
6✔
1457
        defer peerLog.Tracef(ms.stopMsg)
6✔
1458
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
6✔
1459

6✔
1460
        peerLog.Tracef(ms.startMsg)
6✔
1461

6✔
1462
        for {
12✔
1463
                // First, we'll check our condition. If the queue of messages
6✔
1464
                // is empty, then we'll wait until a new item is added.
6✔
1465
                ms.msgCond.L.Lock()
6✔
1466
                for len(ms.msgs) == 0 {
12✔
1467
                        ms.msgCond.Wait()
6✔
1468

6✔
1469
                        // If we woke up in order to exit, then we'll do so.
6✔
1470
                        // Otherwise, we'll check the message queue for any new
6✔
1471
                        // items.
6✔
1472
                        select {
6✔
1473
                        case <-ms.peer.quit:
4✔
1474
                                ms.msgCond.L.Unlock()
4✔
1475
                                return
4✔
1476
                        case <-ms.quit:
4✔
1477
                                ms.msgCond.L.Unlock()
4✔
1478
                                return
4✔
1479
                        default:
4✔
1480
                        }
1481
                }
1482

1483
                // Grab the message off the front of the queue, shifting the
1484
                // slice's reference down one in order to remove the message
1485
                // from the queue.
1486
                msg := ms.msgs[0]
4✔
1487
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
4✔
1488
                ms.msgs = ms.msgs[1:]
4✔
1489

4✔
1490
                ms.msgCond.L.Unlock()
4✔
1491

4✔
1492
                ms.apply(msg)
4✔
1493

4✔
1494
                // We've just successfully processed an item, so we'll signal
4✔
1495
                // to the producer that a new slot in the buffer. We'll use
4✔
1496
                // this to bound the size of the buffer to avoid allowing it to
4✔
1497
                // grow indefinitely.
4✔
1498
                select {
4✔
1499
                case ms.producerSema <- struct{}{}:
4✔
1500
                case <-ms.peer.quit:
4✔
1501
                        return
4✔
1502
                case <-ms.quit:
4✔
1503
                        return
4✔
1504
                }
1505
        }
1506
}
1507

1508
// AddMsg adds a new message to the msgStream. This function is safe for
1509
// concurrent access.
1510
func (ms *msgStream) AddMsg(msg lnwire.Message) {
4✔
1511
        // First, we'll attempt to receive from the producerSema struct. This
4✔
1512
        // acts as a semaphore to prevent us from indefinitely buffering
4✔
1513
        // incoming items from the wire. Either the msg queue isn't full, and
4✔
1514
        // we'll not block, or the queue is full, and we'll block until either
4✔
1515
        // we're signalled to quit, or a slot is freed up.
4✔
1516
        select {
4✔
1517
        case <-ms.producerSema:
4✔
1518
        case <-ms.peer.quit:
×
1519
                return
×
1520
        case <-ms.quit:
×
1521
                return
×
1522
        }
1523

1524
        // Next, we'll lock the condition, and add the message to the end of
1525
        // the message queue.
1526
        ms.msgCond.L.Lock()
4✔
1527
        ms.msgs = append(ms.msgs, msg)
4✔
1528
        ms.msgCond.L.Unlock()
4✔
1529

4✔
1530
        // With the message added, we signal to the msgConsumer that there are
4✔
1531
        // additional messages to consume.
4✔
1532
        ms.msgCond.Signal()
4✔
1533
}
1534

1535
// waitUntilLinkActive waits until the target link is active and returns a
1536
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1537
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1538
func waitUntilLinkActive(p *Brontide,
1539
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
4✔
1540

4✔
1541
        p.log.Tracef("Waiting for link=%v to be active", cid)
4✔
1542

4✔
1543
        // Subscribe to receive channel events.
4✔
1544
        //
4✔
1545
        // NOTE: If the link is already active by SubscribeChannelEvents, then
4✔
1546
        // GetLink will retrieve the link and we can send messages. If the link
4✔
1547
        // becomes active between SubscribeChannelEvents and GetLink, then GetLink
4✔
1548
        // will retrieve the link. If the link becomes active after GetLink, then
4✔
1549
        // we will get an ActiveLinkEvent notification and retrieve the link. If
4✔
1550
        // the call to GetLink is before SubscribeChannelEvents, however, there
4✔
1551
        // will be a race condition.
4✔
1552
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
4✔
1553
        if err != nil {
8✔
1554
                // If we have a non-nil error, then the server is shutting down and we
4✔
1555
                // can exit here and return nil. This means no message will be delivered
4✔
1556
                // to the link.
4✔
1557
                return nil
4✔
1558
        }
4✔
1559
        defer sub.Cancel()
4✔
1560

4✔
1561
        // The link may already be active by this point, and we may have missed the
4✔
1562
        // ActiveLinkEvent. Check if the link exists.
4✔
1563
        link := p.fetchLinkFromKeyAndCid(cid)
4✔
1564
        if link != nil {
8✔
1565
                return link
4✔
1566
        }
4✔
1567

1568
        // If the link is nil, we must wait for it to be active.
1569
        for {
8✔
1570
                select {
4✔
1571
                // A new event has been sent by the ChannelNotifier. We first check
1572
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1573
                // that the event is for this channel. Otherwise, we discard the
1574
                // message.
1575
                case e := <-sub.Updates():
4✔
1576
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
4✔
1577
                        if !ok {
8✔
1578
                                // Ignore this notification.
4✔
1579
                                continue
4✔
1580
                        }
1581

1582
                        chanPoint := event.ChannelPoint
4✔
1583

4✔
1584
                        // Check whether the retrieved chanPoint matches the target
4✔
1585
                        // channel id.
4✔
1586
                        if !cid.IsChanPoint(chanPoint) {
4✔
1587
                                continue
×
1588
                        }
1589

1590
                        // The link shouldn't be nil as we received an
1591
                        // ActiveLinkEvent. If it is nil, we return nil and the
1592
                        // calling function should catch it.
1593
                        return p.fetchLinkFromKeyAndCid(cid)
4✔
1594

1595
                case <-p.quit:
4✔
1596
                        return nil
4✔
1597
                }
1598
        }
1599
}
1600

1601
// newChanMsgStream is used to create a msgStream between the peer and
1602
// particular channel link in the htlcswitch. We utilize additional
1603
// synchronization with the fundingManager to ensure we don't attempt to
1604
// dispatch a message to a channel before it is fully active. A reference to the
1605
// channel this stream forwards to is held in scope to prevent unnecessary
1606
// lookups.
1607
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
4✔
1608
        var chanLink htlcswitch.ChannelUpdateHandler
4✔
1609

4✔
1610
        apply := func(msg lnwire.Message) {
8✔
1611
                // This check is fine because if the link no longer exists, it will
4✔
1612
                // be removed from the activeChannels map and subsequent messages
4✔
1613
                // shouldn't reach the chan msg stream.
4✔
1614
                if chanLink == nil {
8✔
1615
                        chanLink = waitUntilLinkActive(p, cid)
4✔
1616

4✔
1617
                        // If the link is still not active and the calling function
4✔
1618
                        // errored out, just return.
4✔
1619
                        if chanLink == nil {
8✔
1620
                                p.log.Warnf("Link=%v is not active")
4✔
1621
                                return
4✔
1622
                        }
4✔
1623
                }
1624

1625
                // In order to avoid unnecessarily delivering message
1626
                // as the peer is exiting, we'll check quickly to see
1627
                // if we need to exit.
1628
                select {
4✔
1629
                case <-p.quit:
×
1630
                        return
×
1631
                default:
4✔
1632
                }
1633

1634
                chanLink.HandleChannelUpdate(msg)
4✔
1635
        }
1636

1637
        return newMsgStream(p,
4✔
1638
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
4✔
1639
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
4✔
1640
                1000,
4✔
1641
                apply,
4✔
1642
        )
4✔
1643
}
1644

1645
// newDiscMsgStream is used to setup a msgStream between the peer and the
1646
// authenticated gossiper. This stream should be used to forward all remote
1647
// channel announcements.
1648
func newDiscMsgStream(p *Brontide) *msgStream {
6✔
1649
        apply := func(msg lnwire.Message) {
10✔
1650
                // TODO(yy): `ProcessRemoteAnnouncement` returns an error chan
4✔
1651
                // and we need to process it.
4✔
1652
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(msg, p)
4✔
1653
        }
4✔
1654

1655
        return newMsgStream(
6✔
1656
                p,
6✔
1657
                "Update stream for gossiper created",
6✔
1658
                "Update stream for gossiper exited",
6✔
1659
                1000,
6✔
1660
                apply,
6✔
1661
        )
6✔
1662
}
1663

1664
// readHandler is responsible for reading messages off the wire in series, then
1665
// properly dispatching the handling of the message to the proper subsystem.
1666
//
1667
// NOTE: This method MUST be run as a goroutine.
1668
func (p *Brontide) readHandler() {
6✔
1669
        defer p.wg.Done()
6✔
1670

6✔
1671
        // We'll stop the timer after a new messages is received, and also
6✔
1672
        // reset it after we process the next message.
6✔
1673
        idleTimer := time.AfterFunc(idleTimeout, func() {
6✔
1674
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
1675
                        p, idleTimeout)
×
1676
                p.Disconnect(err)
×
1677
        })
×
1678

1679
        // Initialize our negotiated gossip sync method before reading messages
1680
        // off the wire. When using gossip queries, this ensures a gossip
1681
        // syncer is active by the time query messages arrive.
1682
        //
1683
        // TODO(conner): have peer store gossip syncer directly and bypass
1684
        // gossiper?
1685
        p.initGossipSync()
6✔
1686

6✔
1687
        discStream := newDiscMsgStream(p)
6✔
1688
        discStream.Start()
6✔
1689
        defer discStream.Stop()
6✔
1690
out:
6✔
1691
        for atomic.LoadInt32(&p.disconnect) == 0 {
13✔
1692
                nextMsg, err := p.readNextMessage()
7✔
1693
                if !idleTimer.Stop() {
7✔
1694
                        select {
×
1695
                        case <-idleTimer.C:
×
1696
                        default:
×
1697
                        }
1698
                }
1699
                if err != nil {
9✔
1700
                        p.log.Infof("unable to read message from peer: %v", err)
4✔
1701

4✔
1702
                        // If we could not read our peer's message due to an
4✔
1703
                        // unknown type or invalid alias, we continue processing
4✔
1704
                        // as normal. We store unknown message and address
4✔
1705
                        // types, as they may provide debugging insight.
4✔
1706
                        switch e := err.(type) {
4✔
1707
                        // If this is just a message we don't yet recognize,
1708
                        // we'll continue processing as normal as this allows
1709
                        // us to introduce new messages in a forwards
1710
                        // compatible manner.
1711
                        case *lnwire.UnknownMessage:
4✔
1712
                                p.storeError(e)
4✔
1713
                                idleTimer.Reset(idleTimeout)
4✔
1714
                                continue
4✔
1715

1716
                        // If they sent us an address type that we don't yet
1717
                        // know of, then this isn't a wire error, so we'll
1718
                        // simply continue parsing the remainder of their
1719
                        // messages.
1720
                        case *lnwire.ErrUnknownAddrType:
×
1721
                                p.storeError(e)
×
1722
                                idleTimer.Reset(idleTimeout)
×
1723
                                continue
×
1724

1725
                        // If the NodeAnnouncement has an invalid alias, then
1726
                        // we'll log that error above and continue so we can
1727
                        // continue to read messages from the peer. We do not
1728
                        // store this error because it is of little debugging
1729
                        // value.
1730
                        case *lnwire.ErrInvalidNodeAlias:
×
1731
                                idleTimer.Reset(idleTimeout)
×
1732
                                continue
×
1733

1734
                        // If the error we encountered wasn't just a message we
1735
                        // didn't recognize, then we'll stop all processing as
1736
                        // this is a fatal error.
1737
                        default:
4✔
1738
                                break out
4✔
1739
                        }
1740
                }
1741

1742
                var (
5✔
1743
                        targetChan   lnwire.ChannelID
5✔
1744
                        isLinkUpdate bool
5✔
1745
                )
5✔
1746

5✔
1747
                switch msg := nextMsg.(type) {
5✔
1748
                case *lnwire.Pong:
3✔
1749
                        // When we receive a Pong message in response to our
3✔
1750
                        // last ping message, we send it to the pingManager
3✔
1751
                        p.pingManager.ReceivedPong(msg)
3✔
1752

1753
                case *lnwire.Ping:
3✔
1754
                        // First, we'll store their latest ping payload within
3✔
1755
                        // the relevant atomic variable.
3✔
1756
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
3✔
1757

3✔
1758
                        // Next, we'll send over the amount of specified pong
3✔
1759
                        // bytes.
3✔
1760
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
3✔
1761
                        p.queueMsg(pong, nil)
3✔
1762

1763
                case *lnwire.OpenChannel,
1764
                        *lnwire.AcceptChannel,
1765
                        *lnwire.FundingCreated,
1766
                        *lnwire.FundingSigned,
1767
                        *lnwire.ChannelReady:
4✔
1768

4✔
1769
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
4✔
1770

1771
                case *lnwire.Shutdown:
4✔
1772
                        select {
4✔
1773
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
4✔
1774
                        case <-p.quit:
×
1775
                                break out
×
1776
                        }
1777
                case *lnwire.ClosingSigned:
4✔
1778
                        select {
4✔
1779
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
4✔
1780
                        case <-p.quit:
×
1781
                                break out
×
1782
                        }
1783

1784
                case *lnwire.Warning:
×
1785
                        targetChan = msg.ChanID
×
1786
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
1787

1788
                case *lnwire.Error:
4✔
1789
                        targetChan = msg.ChanID
4✔
1790
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
4✔
1791

1792
                case *lnwire.ChannelReestablish:
4✔
1793
                        targetChan = msg.ChanID
4✔
1794
                        isLinkUpdate = p.hasChannel(targetChan)
4✔
1795

4✔
1796
                        // If we failed to find the link in question, and the
4✔
1797
                        // message received was a channel sync message, then
4✔
1798
                        // this might be a peer trying to resync closed channel.
4✔
1799
                        // In this case we'll try to resend our last channel
4✔
1800
                        // sync message, such that the peer can recover funds
4✔
1801
                        // from the closed channel.
4✔
1802
                        if !isLinkUpdate {
8✔
1803
                                err := p.resendChanSyncMsg(targetChan)
4✔
1804
                                if err != nil {
8✔
1805
                                        // TODO(halseth): send error to peer?
4✔
1806
                                        p.log.Errorf("resend failed: %v",
4✔
1807
                                                err)
4✔
1808
                                }
4✔
1809
                        }
1810

1811
                // For messages that implement the LinkUpdater interface, we
1812
                // will consider them as link updates and send them to
1813
                // chanStream. These messages will be queued inside chanStream
1814
                // if the channel is not active yet.
1815
                case lnwire.LinkUpdater:
4✔
1816
                        targetChan = msg.TargetChanID()
4✔
1817
                        isLinkUpdate = p.hasChannel(targetChan)
4✔
1818

4✔
1819
                        // Log an error if we don't have this channel. This
4✔
1820
                        // means the peer has sent us a message with unknown
4✔
1821
                        // channel ID.
4✔
1822
                        if !isLinkUpdate {
8✔
1823
                                p.log.Errorf("Unknown channel ID: %v found "+
4✔
1824
                                        "in received msg=%s", targetChan,
4✔
1825
                                        nextMsg.MsgType())
4✔
1826
                        }
4✔
1827

1828
                case *lnwire.ChannelUpdate,
1829
                        *lnwire.ChannelAnnouncement,
1830
                        *lnwire.NodeAnnouncement,
1831
                        *lnwire.AnnounceSignatures,
1832
                        *lnwire.GossipTimestampRange,
1833
                        *lnwire.QueryShortChanIDs,
1834
                        *lnwire.QueryChannelRange,
1835
                        *lnwire.ReplyChannelRange,
1836
                        *lnwire.ReplyShortChanIDsEnd:
4✔
1837

4✔
1838
                        discStream.AddMsg(msg)
4✔
1839

1840
                case *lnwire.Custom:
5✔
1841
                        err := p.handleCustomMessage(msg)
5✔
1842
                        if err != nil {
5✔
1843
                                p.storeError(err)
×
1844
                                p.log.Errorf("%v", err)
×
1845
                        }
×
1846

1847
                default:
×
1848
                        // If the message we received is unknown to us, store
×
1849
                        // the type to track the failure.
×
1850
                        err := fmt.Errorf("unknown message type %v received",
×
1851
                                uint16(msg.MsgType()))
×
1852
                        p.storeError(err)
×
1853

×
1854
                        p.log.Errorf("%v", err)
×
1855
                }
1856

1857
                if isLinkUpdate {
9✔
1858
                        // If this is a channel update, then we need to feed it
4✔
1859
                        // into the channel's in-order message stream.
4✔
1860
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
4✔
1861
                }
4✔
1862

1863
                idleTimer.Reset(idleTimeout)
5✔
1864
        }
1865

1866
        p.Disconnect(errors.New("read handler closed"))
4✔
1867

4✔
1868
        p.log.Trace("readHandler for peer done")
4✔
1869
}
1870

1871
// handleCustomMessage handles the given custom message if a handler is
1872
// registered.
1873
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
5✔
1874
        if p.cfg.HandleCustomMessage == nil {
5✔
1875
                return fmt.Errorf("no custom message handler for "+
×
1876
                        "message type %v", uint16(msg.MsgType()))
×
1877
        }
×
1878

1879
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
5✔
1880
}
1881

1882
// isLoadedFromDisk returns true if the provided channel ID is loaded from
1883
// disk.
1884
//
1885
// NOTE: only returns true for pending channels.
1886
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
4✔
1887
        // If this is a newly added channel, no need to reestablish.
4✔
1888
        _, added := p.addedChannels.Load(chanID)
4✔
1889
        if added {
8✔
1890
                return false
4✔
1891
        }
4✔
1892

1893
        // Return false if the channel is unknown.
1894
        channel, ok := p.activeChannels.Load(chanID)
4✔
1895
        if !ok {
4✔
1896
                return false
×
1897
        }
×
1898

1899
        // During startup, we will use a nil value to mark a pending channel
1900
        // that's loaded from disk.
1901
        return channel == nil
4✔
1902
}
1903

1904
// isActiveChannel returns true if the provided channel id is active, otherwise
1905
// returns false.
1906
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
12✔
1907
        // The channel would be nil if,
12✔
1908
        // - the channel doesn't exist, or,
12✔
1909
        // - the channel exists, but is pending. In this case, we don't
12✔
1910
        //   consider this channel active.
12✔
1911
        channel, _ := p.activeChannels.Load(chanID)
12✔
1912

12✔
1913
        return channel != nil
12✔
1914
}
12✔
1915

1916
// isPendingChannel returns true if the provided channel ID is pending, and
1917
// returns false if the channel is active or unknown.
1918
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
10✔
1919
        // Return false if the channel is unknown.
10✔
1920
        channel, ok := p.activeChannels.Load(chanID)
10✔
1921
        if !ok {
17✔
1922
                return false
7✔
1923
        }
7✔
1924

1925
        return channel == nil
3✔
1926
}
1927

1928
// hasChannel returns true if the peer has a pending/active channel specified
1929
// by the channel ID.
1930
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
4✔
1931
        _, ok := p.activeChannels.Load(chanID)
4✔
1932
        return ok
4✔
1933
}
4✔
1934

1935
// storeError stores an error in our peer's buffer of recent errors with the
1936
// current timestamp. Errors are only stored if we have at least one active
1937
// channel with the peer to mitigate a dos vector where a peer costlessly
1938
// connects to us and spams us with errors.
1939
func (p *Brontide) storeError(err error) {
4✔
1940
        var haveChannels bool
4✔
1941

4✔
1942
        p.activeChannels.Range(func(_ lnwire.ChannelID,
4✔
1943
                channel *lnwallet.LightningChannel) bool {
8✔
1944

4✔
1945
                // Pending channels will be nil in the activeChannels map.
4✔
1946
                if channel == nil {
8✔
1947
                        // Return true to continue the iteration.
4✔
1948
                        return true
4✔
1949
                }
4✔
1950

1951
                haveChannels = true
4✔
1952

4✔
1953
                // Return false to break the iteration.
4✔
1954
                return false
4✔
1955
        })
1956

1957
        // If we do not have any active channels with the peer, we do not store
1958
        // errors as a dos mitigation.
1959
        if !haveChannels {
8✔
1960
                p.log.Trace("no channels with peer, not storing err")
4✔
1961
                return
4✔
1962
        }
4✔
1963

1964
        p.cfg.ErrorBuffer.Add(
4✔
1965
                &TimestampedError{Timestamp: time.Now(), Error: err},
4✔
1966
        )
4✔
1967
}
1968

1969
// handleWarningOrError processes a warning or error msg and returns true if
1970
// msg should be forwarded to the associated channel link. False is returned if
1971
// any necessary forwarding of msg was already handled by this method. If msg is
1972
// an error from a peer with an active channel, we'll store it in memory.
1973
//
1974
// NOTE: This method should only be called from within the readHandler.
1975
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
1976
        msg lnwire.Message) bool {
4✔
1977

4✔
1978
        if errMsg, ok := msg.(*lnwire.Error); ok {
8✔
1979
                p.storeError(errMsg)
4✔
1980
        }
4✔
1981

1982
        switch {
4✔
1983
        // Connection wide messages should be forwarded to all channel links
1984
        // with this peer.
1985
        case chanID == lnwire.ConnectionWideID:
×
1986
                for _, chanStream := range p.activeMsgStreams {
×
1987
                        chanStream.AddMsg(msg)
×
1988
                }
×
1989

1990
                return false
×
1991

1992
        // If the channel ID for the message corresponds to a pending channel,
1993
        // then the funding manager will handle it.
1994
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
4✔
1995
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
4✔
1996
                return false
4✔
1997

1998
        // If not we hand the message to the channel link for this channel.
1999
        case p.isActiveChannel(chanID):
4✔
2000
                return true
4✔
2001

2002
        default:
4✔
2003
                return false
4✔
2004
        }
2005
}
2006

2007
// messageSummary returns a human-readable string that summarizes a
2008
// incoming/outgoing message. Not all messages will have a summary, only those
2009
// which have additional data that can be informative at a glance.
2010
func messageSummary(msg lnwire.Message) string {
4✔
2011
        switch msg := msg.(type) {
4✔
2012
        case *lnwire.Init:
4✔
2013
                // No summary.
4✔
2014
                return ""
4✔
2015

2016
        case *lnwire.OpenChannel:
4✔
2017
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
4✔
2018
                        "push_amt=%v, reserve=%v, flags=%v",
4✔
2019
                        msg.PendingChannelID[:], msg.ChainHash,
4✔
2020
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
4✔
2021
                        msg.ChannelReserve, msg.ChannelFlags)
4✔
2022

2023
        case *lnwire.AcceptChannel:
4✔
2024
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
4✔
2025
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
4✔
2026
                        msg.MinAcceptDepth)
4✔
2027

2028
        case *lnwire.FundingCreated:
4✔
2029
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
4✔
2030
                        msg.PendingChannelID[:], msg.FundingPoint)
4✔
2031

2032
        case *lnwire.FundingSigned:
4✔
2033
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
4✔
2034

2035
        case *lnwire.ChannelReady:
4✔
2036
                return fmt.Sprintf("chan_id=%v, next_point=%x",
4✔
2037
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
4✔
2038

2039
        case *lnwire.Shutdown:
4✔
2040
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
4✔
2041
                        msg.Address[:])
4✔
2042

2043
        case *lnwire.ClosingSigned:
4✔
2044
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
4✔
2045
                        msg.FeeSatoshis)
4✔
2046

2047
        case *lnwire.UpdateAddHTLC:
4✔
2048
                var blindingPoint []byte
4✔
2049
                msg.BlindingPoint.WhenSome(
4✔
2050
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
4✔
2051
                                *btcec.PublicKey]) {
8✔
2052

4✔
2053
                                blindingPoint = b.Val.SerializeCompressed()
4✔
2054
                        },
4✔
2055
                )
2056

2057
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
4✔
2058
                        "hash=%x, blinding_point=%x", msg.ChanID, msg.ID,
4✔
2059
                        msg.Amount, msg.Expiry, msg.PaymentHash[:],
4✔
2060
                        blindingPoint)
4✔
2061

2062
        case *lnwire.UpdateFailHTLC:
4✔
2063
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
4✔
2064
                        msg.ID, msg.Reason)
4✔
2065

2066
        case *lnwire.UpdateFulfillHTLC:
4✔
2067
                return fmt.Sprintf("chan_id=%v, id=%v, pre_image=%x",
4✔
2068
                        msg.ChanID, msg.ID, msg.PaymentPreimage[:])
4✔
2069

2070
        case *lnwire.CommitSig:
4✔
2071
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
4✔
2072
                        len(msg.HtlcSigs))
4✔
2073

2074
        case *lnwire.RevokeAndAck:
4✔
2075
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
4✔
2076
                        msg.ChanID, msg.Revocation[:],
4✔
2077
                        msg.NextRevocationKey.SerializeCompressed())
4✔
2078

2079
        case *lnwire.UpdateFailMalformedHTLC:
4✔
2080
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
4✔
2081
                        msg.ChanID, msg.ID, msg.FailureCode)
4✔
2082

2083
        case *lnwire.Warning:
×
2084
                return fmt.Sprintf("%v", msg.Warning())
×
2085

2086
        case *lnwire.Error:
4✔
2087
                return fmt.Sprintf("%v", msg.Error())
4✔
2088

2089
        case *lnwire.AnnounceSignatures:
4✔
2090
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
4✔
2091
                        msg.ShortChannelID.ToUint64())
4✔
2092

2093
        case *lnwire.ChannelAnnouncement:
4✔
2094
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
4✔
2095
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
4✔
2096

2097
        case *lnwire.ChannelUpdate:
4✔
2098
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
4✔
2099
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
4✔
2100
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
4✔
2101
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
4✔
2102

2103
        case *lnwire.NodeAnnouncement:
4✔
2104
                return fmt.Sprintf("node=%x, update_time=%v",
4✔
2105
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
4✔
2106

2107
        case *lnwire.Ping:
3✔
2108
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
3✔
2109

2110
        case *lnwire.Pong:
3✔
2111
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
3✔
2112

2113
        case *lnwire.UpdateFee:
×
2114
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2115
                        msg.ChanID, int64(msg.FeePerKw))
×
2116

2117
        case *lnwire.ChannelReestablish:
4✔
2118
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
4✔
2119
                        "remote_tail_height=%v", msg.ChanID,
4✔
2120
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
4✔
2121

2122
        case *lnwire.ReplyShortChanIDsEnd:
4✔
2123
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
4✔
2124
                        msg.Complete)
4✔
2125

2126
        case *lnwire.ReplyChannelRange:
4✔
2127
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
4✔
2128
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
4✔
2129
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
4✔
2130
                        msg.EncodingType)
4✔
2131

2132
        case *lnwire.QueryShortChanIDs:
4✔
2133
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
4✔
2134
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
4✔
2135

2136
        case *lnwire.QueryChannelRange:
4✔
2137
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
4✔
2138
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
4✔
2139
                        msg.LastBlockHeight())
4✔
2140

2141
        case *lnwire.GossipTimestampRange:
4✔
2142
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
4✔
2143
                        "stamp_range=%v", msg.ChainHash,
4✔
2144
                        time.Unix(int64(msg.FirstTimestamp), 0),
4✔
2145
                        msg.TimestampRange)
4✔
2146

2147
        case *lnwire.Custom:
4✔
2148
                return fmt.Sprintf("type=%d", msg.Type)
4✔
2149
        }
2150

2151
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2152
}
2153

2154
// logWireMessage logs the receipt or sending of particular wire message. This
2155
// function is used rather than just logging the message in order to produce
2156
// less spammy log messages in trace mode by setting the 'Curve" parameter to
2157
// nil. Doing this avoids printing out each of the field elements in the curve
2158
// parameters for secp256k1.
2159
func (p *Brontide) logWireMessage(msg lnwire.Message, read bool) {
16✔
2160
        summaryPrefix := "Received"
16✔
2161
        if !read {
29✔
2162
                summaryPrefix = "Sending"
13✔
2163
        }
13✔
2164

2165
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
20✔
2166
                // Debug summary of message.
4✔
2167
                summary := messageSummary(msg)
4✔
2168
                if len(summary) > 0 {
8✔
2169
                        summary = "(" + summary + ")"
4✔
2170
                }
4✔
2171

2172
                preposition := "to"
4✔
2173
                if read {
8✔
2174
                        preposition = "from"
4✔
2175
                }
4✔
2176

2177
                var msgType string
4✔
2178
                if msg.MsgType() < lnwire.CustomTypeStart {
8✔
2179
                        msgType = msg.MsgType().String()
4✔
2180
                } else {
8✔
2181
                        msgType = "custom"
4✔
2182
                }
4✔
2183

2184
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
4✔
2185
                        msgType, summary, preposition, p)
4✔
2186
        }))
2187

2188
        prefix := "readMessage from peer"
16✔
2189
        if !read {
29✔
2190
                prefix = "writeMessage to peer"
13✔
2191
        }
13✔
2192

2193
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
16✔
2194
}
2195

2196
// writeMessage writes and flushes the target lnwire.Message to the remote peer.
2197
// If the passed message is nil, this method will only try to flush an existing
2198
// message buffered on the connection. It is safe to call this method again
2199
// with a nil message iff a timeout error is returned. This will continue to
2200
// flush the pending message to the wire.
2201
//
2202
// NOTE:
2203
// Besides its usage in Start, this function should not be used elsewhere
2204
// except in writeHandler. If multiple goroutines call writeMessage at the same
2205
// time, panics can occur because WriteMessage and Flush don't use any locking
2206
// internally.
2207
func (p *Brontide) writeMessage(msg lnwire.Message) error {
13✔
2208
        // Only log the message on the first attempt.
13✔
2209
        if msg != nil {
26✔
2210
                p.logWireMessage(msg, false)
13✔
2211
        }
13✔
2212

2213
        noiseConn := p.cfg.Conn
13✔
2214

13✔
2215
        flushMsg := func() error {
26✔
2216
                // Ensure the write deadline is set before we attempt to send
13✔
2217
                // the message.
13✔
2218
                writeDeadline := time.Now().Add(
13✔
2219
                        p.scaleTimeout(writeMessageTimeout),
13✔
2220
                )
13✔
2221
                err := noiseConn.SetWriteDeadline(writeDeadline)
13✔
2222
                if err != nil {
13✔
2223
                        return err
×
2224
                }
×
2225

2226
                // Flush the pending message to the wire. If an error is
2227
                // encountered, e.g. write timeout, the number of bytes written
2228
                // so far will be returned.
2229
                n, err := noiseConn.Flush()
13✔
2230

13✔
2231
                // Record the number of bytes written on the wire, if any.
13✔
2232
                if n > 0 {
17✔
2233
                        atomic.AddUint64(&p.bytesSent, uint64(n))
4✔
2234
                }
4✔
2235

2236
                return err
13✔
2237
        }
2238

2239
        // If the current message has already been serialized, encrypted, and
2240
        // buffered on the underlying connection we will skip straight to
2241
        // flushing it to the wire.
2242
        if msg == nil {
13✔
2243
                return flushMsg()
×
2244
        }
×
2245

2246
        // Otherwise, this is a new message. We'll acquire a write buffer to
2247
        // serialize the message and buffer the ciphertext on the connection.
2248
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
26✔
2249
                // Using a buffer allocated by the write pool, encode the
13✔
2250
                // message directly into the buffer.
13✔
2251
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
13✔
2252
                if writeErr != nil {
13✔
2253
                        return writeErr
×
2254
                }
×
2255

2256
                // Finally, write the message itself in a single swoop. This
2257
                // will buffer the ciphertext on the underlying connection. We
2258
                // will defer flushing the message until the write pool has been
2259
                // released.
2260
                return noiseConn.WriteMessage(buf.Bytes())
13✔
2261
        })
2262
        if err != nil {
13✔
2263
                return err
×
2264
        }
×
2265

2266
        return flushMsg()
13✔
2267
}
2268

2269
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2270
// queue, and writing them out to the wire. This goroutine coordinates with the
2271
// queueHandler in order to ensure the incoming message queue is quickly
2272
// drained.
2273
//
2274
// NOTE: This method MUST be run as a goroutine.
2275
func (p *Brontide) writeHandler() {
6✔
2276
        // We'll stop the timer after a new messages is sent, and also reset it
6✔
2277
        // after we process the next message.
6✔
2278
        idleTimer := time.AfterFunc(idleTimeout, func() {
9✔
2279
                err := fmt.Errorf("peer %s no write for %s -- disconnecting",
3✔
2280
                        p, idleTimeout)
3✔
2281
                p.Disconnect(err)
3✔
2282
        })
3✔
2283

2284
        var exitErr error
6✔
2285

6✔
2286
out:
6✔
2287
        for {
14✔
2288
                select {
8✔
2289
                case outMsg := <-p.sendQueue:
6✔
2290
                        // Record the time at which we first attempt to send the
6✔
2291
                        // message.
6✔
2292
                        startTime := time.Now()
6✔
2293

6✔
2294
                retry:
6✔
2295
                        // Write out the message to the socket. If a timeout
2296
                        // error is encountered, we will catch this and retry
2297
                        // after backing off in case the remote peer is just
2298
                        // slow to process messages from the wire.
2299
                        err := p.writeMessage(outMsg.msg)
6✔
2300
                        if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
6✔
2301
                                p.log.Debugf("Write timeout detected for "+
×
2302
                                        "peer, first write for message "+
×
2303
                                        "attempted %v ago",
×
2304
                                        time.Since(startTime))
×
2305

×
2306
                                // If we received a timeout error, this implies
×
2307
                                // that the message was buffered on the
×
2308
                                // connection successfully and that a flush was
×
2309
                                // attempted. We'll set the message to nil so
×
2310
                                // that on a subsequent pass we only try to
×
2311
                                // flush the buffered message, and forgo
×
2312
                                // reserializing or reencrypting it.
×
2313
                                outMsg.msg = nil
×
2314

×
2315
                                goto retry
×
2316
                        }
2317

2318
                        // The write succeeded, reset the idle timer to prevent
2319
                        // us from disconnecting the peer.
2320
                        if !idleTimer.Stop() {
6✔
2321
                                select {
×
2322
                                case <-idleTimer.C:
×
2323
                                default:
×
2324
                                }
2325
                        }
2326
                        idleTimer.Reset(idleTimeout)
6✔
2327

6✔
2328
                        // If the peer requested a synchronous write, respond
6✔
2329
                        // with the error.
6✔
2330
                        if outMsg.errChan != nil {
11✔
2331
                                outMsg.errChan <- err
5✔
2332
                        }
5✔
2333

2334
                        if err != nil {
6✔
2335
                                exitErr = fmt.Errorf("unable to write "+
×
2336
                                        "message: %v", err)
×
2337
                                break out
×
2338
                        }
2339

2340
                case <-p.quit:
4✔
2341
                        exitErr = lnpeer.ErrPeerExiting
4✔
2342
                        break out
4✔
2343
                }
2344
        }
2345

2346
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2347
        // disconnect.
2348
        p.wg.Done()
4✔
2349

4✔
2350
        p.Disconnect(exitErr)
4✔
2351

4✔
2352
        p.log.Trace("writeHandler for peer done")
4✔
2353
}
2354

2355
// queueHandler is responsible for accepting messages from outside subsystems
2356
// to be eventually sent out on the wire by the writeHandler.
2357
//
2358
// NOTE: This method MUST be run as a goroutine.
2359
func (p *Brontide) queueHandler() {
6✔
2360
        defer p.wg.Done()
6✔
2361

6✔
2362
        // priorityMsgs holds an in order list of messages deemed high-priority
6✔
2363
        // to be added to the sendQueue. This predominately includes messages
6✔
2364
        // from the funding manager and htlcswitch.
6✔
2365
        priorityMsgs := list.New()
6✔
2366

6✔
2367
        // lazyMsgs holds an in order list of messages deemed low-priority to be
6✔
2368
        // added to the sendQueue only after all high-priority messages have
6✔
2369
        // been queued. This predominately includes messages from the gossiper.
6✔
2370
        lazyMsgs := list.New()
6✔
2371

6✔
2372
        for {
16✔
2373
                // Examine the front of the priority queue, if it is empty check
10✔
2374
                // the low priority queue.
10✔
2375
                elem := priorityMsgs.Front()
10✔
2376
                if elem == nil {
19✔
2377
                        elem = lazyMsgs.Front()
9✔
2378
                }
9✔
2379

2380
                if elem != nil {
16✔
2381
                        front := elem.Value.(outgoingMsg)
6✔
2382

6✔
2383
                        // There's an element on the queue, try adding
6✔
2384
                        // it to the sendQueue. We also watch for
6✔
2385
                        // messages on the outgoingQueue, in case the
6✔
2386
                        // writeHandler cannot accept messages on the
6✔
2387
                        // sendQueue.
6✔
2388
                        select {
6✔
2389
                        case p.sendQueue <- front:
6✔
2390
                                if front.priority {
11✔
2391
                                        priorityMsgs.Remove(elem)
5✔
2392
                                } else {
10✔
2393
                                        lazyMsgs.Remove(elem)
5✔
2394
                                }
5✔
2395
                        case msg := <-p.outgoingQueue:
4✔
2396
                                if msg.priority {
8✔
2397
                                        priorityMsgs.PushBack(msg)
4✔
2398
                                } else {
8✔
2399
                                        lazyMsgs.PushBack(msg)
4✔
2400
                                }
4✔
2401
                        case <-p.quit:
×
2402
                                return
×
2403
                        }
2404
                } else {
8✔
2405
                        // If there weren't any messages to send to the
8✔
2406
                        // writeHandler, then we'll accept a new message
8✔
2407
                        // into the queue from outside sub-systems.
8✔
2408
                        select {
8✔
2409
                        case msg := <-p.outgoingQueue:
6✔
2410
                                if msg.priority {
11✔
2411
                                        priorityMsgs.PushBack(msg)
5✔
2412
                                } else {
10✔
2413
                                        lazyMsgs.PushBack(msg)
5✔
2414
                                }
5✔
2415
                        case <-p.quit:
4✔
2416
                                return
4✔
2417
                        }
2418
                }
2419
        }
2420
}
2421

2422
// PingTime returns the estimated ping time to the peer in microseconds.
2423
func (p *Brontide) PingTime() int64 {
4✔
2424
        return p.pingManager.GetPingTimeMicroSeconds()
4✔
2425
}
4✔
2426

2427
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2428
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2429
// or failed to write, and nil otherwise.
2430
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
27✔
2431
        p.queue(true, msg, errChan)
27✔
2432
}
27✔
2433

2434
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2435
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2436
// queue or failed to write, and nil otherwise.
2437
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
5✔
2438
        p.queue(false, msg, errChan)
5✔
2439
}
5✔
2440

2441
// queue sends a given message to the queueHandler using the passed priority. If
2442
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2443
// failed to write, and nil otherwise.
2444
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2445
        errChan chan error) {
28✔
2446

28✔
2447
        select {
28✔
2448
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
27✔
2449
        case <-p.quit:
4✔
2450
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
4✔
2451
                        spew.Sdump(msg))
4✔
2452
                if errChan != nil {
4✔
2453
                        errChan <- lnpeer.ErrPeerExiting
×
2454
                }
×
2455
        }
2456
}
2457

2458
// ChannelSnapshots returns a slice of channel snapshots detailing all
2459
// currently active channels maintained with the remote peer.
2460
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
4✔
2461
        snapshots := make(
4✔
2462
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
4✔
2463
        )
4✔
2464

4✔
2465
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
4✔
2466
                activeChan *lnwallet.LightningChannel) error {
8✔
2467

4✔
2468
                // If the activeChan is nil, then we skip it as the channel is
4✔
2469
                // pending.
4✔
2470
                if activeChan == nil {
8✔
2471
                        return nil
4✔
2472
                }
4✔
2473

2474
                // We'll only return a snapshot for channels that are
2475
                // *immediately* available for routing payments over.
2476
                if activeChan.RemoteNextRevocation() == nil {
8✔
2477
                        return nil
4✔
2478
                }
4✔
2479

2480
                snapshot := activeChan.StateSnapshot()
4✔
2481
                snapshots = append(snapshots, snapshot)
4✔
2482

4✔
2483
                return nil
4✔
2484
        })
2485

2486
        return snapshots
4✔
2487
}
2488

2489
// genDeliveryScript returns a new script to be used to send our funds to in
2490
// the case of a cooperative channel close negotiation.
2491
func (p *Brontide) genDeliveryScript() ([]byte, error) {
10✔
2492
        // We'll send a normal p2wkh address unless we've negotiated the
10✔
2493
        // shutdown-any-segwit feature.
10✔
2494
        addrType := lnwallet.WitnessPubKey
10✔
2495
        if p.taprootShutdownAllowed() {
14✔
2496
                addrType = lnwallet.TaprootPubkey
4✔
2497
        }
4✔
2498

2499
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
10✔
2500
                addrType, false, lnwallet.DefaultAccountName,
10✔
2501
        )
10✔
2502
        if err != nil {
10✔
2503
                return nil, err
×
2504
        }
×
2505
        p.log.Infof("Delivery addr for channel close: %v",
10✔
2506
                deliveryAddr)
10✔
2507

10✔
2508
        return txscript.PayToAddrScript(deliveryAddr)
10✔
2509
}
2510

2511
// channelManager is goroutine dedicated to handling all requests/signals
2512
// pertaining to the opening, cooperative closing, and force closing of all
2513
// channels maintained with the remote peer.
2514
//
2515
// NOTE: This method MUST be run as a goroutine.
2516
func (p *Brontide) channelManager() {
19✔
2517
        defer p.wg.Done()
19✔
2518

19✔
2519
        // reenableTimeout will fire once after the configured channel status
19✔
2520
        // interval has elapsed. This will trigger us to sign new channel
19✔
2521
        // updates and broadcast them with the "disabled" flag unset.
19✔
2522
        reenableTimeout := time.After(p.cfg.ChanActiveTimeout)
19✔
2523

19✔
2524
out:
19✔
2525
        for {
59✔
2526
                select {
40✔
2527
                // A new pending channel has arrived which means we are about
2528
                // to complete a funding workflow and is waiting for the final
2529
                // `ChannelReady` messages to be exchanged. We will add this
2530
                // channel to the `activeChannels` with a nil value to indicate
2531
                // this is a pending channel.
2532
                case req := <-p.newPendingChannel:
5✔
2533
                        p.handleNewPendingChannel(req)
5✔
2534

2535
                // A new channel has arrived which means we've just completed a
2536
                // funding workflow. We'll initialize the necessary local
2537
                // state, and notify the htlc switch of a new link.
2538
                case req := <-p.newActiveChannel:
4✔
2539
                        p.handleNewActiveChannel(req)
4✔
2540

2541
                // The funding flow for a pending channel is failed, we will
2542
                // remove it from Brontide.
2543
                case req := <-p.removePendingChannel:
5✔
2544
                        p.handleRemovePendingChannel(req)
5✔
2545

2546
                // We've just received a local request to close an active
2547
                // channel. It will either kick of a cooperative channel
2548
                // closure negotiation, or be a notification of a breached
2549
                // contract that should be abandoned.
2550
                case req := <-p.localCloseChanReqs:
11✔
2551
                        p.handleLocalCloseReq(req)
11✔
2552

2553
                // We've received a link failure from a link that was added to
2554
                // the switch. This will initiate the teardown of the link, and
2555
                // initiate any on-chain closures if necessary.
2556
                case failure := <-p.linkFailures:
4✔
2557
                        p.handleLinkFailure(failure)
4✔
2558

2559
                // We've received a new cooperative channel closure related
2560
                // message from the remote peer, we'll use this message to
2561
                // advance the chan closer state machine.
2562
                case closeMsg := <-p.chanCloseMsgs:
17✔
2563
                        p.handleCloseMsg(closeMsg)
17✔
2564

2565
                // The channel reannounce delay has elapsed, broadcast the
2566
                // reenabled channel updates to the network. This should only
2567
                // fire once, so we set the reenableTimeout channel to nil to
2568
                // mark it for garbage collection. If the peer is torn down
2569
                // before firing, reenabling will not be attempted.
2570
                // TODO(conner): consolidate reenables timers inside chan status
2571
                // manager
2572
                case <-reenableTimeout:
4✔
2573
                        p.reenableActiveChannels()
4✔
2574

4✔
2575
                        // Since this channel will never fire again during the
4✔
2576
                        // lifecycle of the peer, we nil the channel to mark it
4✔
2577
                        // eligible for garbage collection, and make this
4✔
2578
                        // explicitly ineligible to receive in future calls to
4✔
2579
                        // select. This also shaves a few CPU cycles since the
4✔
2580
                        // select will ignore this case entirely.
4✔
2581
                        reenableTimeout = nil
4✔
2582

4✔
2583
                        // Once the reenabling is attempted, we also cancel the
4✔
2584
                        // channel event subscription to free up the overflow
4✔
2585
                        // queue used in channel notifier.
4✔
2586
                        //
4✔
2587
                        // NOTE: channelEventClient will be nil if the
4✔
2588
                        // reenableTimeout is greater than 1 minute.
4✔
2589
                        if p.channelEventClient != nil {
8✔
2590
                                p.channelEventClient.Cancel()
4✔
2591
                        }
4✔
2592

2593
                case <-p.quit:
4✔
2594
                        // As, we've been signalled to exit, we'll reset all
4✔
2595
                        // our active channel back to their default state.
4✔
2596
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
4✔
2597
                                lc *lnwallet.LightningChannel) error {
8✔
2598

4✔
2599
                                // Exit if the channel is nil as it's a pending
4✔
2600
                                // channel.
4✔
2601
                                if lc == nil {
8✔
2602
                                        return nil
4✔
2603
                                }
4✔
2604

2605
                                lc.ResetState()
4✔
2606

4✔
2607
                                return nil
4✔
2608
                        })
2609

2610
                        break out
4✔
2611
                }
2612
        }
2613
}
2614

2615
// reenableActiveChannels searches the index of channels maintained with this
2616
// peer, and reenables each public, non-pending channel. This is done at the
2617
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
2618
// No message will be sent if the channel is already enabled.
2619
func (p *Brontide) reenableActiveChannels() {
4✔
2620
        // First, filter all known channels with this peer for ones that are
4✔
2621
        // both public and not pending.
4✔
2622
        activePublicChans := p.filterChannelsToEnable()
4✔
2623

4✔
2624
        // Create a map to hold channels that needs to be retried.
4✔
2625
        retryChans := make(map[wire.OutPoint]struct{}, len(activePublicChans))
4✔
2626

4✔
2627
        // For each of the public, non-pending channels, set the channel
4✔
2628
        // disabled bit to false and send out a new ChannelUpdate. If this
4✔
2629
        // channel is already active, the update won't be sent.
4✔
2630
        for _, chanPoint := range activePublicChans {
8✔
2631
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
4✔
2632

4✔
2633
                switch {
4✔
2634
                // No error occurred, continue to request the next channel.
2635
                case err == nil:
4✔
2636
                        continue
4✔
2637

2638
                // Cannot auto enable a manually disabled channel so we do
2639
                // nothing but proceed to the next channel.
2640
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
4✔
2641
                        p.log.Debugf("Channel(%v) was manually disabled, "+
4✔
2642
                                "ignoring automatic enable request", chanPoint)
4✔
2643

4✔
2644
                        continue
4✔
2645

2646
                // If the channel is reported as inactive, we will give it
2647
                // another chance. When handling the request, ChanStatusManager
2648
                // will check whether the link is active or not. One of the
2649
                // conditions is whether the link has been marked as
2650
                // reestablished, which happens inside a goroutine(htlcManager)
2651
                // after the link is started. And we may get a false negative
2652
                // saying the link is not active because that goroutine hasn't
2653
                // reached the line to mark the reestablishment. Thus we give
2654
                // it a second chance to send the request.
2655
                case errors.Is(err, netann.ErrEnableInactiveChan):
×
2656
                        // If we don't have a client created, it means we
×
2657
                        // shouldn't retry enabling the channel.
×
2658
                        if p.channelEventClient == nil {
×
2659
                                p.log.Errorf("Channel(%v) request enabling "+
×
2660
                                        "failed due to inactive link",
×
2661
                                        chanPoint)
×
2662

×
2663
                                continue
×
2664
                        }
2665

2666
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
2667
                                "ChanStatusManager reported inactive, retrying")
×
2668

×
2669
                        // Add the channel to the retry map.
×
2670
                        retryChans[chanPoint] = struct{}{}
×
2671
                }
2672
        }
2673

2674
        // Retry the channels if we have any.
2675
        if len(retryChans) != 0 {
4✔
2676
                p.retryRequestEnable(retryChans)
×
2677
        }
×
2678
}
2679

2680
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
2681
// for the target channel ID. If the channel isn't active an error is returned.
2682
// Otherwise, either an existing state machine will be returned, or a new one
2683
// will be created.
2684
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
2685
        *chancloser.ChanCloser, error) {
17✔
2686

17✔
2687
        chanCloser, found := p.activeChanCloses[chanID]
17✔
2688
        if found {
31✔
2689
                // An entry will only be found if the closer has already been
14✔
2690
                // created for a non-pending channel or for a channel that had
14✔
2691
                // previously started the shutdown process but the connection
14✔
2692
                // was restarted.
14✔
2693
                return chanCloser, nil
14✔
2694
        }
14✔
2695

2696
        // First, we'll ensure that we actually know of the target channel. If
2697
        // not, we'll ignore this message.
2698
        channel, ok := p.activeChannels.Load(chanID)
7✔
2699

7✔
2700
        // If the channel isn't in the map or the channel is nil, return
7✔
2701
        // ErrChannelNotFound as the channel is pending.
7✔
2702
        if !ok || channel == nil {
11✔
2703
                return nil, ErrChannelNotFound
4✔
2704
        }
4✔
2705

2706
        // We'll create a valid closing state machine in order to respond to
2707
        // the initiated cooperative channel closure. First, we set the
2708
        // delivery script that our funds will be paid out to. If an upfront
2709
        // shutdown script was set, we will use it. Otherwise, we get a fresh
2710
        // delivery script.
2711
        //
2712
        // TODO: Expose option to allow upfront shutdown script from watch-only
2713
        // accounts.
2714
        deliveryScript := channel.LocalUpfrontShutdownScript()
7✔
2715
        if len(deliveryScript) == 0 {
14✔
2716
                var err error
7✔
2717
                deliveryScript, err = p.genDeliveryScript()
7✔
2718
                if err != nil {
7✔
2719
                        p.log.Errorf("unable to gen delivery script: %v",
×
2720
                                err)
×
2721
                        return nil, fmt.Errorf("close addr unavailable")
×
2722
                }
×
2723
        }
2724

2725
        // In order to begin fee negotiations, we'll first compute our target
2726
        // ideal fee-per-kw.
2727
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
7✔
2728
                p.cfg.CoopCloseTargetConfs,
7✔
2729
        )
7✔
2730
        if err != nil {
7✔
2731
                p.log.Errorf("unable to query fee estimator: %v", err)
×
2732
                return nil, fmt.Errorf("unable to estimate fee")
×
2733
        }
×
2734

2735
        chanCloser, err = p.createChanCloser(
7✔
2736
                channel, deliveryScript, feePerKw, nil, lntypes.Remote,
7✔
2737
        )
7✔
2738
        if err != nil {
7✔
2739
                p.log.Errorf("unable to create chan closer: %v", err)
×
2740
                return nil, fmt.Errorf("unable to create chan closer")
×
2741
        }
×
2742

2743
        p.activeChanCloses[chanID] = chanCloser
7✔
2744

7✔
2745
        return chanCloser, nil
7✔
2746
}
2747

2748
// filterChannelsToEnable filters a list of channels to be enabled upon start.
2749
// The filtered channels are active channels that's neither private nor
2750
// pending.
2751
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
4✔
2752
        var activePublicChans []wire.OutPoint
4✔
2753

4✔
2754
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
4✔
2755
                lnChan *lnwallet.LightningChannel) bool {
8✔
2756

4✔
2757
                // If the lnChan is nil, continue as this is a pending channel.
4✔
2758
                if lnChan == nil {
5✔
2759
                        return true
1✔
2760
                }
1✔
2761

2762
                dbChan := lnChan.State()
4✔
2763
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
4✔
2764
                if !isPublic || dbChan.IsPending {
4✔
2765
                        return true
×
2766
                }
×
2767

2768
                // We'll also skip any channels added during this peer's
2769
                // lifecycle since they haven't waited out the timeout. Their
2770
                // first announcement will be enabled, and the chan status
2771
                // manager will begin monitoring them passively since they exist
2772
                // in the database.
2773
                if _, ok := p.addedChannels.Load(chanID); ok {
7✔
2774
                        return true
3✔
2775
                }
3✔
2776

2777
                activePublicChans = append(
4✔
2778
                        activePublicChans, dbChan.FundingOutpoint,
4✔
2779
                )
4✔
2780

4✔
2781
                return true
4✔
2782
        })
2783

2784
        return activePublicChans
4✔
2785
}
2786

2787
// retryRequestEnable takes a map of channel outpoints and a channel event
2788
// client. It listens to the channel events and removes a channel from the map
2789
// if it's matched to the event. Upon receiving an active channel event, it
2790
// will send the enabling request again.
2791
func (p *Brontide) retryRequestEnable(activeChans map[wire.OutPoint]struct{}) {
×
2792
        p.log.Debugf("Retry enabling %v channels", len(activeChans))
×
2793

×
2794
        // retryEnable is a helper closure that sends an enable request and
×
2795
        // removes the channel from the map if it's matched.
×
2796
        retryEnable := func(chanPoint wire.OutPoint) error {
×
2797
                // If this is an active channel event, check whether it's in
×
2798
                // our targeted channels map.
×
2799
                _, found := activeChans[chanPoint]
×
2800

×
2801
                // If this channel is irrelevant, return nil so the loop can
×
2802
                // jump to next iteration.
×
2803
                if !found {
×
2804
                        return nil
×
2805
                }
×
2806

2807
                // Otherwise we've just received an active signal for a channel
2808
                // that's previously failed to be enabled, we send the request
2809
                // again.
2810
                //
2811
                // We only give the channel one more shot, so we delete it from
2812
                // our map first to keep it from being attempted again.
2813
                delete(activeChans, chanPoint)
×
2814

×
2815
                // Send the request.
×
2816
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
2817
                if err != nil {
×
2818
                        return fmt.Errorf("request enabling channel %v "+
×
2819
                                "failed: %w", chanPoint, err)
×
2820
                }
×
2821

2822
                return nil
×
2823
        }
2824

2825
        for {
×
2826
                // If activeChans is empty, we've done processing all the
×
2827
                // channels.
×
2828
                if len(activeChans) == 0 {
×
2829
                        p.log.Debug("Finished retry enabling channels")
×
2830
                        return
×
2831
                }
×
2832

2833
                select {
×
2834
                // A new event has been sent by the ChannelNotifier. We now
2835
                // check whether it's an active or inactive channel event.
2836
                case e := <-p.channelEventClient.Updates():
×
2837
                        // If this is an active channel event, try enable the
×
2838
                        // channel then jump to the next iteration.
×
2839
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
2840
                        if ok {
×
2841
                                chanPoint := *active.ChannelPoint
×
2842

×
2843
                                // If we received an error for this particular
×
2844
                                // channel, we log an error and won't quit as
×
2845
                                // we still want to retry other channels.
×
2846
                                if err := retryEnable(chanPoint); err != nil {
×
2847
                                        p.log.Errorf("Retry failed: %v", err)
×
2848
                                }
×
2849

2850
                                continue
×
2851
                        }
2852

2853
                        // Otherwise check for inactive link event, and jump to
2854
                        // next iteration if it's not.
2855
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
2856
                        if !ok {
×
2857
                                continue
×
2858
                        }
2859

2860
                        // Found an inactive link event, if this is our
2861
                        // targeted channel, remove it from our map.
2862
                        chanPoint := *inactive.ChannelPoint
×
2863
                        _, found := activeChans[chanPoint]
×
2864
                        if !found {
×
2865
                                continue
×
2866
                        }
2867

2868
                        delete(activeChans, chanPoint)
×
2869
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
2870
                                "inactive link event", chanPoint)
×
2871

2872
                case <-p.quit:
×
2873
                        p.log.Debugf("Peer shutdown during retry enabling")
×
2874
                        return
×
2875
                }
2876
        }
2877
}
2878

2879
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
2880
// a suitable script to close out to. This may be nil if neither script is
2881
// set. If both scripts are set, this function will error if they do not match.
2882
func chooseDeliveryScript(upfront,
2883
        requested lnwire.DeliveryAddress) (lnwire.DeliveryAddress, error) {
16✔
2884

16✔
2885
        // If no upfront shutdown script was provided, return the user
16✔
2886
        // requested address (which may be nil).
16✔
2887
        if len(upfront) == 0 {
26✔
2888
                return requested, nil
10✔
2889
        }
10✔
2890

2891
        // If an upfront shutdown script was provided, and the user did not
2892
        // request a custom shutdown script, return the upfront address.
2893
        if len(requested) == 0 {
16✔
2894
                return upfront, nil
6✔
2895
        }
6✔
2896

2897
        // If both an upfront shutdown script and a custom close script were
2898
        // provided, error if the user provided shutdown script does not match
2899
        // the upfront shutdown script (because closing out to a different
2900
        // script would violate upfront shutdown).
2901
        if !bytes.Equal(upfront, requested) {
6✔
2902
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
2903
        }
2✔
2904

2905
        // The user requested script matches the upfront shutdown script, so we
2906
        // can return it without error.
2907
        return upfront, nil
2✔
2908
}
2909

2910
// restartCoopClose checks whether we need to restart the cooperative close
2911
// process for a given channel.
2912
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
2913
        *lnwire.Shutdown, error) {
×
2914

×
2915
        // If this channel has status ChanStatusCoopBroadcasted and does not
×
2916
        // have a closing transaction, then the cooperative close process was
×
2917
        // started but never finished. We'll re-create the chanCloser state
×
2918
        // machine and resend Shutdown. BOLT#2 requires that we retransmit
×
2919
        // Shutdown exactly, but doing so would mean persisting the RPC
×
2920
        // provided close script. Instead use the LocalUpfrontShutdownScript
×
2921
        // or generate a script.
×
2922
        c := lnChan.State()
×
2923
        _, err := c.BroadcastedCooperative()
×
2924
        if err != nil && err != channeldb.ErrNoCloseTx {
×
2925
                // An error other than ErrNoCloseTx was encountered.
×
2926
                return nil, err
×
2927
        } else if err == nil {
×
2928
                // This channel has already completed the coop close
×
2929
                // negotiation.
×
2930
                return nil, nil
×
2931
        }
×
2932

2933
        var deliveryScript []byte
×
2934

×
2935
        shutdownInfo, err := c.ShutdownInfo()
×
2936
        switch {
×
2937
        // We have previously stored the delivery script that we need to use
2938
        // in the shutdown message. Re-use this script.
2939
        case err == nil:
×
2940
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
×
2941
                        deliveryScript = info.DeliveryScript.Val
×
2942
                })
×
2943

2944
        // An error other than ErrNoShutdownInfo was returned
2945
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
2946
                return nil, err
×
2947

2948
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
2949
                deliveryScript = c.LocalShutdownScript
×
2950
                if len(deliveryScript) == 0 {
×
2951
                        var err error
×
2952
                        deliveryScript, err = p.genDeliveryScript()
×
2953
                        if err != nil {
×
2954
                                p.log.Errorf("unable to gen delivery script: "+
×
2955
                                        "%v", err)
×
2956

×
2957
                                return nil, fmt.Errorf("close addr unavailable")
×
2958
                        }
×
2959
                }
2960
        }
2961

2962
        // Compute an ideal fee.
2963
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
2964
                p.cfg.CoopCloseTargetConfs,
×
2965
        )
×
2966
        if err != nil {
×
2967
                p.log.Errorf("unable to query fee estimator: %v", err)
×
2968
                return nil, fmt.Errorf("unable to estimate fee")
×
2969
        }
×
2970

2971
        // Determine whether we or the peer are the initiator of the coop
2972
        // close attempt by looking at the channel's status.
2973
        closingParty := lntypes.Remote
×
2974
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
2975
                closingParty = lntypes.Local
×
2976
        }
×
2977

2978
        chanCloser, err := p.createChanCloser(
×
2979
                lnChan, deliveryScript, feePerKw, nil, closingParty,
×
2980
        )
×
2981
        if err != nil {
×
2982
                p.log.Errorf("unable to create chan closer: %v", err)
×
2983
                return nil, fmt.Errorf("unable to create chan closer")
×
2984
        }
×
2985

2986
        // This does not need a mutex even though it is in a different
2987
        // goroutine since this is done before the channelManager goroutine is
2988
        // created.
2989
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
×
2990
        p.activeChanCloses[chanID] = chanCloser
×
2991

×
2992
        // Create the Shutdown message.
×
2993
        shutdownMsg, err := chanCloser.ShutdownChan()
×
2994
        if err != nil {
×
2995
                p.log.Errorf("unable to create shutdown message: %v", err)
×
2996
                delete(p.activeChanCloses, chanID)
×
2997
                return nil, err
×
2998
        }
×
2999

3000
        return shutdownMsg, nil
×
3001
}
3002

3003
// createChanCloser constructs a ChanCloser from the passed parameters and is
3004
// used to de-duplicate code.
3005
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3006
        deliveryScript lnwire.DeliveryAddress, fee chainfee.SatPerKWeight,
3007
        req *htlcswitch.ChanClose,
3008
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
13✔
3009

13✔
3010
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
13✔
3011
        if err != nil {
13✔
3012
                p.log.Errorf("unable to obtain best block: %v", err)
×
3013
                return nil, fmt.Errorf("cannot obtain best block")
×
3014
        }
×
3015

3016
        // The req will only be set if we initiated the co-op closing flow.
3017
        var maxFee chainfee.SatPerKWeight
13✔
3018
        if req != nil {
23✔
3019
                maxFee = req.MaxFee
10✔
3020
        }
10✔
3021

3022
        chanCloser := chancloser.NewChanCloser(
13✔
3023
                chancloser.ChanCloseCfg{
13✔
3024
                        Channel:      channel,
13✔
3025
                        MusigSession: NewMusigChanCloser(channel),
13✔
3026
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
13✔
3027
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
13✔
3028
                        DisableChannel: func(op wire.OutPoint) error {
26✔
3029
                                return p.cfg.ChanStatusMgr.RequestDisable(
13✔
3030
                                        op, false,
13✔
3031
                                )
13✔
3032
                        },
13✔
3033
                        MaxFee: maxFee,
3034
                        Disconnect: func() error {
×
3035
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
3036
                        },
×
3037
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3038
                        Quit:        p.quit,
3039
                },
3040
                deliveryScript,
3041
                fee,
3042
                uint32(startingHeight),
3043
                req,
3044
                closer,
3045
        )
3046

3047
        return chanCloser, nil
13✔
3048
}
3049

3050
// handleLocalCloseReq kicks-off the workflow to execute a cooperative or
3051
// forced unilateral closure of the channel initiated by a local subsystem.
3052
func (p *Brontide) handleLocalCloseReq(req *htlcswitch.ChanClose) {
11✔
3053
        chanID := lnwire.NewChanIDFromOutPoint(*req.ChanPoint)
11✔
3054

11✔
3055
        channel, ok := p.activeChannels.Load(chanID)
11✔
3056

11✔
3057
        // Though this function can't be called for pending channels, we still
11✔
3058
        // check whether channel is nil for safety.
11✔
3059
        if !ok || channel == nil {
11✔
3060
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
×
3061
                        "unknown", chanID)
×
3062
                p.log.Errorf(err.Error())
×
3063
                req.Err <- err
×
3064
                return
×
3065
        }
×
3066

3067
        switch req.CloseType {
11✔
3068
        // A type of CloseRegular indicates that the user has opted to close
3069
        // out this channel on-chain, so we execute the cooperative channel
3070
        // closure workflow.
3071
        case contractcourt.CloseRegular:
11✔
3072
                // First, we'll choose a delivery address that we'll use to send the
11✔
3073
                // funds to in the case of a successful negotiation.
11✔
3074

11✔
3075
                // An upfront shutdown and user provided script are both optional,
11✔
3076
                // but must be equal if both set  (because we cannot serve a request
11✔
3077
                // to close out to a script which violates upfront shutdown). Get the
11✔
3078
                // appropriate address to close out to (which may be nil if neither
11✔
3079
                // are set) and error if they are both set and do not match.
11✔
3080
                deliveryScript, err := chooseDeliveryScript(
11✔
3081
                        channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
11✔
3082
                )
11✔
3083
                if err != nil {
12✔
3084
                        p.log.Errorf("cannot close channel %v: %v", req.ChanPoint, err)
1✔
3085
                        req.Err <- err
1✔
3086
                        return
1✔
3087
                }
1✔
3088

3089
                // If neither an upfront address or a user set address was
3090
                // provided, generate a fresh script.
3091
                if len(deliveryScript) == 0 {
17✔
3092
                        deliveryScript, err = p.genDeliveryScript()
7✔
3093
                        if err != nil {
7✔
3094
                                p.log.Errorf(err.Error())
×
3095
                                req.Err <- err
×
3096
                                return
×
3097
                        }
×
3098
                }
3099

3100
                chanCloser, err := p.createChanCloser(
10✔
3101
                        channel, deliveryScript, req.TargetFeePerKw, req,
10✔
3102
                        lntypes.Local,
10✔
3103
                )
10✔
3104
                if err != nil {
10✔
3105
                        p.log.Errorf(err.Error())
×
3106
                        req.Err <- err
×
3107
                        return
×
3108
                }
×
3109

3110
                p.activeChanCloses[chanID] = chanCloser
10✔
3111

10✔
3112
                // Finally, we'll initiate the channel shutdown within the
10✔
3113
                // chanCloser, and send the shutdown message to the remote
10✔
3114
                // party to kick things off.
10✔
3115
                shutdownMsg, err := chanCloser.ShutdownChan()
10✔
3116
                if err != nil {
10✔
3117
                        p.log.Errorf(err.Error())
×
3118
                        req.Err <- err
×
3119
                        delete(p.activeChanCloses, chanID)
×
3120

×
3121
                        // As we were unable to shutdown the channel, we'll
×
3122
                        // return it back to its normal state.
×
3123
                        channel.ResetState()
×
3124
                        return
×
3125
                }
×
3126

3127
                link := p.fetchLinkFromKeyAndCid(chanID)
10✔
3128
                if link == nil {
10✔
3129
                        // If the link is nil then it means it was already
×
3130
                        // removed from the switch or it never existed in the
×
3131
                        // first place. The latter case is handled at the
×
3132
                        // beginning of this function, so in the case where it
×
3133
                        // has already been removed, we can skip adding the
×
3134
                        // commit hook to queue a Shutdown message.
×
3135
                        p.log.Warnf("link not found during attempted closure: "+
×
3136
                                "%v", chanID)
×
3137
                        return
×
3138
                }
×
3139

3140
                if !link.DisableAdds(htlcswitch.Outgoing) {
10✔
3141
                        p.log.Warnf("Outgoing link adds already "+
×
3142
                                "disabled: %v", link.ChanID())
×
3143
                }
×
3144

3145
                link.OnCommitOnce(htlcswitch.Outgoing, func() {
20✔
3146
                        p.queueMsg(shutdownMsg, nil)
10✔
3147
                })
10✔
3148

3149
        // A type of CloseBreach indicates that the counterparty has breached
3150
        // the channel therefore we need to clean up our local state.
3151
        case contractcourt.CloseBreach:
×
3152
                // TODO(roasbeef): no longer need with newer beach logic?
×
3153
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
×
3154
                        "channel", req.ChanPoint)
×
3155
                p.WipeChannel(req.ChanPoint)
×
3156
        }
3157
}
3158

3159
// linkFailureReport is sent to the channelManager whenever a link reports a
3160
// link failure, and is forced to exit. The report houses the necessary
3161
// information to clean up the channel state, send back the error message, and
3162
// force close if necessary.
3163
type linkFailureReport struct {
3164
        chanPoint   wire.OutPoint
3165
        chanID      lnwire.ChannelID
3166
        shortChanID lnwire.ShortChannelID
3167
        linkErr     htlcswitch.LinkFailureError
3168
}
3169

3170
// handleLinkFailure processes a link failure report when a link in the switch
3171
// fails. It facilitates the removal of all channel state within the peer,
3172
// force closing the channel depending on severity, and sending the error
3173
// message back to the remote party.
3174
func (p *Brontide) handleLinkFailure(failure linkFailureReport) {
4✔
3175
        // Retrieve the channel from the map of active channels. We do this to
4✔
3176
        // have access to it even after WipeChannel remove it from the map.
4✔
3177
        chanID := lnwire.NewChanIDFromOutPoint(failure.chanPoint)
4✔
3178
        lnChan, _ := p.activeChannels.Load(chanID)
4✔
3179

4✔
3180
        // We begin by wiping the link, which will remove it from the switch,
4✔
3181
        // such that it won't be attempted used for any more updates.
4✔
3182
        //
4✔
3183
        // TODO(halseth): should introduce a way to atomically stop/pause the
4✔
3184
        // link and cancel back any adds in its mailboxes such that we can
4✔
3185
        // safely force close without the link being added again and updates
4✔
3186
        // being applied.
4✔
3187
        p.WipeChannel(&failure.chanPoint)
4✔
3188

4✔
3189
        // If the error encountered was severe enough, we'll now force close
4✔
3190
        // the channel to prevent reading it to the switch in the future.
4✔
3191
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureForceClose {
8✔
3192
                p.log.Warnf("Force closing link(%v)", failure.shortChanID)
4✔
3193

4✔
3194
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
4✔
3195
                        failure.chanPoint,
4✔
3196
                )
4✔
3197
                if err != nil {
8✔
3198
                        p.log.Errorf("unable to force close "+
4✔
3199
                                "link(%v): %v", failure.shortChanID, err)
4✔
3200
                } else {
8✔
3201
                        p.log.Infof("channel(%v) force "+
4✔
3202
                                "closed with txid %v",
4✔
3203
                                failure.shortChanID, closeTx.TxHash())
4✔
3204
                }
4✔
3205
        }
3206

3207
        // If this is a permanent failure, we will mark the channel borked.
3208
        if failure.linkErr.PermanentFailure && lnChan != nil {
4✔
3209
                p.log.Warnf("Marking link(%v) borked due to permanent "+
×
3210
                        "failure", failure.shortChanID)
×
3211

×
3212
                if err := lnChan.State().MarkBorked(); err != nil {
×
3213
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
3214
                                failure.shortChanID, err)
×
3215
                }
×
3216
        }
3217

3218
        // Send an error to the peer, why we failed the channel.
3219
        if failure.linkErr.ShouldSendToPeer() {
8✔
3220
                // If SendData is set, send it to the peer. If not, we'll use
4✔
3221
                // the standard error messages in the payload. We only include
4✔
3222
                // sendData in the cases where the error data does not contain
4✔
3223
                // sensitive information.
4✔
3224
                data := []byte(failure.linkErr.Error())
4✔
3225
                if failure.linkErr.SendData != nil {
4✔
3226
                        data = failure.linkErr.SendData
×
3227
                }
×
3228

3229
                var networkMsg lnwire.Message
4✔
3230
                if failure.linkErr.Warning {
4✔
3231
                        networkMsg = &lnwire.Warning{
×
3232
                                ChanID: failure.chanID,
×
3233
                                Data:   data,
×
3234
                        }
×
3235
                } else {
4✔
3236
                        networkMsg = &lnwire.Error{
4✔
3237
                                ChanID: failure.chanID,
4✔
3238
                                Data:   data,
4✔
3239
                        }
4✔
3240
                }
4✔
3241

3242
                err := p.SendMessage(true, networkMsg)
4✔
3243
                if err != nil {
4✔
3244
                        p.log.Errorf("unable to send msg to "+
×
3245
                                "remote peer: %v", err)
×
3246
                }
×
3247
        }
3248

3249
        // If the failure action is disconnect, then we'll execute that now. If
3250
        // we had to send an error above, it was a sync call, so we expect the
3251
        // message to be flushed on the wire by now.
3252
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
4✔
3253
                p.Disconnect(fmt.Errorf("link requested disconnect"))
×
3254
        }
×
3255
}
3256

3257
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
3258
// public key and the channel id.
3259
func (p *Brontide) fetchLinkFromKeyAndCid(
3260
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
23✔
3261

23✔
3262
        var chanLink htlcswitch.ChannelUpdateHandler
23✔
3263

23✔
3264
        // We don't need to check the error here, and can instead just loop
23✔
3265
        // over the slice and return nil.
23✔
3266
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
23✔
3267
        for _, link := range links {
45✔
3268
                if link.ChanID() == cid {
44✔
3269
                        chanLink = link
22✔
3270
                        break
22✔
3271
                }
3272
        }
3273

3274
        return chanLink
23✔
3275
}
3276

3277
// finalizeChanClosure performs the final clean up steps once the cooperative
3278
// closure transaction has been fully broadcast. The finalized closing state
3279
// machine should be passed in. Once the transaction has been sufficiently
3280
// confirmed, the channel will be marked as fully closed within the database,
3281
// and any clients will be notified of updates to the closing state.
3282
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
8✔
3283
        closeReq := chanCloser.CloseRequest()
8✔
3284

8✔
3285
        // First, we'll clear all indexes related to the channel in question.
8✔
3286
        chanPoint := chanCloser.Channel().ChannelPoint()
8✔
3287
        p.WipeChannel(&chanPoint)
8✔
3288

8✔
3289
        // Also clear the activeChanCloses map of this channel.
8✔
3290
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
8✔
3291
        delete(p.activeChanCloses, cid)
8✔
3292

8✔
3293
        // Next, we'll launch a goroutine which will request to be notified by
8✔
3294
        // the ChainNotifier once the closure transaction obtains a single
8✔
3295
        // confirmation.
8✔
3296
        notifier := p.cfg.ChainNotifier
8✔
3297

8✔
3298
        // If any error happens during waitForChanToClose, forward it to
8✔
3299
        // closeReq. If this channel closure is not locally initiated, closeReq
8✔
3300
        // will be nil, so just ignore the error.
8✔
3301
        errChan := make(chan error, 1)
8✔
3302
        if closeReq != nil {
14✔
3303
                errChan = closeReq.Err
6✔
3304
        }
6✔
3305

3306
        closingTx, err := chanCloser.ClosingTx()
8✔
3307
        if err != nil {
8✔
3308
                if closeReq != nil {
×
3309
                        p.log.Error(err)
×
3310
                        closeReq.Err <- err
×
3311
                }
×
3312
        }
3313

3314
        closingTxid := closingTx.TxHash()
8✔
3315

8✔
3316
        // If this is a locally requested shutdown, update the caller with a
8✔
3317
        // new event detailing the current pending state of this request.
8✔
3318
        if closeReq != nil {
14✔
3319
                closeReq.Updates <- &PendingUpdate{
6✔
3320
                        Txid: closingTxid[:],
6✔
3321
                }
6✔
3322
        }
6✔
3323

3324
        go WaitForChanToClose(chanCloser.NegotiationHeight(), notifier, errChan,
8✔
3325
                &chanPoint, &closingTxid, closingTx.TxOut[0].PkScript, func() {
16✔
3326
                        // Respond to the local subsystem which requested the
8✔
3327
                        // channel closure.
8✔
3328
                        if closeReq != nil {
14✔
3329
                                closeReq.Updates <- &ChannelCloseUpdate{
6✔
3330
                                        ClosingTxid: closingTxid[:],
6✔
3331
                                        Success:     true,
6✔
3332
                                }
6✔
3333
                        }
6✔
3334
                })
3335
}
3336

3337
// WaitForChanToClose uses the passed notifier to wait until the channel has
3338
// been detected as closed on chain and then concludes by executing the
3339
// following actions: the channel point will be sent over the settleChan, and
3340
// finally the callback will be executed. If any error is encountered within
3341
// the function, then it will be sent over the errChan.
3342
func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
3343
        errChan chan error, chanPoint *wire.OutPoint,
3344
        closingTxID *chainhash.Hash, closeScript []byte, cb func()) {
8✔
3345

8✔
3346
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
8✔
3347
                "with txid: %v", chanPoint, closingTxID)
8✔
3348

8✔
3349
        // TODO(roasbeef): add param for num needed confs
8✔
3350
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
8✔
3351
                closingTxID, closeScript, 1, bestHeight,
8✔
3352
        )
8✔
3353
        if err != nil {
8✔
3354
                if errChan != nil {
×
3355
                        errChan <- err
×
3356
                }
×
3357
                return
×
3358
        }
3359

3360
        // In the case that the ChainNotifier is shutting down, all subscriber
3361
        // notification channels will be closed, generating a nil receive.
3362
        height, ok := <-confNtfn.Confirmed
8✔
3363
        if !ok {
12✔
3364
                return
4✔
3365
        }
4✔
3366

3367
        // The channel has been closed, remove it from any active indexes, and
3368
        // the database state.
3369
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
8✔
3370
                "height %v", chanPoint, height.BlockHeight)
8✔
3371

8✔
3372
        // Finally, execute the closure call back to mark the confirmation of
8✔
3373
        // the transaction closing the contract.
8✔
3374
        cb()
8✔
3375
}
3376

3377
// WipeChannel removes the passed channel point from all indexes associated with
3378
// the peer and the switch.
3379
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
8✔
3380
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
8✔
3381

8✔
3382
        p.activeChannels.Delete(chanID)
8✔
3383

8✔
3384
        // Instruct the HtlcSwitch to close this link as the channel is no
8✔
3385
        // longer active.
8✔
3386
        p.cfg.Switch.RemoveLink(chanID)
8✔
3387
}
8✔
3388

3389
// handleInitMsg handles the incoming init message which contains global and
3390
// local feature vectors. If feature vectors are incompatible then disconnect.
3391
func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
6✔
3392
        // First, merge any features from the legacy global features field into
6✔
3393
        // those presented in the local features fields.
6✔
3394
        err := msg.Features.Merge(msg.GlobalFeatures)
6✔
3395
        if err != nil {
6✔
3396
                return fmt.Errorf("unable to merge legacy global features: %w",
×
3397
                        err)
×
3398
        }
×
3399

3400
        // Then, finalize the remote feature vector providing the flattened
3401
        // feature bit namespace.
3402
        p.remoteFeatures = lnwire.NewFeatureVector(
6✔
3403
                msg.Features, lnwire.Features,
6✔
3404
        )
6✔
3405

6✔
3406
        // Now that we have their features loaded, we'll ensure that they
6✔
3407
        // didn't set any required bits that we don't know of.
6✔
3408
        err = feature.ValidateRequired(p.remoteFeatures)
6✔
3409
        if err != nil {
6✔
3410
                return fmt.Errorf("invalid remote features: %w", err)
×
3411
        }
×
3412

3413
        // Ensure the remote party's feature vector contains all transitive
3414
        // dependencies. We know ours are correct since they are validated
3415
        // during the feature manager's instantiation.
3416
        err = feature.ValidateDeps(p.remoteFeatures)
6✔
3417
        if err != nil {
6✔
3418
                return fmt.Errorf("invalid remote features: %w", err)
×
3419
        }
×
3420

3421
        // Now that we know we understand their requirements, we'll check to
3422
        // see if they don't support anything that we deem to be mandatory.
3423
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
6✔
3424
                return fmt.Errorf("data loss protection required")
×
3425
        }
×
3426

3427
        return nil
6✔
3428
}
3429

3430
// LocalFeatures returns the set of global features that has been advertised by
3431
// the local node. This allows sub-systems that use this interface to gate their
3432
// behavior off the set of negotiated feature bits.
3433
//
3434
// NOTE: Part of the lnpeer.Peer interface.
3435
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
4✔
3436
        return p.cfg.Features
4✔
3437
}
4✔
3438

3439
// RemoteFeatures returns the set of global features that has been advertised by
3440
// the remote node. This allows sub-systems that use this interface to gate
3441
// their behavior off the set of negotiated feature bits.
3442
//
3443
// NOTE: Part of the lnpeer.Peer interface.
3444
func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector {
10✔
3445
        return p.remoteFeatures
10✔
3446
}
10✔
3447

3448
// hasNegotiatedScidAlias returns true if we've negotiated the
3449
// option-scid-alias feature bit with the peer.
3450
func (p *Brontide) hasNegotiatedScidAlias() bool {
6✔
3451
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
6✔
3452
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
6✔
3453
        return peerHas && localHas
6✔
3454
}
6✔
3455

3456
// sendInitMsg sends the Init message to the remote peer. This message contains
3457
// our currently supported local and global features.
3458
func (p *Brontide) sendInitMsg(legacyChan bool) error {
10✔
3459
        features := p.cfg.Features.Clone()
10✔
3460
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
10✔
3461

10✔
3462
        // If we have a legacy channel open with a peer, we downgrade static
10✔
3463
        // remote required to optional in case the peer does not understand the
10✔
3464
        // required feature bit. If we do not do this, the peer will reject our
10✔
3465
        // connection because it does not understand a required feature bit, and
10✔
3466
        // our channel will be unusable.
10✔
3467
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
11✔
3468
                p.log.Infof("Legacy channel open with peer, " +
1✔
3469
                        "downgrading static remote required feature bit to " +
1✔
3470
                        "optional")
1✔
3471

1✔
3472
                // Unset and set in both the local and global features to
1✔
3473
                // ensure both sets are consistent and merge able by old and
1✔
3474
                // new nodes.
1✔
3475
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3476
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3477

1✔
3478
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
3479
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
3480
        }
1✔
3481

3482
        msg := lnwire.NewInitMessage(
10✔
3483
                legacyFeatures.RawFeatureVector,
10✔
3484
                features.RawFeatureVector,
10✔
3485
        )
10✔
3486

10✔
3487
        return p.writeMessage(msg)
10✔
3488
}
3489

3490
// resendChanSyncMsg will attempt to find a channel sync message for the closed
3491
// channel and resend it to our peer.
3492
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
4✔
3493
        // If we already re-sent the mssage for this channel, we won't do it
4✔
3494
        // again.
4✔
3495
        if _, ok := p.resentChanSyncMsg[cid]; ok {
5✔
3496
                return nil
1✔
3497
        }
1✔
3498

3499
        // Check if we have any channel sync messages stored for this channel.
3500
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
4✔
3501
        if err != nil {
8✔
3502
                return fmt.Errorf("unable to fetch channel sync messages for "+
4✔
3503
                        "peer %v: %v", p, err)
4✔
3504
        }
4✔
3505

3506
        if c.LastChanSyncMsg == nil {
4✔
3507
                return fmt.Errorf("no chan sync message stored for channel %v",
×
3508
                        cid)
×
3509
        }
×
3510

3511
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
4✔
3512
                return fmt.Errorf("ignoring channel reestablish from "+
×
3513
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
3514
        }
×
3515

3516
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
4✔
3517
                "peer", cid)
4✔
3518

4✔
3519
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
4✔
3520
                return fmt.Errorf("failed resending channel sync "+
×
3521
                        "message to peer %v: %v", p, err)
×
3522
        }
×
3523

3524
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
4✔
3525
                cid)
4✔
3526

4✔
3527
        // Note down that we sent the message, so we won't resend it again for
4✔
3528
        // this connection.
4✔
3529
        p.resentChanSyncMsg[cid] = struct{}{}
4✔
3530

4✔
3531
        return nil
4✔
3532
}
3533

3534
// SendMessage sends a variadic number of high-priority messages to the remote
3535
// peer. The first argument denotes if the method should block until the
3536
// messages have been sent to the remote peer or an error is returned,
3537
// otherwise it returns immediately after queuing.
3538
//
3539
// NOTE: Part of the lnpeer.Peer interface.
3540
func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error {
5✔
3541
        return p.sendMessage(sync, true, msgs...)
5✔
3542
}
5✔
3543

3544
// SendMessageLazy sends a variadic number of low-priority messages to the
3545
// remote peer. The first argument denotes if the method should block until
3546
// the messages have been sent to the remote peer or an error is returned,
3547
// otherwise it returns immediately after queueing.
3548
//
3549
// NOTE: Part of the lnpeer.Peer interface.
3550
func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
5✔
3551
        return p.sendMessage(sync, false, msgs...)
5✔
3552
}
5✔
3553

3554
// sendMessage queues a variadic number of messages using the passed priority
3555
// to the remote peer. If sync is true, this method will block until the
3556
// messages have been sent to the remote peer or an error is returned, otherwise
3557
// it returns immediately after queueing.
3558
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
6✔
3559
        // Add all incoming messages to the outgoing queue. A list of error
6✔
3560
        // chans is populated for each message if the caller requested a sync
6✔
3561
        // send.
6✔
3562
        var errChans []chan error
6✔
3563
        if sync {
11✔
3564
                errChans = make([]chan error, 0, len(msgs))
5✔
3565
        }
5✔
3566
        for _, msg := range msgs {
12✔
3567
                // If a sync send was requested, create an error chan to listen
6✔
3568
                // for an ack from the writeHandler.
6✔
3569
                var errChan chan error
6✔
3570
                if sync {
11✔
3571
                        errChan = make(chan error, 1)
5✔
3572
                        errChans = append(errChans, errChan)
5✔
3573
                }
5✔
3574

3575
                if priority {
11✔
3576
                        p.queueMsg(msg, errChan)
5✔
3577
                } else {
10✔
3578
                        p.queueMsgLazy(msg, errChan)
5✔
3579
                }
5✔
3580
        }
3581

3582
        // Wait for all replies from the writeHandler. For async sends, this
3583
        // will be a NOP as the list of error chans is nil.
3584
        for _, errChan := range errChans {
11✔
3585
                select {
5✔
3586
                case err := <-errChan:
5✔
3587
                        return err
5✔
3588
                case <-p.quit:
×
3589
                        return lnpeer.ErrPeerExiting
×
3590
                case <-p.cfg.Quit:
×
3591
                        return lnpeer.ErrPeerExiting
×
3592
                }
3593
        }
3594

3595
        return nil
5✔
3596
}
3597

3598
// PubKey returns the pubkey of the peer in compressed serialized format.
3599
//
3600
// NOTE: Part of the lnpeer.Peer interface.
3601
func (p *Brontide) PubKey() [33]byte {
6✔
3602
        return p.cfg.PubKeyBytes
6✔
3603
}
6✔
3604

3605
// IdentityKey returns the public key of the remote peer.
3606
//
3607
// NOTE: Part of the lnpeer.Peer interface.
3608
func (p *Brontide) IdentityKey() *btcec.PublicKey {
17✔
3609
        return p.cfg.Addr.IdentityKey
17✔
3610
}
17✔
3611

3612
// Address returns the network address of the remote peer.
3613
//
3614
// NOTE: Part of the lnpeer.Peer interface.
3615
func (p *Brontide) Address() net.Addr {
4✔
3616
        return p.cfg.Addr.Address
4✔
3617
}
4✔
3618

3619
// AddNewChannel adds a new channel to the peer. The channel should fail to be
3620
// added if the cancel channel is closed.
3621
//
3622
// NOTE: Part of the lnpeer.Peer interface.
3623
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
3624
        cancel <-chan struct{}) error {
4✔
3625

4✔
3626
        errChan := make(chan error, 1)
4✔
3627
        newChanMsg := &newChannelMsg{
4✔
3628
                channel: newChan,
4✔
3629
                err:     errChan,
4✔
3630
        }
4✔
3631

4✔
3632
        select {
4✔
3633
        case p.newActiveChannel <- newChanMsg:
4✔
3634
        case <-cancel:
×
3635
                return errors.New("canceled adding new channel")
×
3636
        case <-p.quit:
×
3637
                return lnpeer.ErrPeerExiting
×
3638
        }
3639

3640
        // We pause here to wait for the peer to recognize the new channel
3641
        // before we close the channel barrier corresponding to the channel.
3642
        select {
4✔
3643
        case err := <-errChan:
4✔
3644
                return err
4✔
3645
        case <-p.quit:
×
3646
                return lnpeer.ErrPeerExiting
×
3647
        }
3648
}
3649

3650
// AddPendingChannel adds a pending open channel to the peer. The channel
3651
// should fail to be added if the cancel channel is closed.
3652
//
3653
// NOTE: Part of the lnpeer.Peer interface.
3654
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
3655
        cancel <-chan struct{}) error {
4✔
3656

4✔
3657
        errChan := make(chan error, 1)
4✔
3658
        newChanMsg := &newChannelMsg{
4✔
3659
                channelID: cid,
4✔
3660
                err:       errChan,
4✔
3661
        }
4✔
3662

4✔
3663
        select {
4✔
3664
        case p.newPendingChannel <- newChanMsg:
4✔
3665

3666
        case <-cancel:
×
3667
                return errors.New("canceled adding pending channel")
×
3668

3669
        case <-p.quit:
×
3670
                return lnpeer.ErrPeerExiting
×
3671
        }
3672

3673
        // We pause here to wait for the peer to recognize the new pending
3674
        // channel before we close the channel barrier corresponding to the
3675
        // channel.
3676
        select {
4✔
3677
        case err := <-errChan:
4✔
3678
                return err
4✔
3679

3680
        case <-cancel:
×
3681
                return errors.New("canceled adding pending channel")
×
3682

3683
        case <-p.quit:
×
3684
                return lnpeer.ErrPeerExiting
×
3685
        }
3686
}
3687

3688
// RemovePendingChannel removes a pending open channel from the peer.
3689
//
3690
// NOTE: Part of the lnpeer.Peer interface.
3691
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
4✔
3692
        errChan := make(chan error, 1)
4✔
3693
        newChanMsg := &newChannelMsg{
4✔
3694
                channelID: cid,
4✔
3695
                err:       errChan,
4✔
3696
        }
4✔
3697

4✔
3698
        select {
4✔
3699
        case p.removePendingChannel <- newChanMsg:
4✔
3700
        case <-p.quit:
×
3701
                return lnpeer.ErrPeerExiting
×
3702
        }
3703

3704
        // We pause here to wait for the peer to respond to the cancellation of
3705
        // the pending channel before we close the channel barrier
3706
        // corresponding to the channel.
3707
        select {
4✔
3708
        case err := <-errChan:
4✔
3709
                return err
4✔
3710

3711
        case <-p.quit:
×
3712
                return lnpeer.ErrPeerExiting
×
3713
        }
3714
}
3715

3716
// StartTime returns the time at which the connection was established if the
3717
// peer started successfully, and zero otherwise.
3718
func (p *Brontide) StartTime() time.Time {
4✔
3719
        return p.startTime
4✔
3720
}
4✔
3721

3722
// handleCloseMsg is called when a new cooperative channel closure related
3723
// message is received from the remote peer. We'll use this message to advance
3724
// the chan closer state machine.
3725
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
17✔
3726
        link := p.fetchLinkFromKeyAndCid(msg.cid)
17✔
3727

17✔
3728
        // We'll now fetch the matching closing state machine in order to continue,
17✔
3729
        // or finalize the channel closure process.
17✔
3730
        chanCloser, err := p.fetchActiveChanCloser(msg.cid)
17✔
3731
        if err != nil {
21✔
3732
                // If the channel is not known to us, we'll simply ignore this message.
4✔
3733
                if err == ErrChannelNotFound {
8✔
3734
                        return
4✔
3735
                }
4✔
3736

3737
                p.log.Errorf("Unable to respond to remote close msg: %v", err)
×
3738

×
3739
                errMsg := &lnwire.Error{
×
3740
                        ChanID: msg.cid,
×
3741
                        Data:   lnwire.ErrorData(err.Error()),
×
3742
                }
×
3743
                p.queueMsg(errMsg, nil)
×
3744
                return
×
3745
        }
3746

3747
        handleErr := func(err error) {
18✔
3748
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
3749
                p.log.Error(err)
1✔
3750

1✔
3751
                // As the negotiations failed, we'll reset the channel state machine to
1✔
3752
                // ensure we act to on-chain events as normal.
1✔
3753
                chanCloser.Channel().ResetState()
1✔
3754

1✔
3755
                if chanCloser.CloseRequest() != nil {
1✔
3756
                        chanCloser.CloseRequest().Err <- err
×
3757
                }
×
3758
                delete(p.activeChanCloses, msg.cid)
1✔
3759

1✔
3760
                p.Disconnect(err)
1✔
3761
        }
3762

3763
        // Next, we'll process the next message using the target state machine.
3764
        // We'll either continue negotiation, or halt.
3765
        switch typed := msg.msg.(type) {
17✔
3766
        case *lnwire.Shutdown:
9✔
3767
                // Disable incoming adds immediately.
9✔
3768
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
9✔
3769
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
3770
                                link.ChanID())
×
3771
                }
×
3772

3773
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
9✔
3774
                if err != nil {
9✔
3775
                        handleErr(err)
×
3776
                        return
×
3777
                }
×
3778

3779
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
16✔
3780
                        // If the link is nil it means we can immediately queue
7✔
3781
                        // the Shutdown message since we don't have to wait for
7✔
3782
                        // commitment transaction synchronization.
7✔
3783
                        if link == nil {
8✔
3784
                                p.queueMsg(&msg, nil)
1✔
3785
                                return
1✔
3786
                        }
1✔
3787

3788
                        // Immediately disallow any new HTLC's from being added
3789
                        // in the outgoing direction.
3790
                        if !link.DisableAdds(htlcswitch.Outgoing) {
6✔
3791
                                p.log.Warnf("Outgoing link adds already "+
×
3792
                                        "disabled: %v", link.ChanID())
×
3793
                        }
×
3794

3795
                        // When we have a Shutdown to send, we defer it till the
3796
                        // next time we send a CommitSig to remain spec
3797
                        // compliant.
3798
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
12✔
3799
                                p.queueMsg(&msg, nil)
6✔
3800
                        })
6✔
3801
                })
3802

3803
                beginNegotiation := func() {
18✔
3804
                        oClosingSigned, err := chanCloser.BeginNegotiation()
9✔
3805
                        if err != nil {
9✔
3806
                                handleErr(err)
×
3807
                                return
×
3808
                        }
×
3809

3810
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
18✔
3811
                                p.queueMsg(&msg, nil)
9✔
3812
                        })
9✔
3813
                }
3814

3815
                if link == nil {
10✔
3816
                        beginNegotiation()
1✔
3817
                } else {
9✔
3818
                        // Now we register a flush hook to advance the
8✔
3819
                        // ChanCloser and possibly send out a ClosingSigned
8✔
3820
                        // when the link finishes draining.
8✔
3821
                        link.OnFlushedOnce(func() {
16✔
3822
                                // Remove link in goroutine to prevent deadlock.
8✔
3823
                                go p.cfg.Switch.RemoveLink(msg.cid)
8✔
3824
                                beginNegotiation()
8✔
3825
                        })
8✔
3826
                }
3827

3828
        case *lnwire.ClosingSigned:
12✔
3829
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
12✔
3830
                if err != nil {
13✔
3831
                        handleErr(err)
1✔
3832
                        return
1✔
3833
                }
1✔
3834

3835
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
24✔
3836
                        p.queueMsg(&msg, nil)
12✔
3837
                })
12✔
3838

3839
        default:
×
3840
                panic("impossible closeMsg type")
×
3841
        }
3842

3843
        // If we haven't finished close negotiations, then we'll continue as we
3844
        // can't yet finalize the closure.
3845
        if _, err := chanCloser.ClosingTx(); err != nil {
28✔
3846
                return
12✔
3847
        }
12✔
3848

3849
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
3850
        // the channel closure by notifying relevant sub-systems and launching a
3851
        // goroutine to wait for close tx conf.
3852
        p.finalizeChanClosure(chanCloser)
8✔
3853
}
3854

3855
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
3856
// the channelManager goroutine, which will shut down the link and possibly
3857
// close the channel.
3858
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
4✔
3859
        select {
4✔
3860
        case p.localCloseChanReqs <- req:
4✔
3861
                p.log.Info("Local close channel request is going to be " +
4✔
3862
                        "delivered to the peer")
4✔
3863
        case <-p.quit:
×
3864
                p.log.Info("Unable to deliver local close channel request " +
×
3865
                        "to peer")
×
3866
        }
3867
}
3868

3869
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
3870
func (p *Brontide) NetAddress() *lnwire.NetAddress {
4✔
3871
        return p.cfg.Addr
4✔
3872
}
4✔
3873

3874
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
3875
func (p *Brontide) Inbound() bool {
4✔
3876
        return p.cfg.Inbound
4✔
3877
}
4✔
3878

3879
// ConnReq is a getter for the Brontide's connReq in cfg.
3880
func (p *Brontide) ConnReq() *connmgr.ConnReq {
4✔
3881
        return p.cfg.ConnReq
4✔
3882
}
4✔
3883

3884
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
3885
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
4✔
3886
        return p.cfg.ErrorBuffer
4✔
3887
}
4✔
3888

3889
// SetAddress sets the remote peer's address given an address.
3890
func (p *Brontide) SetAddress(address net.Addr) {
×
3891
        p.cfg.Addr.Address = address
×
3892
}
×
3893

3894
// ActiveSignal returns the peer's active signal.
3895
func (p *Brontide) ActiveSignal() chan struct{} {
4✔
3896
        return p.activeSignal
4✔
3897
}
4✔
3898

3899
// Conn returns a pointer to the peer's connection struct.
3900
func (p *Brontide) Conn() net.Conn {
4✔
3901
        return p.cfg.Conn
4✔
3902
}
4✔
3903

3904
// BytesReceived returns the number of bytes received from the peer.
3905
func (p *Brontide) BytesReceived() uint64 {
4✔
3906
        return atomic.LoadUint64(&p.bytesReceived)
4✔
3907
}
4✔
3908

3909
// BytesSent returns the number of bytes sent to the peer.
3910
func (p *Brontide) BytesSent() uint64 {
4✔
3911
        return atomic.LoadUint64(&p.bytesSent)
4✔
3912
}
4✔
3913

3914
// LastRemotePingPayload returns the last payload the remote party sent as part
3915
// of their ping.
3916
func (p *Brontide) LastRemotePingPayload() []byte {
4✔
3917
        pingPayload := p.lastPingPayload.Load()
4✔
3918
        if pingPayload == nil {
8✔
3919
                return []byte{}
4✔
3920
        }
4✔
3921

3922
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
3923
        if !ok {
×
3924
                return nil
×
3925
        }
×
3926

3927
        return pingBytes
×
3928
}
3929

3930
// attachChannelEventSubscription creates a channel event subscription and
3931
// attaches to client to Brontide if the reenableTimeout is no greater than 1
3932
// minute.
3933
func (p *Brontide) attachChannelEventSubscription() error {
6✔
3934
        // If the timeout is greater than 1 minute, it's unlikely that the link
6✔
3935
        // hasn't yet finished its reestablishment. Return a nil without
6✔
3936
        // creating the client to specify that we don't want to retry.
6✔
3937
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
10✔
3938
                return nil
4✔
3939
        }
4✔
3940

3941
        // When the reenable timeout is less than 1 minute, it's likely the
3942
        // channel link hasn't finished its reestablishment yet. In that case,
3943
        // we'll give it a second chance by subscribing to the channel update
3944
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
3945
        // enabling the channel again.
3946
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
6✔
3947
        if err != nil {
6✔
3948
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
3949
        }
×
3950

3951
        p.channelEventClient = sub
6✔
3952

6✔
3953
        return nil
6✔
3954
}
3955

3956
// updateNextRevocation updates the existing channel's next revocation if it's
3957
// nil.
3958
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
7✔
3959
        chanPoint := c.FundingOutpoint
7✔
3960
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
7✔
3961

7✔
3962
        // Read the current channel.
7✔
3963
        currentChan, loaded := p.activeChannels.Load(chanID)
7✔
3964

7✔
3965
        // currentChan should exist, but we perform a check anyway to avoid nil
7✔
3966
        // pointer dereference.
7✔
3967
        if !loaded {
8✔
3968
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
3969
                        chanID)
1✔
3970
        }
1✔
3971

3972
        // currentChan should not be nil, but we perform a check anyway to
3973
        // avoid nil pointer dereference.
3974
        if currentChan == nil {
7✔
3975
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
3976
                        chanID)
1✔
3977
        }
1✔
3978

3979
        // If we're being sent a new channel, and our existing channel doesn't
3980
        // have the next revocation, then we need to update the current
3981
        // existing channel.
3982
        if currentChan.RemoteNextRevocation() != nil {
5✔
3983
                return nil
×
3984
        }
×
3985

3986
        p.log.Infof("Processing retransmitted ChannelReady for "+
5✔
3987
                "ChannelPoint(%v)", chanPoint)
5✔
3988

5✔
3989
        nextRevoke := c.RemoteNextRevocation
5✔
3990

5✔
3991
        err := currentChan.InitNextRevocation(nextRevoke)
5✔
3992
        if err != nil {
5✔
3993
                return fmt.Errorf("unable to init next revocation: %w", err)
×
3994
        }
×
3995

3996
        return nil
5✔
3997
}
3998

3999
// addActiveChannel adds a new active channel to the `activeChannels` map. It
4000
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
4001
// it and assembles it with a channel link.
4002
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
4✔
4003
        chanPoint := c.FundingOutpoint
4✔
4004
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
4005

4✔
4006
        // If we've reached this point, there are two possible scenarios.  If
4✔
4007
        // the channel was in the active channels map as nil, then it was
4✔
4008
        // loaded from disk and we need to send reestablish. Else, it was not
4✔
4009
        // loaded from disk and we don't need to send reestablish as this is a
4✔
4010
        // fresh channel.
4✔
4011
        shouldReestablish := p.isLoadedFromDisk(chanID)
4✔
4012

4✔
4013
        chanOpts := c.ChanOpts
4✔
4014
        if shouldReestablish {
8✔
4015
                // If we have to do the reestablish dance for this channel,
4✔
4016
                // ensure that we don't try to call InitRemoteMusigNonces twice
4✔
4017
                // by calling SkipNonceInit.
4✔
4018
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
4✔
4019
        }
4✔
4020

4021
        // If not already active, we'll add this channel to the set of active
4022
        // channels, so we can look it up later easily according to its channel
4023
        // ID.
4024
        lnChan, err := lnwallet.NewLightningChannel(
4✔
4025
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
4✔
4026
        )
4✔
4027
        if err != nil {
4✔
4028
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
4029
        }
×
4030

4031
        // Store the channel in the activeChannels map.
4032
        p.activeChannels.Store(chanID, lnChan)
4✔
4033

4✔
4034
        p.log.Infof("New channel active ChannelPoint(%v) with peer", chanPoint)
4✔
4035

4✔
4036
        // Next, we'll assemble a ChannelLink along with the necessary items it
4✔
4037
        // needs to function.
4✔
4038
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
4✔
4039
        if err != nil {
4✔
4040
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
4041
                        err)
×
4042
        }
×
4043

4044
        // We'll query the channel DB for the new channel's initial forwarding
4045
        // policies to determine the policy we start out with.
4046
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
4✔
4047
        if err != nil {
4✔
4048
                return fmt.Errorf("unable to query for initial forwarding "+
×
4049
                        "policy: %v", err)
×
4050
        }
×
4051

4052
        // Create the link and add it to the switch.
4053
        err = p.addLink(
4✔
4054
                &chanPoint, lnChan, initialPolicy, chainEvents,
4✔
4055
                shouldReestablish, fn.None[lnwire.Shutdown](),
4✔
4056
        )
4✔
4057
        if err != nil {
4✔
4058
                return fmt.Errorf("can't register new channel link(%v) with "+
×
4059
                        "peer", chanPoint)
×
4060
        }
×
4061

4062
        return nil
4✔
4063
}
4064

4065
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
4066
// know this channel ID or not, we'll either add it to the `activeChannels` map
4067
// or init the next revocation for it.
4068
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
4✔
4069
        newChan := req.channel
4✔
4070
        chanPoint := newChan.FundingOutpoint
4✔
4071
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
4072

4✔
4073
        // Only update RemoteNextRevocation if the channel is in the
4✔
4074
        // activeChannels map and if we added the link to the switch. Only
4✔
4075
        // active channels will be added to the switch.
4✔
4076
        if p.isActiveChannel(chanID) {
8✔
4077
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
4✔
4078
                        chanPoint)
4✔
4079

4✔
4080
                // Handle it and close the err chan on the request.
4✔
4081
                close(req.err)
4✔
4082

4✔
4083
                // Update the next revocation point.
4✔
4084
                err := p.updateNextRevocation(newChan.OpenChannel)
4✔
4085
                if err != nil {
4✔
4086
                        p.log.Errorf(err.Error())
×
4087
                }
×
4088

4089
                return
4✔
4090
        }
4091

4092
        // This is a new channel, we now add it to the map.
4093
        if err := p.addActiveChannel(req.channel); err != nil {
4✔
4094
                // Log and send back the error to the request.
×
4095
                p.log.Errorf(err.Error())
×
4096
                req.err <- err
×
4097

×
4098
                return
×
4099
        }
×
4100

4101
        // Close the err chan if everything went fine.
4102
        close(req.err)
4✔
4103
}
4104

4105
// handleNewPendingChannel takes a `newChannelMsg` request and add it to
4106
// `activeChannels` map with nil value. This pending channel will be saved as
4107
// it may become active in the future. Once active, the funding manager will
4108
// send it again via `AddNewChannel`, and we'd handle the link creation there.
4109
func (p *Brontide) handleNewPendingChannel(req *newChannelMsg) {
8✔
4110
        defer close(req.err)
8✔
4111

8✔
4112
        chanID := req.channelID
8✔
4113

8✔
4114
        // If we already have this channel, something is wrong with the funding
8✔
4115
        // flow as it will only be marked as active after `ChannelReady` is
8✔
4116
        // handled. In this case, we will do nothing but log an error, just in
8✔
4117
        // case this is a legit channel.
8✔
4118
        if p.isActiveChannel(chanID) {
9✔
4119
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
4120
                        "pending channel request", chanID)
1✔
4121

1✔
4122
                return
1✔
4123
        }
1✔
4124

4125
        // The channel has already been added, we will do nothing and return.
4126
        if p.isPendingChannel(chanID) {
8✔
4127
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
4128
                        "pending channel request", chanID)
1✔
4129

1✔
4130
                return
1✔
4131
        }
1✔
4132

4133
        // This is a new channel, we now add it to the map `activeChannels`
4134
        // with nil value and mark it as a newly added channel in
4135
        // `addedChannels`.
4136
        p.activeChannels.Store(chanID, nil)
6✔
4137
        p.addedChannels.Store(chanID, struct{}{})
6✔
4138
}
4139

4140
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
4141
// from `activeChannels` map. The request will be ignored if the channel is
4142
// considered active by Brontide. Noop if the channel ID cannot be found.
4143
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
8✔
4144
        defer close(req.err)
8✔
4145

8✔
4146
        chanID := req.channelID
8✔
4147

8✔
4148
        // If we already have this channel, something is wrong with the funding
8✔
4149
        // flow as it will only be marked as active after `ChannelReady` is
8✔
4150
        // handled. In this case, we will log an error and exit.
8✔
4151
        if p.isActiveChannel(chanID) {
9✔
4152
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
4153
                        chanID)
1✔
4154
                return
1✔
4155
        }
1✔
4156

4157
        // The channel has not been added yet, we will log a warning as there
4158
        // is an unexpected call from funding manager.
4159
        if !p.isPendingChannel(chanID) {
12✔
4160
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
5✔
4161
        }
5✔
4162

4163
        // Remove the record of this pending channel.
4164
        p.activeChannels.Delete(chanID)
7✔
4165
        p.addedChannels.Delete(chanID)
7✔
4166
}
4167

4168
// sendLinkUpdateMsg sends a message that updates the channel to the
4169
// channel's message stream.
4170
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
4✔
4171
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
4✔
4172

4✔
4173
        chanStream, ok := p.activeMsgStreams[cid]
4✔
4174
        if !ok {
8✔
4175
                // If a stream hasn't yet been created, then we'll do so, add
4✔
4176
                // it to the map, and finally start it.
4✔
4177
                chanStream = newChanMsgStream(p, cid)
4✔
4178
                p.activeMsgStreams[cid] = chanStream
4✔
4179
                chanStream.Start()
4✔
4180

4✔
4181
                // Stop the stream when quit.
4✔
4182
                go func() {
8✔
4183
                        <-p.quit
4✔
4184
                        chanStream.Stop()
4✔
4185
                }()
4✔
4186
        }
4187

4188
        // With the stream obtained, add the message to the stream so we can
4189
        // continue processing message.
4190
        chanStream.AddMsg(msg)
4✔
4191
}
4192

4193
// scaleTimeout multiplies the argument duration by a constant factor depending
4194
// on variious heuristics. Currently this is only used to check whether our peer
4195
// appears to be connected over Tor and relaxes the timout deadline. However,
4196
// this is subject to change and should be treated as opaque.
4197
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
64✔
4198
        if p.isTorConnection {
68✔
4199
                return timeout * time.Duration(torTimeoutMultiplier)
4✔
4200
        }
4✔
4201

4202
        return timeout
60✔
4203
}
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