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

lightningnetwork / lnd / 16181619122

09 Jul 2025 10:33PM UTC coverage: 55.326% (-2.3%) from 57.611%
16181619122

Pull #10060

github

web-flow
Merge d15e8671f into 0e830da9d
Pull Request #10060: sweep: fix expected spending events being missed

9 of 26 new or added lines in 2 files covered. (34.62%)

23695 existing lines in 280 files now uncovered.

108518 of 196143 relevant lines covered (55.33%)

22354.81 hits per line

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

31.22
/peer/brontide.go
1
package peer
2

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

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

58
const (
59
        // pingInterval is the interval at which ping messages are sent.
60
        pingInterval = 1 * time.Minute
61

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

68
        // idleTimeout is the duration of inactivity before we time out a peer.
69
        idleTimeout = 5 * time.Minute
70

71
        // writeMessageTimeout is the timeout used when writing a message to the
72
        // peer.
73
        writeMessageTimeout = 5 * time.Second
74

75
        // readMessageTimeout is the timeout used when reading a message from a
76
        // peer.
77
        readMessageTimeout = 5 * time.Second
78

79
        // handshakeTimeout is the timeout used when waiting for the peer's init
80
        // message.
81
        handshakeTimeout = 15 * time.Second
82

83
        // ErrorBufferSize is the number of historic peer errors that we store.
84
        ErrorBufferSize = 10
85

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

92
        // torTimeoutMultiplier is the scaling factor we use on network timeouts
93
        // for Tor peers.
94
        torTimeoutMultiplier = 3
95

96
        // msgStreamSize is the size of the message streams.
97
        msgStreamSize = 50
98
)
99

100
var (
101
        // ErrChannelNotFound is an error returned when a channel is queried and
102
        // either the Brontide doesn't know of it, or the channel in question
103
        // is pending.
104
        ErrChannelNotFound = fmt.Errorf("channel not found")
105
)
106

107
// outgoingMsg packages an lnwire.Message to be sent out on the wire, along with
108
// a buffered channel which will be sent upon once the write is complete. This
109
// buffered channel acts as a semaphore to be used for synchronization purposes.
110
type outgoingMsg struct {
111
        priority bool
112
        msg      lnwire.Message
113
        errChan  chan error // MUST be buffered.
114
}
115

116
// newChannelMsg packages a channeldb.OpenChannel with a channel that allows
117
// the receiver of the request to report when the channel creation process has
118
// completed.
119
type newChannelMsg struct {
120
        // channel is used when the pending channel becomes active.
121
        channel *lnpeer.NewChannel
122

123
        // channelID is used when there's a new pending channel.
124
        channelID lnwire.ChannelID
125

126
        err chan error
127
}
128

129
type customMsg struct {
130
        peer [33]byte
131
        msg  lnwire.Custom
132
}
133

134
// closeMsg is a wrapper struct around any wire messages that deal with the
135
// cooperative channel closure negotiation process. This struct includes the
136
// raw channel ID targeted along with the original message.
137
type closeMsg struct {
138
        cid lnwire.ChannelID
139
        msg lnwire.Message
140
}
141

142
// PendingUpdate describes the pending state of a closing channel.
143
type PendingUpdate struct {
144
        // Txid is the txid of the closing transaction.
145
        Txid []byte
146

147
        // OutputIndex is the output index of our output in the closing
148
        // transaction.
149
        OutputIndex uint32
150

151
        // FeePerVByte is an optional field, that is set only when the new RBF
152
        // coop close flow is used. This indicates the new closing fee rate on
153
        // the closing transaction.
154
        FeePerVbyte fn.Option[chainfee.SatPerVByte]
155

156
        // IsLocalCloseTx is an optional field that indicates if this update is
157
        // sent for our local close txn, or the close txn of the remote party.
158
        // This is only set if the new RBF coop close flow is used.
159
        IsLocalCloseTx fn.Option[bool]
160
}
161

162
// ChannelCloseUpdate contains the outcome of the close channel operation.
163
type ChannelCloseUpdate struct {
164
        ClosingTxid []byte
165
        Success     bool
166

167
        // LocalCloseOutput is an optional, additional output on the closing
168
        // transaction that the local party should be paid to. This will only be
169
        // populated if the local balance isn't dust.
170
        LocalCloseOutput fn.Option[chancloser.CloseOutput]
171

172
        // RemoteCloseOutput is an optional, additional output on the closing
173
        // transaction that the remote party should be paid to. This will only
174
        // be populated if the remote balance isn't dust.
175
        RemoteCloseOutput fn.Option[chancloser.CloseOutput]
176

177
        // AuxOutputs is an optional set of additional outputs that might be
178
        // included in the closing transaction. These are used for custom
179
        // channel types.
180
        AuxOutputs fn.Option[chancloser.AuxCloseOutputs]
181
}
182

183
// TimestampedError is a timestamped error that is used to store the most recent
184
// errors we have experienced with our peers.
185
type TimestampedError struct {
186
        Error     error
187
        Timestamp time.Time
188
}
189

190
// Config defines configuration fields that are necessary for a peer object
191
// to function.
192
type Config struct {
193
        // Conn is the underlying network connection for this peer.
194
        Conn MessageConn
195

196
        // ConnReq stores information related to the persistent connection request
197
        // for this peer.
198
        ConnReq *connmgr.ConnReq
199

200
        // PubKeyBytes is the serialized, compressed public key of this peer.
201
        PubKeyBytes [33]byte
202

203
        // Addr is the network address of the peer.
204
        Addr *lnwire.NetAddress
205

206
        // Inbound indicates whether or not the peer is an inbound peer.
207
        Inbound bool
208

209
        // Features is the set of features that we advertise to the remote party.
210
        Features *lnwire.FeatureVector
211

212
        // LegacyFeatures is the set of features that we advertise to the remote
213
        // peer for backwards compatibility. Nodes that have not implemented
214
        // flat features will still be able to read our feature bits from the
215
        // legacy global field, but we will also advertise everything in the
216
        // default features field.
217
        LegacyFeatures *lnwire.FeatureVector
218

219
        // OutgoingCltvRejectDelta defines the number of blocks before expiry of
220
        // an htlc where we don't offer it anymore.
221
        OutgoingCltvRejectDelta uint32
222

223
        // ChanActiveTimeout specifies the duration the peer will wait to request
224
        // a channel reenable, beginning from the time the peer was started.
225
        ChanActiveTimeout time.Duration
226

227
        // ErrorBuffer stores a set of errors related to a peer. It contains error
228
        // messages that our peer has recently sent us over the wire and records of
229
        // unknown messages that were sent to us so that we can have a full track
230
        // record of the communication errors we have had with our peer. If we
231
        // choose to disconnect from a peer, it also stores the reason we had for
232
        // disconnecting.
233
        ErrorBuffer *queue.CircularBuffer
234

235
        // WritePool is the task pool that manages reuse of write buffers. Write
236
        // tasks are submitted to the pool in order to conserve the total number of
237
        // write buffers allocated at any one time, and decouple write buffer
238
        // allocation from the peer life cycle.
239
        WritePool *pool.Write
240

241
        // ReadPool is the task pool that manages reuse of read buffers.
242
        ReadPool *pool.Read
243

244
        // Switch is a pointer to the htlcswitch. It is used to setup, get, and
245
        // tear-down ChannelLinks.
246
        Switch messageSwitch
247

248
        // InterceptSwitch is a pointer to the InterceptableSwitch, a wrapper around
249
        // the regular Switch. We only export it here to pass ForwardPackets to the
250
        // ChannelLinkConfig.
251
        InterceptSwitch *htlcswitch.InterceptableSwitch
252

253
        // ChannelDB is used to fetch opened channels, and closed channels.
254
        ChannelDB *channeldb.ChannelStateDB
255

256
        // ChannelGraph is a pointer to the channel graph which is used to
257
        // query information about the set of known active channels.
258
        ChannelGraph *graphdb.ChannelGraph
259

260
        // ChainArb is used to subscribe to channel events, update contract signals,
261
        // and force close channels.
262
        ChainArb *contractcourt.ChainArbitrator
263

264
        // AuthGossiper is needed so that the Brontide impl can register with the
265
        // gossiper and process remote channel announcements.
266
        AuthGossiper *discovery.AuthenticatedGossiper
267

268
        // ChanStatusMgr is used to set or un-set the disabled bit in channel
269
        // updates.
270
        ChanStatusMgr *netann.ChanStatusManager
271

272
        // ChainIO is used to retrieve the best block.
273
        ChainIO lnwallet.BlockChainIO
274

275
        // FeeEstimator is used to compute our target ideal fee-per-kw when
276
        // initializing the coop close process.
277
        FeeEstimator chainfee.Estimator
278

279
        // Signer is used when creating *lnwallet.LightningChannel instances.
280
        Signer input.Signer
281

282
        // SigPool is used when creating *lnwallet.LightningChannel instances.
283
        SigPool *lnwallet.SigPool
284

285
        // Wallet is used to publish transactions and generates delivery
286
        // scripts during the coop close process.
287
        Wallet *lnwallet.LightningWallet
288

289
        // ChainNotifier is used to receive confirmations of a coop close
290
        // transaction.
291
        ChainNotifier chainntnfs.ChainNotifier
292

293
        // BestBlockView is used to efficiently query for up-to-date
294
        // blockchain state information
295
        BestBlockView chainntnfs.BestBlockView
296

297
        // RoutingPolicy is used to set the forwarding policy for links created by
298
        // the Brontide.
299
        RoutingPolicy models.ForwardingPolicy
300

301
        // Sphinx is used when setting up ChannelLinks so they can decode sphinx
302
        // onion blobs.
303
        Sphinx *hop.OnionProcessor
304

305
        // WitnessBeacon is used when setting up ChannelLinks so they can add any
306
        // preimages that they learn.
307
        WitnessBeacon contractcourt.WitnessBeacon
308

309
        // Invoices is passed to the ChannelLink on creation and handles all
310
        // invoice-related logic.
311
        Invoices *invoices.InvoiceRegistry
312

313
        // ChannelNotifier is used by the link to notify other sub-systems about
314
        // channel-related events and by the Brontide to subscribe to
315
        // ActiveLinkEvents.
316
        ChannelNotifier *channelnotifier.ChannelNotifier
317

318
        // HtlcNotifier is used when creating a ChannelLink.
319
        HtlcNotifier *htlcswitch.HtlcNotifier
320

321
        // TowerClient is used to backup revoked states.
322
        TowerClient wtclient.ClientManager
323

324
        // DisconnectPeer is used to disconnect this peer if the cooperative close
325
        // process fails.
326
        DisconnectPeer func(*btcec.PublicKey) error
327

328
        // GenNodeAnnouncement is used to send our node announcement to the remote
329
        // on startup.
330
        GenNodeAnnouncement func(...netann.NodeAnnModifier) (
331
                lnwire.NodeAnnouncement, error)
332

333
        // PrunePersistentPeerConnection is used to remove all internal state
334
        // related to this peer in the server.
335
        PrunePersistentPeerConnection func([33]byte)
336

337
        // FetchLastChanUpdate fetches our latest channel update for a target
338
        // channel.
339
        FetchLastChanUpdate func(lnwire.ShortChannelID) (*lnwire.ChannelUpdate1,
340
                error)
341

342
        // FundingManager is an implementation of the funding.Controller interface.
343
        FundingManager funding.Controller
344

345
        // Hodl is used when creating ChannelLinks to specify HodlFlags as
346
        // breakpoints in dev builds.
347
        Hodl *hodl.Config
348

349
        // UnsafeReplay is used when creating ChannelLinks to specify whether or
350
        // not to replay adds on its commitment tx.
351
        UnsafeReplay bool
352

353
        // MaxOutgoingCltvExpiry is used when creating ChannelLinks and is the max
354
        // number of blocks that funds could be locked up for when forwarding
355
        // payments.
356
        MaxOutgoingCltvExpiry uint32
357

358
        // MaxChannelFeeAllocation is used when creating ChannelLinks and is the
359
        // maximum percentage of total funds that can be allocated to a channel's
360
        // commitment fee. This only applies for the initiator of the channel.
361
        MaxChannelFeeAllocation float64
362

363
        // MaxAnchorsCommitFeeRate is the maximum fee rate we'll use as an
364
        // initiator for anchor channel commitments.
365
        MaxAnchorsCommitFeeRate chainfee.SatPerKWeight
366

367
        // CoopCloseTargetConfs is the confirmation target that will be used
368
        // to estimate the fee rate to use during a cooperative channel
369
        // closure initiated by the remote peer.
370
        CoopCloseTargetConfs uint32
371

372
        // ServerPubKey is the serialized, compressed public key of our lnd node.
373
        // It is used to determine which policy (channel edge) to pass to the
374
        // ChannelLink.
375
        ServerPubKey [33]byte
376

377
        // ChannelCommitInterval is the maximum time that is allowed to pass between
378
        // receiving a channel state update and signing the next commitment.
379
        // Setting this to a longer duration allows for more efficient channel
380
        // operations at the cost of latency.
381
        ChannelCommitInterval time.Duration
382

383
        // PendingCommitInterval is the maximum time that is allowed to pass
384
        // while waiting for the remote party to revoke a locally initiated
385
        // commitment state. Setting this to a longer duration if a slow
386
        // response is expected from the remote party or large number of
387
        // payments are attempted at the same time.
388
        PendingCommitInterval time.Duration
389

390
        // ChannelCommitBatchSize is the maximum number of channel state updates
391
        // that is accumulated before signing a new commitment.
392
        ChannelCommitBatchSize uint32
393

394
        // HandleCustomMessage is called whenever a custom message is received
395
        // from the peer.
396
        HandleCustomMessage func(peer [33]byte, msg *lnwire.Custom) error
397

398
        // GetAliases is passed to created links so the Switch and link can be
399
        // aware of the channel's aliases.
400
        GetAliases func(base lnwire.ShortChannelID) []lnwire.ShortChannelID
401

402
        // RequestAlias allows the Brontide struct to request an alias to send
403
        // to the peer.
404
        RequestAlias func() (lnwire.ShortChannelID, error)
405

406
        // AddLocalAlias persists an alias to an underlying alias store.
407
        AddLocalAlias func(alias, base lnwire.ShortChannelID,
408
                gossip, liveUpdate bool) error
409

410
        // AuxLeafStore is an optional store that can be used to store auxiliary
411
        // leaves for certain custom channel types.
412
        AuxLeafStore fn.Option[lnwallet.AuxLeafStore]
413

414
        // AuxSigner is an optional signer that can be used to sign auxiliary
415
        // leaves for certain custom channel types.
416
        AuxSigner fn.Option[lnwallet.AuxSigner]
417

418
        // AuxResolver is an optional interface that can be used to modify the
419
        // way contracts are resolved.
420
        AuxResolver fn.Option[lnwallet.AuxContractResolver]
421

422
        // AuxTrafficShaper is an optional auxiliary traffic shaper that can be
423
        // used to manage the bandwidth of peer links.
424
        AuxTrafficShaper fn.Option[htlcswitch.AuxTrafficShaper]
425

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

432
        // Adds the option to disable forwarding payments in blinded routes
433
        // by failing back any blinding-related payloads as if they were
434
        // invalid.
435
        DisallowRouteBlinding bool
436

437
        // DisallowQuiescence is a flag that indicates whether the Brontide
438
        // should have the quiescence feature disabled.
439
        DisallowQuiescence bool
440

441
        // MaxFeeExposure limits the number of outstanding fees in a channel.
442
        // This value will be passed to created links.
443
        MaxFeeExposure lnwire.MilliSatoshi
444

445
        // MsgRouter is an optional instance of the main message router that
446
        // the peer will use. If None, then a new default version will be used
447
        // in place.
448
        MsgRouter fn.Option[msgmux.Router]
449

450
        // AuxChanCloser is an optional instance of an abstraction that can be
451
        // used to modify the way the co-op close transaction is constructed.
452
        AuxChanCloser fn.Option[chancloser.AuxChanCloser]
453

454
        // ShouldFwdExpEndorsement is a closure that indicates whether
455
        // experimental endorsement signals should be set.
456
        ShouldFwdExpEndorsement func() bool
457

458
        // NoDisconnectOnPongFailure indicates whether the peer should *not* be
459
        // disconnected if a pong is not received in time or is mismatched.
460
        NoDisconnectOnPongFailure bool
461

462
        // Quit is the server's quit channel. If this is closed, we halt operation.
463
        Quit chan struct{}
464
}
465

466
// chanCloserFsm is a union-like type that can hold the two versions of co-op
467
// close we support: negotiation, and RBF based.
468
//
469
// TODO(roasbeef): rename to chancloser.Negotiator and chancloser.RBF?
470
type chanCloserFsm = fn.Either[*chancloser.ChanCloser, *chancloser.RbfChanCloser] //nolint:ll
471

472
// makeNegotiateCloser creates a new negotiate closer from a
473
// chancloser.ChanCloser.
474
func makeNegotiateCloser(chanCloser *chancloser.ChanCloser) chanCloserFsm {
9✔
475
        return fn.NewLeft[*chancloser.ChanCloser, *chancloser.RbfChanCloser](
9✔
476
                chanCloser,
9✔
477
        )
9✔
478
}
9✔
479

480
// makeRbfCloser creates a new RBF closer from a chancloser.RbfChanCloser.
UNCOV
481
func makeRbfCloser(rbfCloser *chancloser.RbfChanCloser) chanCloserFsm {
×
UNCOV
482
        return fn.NewRight[*chancloser.ChanCloser](
×
UNCOV
483
                rbfCloser,
×
UNCOV
484
        )
×
UNCOV
485
}
×
486

487
// Brontide is an active peer on the Lightning Network. This struct is responsible
488
// for managing any channel state related to this peer. To do so, it has
489
// several helper goroutines to handle events such as HTLC timeouts, new
490
// funding workflow, and detecting an uncooperative closure of any active
491
// channels.
492
type Brontide struct {
493
        // MUST be used atomically.
494
        started    int32
495
        disconnect int32
496

497
        // MUST be used atomically.
498
        bytesReceived uint64
499
        bytesSent     uint64
500

501
        // isTorConnection is a flag that indicates whether or not we believe
502
        // the remote peer is a tor connection. It is not always possible to
503
        // know this with certainty but we have heuristics we use that should
504
        // catch most cases.
505
        //
506
        // NOTE: We judge the tor-ness of a connection by if the remote peer has
507
        // ".onion" in the address OR if it's connected over localhost.
508
        // This will miss cases where our peer is connected to our clearnet
509
        // address over the tor network (via exit nodes). It will also misjudge
510
        // actual localhost connections as tor. We need to include this because
511
        // inbound connections to our tor address will appear to come from the
512
        // local socks5 proxy. This heuristic is only used to expand the timeout
513
        // window for peers so it is OK to misjudge this. If you use this field
514
        // for any other purpose you should seriously consider whether or not
515
        // this heuristic is good enough for your use case.
516
        isTorConnection bool
517

518
        pingManager *PingManager
519

520
        // lastPingPayload stores an unsafe pointer wrapped as an atomic
521
        // variable which points to the last payload the remote party sent us
522
        // as their ping.
523
        //
524
        // MUST be used atomically.
525
        lastPingPayload atomic.Value
526

527
        cfg Config
528

529
        // activeSignal when closed signals that the peer is now active and
530
        // ready to process messages.
531
        activeSignal chan struct{}
532

533
        // startTime is the time this peer connection was successfully established.
534
        // It will be zero for peers that did not successfully call Start().
535
        startTime time.Time
536

537
        // sendQueue is the channel which is used to queue outgoing messages to be
538
        // written onto the wire. Note that this channel is unbuffered.
539
        sendQueue chan outgoingMsg
540

541
        // outgoingQueue is a buffered channel which allows second/third party
542
        // objects to queue messages to be sent out on the wire.
543
        outgoingQueue chan outgoingMsg
544

545
        // activeChannels is a map which stores the state machines of all
546
        // active channels. Channels are indexed into the map by the txid of
547
        // the funding transaction which opened the channel.
548
        //
549
        // NOTE: On startup, pending channels are stored as nil in this map.
550
        // Confirmed channels have channel data populated in the map. This means
551
        // that accesses to this map should nil-check the LightningChannel to
552
        // see if this is a pending channel or not. The tradeoff here is either
553
        // having two maps everywhere (one for pending, one for confirmed chans)
554
        // or having an extra nil-check per access.
555
        activeChannels *lnutils.SyncMap[
556
                lnwire.ChannelID, *lnwallet.LightningChannel]
557

558
        // addedChannels tracks any new channels opened during this peer's
559
        // lifecycle. We use this to filter out these new channels when the time
560
        // comes to request a reenable for active channels, since they will have
561
        // waited a shorter duration.
562
        addedChannels *lnutils.SyncMap[lnwire.ChannelID, struct{}]
563

564
        // newActiveChannel is used by the fundingManager to send fully opened
565
        // channels to the source peer which handled the funding workflow.
566
        newActiveChannel chan *newChannelMsg
567

568
        // newPendingChannel is used by the fundingManager to send pending open
569
        // channels to the source peer which handled the funding workflow.
570
        newPendingChannel chan *newChannelMsg
571

572
        // removePendingChannel is used by the fundingManager to cancel pending
573
        // open channels to the source peer when the funding flow is failed.
574
        removePendingChannel chan *newChannelMsg
575

576
        // activeMsgStreams is a map from channel id to the channel streams that
577
        // proxy messages to individual, active links.
578
        activeMsgStreams map[lnwire.ChannelID]*msgStream
579

580
        // activeChanCloses is a map that keeps track of all the active
581
        // cooperative channel closures. Any channel closing messages are directed
582
        // to one of these active state machines. Once the channel has been closed,
583
        // the state machine will be deleted from the map.
584
        activeChanCloses *lnutils.SyncMap[lnwire.ChannelID, chanCloserFsm]
585

586
        // localCloseChanReqs is a channel in which any local requests to close
587
        // a particular channel are sent over.
588
        localCloseChanReqs chan *htlcswitch.ChanClose
589

590
        // linkFailures receives all reported channel failures from the switch,
591
        // and instructs the channelManager to clean remaining channel state.
592
        linkFailures chan linkFailureReport
593

594
        // chanCloseMsgs is a channel that any message related to channel
595
        // closures are sent over. This includes lnwire.Shutdown message as
596
        // well as lnwire.ClosingSigned messages.
597
        chanCloseMsgs chan *closeMsg
598

599
        // remoteFeatures is the feature vector received from the peer during
600
        // the connection handshake.
601
        remoteFeatures *lnwire.FeatureVector
602

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

609
        // channelEventClient is the channel event subscription client that's
610
        // used to assist retry enabling the channels. This client is only
611
        // created when the reenableTimeout is no greater than 1 minute. Once
612
        // created, it is canceled once the reenabling has been finished.
613
        //
614
        // NOTE: we choose to create the client conditionally to avoid
615
        // potentially holding lots of un-consumed events.
616
        channelEventClient *subscribe.Client
617

618
        // msgRouter is an instance of the msgmux.Router which is used to send
619
        // off new wire messages for handing.
620
        msgRouter fn.Option[msgmux.Router]
621

622
        // globalMsgRouter is a flag that indicates whether we have a global
623
        // msg router. If so, then we don't worry about stopping the msg router
624
        // when a peer disconnects.
625
        globalMsgRouter bool
626

627
        startReady chan struct{}
628

629
        // cg is a helper that encapsulates a wait group and quit channel and
630
        // allows contexts that either block or cancel on those depending on
631
        // the use case.
632
        cg *fn.ContextGuard
633

634
        // log is a peer-specific logging instance.
635
        log btclog.Logger
636
}
637

638
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer
639
// interface.
640
var _ lnpeer.Peer = (*Brontide)(nil)
641

642
// NewBrontide creates a new Brontide from a peer.Config struct.
643
func NewBrontide(cfg Config) *Brontide {
25✔
644
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
25✔
645

25✔
646
        // We have a global message router if one was passed in via the config.
25✔
647
        // In this case, we don't need to attempt to tear it down when the peer
25✔
648
        // is stopped.
25✔
649
        globalMsgRouter := cfg.MsgRouter.IsSome()
25✔
650

25✔
651
        // We'll either use the msg router instance passed in, or create a new
25✔
652
        // blank instance.
25✔
653
        msgRouter := cfg.MsgRouter.Alt(fn.Some[msgmux.Router](
25✔
654
                msgmux.NewMultiMsgRouter(),
25✔
655
        ))
25✔
656

25✔
657
        p := &Brontide{
25✔
658
                cfg:           cfg,
25✔
659
                activeSignal:  make(chan struct{}),
25✔
660
                sendQueue:     make(chan outgoingMsg),
25✔
661
                outgoingQueue: make(chan outgoingMsg),
25✔
662
                addedChannels: &lnutils.SyncMap[lnwire.ChannelID, struct{}]{},
25✔
663
                activeChannels: &lnutils.SyncMap[
25✔
664
                        lnwire.ChannelID, *lnwallet.LightningChannel,
25✔
665
                ]{},
25✔
666
                newActiveChannel:     make(chan *newChannelMsg, 1),
25✔
667
                newPendingChannel:    make(chan *newChannelMsg, 1),
25✔
668
                removePendingChannel: make(chan *newChannelMsg),
25✔
669

25✔
670
                activeMsgStreams: make(map[lnwire.ChannelID]*msgStream),
25✔
671
                activeChanCloses: &lnutils.SyncMap[
25✔
672
                        lnwire.ChannelID, chanCloserFsm,
25✔
673
                ]{},
25✔
674
                localCloseChanReqs: make(chan *htlcswitch.ChanClose),
25✔
675
                linkFailures:       make(chan linkFailureReport),
25✔
676
                chanCloseMsgs:      make(chan *closeMsg),
25✔
677
                resentChanSyncMsg:  make(map[lnwire.ChannelID]struct{}),
25✔
678
                startReady:         make(chan struct{}),
25✔
679
                log:                peerLog.WithPrefix(logPrefix),
25✔
680
                msgRouter:          msgRouter,
25✔
681
                globalMsgRouter:    globalMsgRouter,
25✔
682
                cg:                 fn.NewContextGuard(),
25✔
683
        }
25✔
684

25✔
685
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
25✔
UNCOV
686
                remoteAddr := cfg.Conn.RemoteAddr().String()
×
UNCOV
687
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
×
UNCOV
688
                        strings.Contains(remoteAddr, "127.0.0.1")
×
UNCOV
689
        }
×
690

691
        var (
25✔
692
                lastBlockHeader           *wire.BlockHeader
25✔
693
                lastSerializedBlockHeader [wire.MaxBlockHeaderPayload]byte
25✔
694
        )
25✔
695
        newPingPayload := func() []byte {
25✔
696
                // We query the BestBlockHeader from our BestBlockView each time
×
697
                // this is called, and update our serialized block header if
×
698
                // they differ.  Over time, we'll use this to disseminate the
×
699
                // latest block header between all our peers, which can later be
×
700
                // used to cross-check our own view of the network to mitigate
×
701
                // various types of eclipse attacks.
×
702
                header, err := p.cfg.BestBlockView.BestBlockHeader()
×
703
                if err != nil && header == lastBlockHeader {
×
704
                        return lastSerializedBlockHeader[:]
×
705
                }
×
706

707
                buf := bytes.NewBuffer(lastSerializedBlockHeader[0:0])
×
708
                err = header.Serialize(buf)
×
709
                if err == nil {
×
710
                        lastBlockHeader = header
×
711
                } else {
×
712
                        p.log.Warn("unable to serialize current block" +
×
713
                                "header for ping payload generation." +
×
714
                                "This should be impossible and means" +
×
715
                                "there is an implementation bug.")
×
716
                }
×
717

718
                return lastSerializedBlockHeader[:]
×
719
        }
720

721
        // TODO(roasbeef): make dynamic in order to create fake cover traffic.
722
        //
723
        // NOTE(proofofkeags): this was changed to be dynamic to allow better
724
        // pong identification, however, more thought is needed to make this
725
        // actually usable as a traffic decoy.
726
        randPongSize := func() uint16 {
25✔
727
                return uint16(
×
728
                        // We don't need cryptographic randomness here.
×
729
                        /* #nosec */
×
730
                        rand.Intn(pongSizeCeiling) + 1,
×
731
                )
×
732
        }
×
733

734
        p.pingManager = NewPingManager(&PingManagerConfig{
25✔
735
                NewPingPayload:   newPingPayload,
25✔
736
                NewPongSize:      randPongSize,
25✔
737
                IntervalDuration: p.scaleTimeout(pingInterval),
25✔
738
                TimeoutDuration:  p.scaleTimeout(pingTimeout),
25✔
739
                SendPing: func(ping *lnwire.Ping) {
25✔
740
                        p.queueMsg(ping, nil)
×
741
                },
×
742
                OnPongFailure: func(reason error,
743
                        timeWaitedForPong time.Duration,
744
                        lastKnownRTT time.Duration) {
×
745

×
746
                        logMsg := fmt.Sprintf("pong response "+
×
747
                                "failure for %s: %v. Time waited for this "+
×
748
                                "pong: %v. Last successful RTT: %v.",
×
749
                                p, reason, timeWaitedForPong, lastKnownRTT)
×
750

×
751
                        // If NoDisconnectOnPongFailure is true, we don't
×
752
                        // disconnect. Otherwise (if it's false, the default),
×
753
                        // we disconnect.
×
754
                        if p.cfg.NoDisconnectOnPongFailure {
×
755
                                p.log.Warnf("%s -- not disconnecting "+
×
756
                                        "due to config", logMsg)
×
757
                                return
×
758
                        }
×
759

760
                        p.log.Warnf("%s -- disconnecting", logMsg)
×
761

×
762
                        go p.Disconnect(fmt.Errorf("pong failure: %w", reason))
×
763
                },
764
        })
765

766
        return p
25✔
767
}
768

769
// Start starts all helper goroutines the peer needs for normal operations.  In
770
// the case this peer has already been started, then this function is a noop.
771
func (p *Brontide) Start() error {
3✔
772
        if atomic.AddInt32(&p.started, 1) != 1 {
3✔
773
                return nil
×
774
        }
×
775

776
        // Once we've finished starting up the peer, we'll signal to other
777
        // goroutines that the they can move forward to tear down the peer, or
778
        // carry out other relevant changes.
779
        defer close(p.startReady)
3✔
780

3✔
781
        p.log.Tracef("starting with conn[%v->%v]",
3✔
782
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
3✔
783

3✔
784
        // Fetch and then load all the active channels we have with this remote
3✔
785
        // peer from the database.
3✔
786
        activeChans, err := p.cfg.ChannelDB.FetchOpenChannels(
3✔
787
                p.cfg.Addr.IdentityKey,
3✔
788
        )
3✔
789
        if err != nil {
3✔
790
                p.log.Errorf("Unable to fetch active chans "+
×
791
                        "for peer: %v", err)
×
792
                return err
×
793
        }
×
794

795
        if len(activeChans) == 0 {
4✔
796
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
1✔
797
        }
1✔
798

799
        // Quickly check if we have any existing legacy channels with this
800
        // peer.
801
        haveLegacyChan := false
3✔
802
        for _, c := range activeChans {
5✔
803
                if c.ChanType.IsTweakless() {
4✔
804
                        continue
2✔
805
                }
806

UNCOV
807
                haveLegacyChan = true
×
UNCOV
808
                break
×
809
        }
810

811
        // Exchange local and global features, the init message should be very
812
        // first between two nodes.
813
        if err := p.sendInitMsg(haveLegacyChan); err != nil {
3✔
UNCOV
814
                return fmt.Errorf("unable to send init msg: %w", err)
×
UNCOV
815
        }
×
816

817
        // Before we launch any of the helper goroutines off the peer struct,
818
        // we'll first ensure proper adherence to the p2p protocol. The init
819
        // message MUST be sent before any other message.
820
        readErr := make(chan error, 1)
3✔
821
        msgChan := make(chan lnwire.Message, 1)
3✔
822
        p.cg.WgAdd(1)
3✔
823
        go func() {
6✔
824
                defer p.cg.WgDone()
3✔
825

3✔
826
                msg, err := p.readNextMessage()
3✔
827
                if err != nil {
3✔
UNCOV
828
                        readErr <- err
×
UNCOV
829
                        msgChan <- nil
×
UNCOV
830
                        return
×
UNCOV
831
                }
×
832
                readErr <- nil
3✔
833
                msgChan <- msg
3✔
834
        }()
835

836
        select {
3✔
837
        // In order to avoid blocking indefinitely, we'll give the other peer
838
        // an upper timeout to respond before we bail out early.
839
        case <-time.After(handshakeTimeout):
×
840
                return fmt.Errorf("peer did not complete handshake within %v",
×
841
                        handshakeTimeout)
×
842
        case err := <-readErr:
3✔
843
                if err != nil {
3✔
UNCOV
844
                        return fmt.Errorf("unable to read init msg: %w", err)
×
UNCOV
845
                }
×
846
        }
847

848
        // Once the init message arrives, we can parse it so we can figure out
849
        // the negotiation of features for this session.
850
        msg := <-msgChan
3✔
851
        if msg, ok := msg.(*lnwire.Init); ok {
6✔
852
                if err := p.handleInitMsg(msg); err != nil {
3✔
853
                        p.storeError(err)
×
854
                        return err
×
855
                }
×
856
        } else {
×
857
                return errors.New("very first message between nodes " +
×
858
                        "must be init message")
×
859
        }
×
860

861
        // Next, load all the active channels we have with this peer,
862
        // registering them with the switch and launching the necessary
863
        // goroutines required to operate them.
864
        p.log.Debugf("Loaded %v active channels from database",
3✔
865
                len(activeChans))
3✔
866

3✔
867
        // Conditionally subscribe to channel events before loading channels so
3✔
868
        // we won't miss events. This subscription is used to listen to active
3✔
869
        // channel event when reenabling channels. Once the reenabling process
3✔
870
        // is finished, this subscription will be canceled.
3✔
871
        //
3✔
872
        // NOTE: ChannelNotifier must be started before subscribing events
3✔
873
        // otherwise we'd panic here.
3✔
874
        if err := p.attachChannelEventSubscription(); err != nil {
3✔
875
                return err
×
876
        }
×
877

878
        // Register the message router now as we may need to register some
879
        // endpoints while loading the channels below.
880
        p.msgRouter.WhenSome(func(router msgmux.Router) {
6✔
881
                router.Start(context.Background())
3✔
882
        })
3✔
883

884
        msgs, err := p.loadActiveChannels(activeChans)
3✔
885
        if err != nil {
3✔
886
                return fmt.Errorf("unable to load channels: %w", err)
×
887
        }
×
888

889
        p.startTime = time.Now()
3✔
890

3✔
891
        // Before launching the writeHandler goroutine, we send any channel
3✔
892
        // sync messages that must be resent for borked channels. We do this to
3✔
893
        // avoid data races with WriteMessage & Flush calls.
3✔
894
        if len(msgs) > 0 {
5✔
895
                p.log.Infof("Sending %d channel sync messages to peer after "+
2✔
896
                        "loading active channels", len(msgs))
2✔
897

2✔
898
                // Send the messages directly via writeMessage and bypass the
2✔
899
                // writeHandler goroutine.
2✔
900
                for _, msg := range msgs {
4✔
901
                        if err := p.writeMessage(msg); err != nil {
2✔
902
                                return fmt.Errorf("unable to send "+
×
903
                                        "reestablish msg: %v", err)
×
904
                        }
×
905
                }
906
        }
907

908
        err = p.pingManager.Start()
3✔
909
        if err != nil {
3✔
910
                return fmt.Errorf("could not start ping manager %w", err)
×
911
        }
×
912

913
        p.cg.WgAdd(4)
3✔
914
        go p.queueHandler()
3✔
915
        go p.writeHandler()
3✔
916
        go p.channelManager()
3✔
917
        go p.readHandler()
3✔
918

3✔
919
        // Signal to any external processes that the peer is now active.
3✔
920
        close(p.activeSignal)
3✔
921

3✔
922
        // Node announcements don't propagate very well throughout the network
3✔
923
        // as there isn't a way to efficiently query for them through their
3✔
924
        // timestamp, mostly affecting nodes that were offline during the time
3✔
925
        // of broadcast. We'll resend our node announcement to the remote peer
3✔
926
        // as a best-effort delivery such that it can also propagate to their
3✔
927
        // peers. To ensure they can successfully process it in most cases,
3✔
928
        // we'll only resend it as long as we have at least one confirmed
3✔
929
        // advertised channel with the remote peer.
3✔
930
        //
3✔
931
        // TODO(wilmer): Remove this once we're able to query for node
3✔
932
        // announcements through their timestamps.
3✔
933
        p.cg.WgAdd(2)
3✔
934
        go p.maybeSendNodeAnn(activeChans)
3✔
935
        go p.maybeSendChannelUpdates()
3✔
936

3✔
937
        return nil
3✔
938
}
939

940
// initGossipSync initializes either a gossip syncer or an initial routing
941
// dump, depending on the negotiated synchronization method.
942
func (p *Brontide) initGossipSync() {
3✔
943
        // If the remote peer knows of the new gossip queries feature, then
3✔
944
        // we'll create a new gossipSyncer in the AuthenticatedGossiper for it.
3✔
945
        if p.remoteFeatures.HasFeature(lnwire.GossipQueriesOptional) {
6✔
946
                p.log.Info("Negotiated chan series queries")
3✔
947

3✔
948
                if p.cfg.AuthGossiper == nil {
6✔
949
                        // This should only ever be hit in the unit tests.
3✔
950
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
3✔
951
                                "gossip sync.")
3✔
952
                        return
3✔
953
                }
3✔
954

955
                // Register the peer's gossip syncer with the gossiper.
956
                // This blocks synchronously to ensure the gossip syncer is
957
                // registered with the gossiper before attempting to read
958
                // messages from the remote peer.
959
                //
960
                // TODO(wilmer): Only sync updates from non-channel peers. This
961
                // requires an improved version of the current network
962
                // bootstrapper to ensure we can find and connect to non-channel
963
                // peers.
UNCOV
964
                p.cfg.AuthGossiper.InitSyncState(p)
×
965
        }
966
}
967

968
// taprootShutdownAllowed returns true if both parties have negotiated the
969
// shutdown-any-segwit feature.
970
func (p *Brontide) taprootShutdownAllowed() bool {
6✔
971
        return p.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
6✔
972
                p.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
6✔
973
}
6✔
974

975
// rbfCoopCloseAllowed returns true if both parties have negotiated the new RBF
976
// coop close feature.
977
func (p *Brontide) rbfCoopCloseAllowed() bool {
7✔
978
        bothHaveBit := func(bit lnwire.FeatureBit) bool {
21✔
979
                return p.RemoteFeatures().HasFeature(bit) &&
14✔
980
                        p.LocalFeatures().HasFeature(bit)
14✔
981
        }
14✔
982

983
        return bothHaveBit(lnwire.RbfCoopCloseOptional) ||
7✔
984
                bothHaveBit(lnwire.RbfCoopCloseOptionalStaging)
7✔
985
}
986

987
// QuitSignal is a method that should return a channel which will be sent upon
988
// or closed once the backing peer exits. This allows callers using the
989
// interface to cancel any processing in the event the backing implementation
990
// exits.
991
//
992
// NOTE: Part of the lnpeer.Peer interface.
UNCOV
993
func (p *Brontide) QuitSignal() <-chan struct{} {
×
UNCOV
994
        return p.cg.Done()
×
UNCOV
995
}
×
996

997
// addrWithInternalKey takes a delivery script, then attempts to supplement it
998
// with information related to the internal key for the addr, but only if it's
999
// a taproot addr.
1000
func (p *Brontide) addrWithInternalKey(
1001
        deliveryScript []byte) (*chancloser.DeliveryAddrWithKey, error) {
9✔
1002

9✔
1003
        // Currently, custom channels cannot be created with external upfront
9✔
1004
        // shutdown addresses, so this shouldn't be an issue. We only require
9✔
1005
        // the internal key for taproot addresses to be able to provide a non
9✔
1006
        // inclusion proof of any scripts.
9✔
1007
        internalKeyDesc, err := lnwallet.InternalKeyForAddr(
9✔
1008
                p.cfg.Wallet, &p.cfg.Wallet.Cfg.NetParams, deliveryScript,
9✔
1009
        )
9✔
1010
        if err != nil {
9✔
1011
                return nil, fmt.Errorf("unable to fetch internal key: %w", err)
×
1012
        }
×
1013

1014
        return &chancloser.DeliveryAddrWithKey{
9✔
1015
                DeliveryAddress: deliveryScript,
9✔
1016
                InternalKey: fn.MapOption(
9✔
1017
                        func(desc keychain.KeyDescriptor) btcec.PublicKey {
9✔
UNCOV
1018
                                return *desc.PubKey
×
UNCOV
1019
                        },
×
1020
                )(internalKeyDesc),
1021
        }, nil
1022
}
1023

1024
// loadActiveChannels creates indexes within the peer for tracking all active
1025
// channels returned by the database. It returns a slice of channel reestablish
1026
// messages that should be sent to the peer immediately, in case we have borked
1027
// channels that haven't been closed yet.
1028
func (p *Brontide) loadActiveChannels(chans []*channeldb.OpenChannel) (
1029
        []lnwire.Message, error) {
3✔
1030

3✔
1031
        // Return a slice of messages to send to the peers in case the channel
3✔
1032
        // cannot be loaded normally.
3✔
1033
        var msgs []lnwire.Message
3✔
1034

3✔
1035
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
3✔
1036

3✔
1037
        for _, dbChan := range chans {
5✔
1038
                hasScidFeature := dbChan.ChanType.HasScidAliasFeature()
2✔
1039
                if scidAliasNegotiated && !hasScidFeature {
2✔
UNCOV
1040
                        // We'll request and store an alias, making sure that a
×
UNCOV
1041
                        // gossiper mapping is not created for the alias to the
×
UNCOV
1042
                        // real SCID. This is done because the peer and funding
×
UNCOV
1043
                        // manager are not aware of each other's states and if
×
UNCOV
1044
                        // we did not do this, we would accept alias channel
×
UNCOV
1045
                        // updates after 6 confirmations, which would be buggy.
×
UNCOV
1046
                        // We'll queue a channel_ready message with the new
×
UNCOV
1047
                        // alias. This should technically be done *after* the
×
UNCOV
1048
                        // reestablish, but this behavior is pre-existing since
×
UNCOV
1049
                        // the funding manager may already queue a
×
UNCOV
1050
                        // channel_ready before the channel_reestablish.
×
UNCOV
1051
                        if !dbChan.IsPending {
×
UNCOV
1052
                                aliasScid, err := p.cfg.RequestAlias()
×
UNCOV
1053
                                if err != nil {
×
1054
                                        return nil, err
×
1055
                                }
×
1056

UNCOV
1057
                                err = p.cfg.AddLocalAlias(
×
UNCOV
1058
                                        aliasScid, dbChan.ShortChanID(), false,
×
UNCOV
1059
                                        false,
×
UNCOV
1060
                                )
×
UNCOV
1061
                                if err != nil {
×
1062
                                        return nil, err
×
1063
                                }
×
1064

UNCOV
1065
                                chanID := lnwire.NewChanIDFromOutPoint(
×
UNCOV
1066
                                        dbChan.FundingOutpoint,
×
UNCOV
1067
                                )
×
UNCOV
1068

×
UNCOV
1069
                                // Fetch the second commitment point to send in
×
UNCOV
1070
                                // the channel_ready message.
×
UNCOV
1071
                                second, err := dbChan.SecondCommitmentPoint()
×
UNCOV
1072
                                if err != nil {
×
1073
                                        return nil, err
×
1074
                                }
×
1075

UNCOV
1076
                                channelReadyMsg := lnwire.NewChannelReady(
×
UNCOV
1077
                                        chanID, second,
×
UNCOV
1078
                                )
×
UNCOV
1079
                                channelReadyMsg.AliasScid = &aliasScid
×
UNCOV
1080

×
UNCOV
1081
                                msgs = append(msgs, channelReadyMsg)
×
1082
                        }
1083

1084
                        // If we've negotiated the option-scid-alias feature
1085
                        // and this channel does not have ScidAliasFeature set
1086
                        // to true due to an upgrade where the feature bit was
1087
                        // turned on, we'll update the channel's database
1088
                        // state.
UNCOV
1089
                        err := dbChan.MarkScidAliasNegotiated()
×
UNCOV
1090
                        if err != nil {
×
1091
                                return nil, err
×
1092
                        }
×
1093
                }
1094

1095
                var chanOpts []lnwallet.ChannelOpt
2✔
1096
                p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
2✔
1097
                        chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
1098
                })
×
1099
                p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
2✔
1100
                        chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
1101
                })
×
1102
                p.cfg.AuxResolver.WhenSome(
2✔
1103
                        func(s lnwallet.AuxContractResolver) {
2✔
1104
                                chanOpts = append(
×
1105
                                        chanOpts, lnwallet.WithAuxResolver(s),
×
1106
                                )
×
1107
                        },
×
1108
                )
1109

1110
                lnChan, err := lnwallet.NewLightningChannel(
2✔
1111
                        p.cfg.Signer, dbChan, p.cfg.SigPool, chanOpts...,
2✔
1112
                )
2✔
1113
                if err != nil {
2✔
1114
                        return nil, fmt.Errorf("unable to create channel "+
×
1115
                                "state machine: %w", err)
×
1116
                }
×
1117

1118
                chanPoint := dbChan.FundingOutpoint
2✔
1119

2✔
1120
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
1121

2✔
1122
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
2✔
1123
                        chanPoint, lnChan.IsPending())
2✔
1124

2✔
1125
                // Skip adding any permanently irreconcilable channels to the
2✔
1126
                // htlcswitch.
2✔
1127
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
2✔
1128
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
4✔
1129

2✔
1130
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
2✔
1131
                                "start.", chanPoint, dbChan.ChanStatus())
2✔
1132

2✔
1133
                        // To help our peer recover from a potential data loss,
2✔
1134
                        // we resend our channel reestablish message if the
2✔
1135
                        // channel is in a borked state. We won't process any
2✔
1136
                        // channel reestablish message sent from the peer, but
2✔
1137
                        // that's okay since the assumption is that we did when
2✔
1138
                        // marking the channel borked.
2✔
1139
                        chanSync, err := dbChan.ChanSyncMsg()
2✔
1140
                        if err != nil {
2✔
1141
                                p.log.Errorf("Unable to create channel "+
×
1142
                                        "reestablish message for channel %v: "+
×
1143
                                        "%v", chanPoint, err)
×
1144
                                continue
×
1145
                        }
1146

1147
                        msgs = append(msgs, chanSync)
2✔
1148

2✔
1149
                        // Check if this channel needs to have the cooperative
2✔
1150
                        // close process restarted. If so, we'll need to send
2✔
1151
                        // the Shutdown message that is returned.
2✔
1152
                        if dbChan.HasChanStatus(
2✔
1153
                                channeldb.ChanStatusCoopBroadcasted,
2✔
1154
                        ) {
2✔
UNCOV
1155

×
UNCOV
1156
                                shutdownMsg, err := p.restartCoopClose(lnChan)
×
UNCOV
1157
                                if err != nil {
×
1158
                                        p.log.Errorf("Unable to restart "+
×
1159
                                                "coop close for channel: %v",
×
1160
                                                err)
×
1161
                                        continue
×
1162
                                }
1163

UNCOV
1164
                                if shutdownMsg == nil {
×
UNCOV
1165
                                        continue
×
1166
                                }
1167

1168
                                // Append the message to the set of messages to
1169
                                // send.
1170
                                msgs = append(msgs, shutdownMsg)
×
1171
                        }
1172

1173
                        continue
2✔
1174
                }
1175

1176
                // Before we register this new link with the HTLC Switch, we'll
1177
                // need to fetch its current link-layer forwarding policy from
1178
                // the database.
UNCOV
1179
                graph := p.cfg.ChannelGraph
×
UNCOV
1180
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
×
UNCOV
1181
                        &chanPoint,
×
UNCOV
1182
                )
×
UNCOV
1183
                if err != nil && !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
1184
                        return nil, err
×
1185
                }
×
1186

1187
                // We'll filter out our policy from the directional channel
1188
                // edges based whom the edge connects to. If it doesn't connect
1189
                // to us, then we know that we were the one that advertised the
1190
                // policy.
1191
                //
1192
                // TODO(roasbeef): can add helper method to get policy for
1193
                // particular channel.
UNCOV
1194
                var selfPolicy *models.ChannelEdgePolicy
×
UNCOV
1195
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
×
UNCOV
1196
                        p.cfg.ServerPubKey[:]) {
×
UNCOV
1197

×
UNCOV
1198
                        selfPolicy = p1
×
UNCOV
1199
                } else {
×
UNCOV
1200
                        selfPolicy = p2
×
UNCOV
1201
                }
×
1202

1203
                // If we don't yet have an advertised routing policy, then
1204
                // we'll use the current default, otherwise we'll translate the
1205
                // routing policy into a forwarding policy.
UNCOV
1206
                var forwardingPolicy *models.ForwardingPolicy
×
UNCOV
1207
                if selfPolicy != nil {
×
UNCOV
1208
                        forwardingPolicy = &models.ForwardingPolicy{
×
UNCOV
1209
                                MinHTLCOut:    selfPolicy.MinHTLC,
×
UNCOV
1210
                                MaxHTLC:       selfPolicy.MaxHTLC,
×
UNCOV
1211
                                BaseFee:       selfPolicy.FeeBaseMSat,
×
UNCOV
1212
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
×
UNCOV
1213
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
×
UNCOV
1214
                        }
×
UNCOV
1215
                        selfPolicy.InboundFee.WhenSome(func(fee lnwire.Fee) {
×
1216
                                inboundFee := models.NewInboundFeeFromWire(fee)
×
1217
                                forwardingPolicy.InboundFee = inboundFee
×
1218
                        })
×
UNCOV
1219
                } else {
×
UNCOV
1220
                        p.log.Warnf("Unable to find our forwarding policy "+
×
UNCOV
1221
                                "for channel %v, using default values",
×
UNCOV
1222
                                chanPoint)
×
UNCOV
1223
                        forwardingPolicy = &p.cfg.RoutingPolicy
×
UNCOV
1224
                }
×
1225

UNCOV
1226
                p.log.Tracef("Using link policy of: %v",
×
UNCOV
1227
                        spew.Sdump(forwardingPolicy))
×
UNCOV
1228

×
UNCOV
1229
                // If the channel is pending, set the value to nil in the
×
UNCOV
1230
                // activeChannels map. This is done to signify that the channel
×
UNCOV
1231
                // is pending. We don't add the link to the switch here - it's
×
UNCOV
1232
                // the funding manager's responsibility to spin up pending
×
UNCOV
1233
                // channels. Adding them here would just be extra work as we'll
×
UNCOV
1234
                // tear them down when creating + adding the final link.
×
UNCOV
1235
                if lnChan.IsPending() {
×
UNCOV
1236
                        p.activeChannels.Store(chanID, nil)
×
UNCOV
1237

×
UNCOV
1238
                        continue
×
1239
                }
1240

UNCOV
1241
                shutdownInfo, err := lnChan.State().ShutdownInfo()
×
UNCOV
1242
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
×
1243
                        return nil, err
×
1244
                }
×
1245

UNCOV
1246
                isTaprootChan := lnChan.ChanType().IsTaproot()
×
UNCOV
1247

×
UNCOV
1248
                var (
×
UNCOV
1249
                        shutdownMsg     fn.Option[lnwire.Shutdown]
×
UNCOV
1250
                        shutdownInfoErr error
×
UNCOV
1251
                )
×
UNCOV
1252
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
×
UNCOV
1253
                        // If we can use the new RBF close feature, we don't
×
UNCOV
1254
                        // need to create the legacy closer. However for taproot
×
UNCOV
1255
                        // channels, we'll continue to use the legacy closer.
×
UNCOV
1256
                        if p.rbfCoopCloseAllowed() && !isTaprootChan {
×
UNCOV
1257
                                return
×
UNCOV
1258
                        }
×
1259

1260
                        // Compute an ideal fee.
UNCOV
1261
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
UNCOV
1262
                                p.cfg.CoopCloseTargetConfs,
×
UNCOV
1263
                        )
×
UNCOV
1264
                        if err != nil {
×
1265
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1266
                                        "estimate fee: %w", err)
×
1267

×
1268
                                return
×
1269
                        }
×
1270

UNCOV
1271
                        addr, err := p.addrWithInternalKey(
×
UNCOV
1272
                                info.DeliveryScript.Val,
×
UNCOV
1273
                        )
×
UNCOV
1274
                        if err != nil {
×
1275
                                shutdownInfoErr = fmt.Errorf("unable to make "+
×
1276
                                        "delivery addr: %w", err)
×
1277
                                return
×
1278
                        }
×
UNCOV
1279
                        negotiateChanCloser, err := p.createChanCloser(
×
UNCOV
1280
                                lnChan, addr, feePerKw, nil,
×
UNCOV
1281
                                info.Closer(),
×
UNCOV
1282
                        )
×
UNCOV
1283
                        if err != nil {
×
1284
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1285
                                        "create chan closer: %w", err)
×
1286

×
1287
                                return
×
1288
                        }
×
1289

UNCOV
1290
                        chanID := lnwire.NewChanIDFromOutPoint(
×
UNCOV
1291
                                lnChan.State().FundingOutpoint,
×
UNCOV
1292
                        )
×
UNCOV
1293

×
UNCOV
1294
                        p.activeChanCloses.Store(chanID, makeNegotiateCloser(
×
UNCOV
1295
                                negotiateChanCloser,
×
UNCOV
1296
                        ))
×
UNCOV
1297

×
UNCOV
1298
                        // Create the Shutdown message.
×
UNCOV
1299
                        shutdown, err := negotiateChanCloser.ShutdownChan()
×
UNCOV
1300
                        if err != nil {
×
1301
                                p.activeChanCloses.Delete(chanID)
×
1302
                                shutdownInfoErr = err
×
1303

×
1304
                                return
×
1305
                        }
×
1306

UNCOV
1307
                        shutdownMsg = fn.Some(*shutdown)
×
1308
                })
UNCOV
1309
                if shutdownInfoErr != nil {
×
1310
                        return nil, shutdownInfoErr
×
1311
                }
×
1312

1313
                // Subscribe to the set of on-chain events for this channel.
UNCOV
1314
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
×
UNCOV
1315
                        chanPoint,
×
UNCOV
1316
                )
×
UNCOV
1317
                if err != nil {
×
1318
                        return nil, err
×
1319
                }
×
1320

UNCOV
1321
                err = p.addLink(
×
UNCOV
1322
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
×
UNCOV
1323
                        true, shutdownMsg,
×
UNCOV
1324
                )
×
UNCOV
1325
                if err != nil {
×
1326
                        return nil, fmt.Errorf("unable to add link %v to "+
×
1327
                                "switch: %v", chanPoint, err)
×
1328
                }
×
1329

UNCOV
1330
                p.activeChannels.Store(chanID, lnChan)
×
UNCOV
1331

×
UNCOV
1332
                // We're using the old co-op close, so we don't need to init
×
UNCOV
1333
                // the new RBF chan closer. If we have a taproot chan, then
×
UNCOV
1334
                // we'll also use the legacy type, so we don't need to make the
×
UNCOV
1335
                // new closer.
×
UNCOV
1336
                if !p.rbfCoopCloseAllowed() || isTaprootChan {
×
UNCOV
1337
                        continue
×
1338
                }
1339

1340
                // Now that the link has been added above, we'll also init an
1341
                // RBF chan closer for this channel, but only if the new close
1342
                // feature is negotiated.
1343
                //
1344
                // Creating this here ensures that any shutdown messages sent
1345
                // will be automatically routed by the msg router.
UNCOV
1346
                if _, err := p.initRbfChanCloser(lnChan); err != nil {
×
1347
                        p.activeChanCloses.Delete(chanID)
×
1348

×
1349
                        return nil, fmt.Errorf("unable to init RBF chan "+
×
1350
                                "closer during peer connect: %w", err)
×
1351
                }
×
1352

1353
                // If the shutdown info isn't blank, then we should kick things
1354
                // off by sending a shutdown message to the remote party to
1355
                // continue the old shutdown flow.
UNCOV
1356
                restartShutdown := func(s channeldb.ShutdownInfo) error {
×
UNCOV
1357
                        return p.startRbfChanCloser(
×
UNCOV
1358
                                newRestartShutdownInit(s),
×
UNCOV
1359
                                lnChan.ChannelPoint(),
×
UNCOV
1360
                        )
×
UNCOV
1361
                }
×
UNCOV
1362
                err = fn.MapOptionZ(shutdownInfo, restartShutdown)
×
UNCOV
1363
                if err != nil {
×
1364
                        return nil, fmt.Errorf("unable to start RBF "+
×
1365
                                "chan closer: %w", err)
×
1366
                }
×
1367
        }
1368

1369
        return msgs, nil
3✔
1370
}
1371

1372
// addLink creates and adds a new ChannelLink from the specified channel.
1373
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1374
        lnChan *lnwallet.LightningChannel,
1375
        forwardingPolicy *models.ForwardingPolicy,
1376
        chainEvents *contractcourt.ChainEventSubscription,
UNCOV
1377
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
×
UNCOV
1378

×
UNCOV
1379
        // onChannelFailure will be called by the link in case the channel
×
UNCOV
1380
        // fails for some reason.
×
UNCOV
1381
        onChannelFailure := func(chanID lnwire.ChannelID,
×
UNCOV
1382
                shortChanID lnwire.ShortChannelID,
×
UNCOV
1383
                linkErr htlcswitch.LinkFailureError) {
×
UNCOV
1384

×
UNCOV
1385
                failure := linkFailureReport{
×
UNCOV
1386
                        chanPoint:   *chanPoint,
×
UNCOV
1387
                        chanID:      chanID,
×
UNCOV
1388
                        shortChanID: shortChanID,
×
UNCOV
1389
                        linkErr:     linkErr,
×
UNCOV
1390
                }
×
UNCOV
1391

×
UNCOV
1392
                select {
×
UNCOV
1393
                case p.linkFailures <- failure:
×
1394
                case <-p.cg.Done():
×
1395
                case <-p.cfg.Quit:
×
1396
                }
1397
        }
1398

UNCOV
1399
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
×
UNCOV
1400
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
×
UNCOV
1401
        }
×
1402

UNCOV
1403
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
×
UNCOV
1404
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
×
UNCOV
1405
        }
×
1406

1407
        //nolint:ll
UNCOV
1408
        linkCfg := htlcswitch.ChannelLinkConfig{
×
UNCOV
1409
                Peer:                   p,
×
UNCOV
1410
                DecodeHopIterators:     p.cfg.Sphinx.DecodeHopIterators,
×
UNCOV
1411
                ExtractErrorEncrypter:  p.cfg.Sphinx.ExtractErrorEncrypter,
×
UNCOV
1412
                FetchLastChannelUpdate: p.cfg.FetchLastChanUpdate,
×
UNCOV
1413
                HodlMask:               p.cfg.Hodl.Mask(),
×
UNCOV
1414
                Registry:               p.cfg.Invoices,
×
UNCOV
1415
                BestHeight:             p.cfg.Switch.BestHeight,
×
UNCOV
1416
                Circuits:               p.cfg.Switch.CircuitModifier(),
×
UNCOV
1417
                ForwardPackets:         p.cfg.InterceptSwitch.ForwardPackets,
×
UNCOV
1418
                FwrdingPolicy:          *forwardingPolicy,
×
UNCOV
1419
                FeeEstimator:           p.cfg.FeeEstimator,
×
UNCOV
1420
                PreimageCache:          p.cfg.WitnessBeacon,
×
UNCOV
1421
                ChainEvents:            chainEvents,
×
UNCOV
1422
                UpdateContractSignals:  updateContractSignals,
×
UNCOV
1423
                NotifyContractUpdate:   notifyContractUpdate,
×
UNCOV
1424
                OnChannelFailure:       onChannelFailure,
×
UNCOV
1425
                SyncStates:             syncStates,
×
UNCOV
1426
                BatchTicker:            ticker.New(p.cfg.ChannelCommitInterval),
×
UNCOV
1427
                FwdPkgGCTicker:         ticker.New(time.Hour),
×
UNCOV
1428
                PendingCommitTicker: ticker.New(
×
UNCOV
1429
                        p.cfg.PendingCommitInterval,
×
UNCOV
1430
                ),
×
UNCOV
1431
                BatchSize:               p.cfg.ChannelCommitBatchSize,
×
UNCOV
1432
                UnsafeReplay:            p.cfg.UnsafeReplay,
×
UNCOV
1433
                MinUpdateTimeout:        htlcswitch.DefaultMinLinkFeeUpdateTimeout,
×
UNCOV
1434
                MaxUpdateTimeout:        htlcswitch.DefaultMaxLinkFeeUpdateTimeout,
×
UNCOV
1435
                OutgoingCltvRejectDelta: p.cfg.OutgoingCltvRejectDelta,
×
UNCOV
1436
                TowerClient:             p.cfg.TowerClient,
×
UNCOV
1437
                MaxOutgoingCltvExpiry:   p.cfg.MaxOutgoingCltvExpiry,
×
UNCOV
1438
                MaxFeeAllocation:        p.cfg.MaxChannelFeeAllocation,
×
UNCOV
1439
                MaxAnchorsCommitFeeRate: p.cfg.MaxAnchorsCommitFeeRate,
×
UNCOV
1440
                NotifyActiveLink:        p.cfg.ChannelNotifier.NotifyActiveLinkEvent,
×
UNCOV
1441
                NotifyActiveChannel:     p.cfg.ChannelNotifier.NotifyActiveChannelEvent,
×
UNCOV
1442
                NotifyInactiveChannel:   p.cfg.ChannelNotifier.NotifyInactiveChannelEvent,
×
UNCOV
1443
                NotifyInactiveLinkEvent: p.cfg.ChannelNotifier.NotifyInactiveLinkEvent,
×
UNCOV
1444
                HtlcNotifier:            p.cfg.HtlcNotifier,
×
UNCOV
1445
                GetAliases:              p.cfg.GetAliases,
×
UNCOV
1446
                PreviouslySentShutdown:  shutdownMsg,
×
UNCOV
1447
                DisallowRouteBlinding:   p.cfg.DisallowRouteBlinding,
×
UNCOV
1448
                MaxFeeExposure:          p.cfg.MaxFeeExposure,
×
UNCOV
1449
                ShouldFwdExpEndorsement: p.cfg.ShouldFwdExpEndorsement,
×
UNCOV
1450
                DisallowQuiescence: p.cfg.DisallowQuiescence ||
×
UNCOV
1451
                        !p.remoteFeatures.HasFeature(lnwire.QuiescenceOptional),
×
UNCOV
1452
                AuxTrafficShaper: p.cfg.AuxTrafficShaper,
×
UNCOV
1453
        }
×
UNCOV
1454

×
UNCOV
1455
        // Before adding our new link, purge the switch of any pending or live
×
UNCOV
1456
        // links going by the same channel id. If one is found, we'll shut it
×
UNCOV
1457
        // down to ensure that the mailboxes are only ever under the control of
×
UNCOV
1458
        // one link.
×
UNCOV
1459
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
×
UNCOV
1460
        p.cfg.Switch.RemoveLink(chanID)
×
UNCOV
1461

×
UNCOV
1462
        // With the channel link created, we'll now notify the htlc switch so
×
UNCOV
1463
        // this channel can be used to dispatch local payments and also
×
UNCOV
1464
        // passively forward payments.
×
UNCOV
1465
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
×
1466
}
1467

1468
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1469
// one confirmed public channel exists with them.
1470
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
3✔
1471
        defer p.cg.WgDone()
3✔
1472

3✔
1473
        hasConfirmedPublicChan := false
3✔
1474
        for _, channel := range channels {
5✔
1475
                if channel.IsPending {
2✔
UNCOV
1476
                        continue
×
1477
                }
1478
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
4✔
1479
                        continue
2✔
1480
                }
1481

UNCOV
1482
                hasConfirmedPublicChan = true
×
UNCOV
1483
                break
×
1484
        }
1485
        if !hasConfirmedPublicChan {
6✔
1486
                return
3✔
1487
        }
3✔
1488

UNCOV
1489
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
×
UNCOV
1490
        if err != nil {
×
1491
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1492
                return
×
1493
        }
×
1494

UNCOV
1495
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
×
1496
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1497
        }
×
1498
}
1499

1500
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1501
// have any active channels with them.
1502
func (p *Brontide) maybeSendChannelUpdates() {
3✔
1503
        defer p.cg.WgDone()
3✔
1504

3✔
1505
        // If we don't have any active channels, then we can exit early.
3✔
1506
        if p.activeChannels.Len() == 0 {
4✔
1507
                return
1✔
1508
        }
1✔
1509

1510
        maybeSendUpd := func(cid lnwire.ChannelID,
2✔
1511
                lnChan *lnwallet.LightningChannel) error {
4✔
1512

2✔
1513
                // Nil channels are pending, so we'll skip them.
2✔
1514
                if lnChan == nil {
2✔
UNCOV
1515
                        return nil
×
UNCOV
1516
                }
×
1517

1518
                dbChan := lnChan.State()
2✔
1519
                scid := func() lnwire.ShortChannelID {
4✔
1520
                        switch {
2✔
1521
                        // Otherwise if it's a zero conf channel and confirmed,
1522
                        // then we need to use the "real" scid.
UNCOV
1523
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
×
UNCOV
1524
                                return dbChan.ZeroConfRealScid()
×
1525

1526
                        // Otherwise, we can use the normal scid.
1527
                        default:
2✔
1528
                                return dbChan.ShortChanID()
2✔
1529
                        }
1530
                }()
1531

1532
                // Now that we know the channel is in a good state, we'll try
1533
                // to fetch the update to send to the remote peer. If the
1534
                // channel is pending, and not a zero conf channel, we'll get
1535
                // an error here which we'll ignore.
1536
                chanUpd, err := p.cfg.FetchLastChanUpdate(scid)
2✔
1537
                if err != nil {
2✔
UNCOV
1538
                        p.log.Debugf("Unable to fetch channel update for "+
×
UNCOV
1539
                                "ChannelPoint(%v), scid=%v: %v",
×
UNCOV
1540
                                dbChan.FundingOutpoint, dbChan.ShortChanID, err)
×
UNCOV
1541

×
UNCOV
1542
                        return nil
×
UNCOV
1543
                }
×
1544

1545
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
2✔
1546
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
2✔
1547

2✔
1548
                // We'll send it as a normal message instead of using the lazy
2✔
1549
                // queue to prioritize transmission of the fresh update.
2✔
1550
                if err := p.SendMessage(false, chanUpd); err != nil {
2✔
1551
                        err := fmt.Errorf("unable to send channel update for "+
×
1552
                                "ChannelPoint(%v), scid=%v: %w",
×
1553
                                dbChan.FundingOutpoint, dbChan.ShortChanID(),
×
1554
                                err)
×
1555
                        p.log.Errorf(err.Error())
×
1556

×
1557
                        return err
×
1558
                }
×
1559

1560
                return nil
2✔
1561
        }
1562

1563
        p.activeChannels.ForEach(maybeSendUpd)
2✔
1564
}
1565

1566
// WaitForDisconnect waits until the peer has disconnected. A peer may be
1567
// disconnected if the local or remote side terminates the connection, or an
1568
// irrecoverable protocol error has been encountered. This method will only
1569
// begin watching the peer's waitgroup after the ready channel or the peer's
1570
// quit channel are signaled. The ready channel should only be signaled if a
1571
// call to Start returns no error. Otherwise, if the peer fails to start,
1572
// calling Disconnect will signal the quit channel and the method will not
1573
// block, since no goroutines were spawned.
UNCOV
1574
func (p *Brontide) WaitForDisconnect(ready chan struct{}) {
×
UNCOV
1575
        // Before we try to call the `Wait` goroutine, we'll make sure the main
×
UNCOV
1576
        // set of goroutines are already active.
×
UNCOV
1577
        select {
×
UNCOV
1578
        case <-p.startReady:
×
UNCOV
1579
        case <-p.cg.Done():
×
UNCOV
1580
                return
×
1581
        }
1582

UNCOV
1583
        select {
×
UNCOV
1584
        case <-ready:
×
UNCOV
1585
        case <-p.cg.Done():
×
1586
        }
1587

UNCOV
1588
        p.cg.WgWait()
×
1589
}
1590

1591
// Disconnect terminates the connection with the remote peer. Additionally, a
1592
// signal is sent to the server and htlcSwitch indicating the resources
1593
// allocated to the peer can now be cleaned up.
1594
//
1595
// NOTE: Be aware that this method will block if the peer is still starting up.
1596
// Therefore consider starting it in a goroutine if you cannot guarantee that
1597
// the peer has finished starting up before calling this method.
UNCOV
1598
func (p *Brontide) Disconnect(reason error) {
×
UNCOV
1599
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
×
UNCOV
1600
                return
×
UNCOV
1601
        }
×
1602

1603
        // Make sure initialization has completed before we try to tear things
1604
        // down.
1605
        //
1606
        // NOTE: We only read the `startReady` chan if the peer has been
1607
        // started, otherwise we will skip reading it as this chan won't be
1608
        // closed, hence blocks forever.
UNCOV
1609
        if atomic.LoadInt32(&p.started) == 1 {
×
UNCOV
1610
                p.log.Debugf("Peer hasn't finished starting up yet, waiting " +
×
UNCOV
1611
                        "on startReady signal before closing connection")
×
UNCOV
1612

×
UNCOV
1613
                select {
×
UNCOV
1614
                case <-p.startReady:
×
1615
                case <-p.cg.Done():
×
1616
                        return
×
1617
                }
1618
        }
1619

UNCOV
1620
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
×
UNCOV
1621
        p.storeError(err)
×
UNCOV
1622

×
UNCOV
1623
        p.log.Infof(err.Error())
×
UNCOV
1624

×
UNCOV
1625
        // Stop PingManager before closing TCP connection.
×
UNCOV
1626
        p.pingManager.Stop()
×
UNCOV
1627

×
UNCOV
1628
        // Ensure that the TCP connection is properly closed before continuing.
×
UNCOV
1629
        p.cfg.Conn.Close()
×
UNCOV
1630

×
UNCOV
1631
        p.cg.Quit()
×
UNCOV
1632

×
UNCOV
1633
        // If our msg router isn't global (local to this instance), then we'll
×
UNCOV
1634
        // stop it. Otherwise, we'll leave it running.
×
UNCOV
1635
        if !p.globalMsgRouter {
×
UNCOV
1636
                p.msgRouter.WhenSome(func(router msgmux.Router) {
×
UNCOV
1637
                        router.Stop()
×
UNCOV
1638
                })
×
1639
        }
1640
}
1641

1642
// String returns the string representation of this peer.
UNCOV
1643
func (p *Brontide) String() string {
×
UNCOV
1644
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
×
UNCOV
1645
}
×
1646

1647
// readNextMessage reads, and returns the next message on the wire along with
1648
// any additional raw payload.
1649
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
7✔
1650
        noiseConn := p.cfg.Conn
7✔
1651
        err := noiseConn.SetReadDeadline(time.Time{})
7✔
1652
        if err != nil {
7✔
1653
                return nil, err
×
1654
        }
×
1655

1656
        pktLen, err := noiseConn.ReadNextHeader()
7✔
1657
        if err != nil {
7✔
UNCOV
1658
                return nil, fmt.Errorf("read next header: %w", err)
×
UNCOV
1659
        }
×
1660

1661
        // First we'll read the next _full_ message. We do this rather than
1662
        // reading incrementally from the stream as the Lightning wire protocol
1663
        // is message oriented and allows nodes to pad on additional data to
1664
        // the message stream.
1665
        var (
4✔
1666
                nextMsg lnwire.Message
4✔
1667
                msgLen  uint64
4✔
1668
        )
4✔
1669
        err = p.cfg.ReadPool.Submit(func(buf *buffer.Read) error {
8✔
1670
                // Before reading the body of the message, set the read timeout
4✔
1671
                // accordingly to ensure we don't block other readers using the
4✔
1672
                // pool. We do so only after the task has been scheduled to
4✔
1673
                // ensure the deadline doesn't expire while the message is in
4✔
1674
                // the process of being scheduled.
4✔
1675
                readDeadline := time.Now().Add(
4✔
1676
                        p.scaleTimeout(readMessageTimeout),
4✔
1677
                )
4✔
1678
                readErr := noiseConn.SetReadDeadline(readDeadline)
4✔
1679
                if readErr != nil {
4✔
1680
                        return readErr
×
1681
                }
×
1682

1683
                // The ReadNextBody method will actually end up re-using the
1684
                // buffer, so within this closure, we can continue to use
1685
                // rawMsg as it's just a slice into the buf from the buffer
1686
                // pool.
1687
                rawMsg, readErr := noiseConn.ReadNextBody(buf[:pktLen])
4✔
1688
                if readErr != nil {
4✔
1689
                        return fmt.Errorf("read next body: %w", readErr)
×
1690
                }
×
1691
                msgLen = uint64(len(rawMsg))
4✔
1692

4✔
1693
                // Next, create a new io.Reader implementation from the raw
4✔
1694
                // message, and use this to decode the message directly from.
4✔
1695
                msgReader := bytes.NewReader(rawMsg)
4✔
1696
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
4✔
1697
                if err != nil {
4✔
UNCOV
1698
                        return err
×
UNCOV
1699
                }
×
1700

1701
                // At this point, rawMsg and buf will be returned back to the
1702
                // buffer pool for re-use.
1703
                return nil
4✔
1704
        })
1705
        atomic.AddUint64(&p.bytesReceived, msgLen)
4✔
1706
        if err != nil {
4✔
UNCOV
1707
                return nil, err
×
UNCOV
1708
        }
×
1709

1710
        p.logWireMessage(nextMsg, true)
4✔
1711

4✔
1712
        return nextMsg, nil
4✔
1713
}
1714

1715
// msgStream implements a goroutine-safe, in-order stream of messages to be
1716
// delivered via closure to a receiver. These messages MUST be in order due to
1717
// the nature of the lightning channel commitment and gossiper state machines.
1718
// TODO(conner): use stream handler interface to abstract out stream
1719
// state/logging.
1720
type msgStream struct {
1721
        streamShutdown int32 // To be used atomically.
1722

1723
        peer *Brontide
1724

1725
        apply func(lnwire.Message)
1726

1727
        startMsg string
1728
        stopMsg  string
1729

1730
        msgCond *sync.Cond
1731
        msgs    []lnwire.Message
1732

1733
        mtx sync.Mutex
1734

1735
        producerSema chan struct{}
1736

1737
        wg   sync.WaitGroup
1738
        quit chan struct{}
1739
}
1740

1741
// newMsgStream creates a new instance of a chanMsgStream for a particular
1742
// channel identified by its channel ID. bufSize is the max number of messages
1743
// that should be buffered in the internal queue. Callers should set this to a
1744
// sane value that avoids blocking unnecessarily, but doesn't allow an
1745
// unbounded amount of memory to be allocated to buffer incoming messages.
1746
func newMsgStream(p *Brontide, startMsg, stopMsg string, bufSize uint32,
1747
        apply func(lnwire.Message)) *msgStream {
3✔
1748

3✔
1749
        stream := &msgStream{
3✔
1750
                peer:         p,
3✔
1751
                apply:        apply,
3✔
1752
                startMsg:     startMsg,
3✔
1753
                stopMsg:      stopMsg,
3✔
1754
                producerSema: make(chan struct{}, bufSize),
3✔
1755
                quit:         make(chan struct{}),
3✔
1756
        }
3✔
1757
        stream.msgCond = sync.NewCond(&stream.mtx)
3✔
1758

3✔
1759
        // Before we return the active stream, we'll populate the producer's
3✔
1760
        // semaphore channel. We'll use this to ensure that the producer won't
3✔
1761
        // attempt to allocate memory in the queue for an item until it has
3✔
1762
        // sufficient extra space.
3✔
1763
        for i := uint32(0); i < bufSize; i++ {
153✔
1764
                stream.producerSema <- struct{}{}
150✔
1765
        }
150✔
1766

1767
        return stream
3✔
1768
}
1769

1770
// Start starts the chanMsgStream.
1771
func (ms *msgStream) Start() {
3✔
1772
        ms.wg.Add(1)
3✔
1773
        go ms.msgConsumer()
3✔
1774
}
3✔
1775

1776
// Stop stops the chanMsgStream.
UNCOV
1777
func (ms *msgStream) Stop() {
×
UNCOV
1778
        // TODO(roasbeef): signal too?
×
UNCOV
1779

×
UNCOV
1780
        close(ms.quit)
×
UNCOV
1781

×
UNCOV
1782
        // Now that we've closed the channel, we'll repeatedly signal the msg
×
UNCOV
1783
        // consumer until we've detected that it has exited.
×
UNCOV
1784
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
×
UNCOV
1785
                ms.msgCond.Signal()
×
UNCOV
1786
                time.Sleep(time.Millisecond * 100)
×
UNCOV
1787
        }
×
1788

UNCOV
1789
        ms.wg.Wait()
×
1790
}
1791

1792
// msgConsumer is the main goroutine that streams messages from the peer's
1793
// readHandler directly to the target channel.
1794
func (ms *msgStream) msgConsumer() {
3✔
1795
        defer ms.wg.Done()
3✔
1796
        defer peerLog.Tracef(ms.stopMsg)
3✔
1797
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
3✔
1798

3✔
1799
        peerLog.Tracef(ms.startMsg)
3✔
1800

3✔
1801
        for {
6✔
1802
                // First, we'll check our condition. If the queue of messages
3✔
1803
                // is empty, then we'll wait until a new item is added.
3✔
1804
                ms.msgCond.L.Lock()
3✔
1805
                for len(ms.msgs) == 0 {
6✔
1806
                        ms.msgCond.Wait()
3✔
1807

3✔
1808
                        // If we woke up in order to exit, then we'll do so.
3✔
1809
                        // Otherwise, we'll check the message queue for any new
3✔
1810
                        // items.
3✔
1811
                        select {
3✔
UNCOV
1812
                        case <-ms.peer.cg.Done():
×
UNCOV
1813
                                ms.msgCond.L.Unlock()
×
UNCOV
1814
                                return
×
UNCOV
1815
                        case <-ms.quit:
×
UNCOV
1816
                                ms.msgCond.L.Unlock()
×
UNCOV
1817
                                return
×
UNCOV
1818
                        default:
×
1819
                        }
1820
                }
1821

1822
                // Grab the message off the front of the queue, shifting the
1823
                // slice's reference down one in order to remove the message
1824
                // from the queue.
UNCOV
1825
                msg := ms.msgs[0]
×
UNCOV
1826
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
×
UNCOV
1827
                ms.msgs = ms.msgs[1:]
×
UNCOV
1828

×
UNCOV
1829
                ms.msgCond.L.Unlock()
×
UNCOV
1830

×
UNCOV
1831
                ms.apply(msg)
×
UNCOV
1832

×
UNCOV
1833
                // We've just successfully processed an item, so we'll signal
×
UNCOV
1834
                // to the producer that a new slot in the buffer. We'll use
×
UNCOV
1835
                // this to bound the size of the buffer to avoid allowing it to
×
UNCOV
1836
                // grow indefinitely.
×
UNCOV
1837
                select {
×
UNCOV
1838
                case ms.producerSema <- struct{}{}:
×
UNCOV
1839
                case <-ms.peer.cg.Done():
×
UNCOV
1840
                        return
×
UNCOV
1841
                case <-ms.quit:
×
UNCOV
1842
                        return
×
1843
                }
1844
        }
1845
}
1846

1847
// AddMsg adds a new message to the msgStream. This function is safe for
1848
// concurrent access.
UNCOV
1849
func (ms *msgStream) AddMsg(msg lnwire.Message) {
×
UNCOV
1850
        // First, we'll attempt to receive from the producerSema struct. This
×
UNCOV
1851
        // acts as a semaphore to prevent us from indefinitely buffering
×
UNCOV
1852
        // incoming items from the wire. Either the msg queue isn't full, and
×
UNCOV
1853
        // we'll not block, or the queue is full, and we'll block until either
×
UNCOV
1854
        // we're signalled to quit, or a slot is freed up.
×
UNCOV
1855
        select {
×
UNCOV
1856
        case <-ms.producerSema:
×
1857
        case <-ms.peer.cg.Done():
×
1858
                return
×
1859
        case <-ms.quit:
×
1860
                return
×
1861
        }
1862

1863
        // Next, we'll lock the condition, and add the message to the end of
1864
        // the message queue.
UNCOV
1865
        ms.msgCond.L.Lock()
×
UNCOV
1866
        ms.msgs = append(ms.msgs, msg)
×
UNCOV
1867
        ms.msgCond.L.Unlock()
×
UNCOV
1868

×
UNCOV
1869
        // With the message added, we signal to the msgConsumer that there are
×
UNCOV
1870
        // additional messages to consume.
×
UNCOV
1871
        ms.msgCond.Signal()
×
1872
}
1873

1874
// waitUntilLinkActive waits until the target link is active and returns a
1875
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1876
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1877
func waitUntilLinkActive(p *Brontide,
UNCOV
1878
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
×
UNCOV
1879

×
UNCOV
1880
        p.log.Tracef("Waiting for link=%v to be active", cid)
×
UNCOV
1881

×
UNCOV
1882
        // Subscribe to receive channel events.
×
UNCOV
1883
        //
×
UNCOV
1884
        // NOTE: If the link is already active by SubscribeChannelEvents, then
×
UNCOV
1885
        // GetLink will retrieve the link and we can send messages. If the link
×
UNCOV
1886
        // becomes active between SubscribeChannelEvents and GetLink, then GetLink
×
UNCOV
1887
        // will retrieve the link. If the link becomes active after GetLink, then
×
UNCOV
1888
        // we will get an ActiveLinkEvent notification and retrieve the link. If
×
UNCOV
1889
        // the call to GetLink is before SubscribeChannelEvents, however, there
×
UNCOV
1890
        // will be a race condition.
×
UNCOV
1891
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
×
UNCOV
1892
        if err != nil {
×
UNCOV
1893
                // If we have a non-nil error, then the server is shutting down and we
×
UNCOV
1894
                // can exit here and return nil. This means no message will be delivered
×
UNCOV
1895
                // to the link.
×
UNCOV
1896
                return nil
×
UNCOV
1897
        }
×
UNCOV
1898
        defer sub.Cancel()
×
UNCOV
1899

×
UNCOV
1900
        // The link may already be active by this point, and we may have missed the
×
UNCOV
1901
        // ActiveLinkEvent. Check if the link exists.
×
UNCOV
1902
        link := p.fetchLinkFromKeyAndCid(cid)
×
UNCOV
1903
        if link != nil {
×
UNCOV
1904
                return link
×
UNCOV
1905
        }
×
1906

1907
        // If the link is nil, we must wait for it to be active.
UNCOV
1908
        for {
×
UNCOV
1909
                select {
×
1910
                // A new event has been sent by the ChannelNotifier. We first check
1911
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1912
                // that the event is for this channel. Otherwise, we discard the
1913
                // message.
UNCOV
1914
                case e := <-sub.Updates():
×
UNCOV
1915
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
×
UNCOV
1916
                        if !ok {
×
UNCOV
1917
                                // Ignore this notification.
×
UNCOV
1918
                                continue
×
1919
                        }
1920

UNCOV
1921
                        chanPoint := event.ChannelPoint
×
UNCOV
1922

×
UNCOV
1923
                        // Check whether the retrieved chanPoint matches the target
×
UNCOV
1924
                        // channel id.
×
UNCOV
1925
                        if !cid.IsChanPoint(chanPoint) {
×
1926
                                continue
×
1927
                        }
1928

1929
                        // The link shouldn't be nil as we received an
1930
                        // ActiveLinkEvent. If it is nil, we return nil and the
1931
                        // calling function should catch it.
UNCOV
1932
                        return p.fetchLinkFromKeyAndCid(cid)
×
1933

UNCOV
1934
                case <-p.cg.Done():
×
UNCOV
1935
                        return nil
×
1936
                }
1937
        }
1938
}
1939

1940
// newChanMsgStream is used to create a msgStream between the peer and
1941
// particular channel link in the htlcswitch. We utilize additional
1942
// synchronization with the fundingManager to ensure we don't attempt to
1943
// dispatch a message to a channel before it is fully active. A reference to the
1944
// channel this stream forwards to is held in scope to prevent unnecessary
1945
// lookups.
UNCOV
1946
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
×
UNCOV
1947
        var chanLink htlcswitch.ChannelUpdateHandler
×
UNCOV
1948

×
UNCOV
1949
        apply := func(msg lnwire.Message) {
×
UNCOV
1950
                // This check is fine because if the link no longer exists, it will
×
UNCOV
1951
                // be removed from the activeChannels map and subsequent messages
×
UNCOV
1952
                // shouldn't reach the chan msg stream.
×
UNCOV
1953
                if chanLink == nil {
×
UNCOV
1954
                        chanLink = waitUntilLinkActive(p, cid)
×
UNCOV
1955

×
UNCOV
1956
                        // If the link is still not active and the calling function
×
UNCOV
1957
                        // errored out, just return.
×
UNCOV
1958
                        if chanLink == nil {
×
UNCOV
1959
                                p.log.Warnf("Link=%v is not active", cid)
×
UNCOV
1960
                                return
×
UNCOV
1961
                        }
×
1962
                }
1963

1964
                // In order to avoid unnecessarily delivering message
1965
                // as the peer is exiting, we'll check quickly to see
1966
                // if we need to exit.
UNCOV
1967
                select {
×
1968
                case <-p.cg.Done():
×
1969
                        return
×
UNCOV
1970
                default:
×
1971
                }
1972

UNCOV
1973
                chanLink.HandleChannelUpdate(msg)
×
1974
        }
1975

UNCOV
1976
        return newMsgStream(p,
×
UNCOV
1977
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
×
UNCOV
1978
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
×
UNCOV
1979
                msgStreamSize,
×
UNCOV
1980
                apply,
×
UNCOV
1981
        )
×
1982
}
1983

1984
// newDiscMsgStream is used to setup a msgStream between the peer and the
1985
// authenticated gossiper. This stream should be used to forward all remote
1986
// channel announcements.
1987
func newDiscMsgStream(p *Brontide) *msgStream {
3✔
1988
        apply := func(msg lnwire.Message) {
3✔
UNCOV
1989
                // TODO(elle): thread contexts through the peer system properly
×
UNCOV
1990
                // so that a parent context can be passed in here.
×
UNCOV
1991
                ctx := context.TODO()
×
UNCOV
1992

×
UNCOV
1993
                // Processing here means we send it to the gossiper which then
×
UNCOV
1994
                // decides whether this message is processed immediately or
×
UNCOV
1995
                // waits for dependent messages to be processed. It can also
×
UNCOV
1996
                // happen that the message is not processed at all if it is
×
UNCOV
1997
                // premature and the LRU cache fills up and the message is
×
UNCOV
1998
                // deleted.
×
UNCOV
1999
                p.log.Debugf("Processing remote msg %T", msg)
×
UNCOV
2000

×
UNCOV
2001
                // TODO(ziggie): ProcessRemoteAnnouncement returns an error
×
UNCOV
2002
                // channel, but we cannot rely on it being written to.
×
UNCOV
2003
                // Because some messages might never be processed (e.g.
×
UNCOV
2004
                // premature channel updates). We should change the design here
×
UNCOV
2005
                // and use the actor model pattern as soon as it is available.
×
UNCOV
2006
                // So for now we should NOT use the error channel.
×
UNCOV
2007
                // See https://github.com/lightningnetwork/lnd/pull/9820.
×
UNCOV
2008
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(ctx, msg, p)
×
UNCOV
2009
        }
×
2010

2011
        return newMsgStream(
3✔
2012
                p,
3✔
2013
                "Update stream for gossiper created",
3✔
2014
                "Update stream for gossiper exited",
3✔
2015
                msgStreamSize,
3✔
2016
                apply,
3✔
2017
        )
3✔
2018
}
2019

2020
// readHandler is responsible for reading messages off the wire in series, then
2021
// properly dispatching the handling of the message to the proper subsystem.
2022
//
2023
// NOTE: This method MUST be run as a goroutine.
2024
func (p *Brontide) readHandler() {
3✔
2025
        defer p.cg.WgDone()
3✔
2026

3✔
2027
        // We'll stop the timer after a new messages is received, and also
3✔
2028
        // reset it after we process the next message.
3✔
2029
        idleTimer := time.AfterFunc(idleTimeout, func() {
3✔
2030
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
2031
                        p, idleTimeout)
×
2032
                p.Disconnect(err)
×
2033
        })
×
2034

2035
        // Initialize our negotiated gossip sync method before reading messages
2036
        // off the wire. When using gossip queries, this ensures a gossip
2037
        // syncer is active by the time query messages arrive.
2038
        //
2039
        // TODO(conner): have peer store gossip syncer directly and bypass
2040
        // gossiper?
2041
        p.initGossipSync()
3✔
2042

3✔
2043
        discStream := newDiscMsgStream(p)
3✔
2044
        discStream.Start()
3✔
2045
        defer discStream.Stop()
3✔
2046
out:
3✔
2047
        for atomic.LoadInt32(&p.disconnect) == 0 {
7✔
2048
                nextMsg, err := p.readNextMessage()
4✔
2049
                if !idleTimer.Stop() {
4✔
UNCOV
2050
                        select {
×
2051
                        case <-idleTimer.C:
×
UNCOV
2052
                        default:
×
2053
                        }
2054
                }
2055
                if err != nil {
1✔
UNCOV
2056
                        p.log.Infof("unable to read message from peer: %v", err)
×
UNCOV
2057

×
UNCOV
2058
                        // If we could not read our peer's message due to an
×
UNCOV
2059
                        // unknown type or invalid alias, we continue processing
×
UNCOV
2060
                        // as normal. We store unknown message and address
×
UNCOV
2061
                        // types, as they may provide debugging insight.
×
UNCOV
2062
                        switch e := err.(type) {
×
2063
                        // If this is just a message we don't yet recognize,
2064
                        // we'll continue processing as normal as this allows
2065
                        // us to introduce new messages in a forwards
2066
                        // compatible manner.
UNCOV
2067
                        case *lnwire.UnknownMessage:
×
UNCOV
2068
                                p.storeError(e)
×
UNCOV
2069
                                idleTimer.Reset(idleTimeout)
×
UNCOV
2070
                                continue
×
2071

2072
                        // If they sent us an address type that we don't yet
2073
                        // know of, then this isn't a wire error, so we'll
2074
                        // simply continue parsing the remainder of their
2075
                        // messages.
2076
                        case *lnwire.ErrUnknownAddrType:
×
2077
                                p.storeError(e)
×
2078
                                idleTimer.Reset(idleTimeout)
×
2079
                                continue
×
2080

2081
                        // If the NodeAnnouncement has an invalid alias, then
2082
                        // we'll log that error above and continue so we can
2083
                        // continue to read messages from the peer. We do not
2084
                        // store this error because it is of little debugging
2085
                        // value.
2086
                        case *lnwire.ErrInvalidNodeAlias:
×
2087
                                idleTimer.Reset(idleTimeout)
×
2088
                                continue
×
2089

2090
                        // If the error we encountered wasn't just a message we
2091
                        // didn't recognize, then we'll stop all processing as
2092
                        // this is a fatal error.
UNCOV
2093
                        default:
×
UNCOV
2094
                                break out
×
2095
                        }
2096
                }
2097

2098
                // If a message router is active, then we'll try to have it
2099
                // handle this message. If it can, then we're able to skip the
2100
                // rest of the message handling logic.
2101
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
2✔
2102
                        return r.RouteMsg(msgmux.PeerMsg{
1✔
2103
                                PeerPub: *p.IdentityKey(),
1✔
2104
                                Message: nextMsg,
1✔
2105
                        })
1✔
2106
                })
1✔
2107

2108
                // No error occurred, and the message was handled by the
2109
                // router.
2110
                if err == nil {
1✔
UNCOV
2111
                        continue
×
2112
                }
2113

2114
                var (
1✔
2115
                        targetChan   lnwire.ChannelID
1✔
2116
                        isLinkUpdate bool
1✔
2117
                )
1✔
2118

1✔
2119
                switch msg := nextMsg.(type) {
1✔
2120
                case *lnwire.Pong:
×
2121
                        // When we receive a Pong message in response to our
×
2122
                        // last ping message, we send it to the pingManager
×
2123
                        p.pingManager.ReceivedPong(msg)
×
2124

2125
                case *lnwire.Ping:
×
2126
                        // First, we'll store their latest ping payload within
×
2127
                        // the relevant atomic variable.
×
2128
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
2129

×
2130
                        // Next, we'll send over the amount of specified pong
×
2131
                        // bytes.
×
2132
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
×
2133
                        p.queueMsg(pong, nil)
×
2134

2135
                case *lnwire.OpenChannel,
2136
                        *lnwire.AcceptChannel,
2137
                        *lnwire.FundingCreated,
2138
                        *lnwire.FundingSigned,
UNCOV
2139
                        *lnwire.ChannelReady:
×
UNCOV
2140

×
UNCOV
2141
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
×
2142

UNCOV
2143
                case *lnwire.Shutdown:
×
UNCOV
2144
                        select {
×
UNCOV
2145
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
×
2146
                        case <-p.cg.Done():
×
2147
                                break out
×
2148
                        }
UNCOV
2149
                case *lnwire.ClosingSigned:
×
UNCOV
2150
                        select {
×
UNCOV
2151
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
×
2152
                        case <-p.cg.Done():
×
2153
                                break out
×
2154
                        }
2155

2156
                case *lnwire.Warning:
×
2157
                        targetChan = msg.ChanID
×
2158
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2159

UNCOV
2160
                case *lnwire.Error:
×
UNCOV
2161
                        targetChan = msg.ChanID
×
UNCOV
2162
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2163

UNCOV
2164
                case *lnwire.ChannelReestablish:
×
UNCOV
2165
                        targetChan = msg.ChanID
×
UNCOV
2166
                        isLinkUpdate = p.hasChannel(targetChan)
×
UNCOV
2167

×
UNCOV
2168
                        // If we failed to find the link in question, and the
×
UNCOV
2169
                        // message received was a channel sync message, then
×
UNCOV
2170
                        // this might be a peer trying to resync closed channel.
×
UNCOV
2171
                        // In this case we'll try to resend our last channel
×
UNCOV
2172
                        // sync message, such that the peer can recover funds
×
UNCOV
2173
                        // from the closed channel.
×
UNCOV
2174
                        if !isLinkUpdate {
×
UNCOV
2175
                                err := p.resendChanSyncMsg(targetChan)
×
UNCOV
2176
                                if err != nil {
×
UNCOV
2177
                                        // TODO(halseth): send error to peer?
×
UNCOV
2178
                                        p.log.Errorf("resend failed: %v",
×
UNCOV
2179
                                                err)
×
UNCOV
2180
                                }
×
2181
                        }
2182

2183
                // For messages that implement the LinkUpdater interface, we
2184
                // will consider them as link updates and send them to
2185
                // chanStream. These messages will be queued inside chanStream
2186
                // if the channel is not active yet.
UNCOV
2187
                case lnwire.LinkUpdater:
×
UNCOV
2188
                        targetChan = msg.TargetChanID()
×
UNCOV
2189
                        isLinkUpdate = p.hasChannel(targetChan)
×
UNCOV
2190

×
UNCOV
2191
                        // Log an error if we don't have this channel. This
×
UNCOV
2192
                        // means the peer has sent us a message with unknown
×
UNCOV
2193
                        // channel ID.
×
UNCOV
2194
                        if !isLinkUpdate {
×
UNCOV
2195
                                p.log.Errorf("Unknown channel ID: %v found "+
×
UNCOV
2196
                                        "in received msg=%s", targetChan,
×
UNCOV
2197
                                        nextMsg.MsgType())
×
UNCOV
2198
                        }
×
2199

2200
                case *lnwire.ChannelUpdate1,
2201
                        *lnwire.ChannelAnnouncement1,
2202
                        *lnwire.NodeAnnouncement,
2203
                        *lnwire.AnnounceSignatures1,
2204
                        *lnwire.GossipTimestampRange,
2205
                        *lnwire.QueryShortChanIDs,
2206
                        *lnwire.QueryChannelRange,
2207
                        *lnwire.ReplyChannelRange,
UNCOV
2208
                        *lnwire.ReplyShortChanIDsEnd:
×
UNCOV
2209

×
UNCOV
2210
                        discStream.AddMsg(msg)
×
2211

2212
                case *lnwire.Custom:
1✔
2213
                        err := p.handleCustomMessage(msg)
1✔
2214
                        if err != nil {
1✔
2215
                                p.storeError(err)
×
2216
                                p.log.Errorf("%v", err)
×
2217
                        }
×
2218

2219
                default:
×
2220
                        // If the message we received is unknown to us, store
×
2221
                        // the type to track the failure.
×
2222
                        err := fmt.Errorf("unknown message type %v received",
×
2223
                                uint16(msg.MsgType()))
×
2224
                        p.storeError(err)
×
2225

×
2226
                        p.log.Errorf("%v", err)
×
2227
                }
2228

2229
                if isLinkUpdate {
1✔
UNCOV
2230
                        // If this is a channel update, then we need to feed it
×
UNCOV
2231
                        // into the channel's in-order message stream.
×
UNCOV
2232
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
×
UNCOV
2233
                }
×
2234

2235
                idleTimer.Reset(idleTimeout)
1✔
2236
        }
2237

UNCOV
2238
        p.Disconnect(errors.New("read handler closed"))
×
UNCOV
2239

×
UNCOV
2240
        p.log.Trace("readHandler for peer done")
×
2241
}
2242

2243
// handleCustomMessage handles the given custom message if a handler is
2244
// registered.
2245
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
1✔
2246
        if p.cfg.HandleCustomMessage == nil {
1✔
2247
                return fmt.Errorf("no custom message handler for "+
×
2248
                        "message type %v", uint16(msg.MsgType()))
×
2249
        }
×
2250

2251
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
1✔
2252
}
2253

2254
// isLoadedFromDisk returns true if the provided channel ID is loaded from
2255
// disk.
2256
//
2257
// NOTE: only returns true for pending channels.
UNCOV
2258
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
×
UNCOV
2259
        // If this is a newly added channel, no need to reestablish.
×
UNCOV
2260
        _, added := p.addedChannels.Load(chanID)
×
UNCOV
2261
        if added {
×
UNCOV
2262
                return false
×
UNCOV
2263
        }
×
2264

2265
        // Return false if the channel is unknown.
UNCOV
2266
        channel, ok := p.activeChannels.Load(chanID)
×
UNCOV
2267
        if !ok {
×
2268
                return false
×
2269
        }
×
2270

2271
        // During startup, we will use a nil value to mark a pending channel
2272
        // that's loaded from disk.
UNCOV
2273
        return channel == nil
×
2274
}
2275

2276
// isActiveChannel returns true if the provided channel id is active, otherwise
2277
// returns false.
2278
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
8✔
2279
        // The channel would be nil if,
8✔
2280
        // - the channel doesn't exist, or,
8✔
2281
        // - the channel exists, but is pending. In this case, we don't
8✔
2282
        //   consider this channel active.
8✔
2283
        channel, _ := p.activeChannels.Load(chanID)
8✔
2284

8✔
2285
        return channel != nil
8✔
2286
}
8✔
2287

2288
// isPendingChannel returns true if the provided channel ID is pending, and
2289
// returns false if the channel is active or unknown.
2290
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
6✔
2291
        // Return false if the channel is unknown.
6✔
2292
        channel, ok := p.activeChannels.Load(chanID)
6✔
2293
        if !ok {
9✔
2294
                return false
3✔
2295
        }
3✔
2296

2297
        return channel == nil
3✔
2298
}
2299

2300
// hasChannel returns true if the peer has a pending/active channel specified
2301
// by the channel ID.
UNCOV
2302
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
×
UNCOV
2303
        _, ok := p.activeChannels.Load(chanID)
×
UNCOV
2304
        return ok
×
UNCOV
2305
}
×
2306

2307
// storeError stores an error in our peer's buffer of recent errors with the
2308
// current timestamp. Errors are only stored if we have at least one active
2309
// channel with the peer to mitigate a dos vector where a peer costlessly
2310
// connects to us and spams us with errors.
UNCOV
2311
func (p *Brontide) storeError(err error) {
×
UNCOV
2312
        var haveChannels bool
×
UNCOV
2313

×
UNCOV
2314
        p.activeChannels.Range(func(_ lnwire.ChannelID,
×
UNCOV
2315
                channel *lnwallet.LightningChannel) bool {
×
UNCOV
2316

×
UNCOV
2317
                // Pending channels will be nil in the activeChannels map.
×
UNCOV
2318
                if channel == nil {
×
UNCOV
2319
                        // Return true to continue the iteration.
×
UNCOV
2320
                        return true
×
UNCOV
2321
                }
×
2322

UNCOV
2323
                haveChannels = true
×
UNCOV
2324

×
UNCOV
2325
                // Return false to break the iteration.
×
UNCOV
2326
                return false
×
2327
        })
2328

2329
        // If we do not have any active channels with the peer, we do not store
2330
        // errors as a dos mitigation.
UNCOV
2331
        if !haveChannels {
×
UNCOV
2332
                p.log.Trace("no channels with peer, not storing err")
×
UNCOV
2333
                return
×
UNCOV
2334
        }
×
2335

UNCOV
2336
        p.cfg.ErrorBuffer.Add(
×
UNCOV
2337
                &TimestampedError{Timestamp: time.Now(), Error: err},
×
UNCOV
2338
        )
×
2339
}
2340

2341
// handleWarningOrError processes a warning or error msg and returns true if
2342
// msg should be forwarded to the associated channel link. False is returned if
2343
// any necessary forwarding of msg was already handled by this method. If msg is
2344
// an error from a peer with an active channel, we'll store it in memory.
2345
//
2346
// NOTE: This method should only be called from within the readHandler.
2347
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
UNCOV
2348
        msg lnwire.Message) bool {
×
UNCOV
2349

×
UNCOV
2350
        if errMsg, ok := msg.(*lnwire.Error); ok {
×
UNCOV
2351
                p.storeError(errMsg)
×
UNCOV
2352
        }
×
2353

UNCOV
2354
        switch {
×
2355
        // Connection wide messages should be forwarded to all channel links
2356
        // with this peer.
2357
        case chanID == lnwire.ConnectionWideID:
×
2358
                for _, chanStream := range p.activeMsgStreams {
×
2359
                        chanStream.AddMsg(msg)
×
2360
                }
×
2361

2362
                return false
×
2363

2364
        // If the channel ID for the message corresponds to a pending channel,
2365
        // then the funding manager will handle it.
UNCOV
2366
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
×
UNCOV
2367
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
×
UNCOV
2368
                return false
×
2369

2370
        // If not we hand the message to the channel link for this channel.
UNCOV
2371
        case p.isActiveChannel(chanID):
×
UNCOV
2372
                return true
×
2373

UNCOV
2374
        default:
×
UNCOV
2375
                return false
×
2376
        }
2377
}
2378

2379
// messageSummary returns a human-readable string that summarizes a
2380
// incoming/outgoing message. Not all messages will have a summary, only those
2381
// which have additional data that can be informative at a glance.
UNCOV
2382
func messageSummary(msg lnwire.Message) string {
×
UNCOV
2383
        switch msg := msg.(type) {
×
UNCOV
2384
        case *lnwire.Init:
×
UNCOV
2385
                // No summary.
×
UNCOV
2386
                return ""
×
2387

UNCOV
2388
        case *lnwire.OpenChannel:
×
UNCOV
2389
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
×
UNCOV
2390
                        "push_amt=%v, reserve=%v, flags=%v",
×
UNCOV
2391
                        msg.PendingChannelID[:], msg.ChainHash,
×
UNCOV
2392
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
×
UNCOV
2393
                        msg.ChannelReserve, msg.ChannelFlags)
×
2394

UNCOV
2395
        case *lnwire.AcceptChannel:
×
UNCOV
2396
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
×
UNCOV
2397
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
×
UNCOV
2398
                        msg.MinAcceptDepth)
×
2399

UNCOV
2400
        case *lnwire.FundingCreated:
×
UNCOV
2401
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
×
UNCOV
2402
                        msg.PendingChannelID[:], msg.FundingPoint)
×
2403

UNCOV
2404
        case *lnwire.FundingSigned:
×
UNCOV
2405
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
×
2406

UNCOV
2407
        case *lnwire.ChannelReady:
×
UNCOV
2408
                return fmt.Sprintf("chan_id=%v, next_point=%x",
×
UNCOV
2409
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
×
2410

UNCOV
2411
        case *lnwire.Shutdown:
×
UNCOV
2412
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
×
UNCOV
2413
                        msg.Address[:])
×
2414

UNCOV
2415
        case *lnwire.ClosingComplete:
×
UNCOV
2416
                return fmt.Sprintf("chan_id=%v, fee_sat=%v, locktime=%v",
×
UNCOV
2417
                        msg.ChannelID, msg.FeeSatoshis, msg.LockTime)
×
2418

UNCOV
2419
        case *lnwire.ClosingSig:
×
UNCOV
2420
                return fmt.Sprintf("chan_id=%v", msg.ChannelID)
×
2421

UNCOV
2422
        case *lnwire.ClosingSigned:
×
UNCOV
2423
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
×
UNCOV
2424
                        msg.FeeSatoshis)
×
2425

UNCOV
2426
        case *lnwire.UpdateAddHTLC:
×
UNCOV
2427
                var blindingPoint []byte
×
UNCOV
2428
                msg.BlindingPoint.WhenSome(
×
UNCOV
2429
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
×
UNCOV
2430
                                *btcec.PublicKey]) {
×
UNCOV
2431

×
UNCOV
2432
                                blindingPoint = b.Val.SerializeCompressed()
×
UNCOV
2433
                        },
×
2434
                )
2435

UNCOV
2436
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
×
UNCOV
2437
                        "hash=%x, blinding_point=%x, custom_records=%v",
×
UNCOV
2438
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
×
UNCOV
2439
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
×
2440

UNCOV
2441
        case *lnwire.UpdateFailHTLC:
×
UNCOV
2442
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
×
UNCOV
2443
                        msg.ID, msg.Reason)
×
2444

UNCOV
2445
        case *lnwire.UpdateFulfillHTLC:
×
UNCOV
2446
                return fmt.Sprintf("chan_id=%v, id=%v, preimage=%x, "+
×
UNCOV
2447
                        "custom_records=%v", msg.ChanID, msg.ID,
×
UNCOV
2448
                        msg.PaymentPreimage[:], msg.CustomRecords)
×
2449

UNCOV
2450
        case *lnwire.CommitSig:
×
UNCOV
2451
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
×
UNCOV
2452
                        len(msg.HtlcSigs))
×
2453

UNCOV
2454
        case *lnwire.RevokeAndAck:
×
UNCOV
2455
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
×
UNCOV
2456
                        msg.ChanID, msg.Revocation[:],
×
UNCOV
2457
                        msg.NextRevocationKey.SerializeCompressed())
×
2458

UNCOV
2459
        case *lnwire.UpdateFailMalformedHTLC:
×
UNCOV
2460
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
×
UNCOV
2461
                        msg.ChanID, msg.ID, msg.FailureCode)
×
2462

2463
        case *lnwire.Warning:
×
2464
                return fmt.Sprintf("%v", msg.Warning())
×
2465

UNCOV
2466
        case *lnwire.Error:
×
UNCOV
2467
                return fmt.Sprintf("%v", msg.Error())
×
2468

UNCOV
2469
        case *lnwire.AnnounceSignatures1:
×
UNCOV
2470
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
×
UNCOV
2471
                        msg.ShortChannelID.ToUint64())
×
2472

UNCOV
2473
        case *lnwire.ChannelAnnouncement1:
×
UNCOV
2474
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
×
UNCOV
2475
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
×
2476

UNCOV
2477
        case *lnwire.ChannelUpdate1:
×
UNCOV
2478
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
×
UNCOV
2479
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
×
UNCOV
2480
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
×
UNCOV
2481
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
×
2482

UNCOV
2483
        case *lnwire.NodeAnnouncement:
×
UNCOV
2484
                return fmt.Sprintf("node=%x, update_time=%v",
×
UNCOV
2485
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
×
2486

2487
        case *lnwire.Ping:
×
2488
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
2489

2490
        case *lnwire.Pong:
×
2491
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
×
2492

2493
        case *lnwire.UpdateFee:
×
2494
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2495
                        msg.ChanID, int64(msg.FeePerKw))
×
2496

UNCOV
2497
        case *lnwire.ChannelReestablish:
×
UNCOV
2498
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
×
UNCOV
2499
                        "remote_tail_height=%v", msg.ChanID,
×
UNCOV
2500
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
×
2501

UNCOV
2502
        case *lnwire.ReplyShortChanIDsEnd:
×
UNCOV
2503
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
×
UNCOV
2504
                        msg.Complete)
×
2505

UNCOV
2506
        case *lnwire.ReplyChannelRange:
×
UNCOV
2507
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
×
UNCOV
2508
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
×
UNCOV
2509
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
×
UNCOV
2510
                        msg.EncodingType)
×
2511

UNCOV
2512
        case *lnwire.QueryShortChanIDs:
×
UNCOV
2513
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
×
UNCOV
2514
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
×
2515

UNCOV
2516
        case *lnwire.QueryChannelRange:
×
UNCOV
2517
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
×
UNCOV
2518
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
×
UNCOV
2519
                        msg.LastBlockHeight())
×
2520

UNCOV
2521
        case *lnwire.GossipTimestampRange:
×
UNCOV
2522
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
×
UNCOV
2523
                        "stamp_range=%v", msg.ChainHash,
×
UNCOV
2524
                        time.Unix(int64(msg.FirstTimestamp), 0),
×
UNCOV
2525
                        msg.TimestampRange)
×
2526

UNCOV
2527
        case *lnwire.Stfu:
×
UNCOV
2528
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
×
UNCOV
2529
                        msg.Initiator)
×
2530

UNCOV
2531
        case *lnwire.Custom:
×
UNCOV
2532
                return fmt.Sprintf("type=%d", msg.Type)
×
2533
        }
2534

2535
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2536
}
2537

2538
// logWireMessage logs the receipt or sending of particular wire message. This
2539
// function is used rather than just logging the message in order to produce
2540
// less spammy log messages in trace mode by setting the 'Curve" parameter to
2541
// nil. Doing this avoids printing out each of the field elements in the curve
2542
// parameters for secp256k1.
2543
func (p *Brontide) logWireMessage(msg lnwire.Message, read bool) {
17✔
2544
        summaryPrefix := "Received"
17✔
2545
        if !read {
30✔
2546
                summaryPrefix = "Sending"
13✔
2547
        }
13✔
2548

2549
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
17✔
UNCOV
2550
                // Debug summary of message.
×
UNCOV
2551
                summary := messageSummary(msg)
×
UNCOV
2552
                if len(summary) > 0 {
×
UNCOV
2553
                        summary = "(" + summary + ")"
×
UNCOV
2554
                }
×
2555

UNCOV
2556
                preposition := "to"
×
UNCOV
2557
                if read {
×
UNCOV
2558
                        preposition = "from"
×
UNCOV
2559
                }
×
2560

UNCOV
2561
                var msgType string
×
UNCOV
2562
                if msg.MsgType() < lnwire.CustomTypeStart {
×
UNCOV
2563
                        msgType = msg.MsgType().String()
×
UNCOV
2564
                } else {
×
UNCOV
2565
                        msgType = "custom"
×
UNCOV
2566
                }
×
2567

UNCOV
2568
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
×
UNCOV
2569
                        msgType, summary, preposition, p)
×
2570
        }))
2571

2572
        prefix := "readMessage from peer"
17✔
2573
        if !read {
30✔
2574
                prefix = "writeMessage to peer"
13✔
2575
        }
13✔
2576

2577
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
17✔
2578
}
2579

2580
// writeMessage writes and flushes the target lnwire.Message to the remote peer.
2581
// If the passed message is nil, this method will only try to flush an existing
2582
// message buffered on the connection. It is safe to call this method again
2583
// with a nil message iff a timeout error is returned. This will continue to
2584
// flush the pending message to the wire.
2585
//
2586
// NOTE:
2587
// Besides its usage in Start, this function should not be used elsewhere
2588
// except in writeHandler. If multiple goroutines call writeMessage at the same
2589
// time, panics can occur because WriteMessage and Flush don't use any locking
2590
// internally.
2591
func (p *Brontide) writeMessage(msg lnwire.Message) error {
13✔
2592
        // Only log the message on the first attempt.
13✔
2593
        if msg != nil {
26✔
2594
                p.logWireMessage(msg, false)
13✔
2595
        }
13✔
2596

2597
        noiseConn := p.cfg.Conn
13✔
2598

13✔
2599
        flushMsg := func() error {
26✔
2600
                // Ensure the write deadline is set before we attempt to send
13✔
2601
                // the message.
13✔
2602
                writeDeadline := time.Now().Add(
13✔
2603
                        p.scaleTimeout(writeMessageTimeout),
13✔
2604
                )
13✔
2605
                err := noiseConn.SetWriteDeadline(writeDeadline)
13✔
2606
                if err != nil {
13✔
2607
                        return err
×
2608
                }
×
2609

2610
                // Flush the pending message to the wire. If an error is
2611
                // encountered, e.g. write timeout, the number of bytes written
2612
                // so far will be returned.
2613
                n, err := noiseConn.Flush()
13✔
2614

13✔
2615
                // Record the number of bytes written on the wire, if any.
13✔
2616
                if n > 0 {
13✔
UNCOV
2617
                        atomic.AddUint64(&p.bytesSent, uint64(n))
×
UNCOV
2618
                }
×
2619

2620
                return err
13✔
2621
        }
2622

2623
        // If the current message has already been serialized, encrypted, and
2624
        // buffered on the underlying connection we will skip straight to
2625
        // flushing it to the wire.
2626
        if msg == nil {
13✔
2627
                return flushMsg()
×
2628
        }
×
2629

2630
        // Otherwise, this is a new message. We'll acquire a write buffer to
2631
        // serialize the message and buffer the ciphertext on the connection.
2632
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
26✔
2633
                // Using a buffer allocated by the write pool, encode the
13✔
2634
                // message directly into the buffer.
13✔
2635
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
13✔
2636
                if writeErr != nil {
13✔
2637
                        return writeErr
×
2638
                }
×
2639

2640
                // Finally, write the message itself in a single swoop. This
2641
                // will buffer the ciphertext on the underlying connection. We
2642
                // will defer flushing the message until the write pool has been
2643
                // released.
2644
                return noiseConn.WriteMessage(buf.Bytes())
13✔
2645
        })
2646
        if err != nil {
13✔
2647
                return err
×
2648
        }
×
2649

2650
        return flushMsg()
13✔
2651
}
2652

2653
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2654
// queue, and writing them out to the wire. This goroutine coordinates with the
2655
// queueHandler in order to ensure the incoming message queue is quickly
2656
// drained.
2657
//
2658
// NOTE: This method MUST be run as a goroutine.
2659
func (p *Brontide) writeHandler() {
3✔
2660
        // We'll stop the timer after a new messages is sent, and also reset it
3✔
2661
        // after we process the next message.
3✔
2662
        idleTimer := time.AfterFunc(idleTimeout, func() {
3✔
2663
                err := fmt.Errorf("peer %s no write for %s -- disconnecting",
×
2664
                        p, idleTimeout)
×
2665
                p.Disconnect(err)
×
2666
        })
×
2667

2668
        var exitErr error
3✔
2669

3✔
2670
out:
3✔
2671
        for {
10✔
2672
                select {
7✔
2673
                case outMsg := <-p.sendQueue:
4✔
2674
                        // Record the time at which we first attempt to send the
4✔
2675
                        // message.
4✔
2676
                        startTime := time.Now()
4✔
2677

4✔
2678
                retry:
4✔
2679
                        // Write out the message to the socket. If a timeout
2680
                        // error is encountered, we will catch this and retry
2681
                        // after backing off in case the remote peer is just
2682
                        // slow to process messages from the wire.
2683
                        err := p.writeMessage(outMsg.msg)
4✔
2684
                        if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
4✔
2685
                                p.log.Debugf("Write timeout detected for "+
×
2686
                                        "peer, first write for message "+
×
2687
                                        "attempted %v ago",
×
2688
                                        time.Since(startTime))
×
2689

×
2690
                                // If we received a timeout error, this implies
×
2691
                                // that the message was buffered on the
×
2692
                                // connection successfully and that a flush was
×
2693
                                // attempted. We'll set the message to nil so
×
2694
                                // that on a subsequent pass we only try to
×
2695
                                // flush the buffered message, and forgo
×
2696
                                // reserializing or reencrypting it.
×
2697
                                outMsg.msg = nil
×
2698

×
2699
                                goto retry
×
2700
                        }
2701

2702
                        // The write succeeded, reset the idle timer to prevent
2703
                        // us from disconnecting the peer.
2704
                        if !idleTimer.Stop() {
4✔
2705
                                select {
×
2706
                                case <-idleTimer.C:
×
2707
                                default:
×
2708
                                }
2709
                        }
2710
                        idleTimer.Reset(idleTimeout)
4✔
2711

4✔
2712
                        // If the peer requested a synchronous write, respond
4✔
2713
                        // with the error.
4✔
2714
                        if outMsg.errChan != nil {
5✔
2715
                                outMsg.errChan <- err
1✔
2716
                        }
1✔
2717

2718
                        if err != nil {
4✔
2719
                                exitErr = fmt.Errorf("unable to write "+
×
2720
                                        "message: %v", err)
×
2721
                                break out
×
2722
                        }
2723

UNCOV
2724
                case <-p.cg.Done():
×
UNCOV
2725
                        exitErr = lnpeer.ErrPeerExiting
×
UNCOV
2726
                        break out
×
2727
                }
2728
        }
2729

2730
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2731
        // disconnect.
UNCOV
2732
        p.cg.WgDone()
×
UNCOV
2733

×
UNCOV
2734
        p.Disconnect(exitErr)
×
UNCOV
2735

×
UNCOV
2736
        p.log.Trace("writeHandler for peer done")
×
2737
}
2738

2739
// queueHandler is responsible for accepting messages from outside subsystems
2740
// to be eventually sent out on the wire by the writeHandler.
2741
//
2742
// NOTE: This method MUST be run as a goroutine.
2743
func (p *Brontide) queueHandler() {
3✔
2744
        defer p.cg.WgDone()
3✔
2745

3✔
2746
        // priorityMsgs holds an in order list of messages deemed high-priority
3✔
2747
        // to be added to the sendQueue. This predominately includes messages
3✔
2748
        // from the funding manager and htlcswitch.
3✔
2749
        priorityMsgs := list.New()
3✔
2750

3✔
2751
        // lazyMsgs holds an in order list of messages deemed low-priority to be
3✔
2752
        // added to the sendQueue only after all high-priority messages have
3✔
2753
        // been queued. This predominately includes messages from the gossiper.
3✔
2754
        lazyMsgs := list.New()
3✔
2755

3✔
2756
        for {
14✔
2757
                // Examine the front of the priority queue, if it is empty check
11✔
2758
                // the low priority queue.
11✔
2759
                elem := priorityMsgs.Front()
11✔
2760
                if elem == nil {
19✔
2761
                        elem = lazyMsgs.Front()
8✔
2762
                }
8✔
2763

2764
                if elem != nil {
15✔
2765
                        front := elem.Value.(outgoingMsg)
4✔
2766

4✔
2767
                        // There's an element on the queue, try adding
4✔
2768
                        // it to the sendQueue. We also watch for
4✔
2769
                        // messages on the outgoingQueue, in case the
4✔
2770
                        // writeHandler cannot accept messages on the
4✔
2771
                        // sendQueue.
4✔
2772
                        select {
4✔
2773
                        case p.sendQueue <- front:
4✔
2774
                                if front.priority {
7✔
2775
                                        priorityMsgs.Remove(elem)
3✔
2776
                                } else {
4✔
2777
                                        lazyMsgs.Remove(elem)
1✔
2778
                                }
1✔
UNCOV
2779
                        case msg := <-p.outgoingQueue:
×
UNCOV
2780
                                if msg.priority {
×
UNCOV
2781
                                        priorityMsgs.PushBack(msg)
×
UNCOV
2782
                                } else {
×
UNCOV
2783
                                        lazyMsgs.PushBack(msg)
×
UNCOV
2784
                                }
×
2785
                        case <-p.cg.Done():
×
2786
                                return
×
2787
                        }
2788
                } else {
7✔
2789
                        // If there weren't any messages to send to the
7✔
2790
                        // writeHandler, then we'll accept a new message
7✔
2791
                        // into the queue from outside sub-systems.
7✔
2792
                        select {
7✔
2793
                        case msg := <-p.outgoingQueue:
4✔
2794
                                if msg.priority {
7✔
2795
                                        priorityMsgs.PushBack(msg)
3✔
2796
                                } else {
4✔
2797
                                        lazyMsgs.PushBack(msg)
1✔
2798
                                }
1✔
UNCOV
2799
                        case <-p.cg.Done():
×
UNCOV
2800
                                return
×
2801
                        }
2802
                }
2803
        }
2804
}
2805

2806
// PingTime returns the estimated ping time to the peer in microseconds.
UNCOV
2807
func (p *Brontide) PingTime() int64 {
×
UNCOV
2808
        return p.pingManager.GetPingTimeMicroSeconds()
×
UNCOV
2809
}
×
2810

2811
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2812
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2813
// or failed to write, and nil otherwise.
2814
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
25✔
2815
        p.queue(true, msg, errChan)
25✔
2816
}
25✔
2817

2818
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2819
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2820
// queue or failed to write, and nil otherwise.
2821
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
1✔
2822
        p.queue(false, msg, errChan)
1✔
2823
}
1✔
2824

2825
// queue sends a given message to the queueHandler using the passed priority. If
2826
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2827
// failed to write, and nil otherwise.
2828
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2829
        errChan chan error) {
26✔
2830

26✔
2831
        select {
26✔
2832
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
25✔
2833
        case <-p.cg.Done():
×
2834
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
×
2835
                        spew.Sdump(msg))
×
2836
                if errChan != nil {
×
2837
                        errChan <- lnpeer.ErrPeerExiting
×
2838
                }
×
2839
        }
2840
}
2841

2842
// ChannelSnapshots returns a slice of channel snapshots detailing all
2843
// currently active channels maintained with the remote peer.
UNCOV
2844
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
×
UNCOV
2845
        snapshots := make(
×
UNCOV
2846
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
×
UNCOV
2847
        )
×
UNCOV
2848

×
UNCOV
2849
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
×
UNCOV
2850
                activeChan *lnwallet.LightningChannel) error {
×
UNCOV
2851

×
UNCOV
2852
                // If the activeChan is nil, then we skip it as the channel is
×
UNCOV
2853
                // pending.
×
UNCOV
2854
                if activeChan == nil {
×
UNCOV
2855
                        return nil
×
UNCOV
2856
                }
×
2857

2858
                // We'll only return a snapshot for channels that are
2859
                // *immediately* available for routing payments over.
UNCOV
2860
                if activeChan.RemoteNextRevocation() == nil {
×
UNCOV
2861
                        return nil
×
UNCOV
2862
                }
×
2863

UNCOV
2864
                snapshot := activeChan.StateSnapshot()
×
UNCOV
2865
                snapshots = append(snapshots, snapshot)
×
UNCOV
2866

×
UNCOV
2867
                return nil
×
2868
        })
2869

UNCOV
2870
        return snapshots
×
2871
}
2872

2873
// genDeliveryScript returns a new script to be used to send our funds to in
2874
// the case of a cooperative channel close negotiation.
2875
func (p *Brontide) genDeliveryScript() ([]byte, error) {
6✔
2876
        // We'll send a normal p2wkh address unless we've negotiated the
6✔
2877
        // shutdown-any-segwit feature.
6✔
2878
        addrType := lnwallet.WitnessPubKey
6✔
2879
        if p.taprootShutdownAllowed() {
6✔
UNCOV
2880
                addrType = lnwallet.TaprootPubkey
×
UNCOV
2881
        }
×
2882

2883
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
6✔
2884
                addrType, false, lnwallet.DefaultAccountName,
6✔
2885
        )
6✔
2886
        if err != nil {
6✔
2887
                return nil, err
×
2888
        }
×
2889
        p.log.Infof("Delivery addr for channel close: %v",
6✔
2890
                deliveryAddr)
6✔
2891

6✔
2892
        return txscript.PayToAddrScript(deliveryAddr)
6✔
2893
}
2894

2895
// channelManager is goroutine dedicated to handling all requests/signals
2896
// pertaining to the opening, cooperative closing, and force closing of all
2897
// channels maintained with the remote peer.
2898
//
2899
// NOTE: This method MUST be run as a goroutine.
2900
func (p *Brontide) channelManager() {
17✔
2901
        defer p.cg.WgDone()
17✔
2902

17✔
2903
        // reenableTimeout will fire once after the configured channel status
17✔
2904
        // interval has elapsed. This will trigger us to sign new channel
17✔
2905
        // updates and broadcast them with the "disabled" flag unset.
17✔
2906
        reenableTimeout := time.After(p.cfg.ChanActiveTimeout)
17✔
2907

17✔
2908
out:
17✔
2909
        for {
55✔
2910
                select {
38✔
2911
                // A new pending channel has arrived which means we are about
2912
                // to complete a funding workflow and is waiting for the final
2913
                // `ChannelReady` messages to be exchanged. We will add this
2914
                // channel to the `activeChannels` with a nil value to indicate
2915
                // this is a pending channel.
2916
                case req := <-p.newPendingChannel:
1✔
2917
                        p.handleNewPendingChannel(req)
1✔
2918

2919
                // A new channel has arrived which means we've just completed a
2920
                // funding workflow. We'll initialize the necessary local
2921
                // state, and notify the htlc switch of a new link.
UNCOV
2922
                case req := <-p.newActiveChannel:
×
UNCOV
2923
                        p.handleNewActiveChannel(req)
×
2924

2925
                // The funding flow for a pending channel is failed, we will
2926
                // remove it from Brontide.
2927
                case req := <-p.removePendingChannel:
1✔
2928
                        p.handleRemovePendingChannel(req)
1✔
2929

2930
                // We've just received a local request to close an active
2931
                // channel. It will either kick of a cooperative channel
2932
                // closure negotiation, or be a notification of a breached
2933
                // contract that should be abandoned.
2934
                case req := <-p.localCloseChanReqs:
7✔
2935
                        p.handleLocalCloseReq(req)
7✔
2936

2937
                // We've received a link failure from a link that was added to
2938
                // the switch. This will initiate the teardown of the link, and
2939
                // initiate any on-chain closures if necessary.
UNCOV
2940
                case failure := <-p.linkFailures:
×
UNCOV
2941
                        p.handleLinkFailure(failure)
×
2942

2943
                // We've received a new cooperative channel closure related
2944
                // message from the remote peer, we'll use this message to
2945
                // advance the chan closer state machine.
2946
                case closeMsg := <-p.chanCloseMsgs:
13✔
2947
                        p.handleCloseMsg(closeMsg)
13✔
2948

2949
                // The channel reannounce delay has elapsed, broadcast the
2950
                // reenabled channel updates to the network. This should only
2951
                // fire once, so we set the reenableTimeout channel to nil to
2952
                // mark it for garbage collection. If the peer is torn down
2953
                // before firing, reenabling will not be attempted.
2954
                // TODO(conner): consolidate reenables timers inside chan status
2955
                // manager
UNCOV
2956
                case <-reenableTimeout:
×
UNCOV
2957
                        p.reenableActiveChannels()
×
UNCOV
2958

×
UNCOV
2959
                        // Since this channel will never fire again during the
×
UNCOV
2960
                        // lifecycle of the peer, we nil the channel to mark it
×
UNCOV
2961
                        // eligible for garbage collection, and make this
×
UNCOV
2962
                        // explicitly ineligible to receive in future calls to
×
UNCOV
2963
                        // select. This also shaves a few CPU cycles since the
×
UNCOV
2964
                        // select will ignore this case entirely.
×
UNCOV
2965
                        reenableTimeout = nil
×
UNCOV
2966

×
UNCOV
2967
                        // Once the reenabling is attempted, we also cancel the
×
UNCOV
2968
                        // channel event subscription to free up the overflow
×
UNCOV
2969
                        // queue used in channel notifier.
×
UNCOV
2970
                        //
×
UNCOV
2971
                        // NOTE: channelEventClient will be nil if the
×
UNCOV
2972
                        // reenableTimeout is greater than 1 minute.
×
UNCOV
2973
                        if p.channelEventClient != nil {
×
UNCOV
2974
                                p.channelEventClient.Cancel()
×
UNCOV
2975
                        }
×
2976

UNCOV
2977
                case <-p.cg.Done():
×
UNCOV
2978
                        // As, we've been signalled to exit, we'll reset all
×
UNCOV
2979
                        // our active channel back to their default state.
×
UNCOV
2980
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
×
UNCOV
2981
                                lc *lnwallet.LightningChannel) error {
×
UNCOV
2982

×
UNCOV
2983
                                // Exit if the channel is nil as it's a pending
×
UNCOV
2984
                                // channel.
×
UNCOV
2985
                                if lc == nil {
×
UNCOV
2986
                                        return nil
×
UNCOV
2987
                                }
×
2988

UNCOV
2989
                                lc.ResetState()
×
UNCOV
2990

×
UNCOV
2991
                                return nil
×
2992
                        })
2993

UNCOV
2994
                        break out
×
2995
                }
2996
        }
2997
}
2998

2999
// reenableActiveChannels searches the index of channels maintained with this
3000
// peer, and reenables each public, non-pending channel. This is done at the
3001
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
3002
// No message will be sent if the channel is already enabled.
UNCOV
3003
func (p *Brontide) reenableActiveChannels() {
×
UNCOV
3004
        // First, filter all known channels with this peer for ones that are
×
UNCOV
3005
        // both public and not pending.
×
UNCOV
3006
        activePublicChans := p.filterChannelsToEnable()
×
UNCOV
3007

×
UNCOV
3008
        // Create a map to hold channels that needs to be retried.
×
UNCOV
3009
        retryChans := make(map[wire.OutPoint]struct{}, len(activePublicChans))
×
UNCOV
3010

×
UNCOV
3011
        // For each of the public, non-pending channels, set the channel
×
UNCOV
3012
        // disabled bit to false and send out a new ChannelUpdate. If this
×
UNCOV
3013
        // channel is already active, the update won't be sent.
×
UNCOV
3014
        for _, chanPoint := range activePublicChans {
×
UNCOV
3015
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
UNCOV
3016

×
UNCOV
3017
                switch {
×
3018
                // No error occurred, continue to request the next channel.
UNCOV
3019
                case err == nil:
×
UNCOV
3020
                        continue
×
3021

3022
                // Cannot auto enable a manually disabled channel so we do
3023
                // nothing but proceed to the next channel.
UNCOV
3024
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
×
UNCOV
3025
                        p.log.Debugf("Channel(%v) was manually disabled, "+
×
UNCOV
3026
                                "ignoring automatic enable request", chanPoint)
×
UNCOV
3027

×
UNCOV
3028
                        continue
×
3029

3030
                // If the channel is reported as inactive, we will give it
3031
                // another chance. When handling the request, ChanStatusManager
3032
                // will check whether the link is active or not. One of the
3033
                // conditions is whether the link has been marked as
3034
                // reestablished, which happens inside a goroutine(htlcManager)
3035
                // after the link is started. And we may get a false negative
3036
                // saying the link is not active because that goroutine hasn't
3037
                // reached the line to mark the reestablishment. Thus we give
3038
                // it a second chance to send the request.
3039
                case errors.Is(err, netann.ErrEnableInactiveChan):
×
3040
                        // If we don't have a client created, it means we
×
3041
                        // shouldn't retry enabling the channel.
×
3042
                        if p.channelEventClient == nil {
×
3043
                                p.log.Errorf("Channel(%v) request enabling "+
×
3044
                                        "failed due to inactive link",
×
3045
                                        chanPoint)
×
3046

×
3047
                                continue
×
3048
                        }
3049

3050
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
3051
                                "ChanStatusManager reported inactive, retrying")
×
3052

×
3053
                        // Add the channel to the retry map.
×
3054
                        retryChans[chanPoint] = struct{}{}
×
3055
                }
3056
        }
3057

3058
        // Retry the channels if we have any.
UNCOV
3059
        if len(retryChans) != 0 {
×
3060
                p.retryRequestEnable(retryChans)
×
3061
        }
×
3062
}
3063

3064
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
3065
// for the target channel ID. If the channel isn't active an error is returned.
3066
// Otherwise, either an existing state machine will be returned, or a new one
3067
// will be created.
3068
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
3069
        *chanCloserFsm, error) {
13✔
3070

13✔
3071
        chanCloser, found := p.activeChanCloses.Load(chanID)
13✔
3072
        if found {
23✔
3073
                // An entry will only be found if the closer has already been
10✔
3074
                // created for a non-pending channel or for a channel that had
10✔
3075
                // previously started the shutdown process but the connection
10✔
3076
                // was restarted.
10✔
3077
                return &chanCloser, nil
10✔
3078
        }
10✔
3079

3080
        // First, we'll ensure that we actually know of the target channel. If
3081
        // not, we'll ignore this message.
3082
        channel, ok := p.activeChannels.Load(chanID)
3✔
3083

3✔
3084
        // If the channel isn't in the map or the channel is nil, return
3✔
3085
        // ErrChannelNotFound as the channel is pending.
3✔
3086
        if !ok || channel == nil {
3✔
UNCOV
3087
                return nil, ErrChannelNotFound
×
UNCOV
3088
        }
×
3089

3090
        // We'll create a valid closing state machine in order to respond to
3091
        // the initiated cooperative channel closure. First, we set the
3092
        // delivery script that our funds will be paid out to. If an upfront
3093
        // shutdown script was set, we will use it. Otherwise, we get a fresh
3094
        // delivery script.
3095
        //
3096
        // TODO: Expose option to allow upfront shutdown script from watch-only
3097
        // accounts.
3098
        deliveryScript := channel.LocalUpfrontShutdownScript()
3✔
3099
        if len(deliveryScript) == 0 {
6✔
3100
                var err error
3✔
3101
                deliveryScript, err = p.genDeliveryScript()
3✔
3102
                if err != nil {
3✔
3103
                        p.log.Errorf("unable to gen delivery script: %v",
×
3104
                                err)
×
3105
                        return nil, fmt.Errorf("close addr unavailable")
×
3106
                }
×
3107
        }
3108

3109
        // In order to begin fee negotiations, we'll first compute our target
3110
        // ideal fee-per-kw.
3111
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
3112
                p.cfg.CoopCloseTargetConfs,
3✔
3113
        )
3✔
3114
        if err != nil {
3✔
3115
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3116
                return nil, fmt.Errorf("unable to estimate fee")
×
3117
        }
×
3118

3119
        addr, err := p.addrWithInternalKey(deliveryScript)
3✔
3120
        if err != nil {
3✔
3121
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3122
        }
×
3123
        negotiateChanCloser, err := p.createChanCloser(
3✔
3124
                channel, addr, feePerKw, nil, lntypes.Remote,
3✔
3125
        )
3✔
3126
        if err != nil {
3✔
3127
                p.log.Errorf("unable to create chan closer: %v", err)
×
3128
                return nil, fmt.Errorf("unable to create chan closer")
×
3129
        }
×
3130

3131
        chanCloser = makeNegotiateCloser(negotiateChanCloser)
3✔
3132

3✔
3133
        p.activeChanCloses.Store(chanID, chanCloser)
3✔
3134

3✔
3135
        return &chanCloser, nil
3✔
3136
}
3137

3138
// filterChannelsToEnable filters a list of channels to be enabled upon start.
3139
// The filtered channels are active channels that's neither private nor
3140
// pending.
UNCOV
3141
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
×
UNCOV
3142
        var activePublicChans []wire.OutPoint
×
UNCOV
3143

×
UNCOV
3144
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
×
UNCOV
3145
                lnChan *lnwallet.LightningChannel) bool {
×
UNCOV
3146

×
UNCOV
3147
                // If the lnChan is nil, continue as this is a pending channel.
×
UNCOV
3148
                if lnChan == nil {
×
UNCOV
3149
                        return true
×
UNCOV
3150
                }
×
3151

UNCOV
3152
                dbChan := lnChan.State()
×
UNCOV
3153
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
×
UNCOV
3154
                if !isPublic || dbChan.IsPending {
×
3155
                        return true
×
3156
                }
×
3157

3158
                // We'll also skip any channels added during this peer's
3159
                // lifecycle since they haven't waited out the timeout. Their
3160
                // first announcement will be enabled, and the chan status
3161
                // manager will begin monitoring them passively since they exist
3162
                // in the database.
UNCOV
3163
                if _, ok := p.addedChannels.Load(chanID); ok {
×
UNCOV
3164
                        return true
×
UNCOV
3165
                }
×
3166

UNCOV
3167
                activePublicChans = append(
×
UNCOV
3168
                        activePublicChans, dbChan.FundingOutpoint,
×
UNCOV
3169
                )
×
UNCOV
3170

×
UNCOV
3171
                return true
×
3172
        })
3173

UNCOV
3174
        return activePublicChans
×
3175
}
3176

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

×
3184
        // retryEnable is a helper closure that sends an enable request and
×
3185
        // removes the channel from the map if it's matched.
×
3186
        retryEnable := func(chanPoint wire.OutPoint) error {
×
3187
                // If this is an active channel event, check whether it's in
×
3188
                // our targeted channels map.
×
3189
                _, found := activeChans[chanPoint]
×
3190

×
3191
                // If this channel is irrelevant, return nil so the loop can
×
3192
                // jump to next iteration.
×
3193
                if !found {
×
3194
                        return nil
×
3195
                }
×
3196

3197
                // Otherwise we've just received an active signal for a channel
3198
                // that's previously failed to be enabled, we send the request
3199
                // again.
3200
                //
3201
                // We only give the channel one more shot, so we delete it from
3202
                // our map first to keep it from being attempted again.
3203
                delete(activeChans, chanPoint)
×
3204

×
3205
                // Send the request.
×
3206
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3207
                if err != nil {
×
3208
                        return fmt.Errorf("request enabling channel %v "+
×
3209
                                "failed: %w", chanPoint, err)
×
3210
                }
×
3211

3212
                return nil
×
3213
        }
3214

3215
        for {
×
3216
                // If activeChans is empty, we've done processing all the
×
3217
                // channels.
×
3218
                if len(activeChans) == 0 {
×
3219
                        p.log.Debug("Finished retry enabling channels")
×
3220
                        return
×
3221
                }
×
3222

3223
                select {
×
3224
                // A new event has been sent by the ChannelNotifier. We now
3225
                // check whether it's an active or inactive channel event.
3226
                case e := <-p.channelEventClient.Updates():
×
3227
                        // If this is an active channel event, try enable the
×
3228
                        // channel then jump to the next iteration.
×
3229
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
3230
                        if ok {
×
3231
                                chanPoint := *active.ChannelPoint
×
3232

×
3233
                                // If we received an error for this particular
×
3234
                                // channel, we log an error and won't quit as
×
3235
                                // we still want to retry other channels.
×
3236
                                if err := retryEnable(chanPoint); err != nil {
×
3237
                                        p.log.Errorf("Retry failed: %v", err)
×
3238
                                }
×
3239

3240
                                continue
×
3241
                        }
3242

3243
                        // Otherwise check for inactive link event, and jump to
3244
                        // next iteration if it's not.
3245
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3246
                        if !ok {
×
3247
                                continue
×
3248
                        }
3249

3250
                        // Found an inactive link event, if this is our
3251
                        // targeted channel, remove it from our map.
3252
                        chanPoint := *inactive.ChannelPoint
×
3253
                        _, found := activeChans[chanPoint]
×
3254
                        if !found {
×
3255
                                continue
×
3256
                        }
3257

3258
                        delete(activeChans, chanPoint)
×
3259
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3260
                                "inactive link event", chanPoint)
×
3261

3262
                case <-p.cg.Done():
×
3263
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3264
                        return
×
3265
                }
3266
        }
3267
}
3268

3269
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3270
// a suitable script to close out to. This may be nil if neither script is
3271
// set. If both scripts are set, this function will error if they do not match.
3272
func chooseDeliveryScript(upfront, requested lnwire.DeliveryAddress,
3273
        genDeliveryScript func() ([]byte, error),
3274
) (lnwire.DeliveryAddress, error) {
12✔
3275

12✔
3276
        switch {
12✔
3277
        // If no script was provided, then we'll generate a new delivery script.
3278
        case len(upfront) == 0 && len(requested) == 0:
4✔
3279
                return genDeliveryScript()
4✔
3280

3281
        // If no upfront shutdown script was provided, return the user
3282
        // requested address (which may be nil).
3283
        case len(upfront) == 0:
2✔
3284
                return requested, nil
2✔
3285

3286
        // If an upfront shutdown script was provided, and the user did not
3287
        // request a custom shutdown script, return the upfront address.
3288
        case len(requested) == 0:
2✔
3289
                return upfront, nil
2✔
3290

3291
        // If both an upfront shutdown script and a custom close script were
3292
        // provided, error if the user provided shutdown script does not match
3293
        // the upfront shutdown script (because closing out to a different
3294
        // script would violate upfront shutdown).
3295
        case !bytes.Equal(upfront, requested):
2✔
3296
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
3297

3298
        // The user requested script matches the upfront shutdown script, so we
3299
        // can return it without error.
3300
        default:
2✔
3301
                return upfront, nil
2✔
3302
        }
3303
}
3304

3305
// restartCoopClose checks whether we need to restart the cooperative close
3306
// process for a given channel.
3307
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
UNCOV
3308
        *lnwire.Shutdown, error) {
×
UNCOV
3309

×
UNCOV
3310
        isTaprootChan := lnChan.ChanType().IsTaproot()
×
UNCOV
3311

×
UNCOV
3312
        // If this channel has status ChanStatusCoopBroadcasted and does not
×
UNCOV
3313
        // have a closing transaction, then the cooperative close process was
×
UNCOV
3314
        // started but never finished. We'll re-create the chanCloser state
×
UNCOV
3315
        // machine and resend Shutdown. BOLT#2 requires that we retransmit
×
UNCOV
3316
        // Shutdown exactly, but doing so would mean persisting the RPC
×
UNCOV
3317
        // provided close script. Instead use the LocalUpfrontShutdownScript
×
UNCOV
3318
        // or generate a script.
×
UNCOV
3319
        c := lnChan.State()
×
UNCOV
3320
        _, err := c.BroadcastedCooperative()
×
UNCOV
3321
        if err != nil && err != channeldb.ErrNoCloseTx {
×
3322
                // An error other than ErrNoCloseTx was encountered.
×
3323
                return nil, err
×
UNCOV
3324
        } else if err == nil && !p.rbfCoopCloseAllowed() {
×
3325
                // This is a channel that doesn't support RBF coop close, and it
×
3326
                // already had a coop close txn broadcast. As a result, we can
×
3327
                // just exit here as all we can do is wait for it to confirm.
×
3328
                return nil, nil
×
3329
        }
×
3330

UNCOV
3331
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
×
UNCOV
3332

×
UNCOV
3333
        var deliveryScript []byte
×
UNCOV
3334

×
UNCOV
3335
        shutdownInfo, err := c.ShutdownInfo()
×
UNCOV
3336
        switch {
×
3337
        // We have previously stored the delivery script that we need to use
3338
        // in the shutdown message. Re-use this script.
UNCOV
3339
        case err == nil:
×
UNCOV
3340
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
×
UNCOV
3341
                        deliveryScript = info.DeliveryScript.Val
×
UNCOV
3342
                })
×
3343

3344
        // An error other than ErrNoShutdownInfo was returned
3345
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3346
                return nil, err
×
3347

3348
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3349
                deliveryScript = c.LocalShutdownScript
×
3350
                if len(deliveryScript) == 0 {
×
3351
                        var err error
×
3352
                        deliveryScript, err = p.genDeliveryScript()
×
3353
                        if err != nil {
×
3354
                                p.log.Errorf("unable to gen delivery script: "+
×
3355
                                        "%v", err)
×
3356

×
3357
                                return nil, fmt.Errorf("close addr unavailable")
×
3358
                        }
×
3359
                }
3360
        }
3361

3362
        // If the new RBF co-op close is negotiated, then we'll init and start
3363
        // that state machine, skipping the steps for the negotiate machine
3364
        // below. We don't support this close type for taproot channels though.
UNCOV
3365
        if p.rbfCoopCloseAllowed() && !isTaprootChan {
×
UNCOV
3366
                _, err := p.initRbfChanCloser(lnChan)
×
UNCOV
3367
                if err != nil {
×
3368
                        return nil, fmt.Errorf("unable to init rbf chan "+
×
3369
                                "closer during restart: %w", err)
×
3370
                }
×
3371

UNCOV
3372
                shutdownDesc := fn.MapOption(
×
UNCOV
3373
                        newRestartShutdownInit,
×
UNCOV
3374
                )(shutdownInfo)
×
UNCOV
3375

×
UNCOV
3376
                err = p.startRbfChanCloser(
×
UNCOV
3377
                        fn.FlattenOption(shutdownDesc), lnChan.ChannelPoint(),
×
UNCOV
3378
                )
×
UNCOV
3379

×
UNCOV
3380
                return nil, err
×
3381
        }
3382

3383
        // Compute an ideal fee.
3384
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
3385
                p.cfg.CoopCloseTargetConfs,
×
3386
        )
×
3387
        if err != nil {
×
3388
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3389
                return nil, fmt.Errorf("unable to estimate fee")
×
3390
        }
×
3391

3392
        // Determine whether we or the peer are the initiator of the coop
3393
        // close attempt by looking at the channel's status.
3394
        closingParty := lntypes.Remote
×
3395
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3396
                closingParty = lntypes.Local
×
3397
        }
×
3398

3399
        addr, err := p.addrWithInternalKey(deliveryScript)
×
3400
        if err != nil {
×
3401
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3402
        }
×
3403
        chanCloser, err := p.createChanCloser(
×
3404
                lnChan, addr, feePerKw, nil, closingParty,
×
3405
        )
×
3406
        if err != nil {
×
3407
                p.log.Errorf("unable to create chan closer: %v", err)
×
3408
                return nil, fmt.Errorf("unable to create chan closer")
×
3409
        }
×
3410

3411
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
×
3412

×
3413
        // Create the Shutdown message.
×
3414
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3415
        if err != nil {
×
3416
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3417
                p.activeChanCloses.Delete(chanID)
×
3418
                return nil, err
×
3419
        }
×
3420

3421
        return shutdownMsg, nil
×
3422
}
3423

3424
// createChanCloser constructs a ChanCloser from the passed parameters and is
3425
// used to de-duplicate code.
3426
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3427
        deliveryScript *chancloser.DeliveryAddrWithKey,
3428
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3429
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
9✔
3430

9✔
3431
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
9✔
3432
        if err != nil {
9✔
3433
                p.log.Errorf("unable to obtain best block: %v", err)
×
3434
                return nil, fmt.Errorf("cannot obtain best block")
×
3435
        }
×
3436

3437
        // The req will only be set if we initiated the co-op closing flow.
3438
        var maxFee chainfee.SatPerKWeight
9✔
3439
        if req != nil {
15✔
3440
                maxFee = req.MaxFee
6✔
3441
        }
6✔
3442

3443
        chanCloser := chancloser.NewChanCloser(
9✔
3444
                chancloser.ChanCloseCfg{
9✔
3445
                        Channel:      channel,
9✔
3446
                        MusigSession: NewMusigChanCloser(channel),
9✔
3447
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
9✔
3448
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
9✔
3449
                        AuxCloser:    p.cfg.AuxChanCloser,
9✔
3450
                        DisableChannel: func(op wire.OutPoint) error {
18✔
3451
                                return p.cfg.ChanStatusMgr.RequestDisable(
9✔
3452
                                        op, false,
9✔
3453
                                )
9✔
3454
                        },
9✔
3455
                        MaxFee: maxFee,
3456
                        Disconnect: func() error {
×
3457
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
3458
                        },
×
3459
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3460
                },
3461
                *deliveryScript,
3462
                fee,
3463
                uint32(startingHeight),
3464
                req,
3465
                closer,
3466
        )
3467

3468
        return chanCloser, nil
9✔
3469
}
3470

3471
// initNegotiateChanCloser initializes the channel closer for a channel that is
3472
// using the original "negotiation" based protocol. This path is used when
3473
// we're the one initiating the channel close.
3474
//
3475
// TODO(roasbeef): can make a MsgEndpoint for existing handling logic to
3476
// further abstract.
3477
func (p *Brontide) initNegotiateChanCloser(req *htlcswitch.ChanClose,
3478
        channel *lnwallet.LightningChannel) error {
7✔
3479

7✔
3480
        // First, we'll choose a delivery address that we'll use to send the
7✔
3481
        // funds to in the case of a successful negotiation.
7✔
3482

7✔
3483
        // An upfront shutdown and user provided script are both optional, but
7✔
3484
        // must be equal if both set  (because we cannot serve a request to
7✔
3485
        // close out to a script which violates upfront shutdown). Get the
7✔
3486
        // appropriate address to close out to (which may be nil if neither are
7✔
3487
        // set) and error if they are both set and do not match.
7✔
3488
        deliveryScript, err := chooseDeliveryScript(
7✔
3489
                channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
7✔
3490
                p.genDeliveryScript,
7✔
3491
        )
7✔
3492
        if err != nil {
8✔
3493
                return fmt.Errorf("cannot close channel %v: %w",
1✔
3494
                        req.ChanPoint, err)
1✔
3495
        }
1✔
3496

3497
        addr, err := p.addrWithInternalKey(deliveryScript)
6✔
3498
        if err != nil {
6✔
3499
                return fmt.Errorf("unable to parse addr for channel "+
×
3500
                        "%v: %w", req.ChanPoint, err)
×
3501
        }
×
3502

3503
        chanCloser, err := p.createChanCloser(
6✔
3504
                channel, addr, req.TargetFeePerKw, req, lntypes.Local,
6✔
3505
        )
6✔
3506
        if err != nil {
6✔
3507
                return fmt.Errorf("unable to make chan closer: %w", err)
×
3508
        }
×
3509

3510
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
6✔
3511
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
6✔
3512

6✔
3513
        // Finally, we'll initiate the channel shutdown within the
6✔
3514
        // chanCloser, and send the shutdown message to the remote
6✔
3515
        // party to kick things off.
6✔
3516
        shutdownMsg, err := chanCloser.ShutdownChan()
6✔
3517
        if err != nil {
6✔
3518
                // As we were unable to shutdown the channel, we'll return it
×
3519
                // back to its normal state.
×
3520
                defer channel.ResetState()
×
3521

×
3522
                p.activeChanCloses.Delete(chanID)
×
3523

×
3524
                return fmt.Errorf("unable to shutdown channel: %w", err)
×
3525
        }
×
3526

3527
        link := p.fetchLinkFromKeyAndCid(chanID)
6✔
3528
        if link == nil {
6✔
3529
                // If the link is nil then it means it was already removed from
×
3530
                // the switch or it never existed in the first place. The
×
3531
                // latter case is handled at the beginning of this function, so
×
3532
                // in the case where it has already been removed, we can skip
×
3533
                // adding the commit hook to queue a Shutdown message.
×
3534
                p.log.Warnf("link not found during attempted closure: "+
×
3535
                        "%v", chanID)
×
3536
                return nil
×
3537
        }
×
3538

3539
        if !link.DisableAdds(htlcswitch.Outgoing) {
6✔
3540
                p.log.Warnf("Outgoing link adds already "+
×
3541
                        "disabled: %v", link.ChanID())
×
3542
        }
×
3543

3544
        link.OnCommitOnce(htlcswitch.Outgoing, func() {
12✔
3545
                p.queueMsg(shutdownMsg, nil)
6✔
3546
        })
6✔
3547

3548
        return nil
6✔
3549
}
3550

3551
// chooseAddr returns the provided address if it is non-zero length, otherwise
3552
// None.
UNCOV
3553
func chooseAddr(addr lnwire.DeliveryAddress) fn.Option[lnwire.DeliveryAddress] {
×
UNCOV
3554
        if len(addr) == 0 {
×
UNCOV
3555
                return fn.None[lnwire.DeliveryAddress]()
×
UNCOV
3556
        }
×
3557

3558
        return fn.Some(addr)
×
3559
}
3560

3561
// observeRbfCloseUpdates observes the channel for any updates that may
3562
// indicate that a new txid has been broadcasted, or the channel fully closed
3563
// on chain.
3564
func (p *Brontide) observeRbfCloseUpdates(chanCloser *chancloser.RbfChanCloser,
3565
        closeReq *htlcswitch.ChanClose,
UNCOV
3566
        coopCloseStates chancloser.RbfStateSub) {
×
UNCOV
3567

×
UNCOV
3568
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
×
UNCOV
3569
        defer chanCloser.RemoveStateSub(coopCloseStates)
×
UNCOV
3570

×
UNCOV
3571
        var (
×
UNCOV
3572
                lastTxids    lntypes.Dual[chainhash.Hash]
×
UNCOV
3573
                lastFeeRates lntypes.Dual[chainfee.SatPerVByte]
×
UNCOV
3574
        )
×
UNCOV
3575

×
UNCOV
3576
        maybeNotifyTxBroadcast := func(state chancloser.AsymmetricPeerState,
×
UNCOV
3577
                party lntypes.ChannelParty) {
×
UNCOV
3578

×
UNCOV
3579
                // First, check to see if we have an error to report to the
×
UNCOV
3580
                // caller. If so, then we''ll return that error and exit, as the
×
UNCOV
3581
                // stream will exit as well.
×
UNCOV
3582
                if closeErr, ok := state.(*chancloser.CloseErr); ok {
×
UNCOV
3583
                        // We hit an error during the last state transition, so
×
UNCOV
3584
                        // we'll extract the error then send it to the
×
UNCOV
3585
                        // user.
×
UNCOV
3586
                        err := closeErr.Err()
×
UNCOV
3587

×
UNCOV
3588
                        peerLog.Warnf("ChannelPoint(%v): encountered close "+
×
UNCOV
3589
                                "err: %v", closeReq.ChanPoint, err)
×
UNCOV
3590

×
UNCOV
3591
                        select {
×
UNCOV
3592
                        case closeReq.Err <- err:
×
3593
                        case <-closeReq.Ctx.Done():
×
3594
                        case <-p.cg.Done():
×
3595
                        }
3596

UNCOV
3597
                        return
×
3598
                }
3599

UNCOV
3600
                closePending, ok := state.(*chancloser.ClosePending)
×
UNCOV
3601

×
UNCOV
3602
                // If this isn't the close pending state, we aren't at the
×
UNCOV
3603
                // terminal state yet.
×
UNCOV
3604
                if !ok {
×
UNCOV
3605
                        return
×
UNCOV
3606
                }
×
3607

3608
                // Only notify if the fee rate is greater.
UNCOV
3609
                newFeeRate := closePending.FeeRate
×
UNCOV
3610
                lastFeeRate := lastFeeRates.GetForParty(party)
×
UNCOV
3611
                if newFeeRate <= lastFeeRate {
×
UNCOV
3612
                        peerLog.Debugf("ChannelPoint(%v): remote party made "+
×
UNCOV
3613
                                "update for fee rate %v, but we already have "+
×
UNCOV
3614
                                "a higher fee rate of %v", closeReq.ChanPoint,
×
UNCOV
3615
                                newFeeRate, lastFeeRate)
×
UNCOV
3616

×
UNCOV
3617
                        return
×
UNCOV
3618
                }
×
3619

UNCOV
3620
                feeRate := closePending.FeeRate
×
UNCOV
3621
                lastFeeRates.SetForParty(party, feeRate)
×
UNCOV
3622

×
UNCOV
3623
                // At this point, we'll have a txid that we can use to notify
×
UNCOV
3624
                // the client, but only if it's different from the last one we
×
UNCOV
3625
                // sent. If the user attempted to bump, but was rejected due to
×
UNCOV
3626
                // RBF, then we'll send a redundant update.
×
UNCOV
3627
                closingTxid := closePending.CloseTx.TxHash()
×
UNCOV
3628
                lastTxid := lastTxids.GetForParty(party)
×
UNCOV
3629
                if closeReq != nil && closingTxid != lastTxid {
×
UNCOV
3630
                        select {
×
3631
                        case closeReq.Updates <- &PendingUpdate{
3632
                                Txid:        closingTxid[:],
3633
                                FeePerVbyte: fn.Some(closePending.FeeRate),
3634
                                IsLocalCloseTx: fn.Some(
3635
                                        party == lntypes.Local,
3636
                                ),
UNCOV
3637
                        }:
×
3638

3639
                        case <-closeReq.Ctx.Done():
×
3640
                                return
×
3641

3642
                        case <-p.cg.Done():
×
3643
                                return
×
3644
                        }
3645
                }
3646

UNCOV
3647
                lastTxids.SetForParty(party, closingTxid)
×
3648
        }
3649

UNCOV
3650
        peerLog.Infof("Observing RBF close updates for channel %v",
×
UNCOV
3651
                closeReq.ChanPoint)
×
UNCOV
3652

×
UNCOV
3653
        // We'll consume each new incoming state to send out the appropriate
×
UNCOV
3654
        // RPC update.
×
UNCOV
3655
        for {
×
UNCOV
3656
                select {
×
UNCOV
3657
                case newState := <-newStateChan:
×
UNCOV
3658

×
UNCOV
3659
                        switch closeState := newState.(type) {
×
3660
                        // Once we've reached the state of pending close, we
3661
                        // have a txid that we broadcasted.
UNCOV
3662
                        case *chancloser.ClosingNegotiation:
×
UNCOV
3663
                                peerState := closeState.PeerState
×
UNCOV
3664

×
UNCOV
3665
                                // Each side may have gained a new co-op close
×
UNCOV
3666
                                // tx, so we'll examine both to see if they've
×
UNCOV
3667
                                // changed.
×
UNCOV
3668
                                maybeNotifyTxBroadcast(
×
UNCOV
3669
                                        peerState.GetForParty(lntypes.Local),
×
UNCOV
3670
                                        lntypes.Local,
×
UNCOV
3671
                                )
×
UNCOV
3672
                                maybeNotifyTxBroadcast(
×
UNCOV
3673
                                        peerState.GetForParty(lntypes.Remote),
×
UNCOV
3674
                                        lntypes.Remote,
×
UNCOV
3675
                                )
×
3676

3677
                        // Otherwise, if we're transition to CloseFin, then we
3678
                        // know that we're done.
UNCOV
3679
                        case *chancloser.CloseFin:
×
UNCOV
3680
                                // To clean up, we'll remove the chan closer
×
UNCOV
3681
                                // from the active map, and send the final
×
UNCOV
3682
                                // update to the client.
×
UNCOV
3683
                                closingTxid := closeState.ConfirmedTx.TxHash()
×
UNCOV
3684
                                if closeReq != nil {
×
UNCOV
3685
                                        closeReq.Updates <- &ChannelCloseUpdate{
×
UNCOV
3686
                                                ClosingTxid: closingTxid[:],
×
UNCOV
3687
                                                Success:     true,
×
UNCOV
3688
                                        }
×
UNCOV
3689
                                }
×
UNCOV
3690
                                chanID := lnwire.NewChanIDFromOutPoint(
×
UNCOV
3691
                                        *closeReq.ChanPoint,
×
UNCOV
3692
                                )
×
UNCOV
3693
                                p.activeChanCloses.Delete(chanID)
×
UNCOV
3694

×
UNCOV
3695
                                return
×
3696
                        }
3697

UNCOV
3698
                case <-closeReq.Ctx.Done():
×
UNCOV
3699
                        return
×
3700

UNCOV
3701
                case <-p.cg.Done():
×
UNCOV
3702
                        return
×
3703
                }
3704
        }
3705
}
3706

3707
// chanErrorReporter is a simple implementation of the
3708
// chancloser.ErrorReporter. This is bound to a single channel by the channel
3709
// ID.
3710
type chanErrorReporter struct {
3711
        chanID lnwire.ChannelID
3712
        peer   *Brontide
3713
}
3714

3715
// newChanErrorReporter creates a new instance of the chanErrorReporter.
3716
func newChanErrorReporter(chanID lnwire.ChannelID,
UNCOV
3717
        peer *Brontide) *chanErrorReporter {
×
UNCOV
3718

×
UNCOV
3719
        return &chanErrorReporter{
×
UNCOV
3720
                chanID: chanID,
×
UNCOV
3721
                peer:   peer,
×
UNCOV
3722
        }
×
UNCOV
3723
}
×
3724

3725
// ReportError is a method that's used to report an error that occurred during
3726
// state machine execution. This is used by the RBF close state machine to
3727
// terminate the state machine and send an error to the remote peer.
3728
//
3729
// This is a part of the chancloser.ErrorReporter interface.
3730
func (c *chanErrorReporter) ReportError(chanErr error) {
×
3731
        c.peer.log.Errorf("coop close error for channel %v: %v",
×
3732
                c.chanID, chanErr)
×
3733

×
3734
        var errMsg []byte
×
3735
        if errors.Is(chanErr, chancloser.ErrInvalidStateTransition) {
×
3736
                errMsg = []byte("unexpected protocol message")
×
3737
        } else {
×
3738
                errMsg = []byte(chanErr.Error())
×
3739
        }
×
3740

3741
        err := c.peer.SendMessageLazy(false, &lnwire.Error{
×
3742
                ChanID: c.chanID,
×
3743
                Data:   errMsg,
×
3744
        })
×
3745
        if err != nil {
×
3746
                c.peer.log.Warnf("unable to send error message to peer: %v",
×
3747
                        err)
×
3748
        }
×
3749

3750
        // After we send the error message to the peer, we'll re-initialize the
3751
        // coop close state machine as they may send a shutdown message to
3752
        // retry the coop close.
3753
        lnChan, ok := c.peer.activeChannels.Load(c.chanID)
×
3754
        if !ok {
×
3755
                return
×
3756
        }
×
3757

3758
        if lnChan == nil {
×
3759
                c.peer.log.Debugf("channel %v is pending, not "+
×
3760
                        "re-initializing coop close state machine",
×
3761
                        c.chanID)
×
3762

×
3763
                return
×
3764
        }
×
3765

3766
        if _, err := c.peer.initRbfChanCloser(lnChan); err != nil {
×
3767
                c.peer.activeChanCloses.Delete(c.chanID)
×
3768

×
3769
                c.peer.log.Errorf("unable to init RBF chan closer after "+
×
3770
                        "error case: %v", err)
×
3771
        }
×
3772
}
3773

3774
// chanFlushEventSentinel is used to send the RBF coop close state machine the
3775
// channel flushed event. We'll wait until the state machine enters the
3776
// ChannelFlushing state, then request the link to send the event once flushed.
3777
//
3778
// NOTE: This MUST be run as a goroutine.
3779
func (p *Brontide) chanFlushEventSentinel(chanCloser *chancloser.RbfChanCloser,
3780
        link htlcswitch.ChannelUpdateHandler,
UNCOV
3781
        channel *lnwallet.LightningChannel) {
×
UNCOV
3782

×
UNCOV
3783
        defer p.cg.WgDone()
×
UNCOV
3784

×
UNCOV
3785
        // If there's no link, then the channel has already been flushed, so we
×
UNCOV
3786
        // don't need to continue.
×
UNCOV
3787
        if link == nil {
×
UNCOV
3788
                return
×
UNCOV
3789
        }
×
3790

UNCOV
3791
        coopCloseStates := chanCloser.RegisterStateEvents()
×
UNCOV
3792
        defer chanCloser.RemoveStateSub(coopCloseStates)
×
UNCOV
3793

×
UNCOV
3794
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
×
UNCOV
3795

×
UNCOV
3796
        sendChanFlushed := func() {
×
UNCOV
3797
                chanState := channel.StateSnapshot()
×
UNCOV
3798

×
UNCOV
3799
                peerLog.Infof("ChannelPoint(%v) has been flushed for co-op "+
×
UNCOV
3800
                        "close, sending event to chan closer",
×
UNCOV
3801
                        channel.ChannelPoint())
×
UNCOV
3802

×
UNCOV
3803
                chanBalances := chancloser.ShutdownBalances{
×
UNCOV
3804
                        LocalBalance:  chanState.LocalBalance,
×
UNCOV
3805
                        RemoteBalance: chanState.RemoteBalance,
×
UNCOV
3806
                }
×
UNCOV
3807
                ctx := context.Background()
×
UNCOV
3808
                chanCloser.SendEvent(ctx, &chancloser.ChannelFlushed{
×
UNCOV
3809
                        ShutdownBalances: chanBalances,
×
UNCOV
3810
                        FreshFlush:       true,
×
UNCOV
3811
                })
×
UNCOV
3812
        }
×
3813

3814
        // We'll wait until the channel enters the ChannelFlushing state. We
3815
        // exit after a success loop. As after the first RBF iteration, the
3816
        // channel will always be flushed.
UNCOV
3817
        for {
×
UNCOV
3818
                select {
×
UNCOV
3819
                case newState, ok := <-newStateChan:
×
UNCOV
3820
                        if !ok {
×
3821
                                return
×
3822
                        }
×
3823

UNCOV
3824
                        if _, ok := newState.(*chancloser.ChannelFlushing); ok {
×
UNCOV
3825
                                peerLog.Infof("ChannelPoint(%v): rbf coop "+
×
UNCOV
3826
                                        "close is awaiting a flushed state, "+
×
UNCOV
3827
                                        "registering with link..., ",
×
UNCOV
3828
                                        channel.ChannelPoint())
×
UNCOV
3829

×
UNCOV
3830
                                // Request the link to send the event once the
×
UNCOV
3831
                                // channel is flushed. We only need this event
×
UNCOV
3832
                                // sent once, so we can exit now.
×
UNCOV
3833
                                link.OnFlushedOnce(sendChanFlushed)
×
UNCOV
3834

×
UNCOV
3835
                                return
×
UNCOV
3836
                        }
×
3837

UNCOV
3838
                case <-p.cg.Done():
×
UNCOV
3839
                        return
×
3840
                }
3841
        }
3842
}
3843

3844
// initRbfChanCloser initializes the channel closer for a channel that
3845
// is using the new RBF based co-op close protocol. This only creates the chan
3846
// closer, but doesn't attempt to trigger any manual state transitions.
3847
func (p *Brontide) initRbfChanCloser(
UNCOV
3848
        channel *lnwallet.LightningChannel) (*chancloser.RbfChanCloser, error) {
×
UNCOV
3849

×
UNCOV
3850
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
×
UNCOV
3851

×
UNCOV
3852
        link := p.fetchLinkFromKeyAndCid(chanID)
×
UNCOV
3853

×
UNCOV
3854
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
×
UNCOV
3855
        if err != nil {
×
3856
                return nil, fmt.Errorf("cannot obtain best block: %w", err)
×
3857
        }
×
3858

UNCOV
3859
        defaultFeePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
UNCOV
3860
                p.cfg.CoopCloseTargetConfs,
×
UNCOV
3861
        )
×
UNCOV
3862
        if err != nil {
×
3863
                return nil, fmt.Errorf("unable to estimate fee: %w", err)
×
3864
        }
×
3865

UNCOV
3866
        thawHeight, err := channel.AbsoluteThawHeight()
×
UNCOV
3867
        if err != nil {
×
3868
                return nil, fmt.Errorf("unable to get thaw height: %w", err)
×
3869
        }
×
3870

UNCOV
3871
        peerPub := *p.IdentityKey()
×
UNCOV
3872

×
UNCOV
3873
        msgMapper := chancloser.NewRbfMsgMapper(
×
UNCOV
3874
                uint32(startingHeight), chanID, peerPub,
×
UNCOV
3875
        )
×
UNCOV
3876

×
UNCOV
3877
        initialState := chancloser.ChannelActive{}
×
UNCOV
3878

×
UNCOV
3879
        scid := channel.ZeroConfRealScid().UnwrapOr(
×
UNCOV
3880
                channel.ShortChanID(),
×
UNCOV
3881
        )
×
UNCOV
3882

×
UNCOV
3883
        env := chancloser.Environment{
×
UNCOV
3884
                ChainParams:    p.cfg.Wallet.Cfg.NetParams,
×
UNCOV
3885
                ChanPeer:       peerPub,
×
UNCOV
3886
                ChanPoint:      channel.ChannelPoint(),
×
UNCOV
3887
                ChanID:         chanID,
×
UNCOV
3888
                Scid:           scid,
×
UNCOV
3889
                ChanType:       channel.ChanType(),
×
UNCOV
3890
                DefaultFeeRate: defaultFeePerKw.FeePerVByte(),
×
UNCOV
3891
                ThawHeight:     fn.Some(thawHeight),
×
UNCOV
3892
                RemoteUpfrontShutdown: chooseAddr(
×
UNCOV
3893
                        channel.RemoteUpfrontShutdownScript(),
×
UNCOV
3894
                ),
×
UNCOV
3895
                LocalUpfrontShutdown: chooseAddr(
×
UNCOV
3896
                        channel.LocalUpfrontShutdownScript(),
×
UNCOV
3897
                ),
×
UNCOV
3898
                NewDeliveryScript: func() (lnwire.DeliveryAddress, error) {
×
UNCOV
3899
                        return p.genDeliveryScript()
×
UNCOV
3900
                },
×
3901
                FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
3902
                CloseSigner:  channel,
3903
                ChanObserver: newChanObserver(
3904
                        channel, link, p.cfg.ChanStatusMgr,
3905
                ),
3906
        }
3907

UNCOV
3908
        spendEvent := protofsm.RegisterSpend[chancloser.ProtocolEvent]{
×
UNCOV
3909
                OutPoint:   channel.ChannelPoint(),
×
UNCOV
3910
                PkScript:   channel.FundingTxOut().PkScript,
×
UNCOV
3911
                HeightHint: channel.DeriveHeightHint(),
×
UNCOV
3912
                PostSpendEvent: fn.Some[chancloser.RbfSpendMapper](
×
UNCOV
3913
                        chancloser.SpendMapper,
×
UNCOV
3914
                ),
×
UNCOV
3915
        }
×
UNCOV
3916

×
UNCOV
3917
        daemonAdapters := NewLndDaemonAdapters(LndAdapterCfg{
×
UNCOV
3918
                MsgSender:     newPeerMsgSender(peerPub, p),
×
UNCOV
3919
                TxBroadcaster: p.cfg.Wallet,
×
UNCOV
3920
                ChainNotifier: p.cfg.ChainNotifier,
×
UNCOV
3921
        })
×
UNCOV
3922

×
UNCOV
3923
        protoCfg := chancloser.RbfChanCloserCfg{
×
UNCOV
3924
                Daemon:        daemonAdapters,
×
UNCOV
3925
                InitialState:  &initialState,
×
UNCOV
3926
                Env:           &env,
×
UNCOV
3927
                InitEvent:     fn.Some[protofsm.DaemonEvent](&spendEvent),
×
UNCOV
3928
                ErrorReporter: newChanErrorReporter(chanID, p),
×
UNCOV
3929
                MsgMapper: fn.Some[protofsm.MsgMapper[chancloser.ProtocolEvent]]( //nolint:ll
×
UNCOV
3930
                        msgMapper,
×
UNCOV
3931
                ),
×
UNCOV
3932
        }
×
UNCOV
3933

×
UNCOV
3934
        ctx := context.Background()
×
UNCOV
3935
        chanCloser := protofsm.NewStateMachine(protoCfg)
×
UNCOV
3936
        chanCloser.Start(ctx)
×
UNCOV
3937

×
UNCOV
3938
        // Finally, we'll register this new endpoint with the message router so
×
UNCOV
3939
        // future co-op close messages are handled by this state machine.
×
UNCOV
3940
        err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
×
UNCOV
3941
                _ = r.UnregisterEndpoint(chanCloser.Name())
×
UNCOV
3942

×
UNCOV
3943
                return r.RegisterEndpoint(&chanCloser)
×
UNCOV
3944
        })
×
UNCOV
3945
        if err != nil {
×
3946
                chanCloser.Stop()
×
3947

×
3948
                return nil, fmt.Errorf("unable to register endpoint for co-op "+
×
3949
                        "close: %w", err)
×
3950
        }
×
3951

UNCOV
3952
        p.activeChanCloses.Store(chanID, makeRbfCloser(&chanCloser))
×
UNCOV
3953

×
UNCOV
3954
        // Now that we've created the rbf closer state machine, we'll launch a
×
UNCOV
3955
        // new goroutine to eventually send in the ChannelFlushed event once
×
UNCOV
3956
        // needed.
×
UNCOV
3957
        p.cg.WgAdd(1)
×
UNCOV
3958
        go p.chanFlushEventSentinel(&chanCloser, link, channel)
×
UNCOV
3959

×
UNCOV
3960
        return &chanCloser, nil
×
3961
}
3962

3963
// shutdownInit describes the two ways we can initiate a new shutdown. Either we
3964
// got an RPC request to do so (left), or we sent a shutdown message to the
3965
// party (for w/e reason), but crashed before the close was complete.
3966
//
3967
//nolint:ll
3968
type shutdownInit = fn.Option[fn.Either[*htlcswitch.ChanClose, channeldb.ShutdownInfo]]
3969

3970
// shutdownStartFeeRate returns the fee rate that should be used for the
3971
// shutdown.  This returns a doubly wrapped option as the shutdown info might
3972
// be none, and the fee rate is only defined for the user initiated shutdown.
UNCOV
3973
func shutdownStartFeeRate(s shutdownInit) fn.Option[chainfee.SatPerKWeight] {
×
UNCOV
3974
        feeRateOpt := fn.MapOption(func(init fn.Either[*htlcswitch.ChanClose,
×
UNCOV
3975
                channeldb.ShutdownInfo]) fn.Option[chainfee.SatPerKWeight] {
×
UNCOV
3976

×
UNCOV
3977
                var feeRate fn.Option[chainfee.SatPerKWeight]
×
UNCOV
3978
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
×
UNCOV
3979
                        feeRate = fn.Some(req.TargetFeePerKw)
×
UNCOV
3980
                })
×
3981

UNCOV
3982
                return feeRate
×
3983
        })(s)
3984

UNCOV
3985
        return fn.FlattenOption(feeRateOpt)
×
3986
}
3987

3988
// shutdownStartAddr returns the delivery address that should be used when
3989
// restarting the shutdown process.  If we didn't send a shutdown before we
3990
// restarted, and the user didn't initiate one either, then None is returned.
UNCOV
3991
func shutdownStartAddr(s shutdownInit) fn.Option[lnwire.DeliveryAddress] {
×
UNCOV
3992
        addrOpt := fn.MapOption(func(init fn.Either[*htlcswitch.ChanClose,
×
UNCOV
3993
                channeldb.ShutdownInfo]) fn.Option[lnwire.DeliveryAddress] {
×
UNCOV
3994

×
UNCOV
3995
                var addr fn.Option[lnwire.DeliveryAddress]
×
UNCOV
3996
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
×
UNCOV
3997
                        if len(req.DeliveryScript) != 0 {
×
UNCOV
3998
                                addr = fn.Some(req.DeliveryScript)
×
UNCOV
3999
                        }
×
4000
                })
UNCOV
4001
                init.WhenRight(func(info channeldb.ShutdownInfo) {
×
UNCOV
4002
                        addr = fn.Some(info.DeliveryScript.Val)
×
UNCOV
4003
                })
×
4004

UNCOV
4005
                return addr
×
4006
        })(s)
4007

UNCOV
4008
        return fn.FlattenOption(addrOpt)
×
4009
}
4010

4011
// whenRPCShutdown registers a callback to be executed when the shutdown init
4012
// type is and RPC request.
UNCOV
4013
func whenRPCShutdown(s shutdownInit, f func(r *htlcswitch.ChanClose)) {
×
UNCOV
4014
        s.WhenSome(func(init fn.Either[*htlcswitch.ChanClose,
×
UNCOV
4015
                channeldb.ShutdownInfo]) {
×
UNCOV
4016

×
UNCOV
4017
                init.WhenLeft(f)
×
UNCOV
4018
        })
×
4019
}
4020

4021
// newRestartShutdownInit creates a new shutdownInit for the case where we need
4022
// to restart the shutdown flow after a restart.
UNCOV
4023
func newRestartShutdownInit(info channeldb.ShutdownInfo) shutdownInit {
×
UNCOV
4024
        return fn.Some(fn.NewRight[*htlcswitch.ChanClose](info))
×
UNCOV
4025
}
×
4026

4027
// newRPCShutdownInit creates a new shutdownInit for the case where we
4028
// initiated the shutdown via an RPC client.
UNCOV
4029
func newRPCShutdownInit(req *htlcswitch.ChanClose) shutdownInit {
×
UNCOV
4030
        return fn.Some(
×
UNCOV
4031
                fn.NewLeft[*htlcswitch.ChanClose, channeldb.ShutdownInfo](req),
×
UNCOV
4032
        )
×
UNCOV
4033
}
×
4034

4035
// waitUntilRbfCoastClear waits until the RBF co-op close state machine has
4036
// advanced to a terminal state before attempting another fee bump.
4037
func waitUntilRbfCoastClear(ctx context.Context,
UNCOV
4038
        rbfCloser *chancloser.RbfChanCloser) error {
×
UNCOV
4039

×
UNCOV
4040
        coopCloseStates := rbfCloser.RegisterStateEvents()
×
UNCOV
4041
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
×
UNCOV
4042
        defer rbfCloser.RemoveStateSub(coopCloseStates)
×
UNCOV
4043

×
UNCOV
4044
        isTerminalState := func(newState chancloser.RbfState) bool {
×
UNCOV
4045
                // If we're not in the negotiation sub-state, then we aren't at
×
UNCOV
4046
                // the terminal state yet.
×
UNCOV
4047
                state, ok := newState.(*chancloser.ClosingNegotiation)
×
UNCOV
4048
                if !ok {
×
4049
                        return false
×
4050
                }
×
4051

UNCOV
4052
                localState := state.PeerState.GetForParty(lntypes.Local)
×
UNCOV
4053

×
UNCOV
4054
                // If this isn't the close pending state, we aren't at the
×
UNCOV
4055
                // terminal state yet.
×
UNCOV
4056
                _, ok = localState.(*chancloser.ClosePending)
×
UNCOV
4057

×
UNCOV
4058
                return ok
×
4059
        }
4060

4061
        // Before we enter the subscription loop below, check to see if we're
4062
        // already in the terminal state.
UNCOV
4063
        rbfState, err := rbfCloser.CurrentState()
×
UNCOV
4064
        if err != nil {
×
4065
                return err
×
4066
        }
×
UNCOV
4067
        if isTerminalState(rbfState) {
×
UNCOV
4068
                return nil
×
UNCOV
4069
        }
×
4070

4071
        peerLog.Debugf("Waiting for RBF iteration to complete...")
×
4072

×
4073
        for {
×
4074
                select {
×
4075
                case newState := <-newStateChan:
×
4076
                        if isTerminalState(newState) {
×
4077
                                return nil
×
4078
                        }
×
4079

4080
                case <-ctx.Done():
×
4081
                        return fmt.Errorf("context canceled")
×
4082
                }
4083
        }
4084
}
4085

4086
// startRbfChanCloser kicks off the co-op close process using the new RBF based
4087
// co-op close protocol. This is called when we're the one that's initiating
4088
// the cooperative channel close.
4089
//
4090
// TODO(roasbeef): just accept the two shutdown pointer params instead??
4091
func (p *Brontide) startRbfChanCloser(shutdown shutdownInit,
UNCOV
4092
        chanPoint wire.OutPoint) error {
×
UNCOV
4093

×
UNCOV
4094
        // Unlike the old negotiate chan closer, we'll always create the RBF
×
UNCOV
4095
        // chan closer on startup, so we can skip init here.
×
UNCOV
4096
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
4097
        chanCloser, found := p.activeChanCloses.Load(chanID)
×
UNCOV
4098
        if !found {
×
4099
                return fmt.Errorf("rbf chan closer not found for channel %v",
×
4100
                        chanPoint)
×
4101
        }
×
4102

UNCOV
4103
        defaultFeePerKw, err := shutdownStartFeeRate(
×
UNCOV
4104
                shutdown,
×
UNCOV
4105
        ).UnwrapOrFuncErr(func() (chainfee.SatPerKWeight, error) {
×
UNCOV
4106
                return p.cfg.FeeEstimator.EstimateFeePerKW(
×
UNCOV
4107
                        p.cfg.CoopCloseTargetConfs,
×
UNCOV
4108
                )
×
UNCOV
4109
        })
×
UNCOV
4110
        if err != nil {
×
4111
                return fmt.Errorf("unable to estimate fee: %w", err)
×
4112
        }
×
4113

UNCOV
4114
        chanCloser.WhenRight(func(rbfCloser *chancloser.RbfChanCloser) {
×
UNCOV
4115
                peerLog.Infof("ChannelPoint(%v): rbf-coop close requested, "+
×
UNCOV
4116
                        "sending shutdown", chanPoint)
×
UNCOV
4117

×
UNCOV
4118
                rbfState, err := rbfCloser.CurrentState()
×
UNCOV
4119
                if err != nil {
×
4120
                        peerLog.Warnf("ChannelPoint(%v): unable to get "+
×
4121
                                "current state for rbf-coop close: %v",
×
4122
                                chanPoint, err)
×
4123

×
4124
                        return
×
4125
                }
×
4126

UNCOV
4127
                coopCloseStates := rbfCloser.RegisterStateEvents()
×
UNCOV
4128

×
UNCOV
4129
                // Before we send our event below, we'll launch a goroutine to
×
UNCOV
4130
                // watch for the final terminal state to send updates to the RPC
×
UNCOV
4131
                // client. We only need to do this if there's an RPC caller.
×
UNCOV
4132
                var rpcShutdown bool
×
UNCOV
4133
                whenRPCShutdown(shutdown, func(req *htlcswitch.ChanClose) {
×
UNCOV
4134
                        rpcShutdown = true
×
UNCOV
4135

×
UNCOV
4136
                        p.cg.WgAdd(1)
×
UNCOV
4137
                        go func() {
×
UNCOV
4138
                                defer p.cg.WgDone()
×
UNCOV
4139

×
UNCOV
4140
                                p.observeRbfCloseUpdates(
×
UNCOV
4141
                                        rbfCloser, req, coopCloseStates,
×
UNCOV
4142
                                )
×
UNCOV
4143
                        }()
×
4144
                })
4145

UNCOV
4146
                if !rpcShutdown {
×
UNCOV
4147
                        defer rbfCloser.RemoveStateSub(coopCloseStates)
×
UNCOV
4148
                }
×
4149

UNCOV
4150
                ctx, _ := p.cg.Create(context.Background())
×
UNCOV
4151
                feeRate := defaultFeePerKw.FeePerVByte()
×
UNCOV
4152

×
UNCOV
4153
                // Depending on the state of the state machine, we'll either
×
UNCOV
4154
                // kick things off by sending shutdown, or attempt to send a new
×
UNCOV
4155
                // offer to the remote party.
×
UNCOV
4156
                switch rbfState.(type) {
×
4157
                // The channel is still active, so we'll now kick off the co-op
4158
                // close process by instructing it to send a shutdown message to
4159
                // the remote party.
UNCOV
4160
                case *chancloser.ChannelActive:
×
UNCOV
4161
                        rbfCloser.SendEvent(
×
UNCOV
4162
                                context.Background(),
×
UNCOV
4163
                                &chancloser.SendShutdown{
×
UNCOV
4164
                                        IdealFeeRate: feeRate,
×
UNCOV
4165
                                        DeliveryAddr: shutdownStartAddr(
×
UNCOV
4166
                                                shutdown,
×
UNCOV
4167
                                        ),
×
UNCOV
4168
                                },
×
UNCOV
4169
                        )
×
4170

4171
                // If we haven't yet sent an offer (didn't have enough funds at
4172
                // the prior fee rate), or we've sent an offer, then we'll
4173
                // trigger a new offer event.
UNCOV
4174
                case *chancloser.ClosingNegotiation:
×
UNCOV
4175
                        // Before we send the event below, we'll wait until
×
UNCOV
4176
                        // we're in a semi-terminal state.
×
UNCOV
4177
                        err := waitUntilRbfCoastClear(ctx, rbfCloser)
×
UNCOV
4178
                        if err != nil {
×
4179
                                peerLog.Warnf("ChannelPoint(%v): unable to "+
×
4180
                                        "wait for coast to clear: %v",
×
4181
                                        chanPoint, err)
×
4182

×
4183
                                return
×
4184
                        }
×
4185

UNCOV
4186
                        event := chancloser.ProtocolEvent(
×
UNCOV
4187
                                &chancloser.SendOfferEvent{
×
UNCOV
4188
                                        TargetFeeRate: feeRate,
×
UNCOV
4189
                                },
×
UNCOV
4190
                        )
×
UNCOV
4191
                        rbfCloser.SendEvent(ctx, event)
×
4192

4193
                default:
×
4194
                        peerLog.Warnf("ChannelPoint(%v): unexpected state "+
×
4195
                                "for rbf-coop close: %T", chanPoint, rbfState)
×
4196
                }
4197
        })
4198

UNCOV
4199
        return nil
×
4200
}
4201

4202
// handleLocalCloseReq kicks-off the workflow to execute a cooperative or
4203
// forced unilateral closure of the channel initiated by a local subsystem.
4204
func (p *Brontide) handleLocalCloseReq(req *htlcswitch.ChanClose) {
7✔
4205
        chanID := lnwire.NewChanIDFromOutPoint(*req.ChanPoint)
7✔
4206

7✔
4207
        channel, ok := p.activeChannels.Load(chanID)
7✔
4208

7✔
4209
        // Though this function can't be called for pending channels, we still
7✔
4210
        // check whether channel is nil for safety.
7✔
4211
        if !ok || channel == nil {
7✔
4212
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
×
4213
                        "unknown", chanID)
×
4214
                p.log.Errorf(err.Error())
×
4215
                req.Err <- err
×
4216
                return
×
4217
        }
×
4218

4219
        isTaprootChan := channel.ChanType().IsTaproot()
7✔
4220

7✔
4221
        switch req.CloseType {
7✔
4222
        // A type of CloseRegular indicates that the user has opted to close
4223
        // out this channel on-chain, so we execute the cooperative channel
4224
        // closure workflow.
4225
        case contractcourt.CloseRegular:
7✔
4226
                var err error
7✔
4227
                switch {
7✔
4228
                // If this is the RBF coop state machine, then we'll instruct
4229
                // it to send the shutdown message. This also might be an RBF
4230
                // iteration, in which case we'll be obtaining a new
4231
                // transaction w/ a higher fee rate.
4232
                //
4233
                // We don't support this close type for taproot channels yet
4234
                // however.
UNCOV
4235
                case !isTaprootChan && p.rbfCoopCloseAllowed():
×
UNCOV
4236
                        err = p.startRbfChanCloser(
×
UNCOV
4237
                                newRPCShutdownInit(req), channel.ChannelPoint(),
×
UNCOV
4238
                        )
×
4239
                default:
7✔
4240
                        err = p.initNegotiateChanCloser(req, channel)
7✔
4241
                }
4242

4243
                if err != nil {
8✔
4244
                        p.log.Errorf(err.Error())
1✔
4245
                        req.Err <- err
1✔
4246
                }
1✔
4247

4248
        // A type of CloseBreach indicates that the counterparty has breached
4249
        // the channel therefore we need to clean up our local state.
UNCOV
4250
        case contractcourt.CloseBreach:
×
UNCOV
4251
                // TODO(roasbeef): no longer need with newer beach logic?
×
UNCOV
4252
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
×
UNCOV
4253
                        "channel", req.ChanPoint)
×
UNCOV
4254
                p.WipeChannel(req.ChanPoint)
×
4255
        }
4256
}
4257

4258
// linkFailureReport is sent to the channelManager whenever a link reports a
4259
// link failure, and is forced to exit. The report houses the necessary
4260
// information to clean up the channel state, send back the error message, and
4261
// force close if necessary.
4262
type linkFailureReport struct {
4263
        chanPoint   wire.OutPoint
4264
        chanID      lnwire.ChannelID
4265
        shortChanID lnwire.ShortChannelID
4266
        linkErr     htlcswitch.LinkFailureError
4267
}
4268

4269
// handleLinkFailure processes a link failure report when a link in the switch
4270
// fails. It facilitates the removal of all channel state within the peer,
4271
// force closing the channel depending on severity, and sending the error
4272
// message back to the remote party.
UNCOV
4273
func (p *Brontide) handleLinkFailure(failure linkFailureReport) {
×
UNCOV
4274
        // Retrieve the channel from the map of active channels. We do this to
×
UNCOV
4275
        // have access to it even after WipeChannel remove it from the map.
×
UNCOV
4276
        chanID := lnwire.NewChanIDFromOutPoint(failure.chanPoint)
×
UNCOV
4277
        lnChan, _ := p.activeChannels.Load(chanID)
×
UNCOV
4278

×
UNCOV
4279
        // We begin by wiping the link, which will remove it from the switch,
×
UNCOV
4280
        // such that it won't be attempted used for any more updates.
×
UNCOV
4281
        //
×
UNCOV
4282
        // TODO(halseth): should introduce a way to atomically stop/pause the
×
UNCOV
4283
        // link and cancel back any adds in its mailboxes such that we can
×
UNCOV
4284
        // safely force close without the link being added again and updates
×
UNCOV
4285
        // being applied.
×
UNCOV
4286
        p.WipeChannel(&failure.chanPoint)
×
UNCOV
4287

×
UNCOV
4288
        // If the error encountered was severe enough, we'll now force close
×
UNCOV
4289
        // the channel to prevent reading it to the switch in the future.
×
UNCOV
4290
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureForceClose {
×
UNCOV
4291
                p.log.Warnf("Force closing link(%v)", failure.shortChanID)
×
UNCOV
4292

×
UNCOV
4293
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
×
UNCOV
4294
                        failure.chanPoint,
×
UNCOV
4295
                )
×
UNCOV
4296
                if err != nil {
×
UNCOV
4297
                        p.log.Errorf("unable to force close "+
×
UNCOV
4298
                                "link(%v): %v", failure.shortChanID, err)
×
UNCOV
4299
                } else {
×
UNCOV
4300
                        p.log.Infof("channel(%v) force "+
×
UNCOV
4301
                                "closed with txid %v",
×
UNCOV
4302
                                failure.shortChanID, closeTx.TxHash())
×
UNCOV
4303
                }
×
4304
        }
4305

4306
        // If this is a permanent failure, we will mark the channel borked.
UNCOV
4307
        if failure.linkErr.PermanentFailure && lnChan != nil {
×
4308
                p.log.Warnf("Marking link(%v) borked due to permanent "+
×
4309
                        "failure", failure.shortChanID)
×
4310

×
4311
                if err := lnChan.State().MarkBorked(); err != nil {
×
4312
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
4313
                                failure.shortChanID, err)
×
4314
                }
×
4315
        }
4316

4317
        // Send an error to the peer, why we failed the channel.
UNCOV
4318
        if failure.linkErr.ShouldSendToPeer() {
×
UNCOV
4319
                // If SendData is set, send it to the peer. If not, we'll use
×
UNCOV
4320
                // the standard error messages in the payload. We only include
×
UNCOV
4321
                // sendData in the cases where the error data does not contain
×
UNCOV
4322
                // sensitive information.
×
UNCOV
4323
                data := []byte(failure.linkErr.Error())
×
UNCOV
4324
                if failure.linkErr.SendData != nil {
×
4325
                        data = failure.linkErr.SendData
×
4326
                }
×
4327

UNCOV
4328
                var networkMsg lnwire.Message
×
UNCOV
4329
                if failure.linkErr.Warning {
×
4330
                        networkMsg = &lnwire.Warning{
×
4331
                                ChanID: failure.chanID,
×
4332
                                Data:   data,
×
4333
                        }
×
UNCOV
4334
                } else {
×
UNCOV
4335
                        networkMsg = &lnwire.Error{
×
UNCOV
4336
                                ChanID: failure.chanID,
×
UNCOV
4337
                                Data:   data,
×
UNCOV
4338
                        }
×
UNCOV
4339
                }
×
4340

UNCOV
4341
                err := p.SendMessage(true, networkMsg)
×
UNCOV
4342
                if err != nil {
×
4343
                        p.log.Errorf("unable to send msg to "+
×
4344
                                "remote peer: %v", err)
×
4345
                }
×
4346
        }
4347

4348
        // If the failure action is disconnect, then we'll execute that now. If
4349
        // we had to send an error above, it was a sync call, so we expect the
4350
        // message to be flushed on the wire by now.
UNCOV
4351
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
×
4352
                p.Disconnect(fmt.Errorf("link requested disconnect"))
×
4353
        }
×
4354
}
4355

4356
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
4357
// public key and the channel id.
4358
func (p *Brontide) fetchLinkFromKeyAndCid(
4359
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
19✔
4360

19✔
4361
        var chanLink htlcswitch.ChannelUpdateHandler
19✔
4362

19✔
4363
        // We don't need to check the error here, and can instead just loop
19✔
4364
        // over the slice and return nil.
19✔
4365
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
19✔
4366
        for _, link := range links {
37✔
4367
                if link.ChanID() == cid {
36✔
4368
                        chanLink = link
18✔
4369
                        break
18✔
4370
                }
4371
        }
4372

4373
        return chanLink
19✔
4374
}
4375

4376
// finalizeChanClosure performs the final clean up steps once the cooperative
4377
// closure transaction has been fully broadcast. The finalized closing state
4378
// machine should be passed in. Once the transaction has been sufficiently
4379
// confirmed, the channel will be marked as fully closed within the database,
4380
// and any clients will be notified of updates to the closing state.
4381
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
4✔
4382
        closeReq := chanCloser.CloseRequest()
4✔
4383

4✔
4384
        // First, we'll clear all indexes related to the channel in question.
4✔
4385
        chanPoint := chanCloser.Channel().ChannelPoint()
4✔
4386
        p.WipeChannel(&chanPoint)
4✔
4387

4✔
4388
        // Also clear the activeChanCloses map of this channel.
4✔
4389
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
4390
        p.activeChanCloses.Delete(cid) // TODO(roasbeef): existing race
4✔
4391

4✔
4392
        // Next, we'll launch a goroutine which will request to be notified by
4✔
4393
        // the ChainNotifier once the closure transaction obtains a single
4✔
4394
        // confirmation.
4✔
4395
        notifier := p.cfg.ChainNotifier
4✔
4396

4✔
4397
        // If any error happens during waitForChanToClose, forward it to
4✔
4398
        // closeReq. If this channel closure is not locally initiated, closeReq
4✔
4399
        // will be nil, so just ignore the error.
4✔
4400
        errChan := make(chan error, 1)
4✔
4401
        if closeReq != nil {
6✔
4402
                errChan = closeReq.Err
2✔
4403
        }
2✔
4404

4405
        closingTx, err := chanCloser.ClosingTx()
4✔
4406
        if err != nil {
4✔
4407
                if closeReq != nil {
×
4408
                        p.log.Error(err)
×
4409
                        closeReq.Err <- err
×
4410
                }
×
4411
        }
4412

4413
        closingTxid := closingTx.TxHash()
4✔
4414

4✔
4415
        // If this is a locally requested shutdown, update the caller with a
4✔
4416
        // new event detailing the current pending state of this request.
4✔
4417
        if closeReq != nil {
6✔
4418
                closeReq.Updates <- &PendingUpdate{
2✔
4419
                        Txid: closingTxid[:],
2✔
4420
                }
2✔
4421
        }
2✔
4422

4423
        localOut := chanCloser.LocalCloseOutput()
4✔
4424
        remoteOut := chanCloser.RemoteCloseOutput()
4✔
4425
        auxOut := chanCloser.AuxOutputs()
4✔
4426
        go WaitForChanToClose(
4✔
4427
                chanCloser.NegotiationHeight(), notifier, errChan,
4✔
4428
                &chanPoint, &closingTxid, closingTx.TxOut[0].PkScript, func() {
8✔
4429
                        // Respond to the local subsystem which requested the
4✔
4430
                        // channel closure.
4✔
4431
                        if closeReq != nil {
6✔
4432
                                closeReq.Updates <- &ChannelCloseUpdate{
2✔
4433
                                        ClosingTxid:       closingTxid[:],
2✔
4434
                                        Success:           true,
2✔
4435
                                        LocalCloseOutput:  localOut,
2✔
4436
                                        RemoteCloseOutput: remoteOut,
2✔
4437
                                        AuxOutputs:        auxOut,
2✔
4438
                                }
2✔
4439
                        }
2✔
4440
                },
4441
        )
4442
}
4443

4444
// WaitForChanToClose uses the passed notifier to wait until the channel has
4445
// been detected as closed on chain and then concludes by executing the
4446
// following actions: the channel point will be sent over the settleChan, and
4447
// finally the callback will be executed. If any error is encountered within
4448
// the function, then it will be sent over the errChan.
4449
func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
4450
        errChan chan error, chanPoint *wire.OutPoint,
4451
        closingTxID *chainhash.Hash, closeScript []byte, cb func()) {
4✔
4452

4✔
4453
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
4✔
4454
                "with txid: %v", chanPoint, closingTxID)
4✔
4455

4✔
4456
        // TODO(roasbeef): add param for num needed confs
4✔
4457
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
4✔
4458
                closingTxID, closeScript, 1, bestHeight,
4✔
4459
        )
4✔
4460
        if err != nil {
4✔
4461
                if errChan != nil {
×
4462
                        errChan <- err
×
4463
                }
×
4464
                return
×
4465
        }
4466

4467
        // In the case that the ChainNotifier is shutting down, all subscriber
4468
        // notification channels will be closed, generating a nil receive.
4469
        height, ok := <-confNtfn.Confirmed
4✔
4470
        if !ok {
4✔
UNCOV
4471
                return
×
UNCOV
4472
        }
×
4473

4474
        // The channel has been closed, remove it from any active indexes, and
4475
        // the database state.
4476
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
4✔
4477
                "height %v", chanPoint, height.BlockHeight)
4✔
4478

4✔
4479
        // Finally, execute the closure call back to mark the confirmation of
4✔
4480
        // the transaction closing the contract.
4✔
4481
        cb()
4✔
4482
}
4483

4484
// WipeChannel removes the passed channel point from all indexes associated with
4485
// the peer and the switch.
4486
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
4✔
4487
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
4✔
4488

4✔
4489
        p.activeChannels.Delete(chanID)
4✔
4490

4✔
4491
        // Instruct the HtlcSwitch to close this link as the channel is no
4✔
4492
        // longer active.
4✔
4493
        p.cfg.Switch.RemoveLink(chanID)
4✔
4494
}
4✔
4495

4496
// handleInitMsg handles the incoming init message which contains global and
4497
// local feature vectors. If feature vectors are incompatible then disconnect.
4498
func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
3✔
4499
        // First, merge any features from the legacy global features field into
3✔
4500
        // those presented in the local features fields.
3✔
4501
        err := msg.Features.Merge(msg.GlobalFeatures)
3✔
4502
        if err != nil {
3✔
4503
                return fmt.Errorf("unable to merge legacy global features: %w",
×
4504
                        err)
×
4505
        }
×
4506

4507
        // Then, finalize the remote feature vector providing the flattened
4508
        // feature bit namespace.
4509
        p.remoteFeatures = lnwire.NewFeatureVector(
3✔
4510
                msg.Features, lnwire.Features,
3✔
4511
        )
3✔
4512

3✔
4513
        // Now that we have their features loaded, we'll ensure that they
3✔
4514
        // didn't set any required bits that we don't know of.
3✔
4515
        err = feature.ValidateRequired(p.remoteFeatures)
3✔
4516
        if err != nil {
3✔
4517
                return fmt.Errorf("invalid remote features: %w", err)
×
4518
        }
×
4519

4520
        // Ensure the remote party's feature vector contains all transitive
4521
        // dependencies. We know ours are correct since they are validated
4522
        // during the feature manager's instantiation.
4523
        err = feature.ValidateDeps(p.remoteFeatures)
3✔
4524
        if err != nil {
3✔
4525
                return fmt.Errorf("invalid remote features: %w", err)
×
4526
        }
×
4527

4528
        // Now that we know we understand their requirements, we'll check to
4529
        // see if they don't support anything that we deem to be mandatory.
4530
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
3✔
4531
                return fmt.Errorf("data loss protection required")
×
4532
        }
×
4533

4534
        return nil
3✔
4535
}
4536

4537
// LocalFeatures returns the set of global features that has been advertised by
4538
// the local node. This allows sub-systems that use this interface to gate their
4539
// behavior off the set of negotiated feature bits.
4540
//
4541
// NOTE: Part of the lnpeer.Peer interface.
UNCOV
4542
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
×
UNCOV
4543
        return p.cfg.Features
×
UNCOV
4544
}
×
4545

4546
// RemoteFeatures returns the set of global features that has been advertised by
4547
// the remote node. This allows sub-systems that use this interface to gate
4548
// their behavior off the set of negotiated feature bits.
4549
//
4550
// NOTE: Part of the lnpeer.Peer interface.
4551
func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector {
20✔
4552
        return p.remoteFeatures
20✔
4553
}
20✔
4554

4555
// hasNegotiatedScidAlias returns true if we've negotiated the
4556
// option-scid-alias feature bit with the peer.
4557
func (p *Brontide) hasNegotiatedScidAlias() bool {
3✔
4558
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
3✔
4559
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
3✔
4560
        return peerHas && localHas
3✔
4561
}
3✔
4562

4563
// sendInitMsg sends the Init message to the remote peer. This message contains
4564
// our currently supported local and global features.
4565
func (p *Brontide) sendInitMsg(legacyChan bool) error {
7✔
4566
        features := p.cfg.Features.Clone()
7✔
4567
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
7✔
4568

7✔
4569
        // If we have a legacy channel open with a peer, we downgrade static
7✔
4570
        // remote required to optional in case the peer does not understand the
7✔
4571
        // required feature bit. If we do not do this, the peer will reject our
7✔
4572
        // connection because it does not understand a required feature bit, and
7✔
4573
        // our channel will be unusable.
7✔
4574
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
8✔
4575
                p.log.Infof("Legacy channel open with peer, " +
1✔
4576
                        "downgrading static remote required feature bit to " +
1✔
4577
                        "optional")
1✔
4578

1✔
4579
                // Unset and set in both the local and global features to
1✔
4580
                // ensure both sets are consistent and merge able by old and
1✔
4581
                // new nodes.
1✔
4582
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4583
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4584

1✔
4585
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
4586
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
4587
        }
1✔
4588

4589
        msg := lnwire.NewInitMessage(
7✔
4590
                legacyFeatures.RawFeatureVector,
7✔
4591
                features.RawFeatureVector,
7✔
4592
        )
7✔
4593

7✔
4594
        return p.writeMessage(msg)
7✔
4595
}
4596

4597
// resendChanSyncMsg will attempt to find a channel sync message for the closed
4598
// channel and resend it to our peer.
UNCOV
4599
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
×
UNCOV
4600
        // If we already re-sent the mssage for this channel, we won't do it
×
UNCOV
4601
        // again.
×
UNCOV
4602
        if _, ok := p.resentChanSyncMsg[cid]; ok {
×
UNCOV
4603
                return nil
×
UNCOV
4604
        }
×
4605

4606
        // Check if we have any channel sync messages stored for this channel.
UNCOV
4607
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
×
UNCOV
4608
        if err != nil {
×
UNCOV
4609
                return fmt.Errorf("unable to fetch channel sync messages for "+
×
UNCOV
4610
                        "peer %v: %v", p, err)
×
UNCOV
4611
        }
×
4612

UNCOV
4613
        if c.LastChanSyncMsg == nil {
×
4614
                return fmt.Errorf("no chan sync message stored for channel %v",
×
4615
                        cid)
×
4616
        }
×
4617

UNCOV
4618
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
×
4619
                return fmt.Errorf("ignoring channel reestablish from "+
×
4620
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
4621
        }
×
4622

UNCOV
4623
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
×
UNCOV
4624
                "peer", cid)
×
UNCOV
4625

×
UNCOV
4626
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
×
4627
                return fmt.Errorf("failed resending channel sync "+
×
4628
                        "message to peer %v: %v", p, err)
×
4629
        }
×
4630

UNCOV
4631
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
×
UNCOV
4632
                cid)
×
UNCOV
4633

×
UNCOV
4634
        // Note down that we sent the message, so we won't resend it again for
×
UNCOV
4635
        // this connection.
×
UNCOV
4636
        p.resentChanSyncMsg[cid] = struct{}{}
×
UNCOV
4637

×
UNCOV
4638
        return nil
×
4639
}
4640

4641
// SendMessage sends a variadic number of high-priority messages to the remote
4642
// peer. The first argument denotes if the method should block until the
4643
// messages have been sent to the remote peer or an error is returned,
4644
// otherwise it returns immediately after queuing.
4645
//
4646
// NOTE: Part of the lnpeer.Peer interface.
4647
func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error {
3✔
4648
        return p.sendMessage(sync, true, msgs...)
3✔
4649
}
3✔
4650

4651
// SendMessageLazy sends a variadic number of low-priority messages to the
4652
// remote peer. The first argument denotes if the method should block until
4653
// the messages have been sent to the remote peer or an error is returned,
4654
// otherwise it returns immediately after queueing.
4655
//
4656
// NOTE: Part of the lnpeer.Peer interface.
4657
func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
1✔
4658
        return p.sendMessage(sync, false, msgs...)
1✔
4659
}
1✔
4660

4661
// sendMessage queues a variadic number of messages using the passed priority
4662
// to the remote peer. If sync is true, this method will block until the
4663
// messages have been sent to the remote peer or an error is returned, otherwise
4664
// it returns immediately after queueing.
4665
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
4✔
4666
        // Add all incoming messages to the outgoing queue. A list of error
4✔
4667
        // chans is populated for each message if the caller requested a sync
4✔
4668
        // send.
4✔
4669
        var errChans []chan error
4✔
4670
        if sync {
5✔
4671
                errChans = make([]chan error, 0, len(msgs))
1✔
4672
        }
1✔
4673
        for _, msg := range msgs {
8✔
4674
                // If a sync send was requested, create an error chan to listen
4✔
4675
                // for an ack from the writeHandler.
4✔
4676
                var errChan chan error
4✔
4677
                if sync {
5✔
4678
                        errChan = make(chan error, 1)
1✔
4679
                        errChans = append(errChans, errChan)
1✔
4680
                }
1✔
4681

4682
                if priority {
7✔
4683
                        p.queueMsg(msg, errChan)
3✔
4684
                } else {
4✔
4685
                        p.queueMsgLazy(msg, errChan)
1✔
4686
                }
1✔
4687
        }
4688

4689
        // Wait for all replies from the writeHandler. For async sends, this
4690
        // will be a NOP as the list of error chans is nil.
4691
        for _, errChan := range errChans {
5✔
4692
                select {
1✔
4693
                case err := <-errChan:
1✔
4694
                        return err
1✔
4695
                case <-p.cg.Done():
×
4696
                        return lnpeer.ErrPeerExiting
×
4697
                case <-p.cfg.Quit:
×
4698
                        return lnpeer.ErrPeerExiting
×
4699
                }
4700
        }
4701

4702
        return nil
3✔
4703
}
4704

4705
// PubKey returns the pubkey of the peer in compressed serialized format.
4706
//
4707
// NOTE: Part of the lnpeer.Peer interface.
4708
func (p *Brontide) PubKey() [33]byte {
2✔
4709
        return p.cfg.PubKeyBytes
2✔
4710
}
2✔
4711

4712
// IdentityKey returns the public key of the remote peer.
4713
//
4714
// NOTE: Part of the lnpeer.Peer interface.
4715
func (p *Brontide) IdentityKey() *btcec.PublicKey {
15✔
4716
        return p.cfg.Addr.IdentityKey
15✔
4717
}
15✔
4718

4719
// Address returns the network address of the remote peer.
4720
//
4721
// NOTE: Part of the lnpeer.Peer interface.
UNCOV
4722
func (p *Brontide) Address() net.Addr {
×
UNCOV
4723
        return p.cfg.Addr.Address
×
UNCOV
4724
}
×
4725

4726
// AddNewChannel adds a new channel to the peer. The channel should fail to be
4727
// added if the cancel channel is closed.
4728
//
4729
// NOTE: Part of the lnpeer.Peer interface.
4730
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
UNCOV
4731
        cancel <-chan struct{}) error {
×
UNCOV
4732

×
UNCOV
4733
        errChan := make(chan error, 1)
×
UNCOV
4734
        newChanMsg := &newChannelMsg{
×
UNCOV
4735
                channel: newChan,
×
UNCOV
4736
                err:     errChan,
×
UNCOV
4737
        }
×
UNCOV
4738

×
UNCOV
4739
        select {
×
UNCOV
4740
        case p.newActiveChannel <- newChanMsg:
×
4741
        case <-cancel:
×
4742
                return errors.New("canceled adding new channel")
×
4743
        case <-p.cg.Done():
×
4744
                return lnpeer.ErrPeerExiting
×
4745
        }
4746

4747
        // We pause here to wait for the peer to recognize the new channel
4748
        // before we close the channel barrier corresponding to the channel.
UNCOV
4749
        select {
×
UNCOV
4750
        case err := <-errChan:
×
UNCOV
4751
                return err
×
4752
        case <-p.cg.Done():
×
4753
                return lnpeer.ErrPeerExiting
×
4754
        }
4755
}
4756

4757
// AddPendingChannel adds a pending open channel to the peer. The channel
4758
// should fail to be added if the cancel channel is closed.
4759
//
4760
// NOTE: Part of the lnpeer.Peer interface.
4761
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
UNCOV
4762
        cancel <-chan struct{}) error {
×
UNCOV
4763

×
UNCOV
4764
        errChan := make(chan error, 1)
×
UNCOV
4765
        newChanMsg := &newChannelMsg{
×
UNCOV
4766
                channelID: cid,
×
UNCOV
4767
                err:       errChan,
×
UNCOV
4768
        }
×
UNCOV
4769

×
UNCOV
4770
        select {
×
UNCOV
4771
        case p.newPendingChannel <- newChanMsg:
×
4772

4773
        case <-cancel:
×
4774
                return errors.New("canceled adding pending channel")
×
4775

4776
        case <-p.cg.Done():
×
4777
                return lnpeer.ErrPeerExiting
×
4778
        }
4779

4780
        // We pause here to wait for the peer to recognize the new pending
4781
        // channel before we close the channel barrier corresponding to the
4782
        // channel.
UNCOV
4783
        select {
×
UNCOV
4784
        case err := <-errChan:
×
UNCOV
4785
                return err
×
4786

4787
        case <-cancel:
×
4788
                return errors.New("canceled adding pending channel")
×
4789

4790
        case <-p.cg.Done():
×
4791
                return lnpeer.ErrPeerExiting
×
4792
        }
4793
}
4794

4795
// RemovePendingChannel removes a pending open channel from the peer.
4796
//
4797
// NOTE: Part of the lnpeer.Peer interface.
UNCOV
4798
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
×
UNCOV
4799
        errChan := make(chan error, 1)
×
UNCOV
4800
        newChanMsg := &newChannelMsg{
×
UNCOV
4801
                channelID: cid,
×
UNCOV
4802
                err:       errChan,
×
UNCOV
4803
        }
×
UNCOV
4804

×
UNCOV
4805
        select {
×
UNCOV
4806
        case p.removePendingChannel <- newChanMsg:
×
4807
        case <-p.cg.Done():
×
4808
                return lnpeer.ErrPeerExiting
×
4809
        }
4810

4811
        // We pause here to wait for the peer to respond to the cancellation of
4812
        // the pending channel before we close the channel barrier
4813
        // corresponding to the channel.
UNCOV
4814
        select {
×
UNCOV
4815
        case err := <-errChan:
×
UNCOV
4816
                return err
×
4817

4818
        case <-p.cg.Done():
×
4819
                return lnpeer.ErrPeerExiting
×
4820
        }
4821
}
4822

4823
// StartTime returns the time at which the connection was established if the
4824
// peer started successfully, and zero otherwise.
UNCOV
4825
func (p *Brontide) StartTime() time.Time {
×
UNCOV
4826
        return p.startTime
×
UNCOV
4827
}
×
4828

4829
// handleCloseMsg is called when a new cooperative channel closure related
4830
// message is received from the remote peer. We'll use this message to advance
4831
// the chan closer state machine.
4832
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
13✔
4833
        link := p.fetchLinkFromKeyAndCid(msg.cid)
13✔
4834

13✔
4835
        // We'll now fetch the matching closing state machine in order to
13✔
4836
        // continue, or finalize the channel closure process.
13✔
4837
        chanCloserE, err := p.fetchActiveChanCloser(msg.cid)
13✔
4838
        if err != nil {
13✔
UNCOV
4839
                // If the channel is not known to us, we'll simply ignore this
×
UNCOV
4840
                // message.
×
UNCOV
4841
                if err == ErrChannelNotFound {
×
UNCOV
4842
                        return
×
UNCOV
4843
                }
×
4844

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

×
4847
                errMsg := &lnwire.Error{
×
4848
                        ChanID: msg.cid,
×
4849
                        Data:   lnwire.ErrorData(err.Error()),
×
4850
                }
×
4851
                p.queueMsg(errMsg, nil)
×
4852
                return
×
4853
        }
4854

4855
        if chanCloserE.IsRight() {
13✔
4856
                // TODO(roasbeef): assert?
×
4857
                return
×
4858
        }
×
4859

4860
        // At this point, we'll only enter this call path if a negotiate chan
4861
        // closer was used. So we'll extract that from the either now.
4862
        //
4863
        // TODO(roabeef): need extra helper func for either to make cleaner
4864
        var chanCloser *chancloser.ChanCloser
13✔
4865
        chanCloserE.WhenLeft(func(c *chancloser.ChanCloser) {
26✔
4866
                chanCloser = c
13✔
4867
        })
13✔
4868

4869
        handleErr := func(err error) {
13✔
UNCOV
4870
                err = fmt.Errorf("unable to process close msg: %w", err)
×
UNCOV
4871
                p.log.Error(err)
×
UNCOV
4872

×
UNCOV
4873
                // As the negotiations failed, we'll reset the channel state
×
UNCOV
4874
                // machine to ensure we act to on-chain events as normal.
×
UNCOV
4875
                chanCloser.Channel().ResetState()
×
UNCOV
4876
                if chanCloser.CloseRequest() != nil {
×
4877
                        chanCloser.CloseRequest().Err <- err
×
4878
                }
×
4879

UNCOV
4880
                p.activeChanCloses.Delete(msg.cid)
×
UNCOV
4881

×
UNCOV
4882
                p.Disconnect(err)
×
4883
        }
4884

4885
        // Next, we'll process the next message using the target state machine.
4886
        // We'll either continue negotiation, or halt.
4887
        switch typed := msg.msg.(type) {
13✔
4888
        case *lnwire.Shutdown:
5✔
4889
                // Disable incoming adds immediately.
5✔
4890
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
5✔
4891
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
4892
                                link.ChanID())
×
4893
                }
×
4894

4895
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
5✔
4896
                if err != nil {
5✔
4897
                        handleErr(err)
×
4898
                        return
×
4899
                }
×
4900

4901
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
8✔
4902
                        // If the link is nil it means we can immediately queue
3✔
4903
                        // the Shutdown message since we don't have to wait for
3✔
4904
                        // commitment transaction synchronization.
3✔
4905
                        if link == nil {
4✔
4906
                                p.queueMsg(&msg, nil)
1✔
4907
                                return
1✔
4908
                        }
1✔
4909

4910
                        // Immediately disallow any new HTLC's from being added
4911
                        // in the outgoing direction.
4912
                        if !link.DisableAdds(htlcswitch.Outgoing) {
2✔
4913
                                p.log.Warnf("Outgoing link adds already "+
×
4914
                                        "disabled: %v", link.ChanID())
×
4915
                        }
×
4916

4917
                        // When we have a Shutdown to send, we defer it till the
4918
                        // next time we send a CommitSig to remain spec
4919
                        // compliant.
4920
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
4✔
4921
                                p.queueMsg(&msg, nil)
2✔
4922
                        })
2✔
4923
                })
4924

4925
                beginNegotiation := func() {
10✔
4926
                        oClosingSigned, err := chanCloser.BeginNegotiation()
5✔
4927
                        if err != nil {
5✔
4928
                                handleErr(err)
×
4929
                                return
×
4930
                        }
×
4931

4932
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
10✔
4933
                                p.queueMsg(&msg, nil)
5✔
4934
                        })
5✔
4935
                }
4936

4937
                if link == nil {
6✔
4938
                        beginNegotiation()
1✔
4939
                } else {
5✔
4940
                        // Now we register a flush hook to advance the
4✔
4941
                        // ChanCloser and possibly send out a ClosingSigned
4✔
4942
                        // when the link finishes draining.
4✔
4943
                        link.OnFlushedOnce(func() {
8✔
4944
                                // Remove link in goroutine to prevent deadlock.
4✔
4945
                                go p.cfg.Switch.RemoveLink(msg.cid)
4✔
4946
                                beginNegotiation()
4✔
4947
                        })
4✔
4948
                }
4949

4950
        case *lnwire.ClosingSigned:
8✔
4951
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
8✔
4952
                if err != nil {
8✔
UNCOV
4953
                        handleErr(err)
×
UNCOV
4954
                        return
×
UNCOV
4955
                }
×
4956

4957
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
16✔
4958
                        p.queueMsg(&msg, nil)
8✔
4959
                })
8✔
4960

4961
        default:
×
4962
                panic("impossible closeMsg type")
×
4963
        }
4964

4965
        // If we haven't finished close negotiations, then we'll continue as we
4966
        // can't yet finalize the closure.
4967
        if _, err := chanCloser.ClosingTx(); err != nil {
20✔
4968
                return
8✔
4969
        }
8✔
4970

4971
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
4972
        // the channel closure by notifying relevant sub-systems and launching a
4973
        // goroutine to wait for close tx conf.
4974
        p.finalizeChanClosure(chanCloser)
4✔
4975
}
4976

4977
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
4978
// the channelManager goroutine, which will shut down the link and possibly
4979
// close the channel.
UNCOV
4980
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
×
UNCOV
4981
        select {
×
UNCOV
4982
        case p.localCloseChanReqs <- req:
×
UNCOV
4983
                p.log.Info("Local close channel request is going to be " +
×
UNCOV
4984
                        "delivered to the peer")
×
4985
        case <-p.cg.Done():
×
4986
                p.log.Info("Unable to deliver local close channel request " +
×
4987
                        "to peer")
×
4988
        }
4989
}
4990

4991
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
UNCOV
4992
func (p *Brontide) NetAddress() *lnwire.NetAddress {
×
UNCOV
4993
        return p.cfg.Addr
×
UNCOV
4994
}
×
4995

4996
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
UNCOV
4997
func (p *Brontide) Inbound() bool {
×
UNCOV
4998
        return p.cfg.Inbound
×
UNCOV
4999
}
×
5000

5001
// ConnReq is a getter for the Brontide's connReq in cfg.
UNCOV
5002
func (p *Brontide) ConnReq() *connmgr.ConnReq {
×
UNCOV
5003
        return p.cfg.ConnReq
×
UNCOV
5004
}
×
5005

5006
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
UNCOV
5007
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
×
UNCOV
5008
        return p.cfg.ErrorBuffer
×
UNCOV
5009
}
×
5010

5011
// SetAddress sets the remote peer's address given an address.
5012
func (p *Brontide) SetAddress(address net.Addr) {
×
5013
        p.cfg.Addr.Address = address
×
5014
}
×
5015

5016
// ActiveSignal returns the peer's active signal.
UNCOV
5017
func (p *Brontide) ActiveSignal() chan struct{} {
×
UNCOV
5018
        return p.activeSignal
×
UNCOV
5019
}
×
5020

5021
// Conn returns a pointer to the peer's connection struct.
UNCOV
5022
func (p *Brontide) Conn() net.Conn {
×
UNCOV
5023
        return p.cfg.Conn
×
UNCOV
5024
}
×
5025

5026
// BytesReceived returns the number of bytes received from the peer.
UNCOV
5027
func (p *Brontide) BytesReceived() uint64 {
×
UNCOV
5028
        return atomic.LoadUint64(&p.bytesReceived)
×
UNCOV
5029
}
×
5030

5031
// BytesSent returns the number of bytes sent to the peer.
UNCOV
5032
func (p *Brontide) BytesSent() uint64 {
×
UNCOV
5033
        return atomic.LoadUint64(&p.bytesSent)
×
UNCOV
5034
}
×
5035

5036
// LastRemotePingPayload returns the last payload the remote party sent as part
5037
// of their ping.
UNCOV
5038
func (p *Brontide) LastRemotePingPayload() []byte {
×
UNCOV
5039
        pingPayload := p.lastPingPayload.Load()
×
UNCOV
5040
        if pingPayload == nil {
×
UNCOV
5041
                return []byte{}
×
UNCOV
5042
        }
×
5043

5044
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
5045
        if !ok {
×
5046
                return nil
×
5047
        }
×
5048

5049
        return pingBytes
×
5050
}
5051

5052
// attachChannelEventSubscription creates a channel event subscription and
5053
// attaches to client to Brontide if the reenableTimeout is no greater than 1
5054
// minute.
5055
func (p *Brontide) attachChannelEventSubscription() error {
3✔
5056
        // If the timeout is greater than 1 minute, it's unlikely that the link
3✔
5057
        // hasn't yet finished its reestablishment. Return a nil without
3✔
5058
        // creating the client to specify that we don't want to retry.
3✔
5059
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
3✔
UNCOV
5060
                return nil
×
UNCOV
5061
        }
×
5062

5063
        // When the reenable timeout is less than 1 minute, it's likely the
5064
        // channel link hasn't finished its reestablishment yet. In that case,
5065
        // we'll give it a second chance by subscribing to the channel update
5066
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
5067
        // enabling the channel again.
5068
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
3✔
5069
        if err != nil {
3✔
5070
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
5071
        }
×
5072

5073
        p.channelEventClient = sub
3✔
5074

3✔
5075
        return nil
3✔
5076
}
5077

5078
// updateNextRevocation updates the existing channel's next revocation if it's
5079
// nil.
5080
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
3✔
5081
        chanPoint := c.FundingOutpoint
3✔
5082
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5083

3✔
5084
        // Read the current channel.
3✔
5085
        currentChan, loaded := p.activeChannels.Load(chanID)
3✔
5086

3✔
5087
        // currentChan should exist, but we perform a check anyway to avoid nil
3✔
5088
        // pointer dereference.
3✔
5089
        if !loaded {
4✔
5090
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
5091
                        chanID)
1✔
5092
        }
1✔
5093

5094
        // currentChan should not be nil, but we perform a check anyway to
5095
        // avoid nil pointer dereference.
5096
        if currentChan == nil {
3✔
5097
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
5098
                        chanID)
1✔
5099
        }
1✔
5100

5101
        // If we're being sent a new channel, and our existing channel doesn't
5102
        // have the next revocation, then we need to update the current
5103
        // existing channel.
5104
        if currentChan.RemoteNextRevocation() != nil {
1✔
5105
                return nil
×
5106
        }
×
5107

5108
        p.log.Infof("Processing retransmitted ChannelReady for "+
1✔
5109
                "ChannelPoint(%v)", chanPoint)
1✔
5110

1✔
5111
        nextRevoke := c.RemoteNextRevocation
1✔
5112

1✔
5113
        err := currentChan.InitNextRevocation(nextRevoke)
1✔
5114
        if err != nil {
1✔
5115
                return fmt.Errorf("unable to init next revocation: %w", err)
×
5116
        }
×
5117

5118
        return nil
1✔
5119
}
5120

5121
// addActiveChannel adds a new active channel to the `activeChannels` map. It
5122
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
5123
// it and assembles it with a channel link.
UNCOV
5124
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
×
UNCOV
5125
        chanPoint := c.FundingOutpoint
×
UNCOV
5126
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
5127

×
UNCOV
5128
        // If we've reached this point, there are two possible scenarios.  If
×
UNCOV
5129
        // the channel was in the active channels map as nil, then it was
×
UNCOV
5130
        // loaded from disk and we need to send reestablish. Else, it was not
×
UNCOV
5131
        // loaded from disk and we don't need to send reestablish as this is a
×
UNCOV
5132
        // fresh channel.
×
UNCOV
5133
        shouldReestablish := p.isLoadedFromDisk(chanID)
×
UNCOV
5134

×
UNCOV
5135
        chanOpts := c.ChanOpts
×
UNCOV
5136
        if shouldReestablish {
×
UNCOV
5137
                // If we have to do the reestablish dance for this channel,
×
UNCOV
5138
                // ensure that we don't try to call InitRemoteMusigNonces twice
×
UNCOV
5139
                // by calling SkipNonceInit.
×
UNCOV
5140
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
×
UNCOV
5141
        }
×
5142

UNCOV
5143
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
×
5144
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
5145
        })
×
UNCOV
5146
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
×
5147
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
5148
        })
×
UNCOV
5149
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
×
5150
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
5151
        })
×
5152

5153
        // If not already active, we'll add this channel to the set of active
5154
        // channels, so we can look it up later easily according to its channel
5155
        // ID.
UNCOV
5156
        lnChan, err := lnwallet.NewLightningChannel(
×
UNCOV
5157
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
×
UNCOV
5158
        )
×
UNCOV
5159
        if err != nil {
×
5160
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
5161
        }
×
5162

5163
        // Store the channel in the activeChannels map.
UNCOV
5164
        p.activeChannels.Store(chanID, lnChan)
×
UNCOV
5165

×
UNCOV
5166
        p.log.Infof("New channel active ChannelPoint(%v) with peer", chanPoint)
×
UNCOV
5167

×
UNCOV
5168
        // Next, we'll assemble a ChannelLink along with the necessary items it
×
UNCOV
5169
        // needs to function.
×
UNCOV
5170
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
×
UNCOV
5171
        if err != nil {
×
5172
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
5173
                        err)
×
5174
        }
×
5175

5176
        // We'll query the channel DB for the new channel's initial forwarding
5177
        // policies to determine the policy we start out with.
UNCOV
5178
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
×
UNCOV
5179
        if err != nil {
×
5180
                return fmt.Errorf("unable to query for initial forwarding "+
×
5181
                        "policy: %v", err)
×
5182
        }
×
5183

5184
        // Create the link and add it to the switch.
UNCOV
5185
        err = p.addLink(
×
UNCOV
5186
                &chanPoint, lnChan, initialPolicy, chainEvents,
×
UNCOV
5187
                shouldReestablish, fn.None[lnwire.Shutdown](),
×
UNCOV
5188
        )
×
UNCOV
5189
        if err != nil {
×
5190
                return fmt.Errorf("can't register new channel link(%v) with "+
×
5191
                        "peer", chanPoint)
×
5192
        }
×
5193

UNCOV
5194
        isTaprootChan := c.ChanType.IsTaproot()
×
UNCOV
5195

×
UNCOV
5196
        // We're using the old co-op close, so we don't need to init the new RBF
×
UNCOV
5197
        // chan closer. If this is a taproot channel, then we'll also fall
×
UNCOV
5198
        // through, as we don't support this type yet w/ rbf close.
×
UNCOV
5199
        if !p.rbfCoopCloseAllowed() || isTaprootChan {
×
UNCOV
5200
                return nil
×
UNCOV
5201
        }
×
5202

5203
        // Now that the link has been added above, we'll also init an RBF chan
5204
        // closer for this channel, but only if the new close feature is
5205
        // negotiated.
5206
        //
5207
        // Creating this here ensures that any shutdown messages sent will be
5208
        // automatically routed by the msg router.
UNCOV
5209
        if _, err := p.initRbfChanCloser(lnChan); err != nil {
×
5210
                p.activeChanCloses.Delete(chanID)
×
5211

×
5212
                return fmt.Errorf("unable to init RBF chan closer for new "+
×
5213
                        "chan: %w", err)
×
5214
        }
×
5215

UNCOV
5216
        return nil
×
5217
}
5218

5219
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
5220
// know this channel ID or not, we'll either add it to the `activeChannels` map
5221
// or init the next revocation for it.
UNCOV
5222
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
×
UNCOV
5223
        newChan := req.channel
×
UNCOV
5224
        chanPoint := newChan.FundingOutpoint
×
UNCOV
5225
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
5226

×
UNCOV
5227
        // Only update RemoteNextRevocation if the channel is in the
×
UNCOV
5228
        // activeChannels map and if we added the link to the switch. Only
×
UNCOV
5229
        // active channels will be added to the switch.
×
UNCOV
5230
        if p.isActiveChannel(chanID) {
×
UNCOV
5231
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
×
UNCOV
5232
                        chanPoint)
×
UNCOV
5233

×
UNCOV
5234
                // Handle it and close the err chan on the request.
×
UNCOV
5235
                close(req.err)
×
UNCOV
5236

×
UNCOV
5237
                // Update the next revocation point.
×
UNCOV
5238
                err := p.updateNextRevocation(newChan.OpenChannel)
×
UNCOV
5239
                if err != nil {
×
5240
                        p.log.Errorf(err.Error())
×
5241
                }
×
5242

UNCOV
5243
                return
×
5244
        }
5245

5246
        // This is a new channel, we now add it to the map.
UNCOV
5247
        if err := p.addActiveChannel(req.channel); err != nil {
×
5248
                // Log and send back the error to the request.
×
5249
                p.log.Errorf(err.Error())
×
5250
                req.err <- err
×
5251

×
5252
                return
×
5253
        }
×
5254

5255
        // Close the err chan if everything went fine.
UNCOV
5256
        close(req.err)
×
5257
}
5258

5259
// handleNewPendingChannel takes a `newChannelMsg` request and add it to
5260
// `activeChannels` map with nil value. This pending channel will be saved as
5261
// it may become active in the future. Once active, the funding manager will
5262
// send it again via `AddNewChannel`, and we'd handle the link creation there.
5263
func (p *Brontide) handleNewPendingChannel(req *newChannelMsg) {
4✔
5264
        defer close(req.err)
4✔
5265

4✔
5266
        chanID := req.channelID
4✔
5267

4✔
5268
        // If we already have this channel, something is wrong with the funding
4✔
5269
        // flow as it will only be marked as active after `ChannelReady` is
4✔
5270
        // handled. In this case, we will do nothing but log an error, just in
4✔
5271
        // case this is a legit channel.
4✔
5272
        if p.isActiveChannel(chanID) {
5✔
5273
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
5274
                        "pending channel request", chanID)
1✔
5275

1✔
5276
                return
1✔
5277
        }
1✔
5278

5279
        // The channel has already been added, we will do nothing and return.
5280
        if p.isPendingChannel(chanID) {
4✔
5281
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
5282
                        "pending channel request", chanID)
1✔
5283

1✔
5284
                return
1✔
5285
        }
1✔
5286

5287
        // This is a new channel, we now add it to the map `activeChannels`
5288
        // with nil value and mark it as a newly added channel in
5289
        // `addedChannels`.
5290
        p.activeChannels.Store(chanID, nil)
2✔
5291
        p.addedChannels.Store(chanID, struct{}{})
2✔
5292
}
5293

5294
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
5295
// from `activeChannels` map. The request will be ignored if the channel is
5296
// considered active by Brontide. Noop if the channel ID cannot be found.
5297
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
4✔
5298
        defer close(req.err)
4✔
5299

4✔
5300
        chanID := req.channelID
4✔
5301

4✔
5302
        // If we already have this channel, something is wrong with the funding
4✔
5303
        // flow as it will only be marked as active after `ChannelReady` is
4✔
5304
        // handled. In this case, we will log an error and exit.
4✔
5305
        if p.isActiveChannel(chanID) {
5✔
5306
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
5307
                        chanID)
1✔
5308
                return
1✔
5309
        }
1✔
5310

5311
        // The channel has not been added yet, we will log a warning as there
5312
        // is an unexpected call from funding manager.
5313
        if !p.isPendingChannel(chanID) {
4✔
5314
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
1✔
5315
        }
1✔
5316

5317
        // Remove the record of this pending channel.
5318
        p.activeChannels.Delete(chanID)
3✔
5319
        p.addedChannels.Delete(chanID)
3✔
5320
}
5321

5322
// sendLinkUpdateMsg sends a message that updates the channel to the
5323
// channel's message stream.
UNCOV
5324
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
×
UNCOV
5325
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
×
UNCOV
5326

×
UNCOV
5327
        chanStream, ok := p.activeMsgStreams[cid]
×
UNCOV
5328
        if !ok {
×
UNCOV
5329
                // If a stream hasn't yet been created, then we'll do so, add
×
UNCOV
5330
                // it to the map, and finally start it.
×
UNCOV
5331
                chanStream = newChanMsgStream(p, cid)
×
UNCOV
5332
                p.activeMsgStreams[cid] = chanStream
×
UNCOV
5333
                chanStream.Start()
×
UNCOV
5334

×
UNCOV
5335
                // Stop the stream when quit.
×
UNCOV
5336
                go func() {
×
UNCOV
5337
                        <-p.cg.Done()
×
UNCOV
5338
                        chanStream.Stop()
×
UNCOV
5339
                }()
×
5340
        }
5341

5342
        // With the stream obtained, add the message to the stream so we can
5343
        // continue processing message.
UNCOV
5344
        chanStream.AddMsg(msg)
×
5345
}
5346

5347
// scaleTimeout multiplies the argument duration by a constant factor depending
5348
// on variious heuristics. Currently this is only used to check whether our peer
5349
// appears to be connected over Tor and relaxes the timout deadline. However,
5350
// this is subject to change and should be treated as opaque.
5351
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
67✔
5352
        if p.isTorConnection {
67✔
UNCOV
5353
                return timeout * time.Duration(torTimeoutMultiplier)
×
UNCOV
5354
        }
×
5355

5356
        return timeout
67✔
5357
}
5358

5359
// CoopCloseUpdates is a struct used to communicate updates for an active close
5360
// to the caller.
5361
type CoopCloseUpdates struct {
5362
        UpdateChan chan interface{}
5363

5364
        ErrChan chan error
5365
}
5366

5367
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5368
// point has an active RBF chan closer.
UNCOV
5369
func (p *Brontide) ChanHasRbfCoopCloser(chanPoint wire.OutPoint) bool {
×
UNCOV
5370
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
5371
        chanCloser, found := p.activeChanCloses.Load(chanID)
×
UNCOV
5372
        if !found {
×
UNCOV
5373
                return false
×
UNCOV
5374
        }
×
5375

UNCOV
5376
        return chanCloser.IsRight()
×
5377
}
5378

5379
// TriggerCoopCloseRbfBump given a chan ID, and the params needed to trigger a
5380
// new RBF co-op close update, a bump is attempted. A channel used for updates,
5381
// along with one used to o=communicate any errors is returned. If no chan
5382
// closer is found, then false is returned for the second argument.
5383
func (p *Brontide) TriggerCoopCloseRbfBump(ctx context.Context,
5384
        chanPoint wire.OutPoint, feeRate chainfee.SatPerKWeight,
UNCOV
5385
        deliveryScript lnwire.DeliveryAddress) (*CoopCloseUpdates, error) {
×
UNCOV
5386

×
UNCOV
5387
        // If RBF coop close isn't permitted, then we'll an error.
×
UNCOV
5388
        if !p.rbfCoopCloseAllowed() {
×
5389
                return nil, fmt.Errorf("rbf coop close not enabled for " +
×
5390
                        "channel")
×
5391
        }
×
5392

UNCOV
5393
        closeUpdates := &CoopCloseUpdates{
×
UNCOV
5394
                UpdateChan: make(chan interface{}, 1),
×
UNCOV
5395
                ErrChan:    make(chan error, 1),
×
UNCOV
5396
        }
×
UNCOV
5397

×
UNCOV
5398
        // We'll re-use the existing switch struct here, even though we're
×
UNCOV
5399
        // bypassing the switch entirely.
×
UNCOV
5400
        closeReq := htlcswitch.ChanClose{
×
UNCOV
5401
                CloseType:      contractcourt.CloseRegular,
×
UNCOV
5402
                ChanPoint:      &chanPoint,
×
UNCOV
5403
                TargetFeePerKw: feeRate,
×
UNCOV
5404
                DeliveryScript: deliveryScript,
×
UNCOV
5405
                Updates:        closeUpdates.UpdateChan,
×
UNCOV
5406
                Err:            closeUpdates.ErrChan,
×
UNCOV
5407
                Ctx:            ctx,
×
UNCOV
5408
        }
×
UNCOV
5409

×
UNCOV
5410
        err := p.startRbfChanCloser(newRPCShutdownInit(&closeReq), chanPoint)
×
UNCOV
5411
        if err != nil {
×
5412
                return nil, err
×
5413
        }
×
5414

UNCOV
5415
        return closeUpdates, nil
×
5416
}
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