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

lightningnetwork / lnd / 17832014233

18 Sep 2025 02:30PM UTC coverage: 57.196% (-9.4%) from 66.637%
17832014233

Pull #10133

github

web-flow
Merge 3e12b2767 into b34fc964b
Pull Request #10133: Add `XFindBaseLocalChanAlias` RPC

20 of 34 new or added lines in 4 files covered. (58.82%)

28528 existing lines in 459 files now uncovered.

99371 of 173739 relevant lines covered (57.2%)

1.78 hits per line

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

77.05
/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/lightningnetwork/lnd/buffer"
23
        "github.com/lightningnetwork/lnd/chainntnfs"
24
        "github.com/lightningnetwork/lnd/channeldb"
25
        "github.com/lightningnetwork/lnd/channelnotifier"
26
        "github.com/lightningnetwork/lnd/contractcourt"
27
        "github.com/lightningnetwork/lnd/discovery"
28
        "github.com/lightningnetwork/lnd/feature"
29
        "github.com/lightningnetwork/lnd/fn/v2"
30
        "github.com/lightningnetwork/lnd/funding"
31
        graphdb "github.com/lightningnetwork/lnd/graph/db"
32
        "github.com/lightningnetwork/lnd/graph/db/models"
33
        "github.com/lightningnetwork/lnd/htlcswitch"
34
        "github.com/lightningnetwork/lnd/htlcswitch/hodl"
35
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
36
        "github.com/lightningnetwork/lnd/input"
37
        "github.com/lightningnetwork/lnd/invoices"
38
        "github.com/lightningnetwork/lnd/keychain"
39
        "github.com/lightningnetwork/lnd/lnpeer"
40
        "github.com/lightningnetwork/lnd/lntypes"
41
        "github.com/lightningnetwork/lnd/lnutils"
42
        "github.com/lightningnetwork/lnd/lnwallet"
43
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
44
        "github.com/lightningnetwork/lnd/lnwallet/chancloser"
45
        "github.com/lightningnetwork/lnd/lnwire"
46
        "github.com/lightningnetwork/lnd/msgmux"
47
        "github.com/lightningnetwork/lnd/netann"
48
        "github.com/lightningnetwork/lnd/pool"
49
        "github.com/lightningnetwork/lnd/protofsm"
50
        "github.com/lightningnetwork/lnd/queue"
51
        "github.com/lightningnetwork/lnd/subscribe"
52
        "github.com/lightningnetwork/lnd/ticker"
53
        "github.com/lightningnetwork/lnd/tlv"
54
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
55
)
56

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

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

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

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

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

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

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

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

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

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

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

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

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

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

125
        err chan error
126
}
127

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

440
        // QuiescenceTimeout is the max duration that the channel can be
441
        // quiesced. Any dependent protocols (dynamic commitments, splicing,
442
        // etc.) must finish their operations under this timeout value,
443
        // otherwise the node will disconnect.
444
        QuiescenceTimeout time.Duration
445

446
        // MaxFeeExposure limits the number of outstanding fees in a channel.
447
        // This value will be passed to created links.
448
        MaxFeeExposure lnwire.MilliSatoshi
449

450
        // MsgRouter is an optional instance of the main message router that
451
        // the peer will use. If None, then a new default version will be used
452
        // in place.
453
        MsgRouter fn.Option[msgmux.Router]
454

455
        // AuxChanCloser is an optional instance of an abstraction that can be
456
        // used to modify the way the co-op close transaction is constructed.
457
        AuxChanCloser fn.Option[chancloser.AuxChanCloser]
458

459
        // ShouldFwdExpEndorsement is a closure that indicates whether
460
        // experimental endorsement signals should be set.
461
        ShouldFwdExpEndorsement func() bool
462

463
        // NoDisconnectOnPongFailure indicates whether the peer should *not* be
464
        // disconnected if a pong is not received in time or is mismatched.
465
        NoDisconnectOnPongFailure bool
466

467
        // Quit is the server's quit channel. If this is closed, we halt operation.
468
        Quit chan struct{}
469
}
470

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

477
// makeNegotiateCloser creates a new negotiate closer from a
478
// chancloser.ChanCloser.
479
func makeNegotiateCloser(chanCloser *chancloser.ChanCloser) chanCloserFsm {
3✔
480
        return fn.NewLeft[*chancloser.ChanCloser, *chancloser.RbfChanCloser](
3✔
481
                chanCloser,
3✔
482
        )
3✔
483
}
3✔
484

485
// makeRbfCloser creates a new RBF closer from a chancloser.RbfChanCloser.
486
func makeRbfCloser(rbfCloser *chancloser.RbfChanCloser) chanCloserFsm {
3✔
487
        return fn.NewRight[*chancloser.ChanCloser](
3✔
488
                rbfCloser,
3✔
489
        )
3✔
490
}
3✔
491

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

502
        // MUST be used atomically.
503
        bytesReceived uint64
504
        bytesSent     uint64
505

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

523
        pingManager *PingManager
524

525
        // lastPingPayload stores an unsafe pointer wrapped as an atomic
526
        // variable which points to the last payload the remote party sent us
527
        // as their ping.
528
        //
529
        // MUST be used atomically.
530
        lastPingPayload atomic.Value
531

532
        cfg Config
533

534
        // activeSignal when closed signals that the peer is now active and
535
        // ready to process messages.
536
        activeSignal chan struct{}
537

538
        // startTime is the time this peer connection was successfully established.
539
        // It will be zero for peers that did not successfully call Start().
540
        startTime time.Time
541

542
        // sendQueue is the channel which is used to queue outgoing messages to be
543
        // written onto the wire. Note that this channel is unbuffered.
544
        sendQueue chan outgoingMsg
545

546
        // outgoingQueue is a buffered channel which allows second/third party
547
        // objects to queue messages to be sent out on the wire.
548
        outgoingQueue chan outgoingMsg
549

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

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

569
        // newActiveChannel is used by the fundingManager to send fully opened
570
        // channels to the source peer which handled the funding workflow.
571
        newActiveChannel chan *newChannelMsg
572

573
        // newPendingChannel is used by the fundingManager to send pending open
574
        // channels to the source peer which handled the funding workflow.
575
        newPendingChannel chan *newChannelMsg
576

577
        // removePendingChannel is used by the fundingManager to cancel pending
578
        // open channels to the source peer when the funding flow is failed.
579
        removePendingChannel chan *newChannelMsg
580

581
        // activeMsgStreams is a map from channel id to the channel streams that
582
        // proxy messages to individual, active links.
583
        activeMsgStreams map[lnwire.ChannelID]*msgStream
584

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

591
        // localCloseChanReqs is a channel in which any local requests to close
592
        // a particular channel are sent over.
593
        localCloseChanReqs chan *htlcswitch.ChanClose
594

595
        // linkFailures receives all reported channel failures from the switch,
596
        // and instructs the channelManager to clean remaining channel state.
597
        linkFailures chan linkFailureReport
598

599
        // chanCloseMsgs is a channel that any message related to channel
600
        // closures are sent over. This includes lnwire.Shutdown message as
601
        // well as lnwire.ClosingSigned messages.
602
        chanCloseMsgs chan *closeMsg
603

604
        // remoteFeatures is the feature vector received from the peer during
605
        // the connection handshake.
606
        remoteFeatures *lnwire.FeatureVector
607

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

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

623
        // msgRouter is an instance of the msgmux.Router which is used to send
624
        // off new wire messages for handing.
625
        msgRouter fn.Option[msgmux.Router]
626

627
        // globalMsgRouter is a flag that indicates whether we have a global
628
        // msg router. If so, then we don't worry about stopping the msg router
629
        // when a peer disconnects.
630
        globalMsgRouter bool
631

632
        startReady chan struct{}
633

634
        // cg is a helper that encapsulates a wait group and quit channel and
635
        // allows contexts that either block or cancel on those depending on
636
        // the use case.
637
        cg *fn.ContextGuard
638

639
        // log is a peer-specific logging instance.
640
        log btclog.Logger
641
}
642

643
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer
644
// interface.
645
var _ lnpeer.Peer = (*Brontide)(nil)
646

647
// NewBrontide creates a new Brontide from a peer.Config struct.
648
func NewBrontide(cfg Config) *Brontide {
3✔
649
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
3✔
650

3✔
651
        // We have a global message router if one was passed in via the config.
3✔
652
        // In this case, we don't need to attempt to tear it down when the peer
3✔
653
        // is stopped.
3✔
654
        globalMsgRouter := cfg.MsgRouter.IsSome()
3✔
655

3✔
656
        // We'll either use the msg router instance passed in, or create a new
3✔
657
        // blank instance.
3✔
658
        msgRouter := cfg.MsgRouter.Alt(fn.Some[msgmux.Router](
3✔
659
                msgmux.NewMultiMsgRouter(),
3✔
660
        ))
3✔
661

3✔
662
        p := &Brontide{
3✔
663
                cfg:           cfg,
3✔
664
                activeSignal:  make(chan struct{}),
3✔
665
                sendQueue:     make(chan outgoingMsg),
3✔
666
                outgoingQueue: make(chan outgoingMsg),
3✔
667
                addedChannels: &lnutils.SyncMap[lnwire.ChannelID, struct{}]{},
3✔
668
                activeChannels: &lnutils.SyncMap[
3✔
669
                        lnwire.ChannelID, *lnwallet.LightningChannel,
3✔
670
                ]{},
3✔
671
                newActiveChannel:     make(chan *newChannelMsg, 1),
3✔
672
                newPendingChannel:    make(chan *newChannelMsg, 1),
3✔
673
                removePendingChannel: make(chan *newChannelMsg),
3✔
674

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

3✔
690
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
6✔
691
                remoteAddr := cfg.Conn.RemoteAddr().String()
3✔
692
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
3✔
693
                        strings.Contains(remoteAddr, "127.0.0.1")
3✔
694
        }
3✔
695

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

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

723
                return lastSerializedBlockHeader[:]
×
724
        }
725

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

739
        p.pingManager = NewPingManager(&PingManagerConfig{
3✔
740
                NewPingPayload:   newPingPayload,
3✔
741
                NewPongSize:      randPongSize,
3✔
742
                IntervalDuration: p.scaleTimeout(pingInterval),
3✔
743
                TimeoutDuration:  p.scaleTimeout(pingTimeout),
3✔
744
                SendPing: func(ping *lnwire.Ping) {
3✔
745
                        p.queueMsg(ping, nil)
×
746
                },
×
747
                OnPongFailure: func(reason error,
748
                        timeWaitedForPong time.Duration,
749
                        lastKnownRTT time.Duration) {
×
750

×
751
                        logMsg := fmt.Sprintf("pong response "+
×
752
                                "failure for %s: %v. Time waited for this "+
×
753
                                "pong: %v. Last successful RTT: %v.",
×
754
                                p, reason, timeWaitedForPong, lastKnownRTT)
×
755

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

765
                        p.log.Warnf("%s -- disconnecting", logMsg)
×
766

×
767
                        go p.Disconnect(fmt.Errorf("pong failure: %w", reason))
×
768
                },
769
        })
770

771
        return p
3✔
772
}
773

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

781
        // Once we've finished starting up the peer, we'll signal to other
782
        // goroutines that the they can move forward to tear down the peer, or
783
        // carry out other relevant changes.
784
        defer close(p.startReady)
3✔
785

3✔
786
        p.log.Tracef("starting with conn[%v->%v]",
3✔
787
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
3✔
788

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

800
        if len(activeChans) == 0 {
6✔
801
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
3✔
802
        }
3✔
803

804
        // Quickly check if we have any existing legacy channels with this
805
        // peer.
806
        haveLegacyChan := false
3✔
807
        for _, c := range activeChans {
6✔
808
                if c.ChanType.IsTweakless() {
6✔
809
                        continue
3✔
810
                }
811

812
                haveLegacyChan = true
3✔
813
                break
3✔
814
        }
815

816
        // Exchange local and global features, the init message should be very
817
        // first between two nodes.
818
        if err := p.sendInitMsg(haveLegacyChan); err != nil {
6✔
819
                return fmt.Errorf("unable to send init msg: %w", err)
3✔
820
        }
3✔
821

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

3✔
831
                msg, err := p.readNextMessage()
3✔
832
                if err != nil {
5✔
833
                        readErr <- err
2✔
834
                        msgChan <- nil
2✔
835
                        return
2✔
836
                }
2✔
837
                readErr <- nil
3✔
838
                msgChan <- msg
3✔
839
        }()
840

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

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

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

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

883
        // Register the message router now as we may need to register some
884
        // endpoints while loading the channels below.
885
        p.msgRouter.WhenSome(func(router msgmux.Router) {
6✔
886
                router.Start(context.Background())
3✔
887
        })
3✔
888

889
        msgs, err := p.loadActiveChannels(activeChans)
3✔
890
        if err != nil {
3✔
891
                return fmt.Errorf("unable to load channels: %w", err)
×
892
        }
×
893

894
        p.startTime = time.Now()
3✔
895

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

3✔
903
                // Send the messages directly via writeMessage and bypass the
3✔
904
                // writeHandler goroutine.
3✔
905
                for _, msg := range msgs {
6✔
906
                        if err := p.writeMessage(msg); err != nil {
3✔
907
                                return fmt.Errorf("unable to send "+
×
908
                                        "reestablish msg: %v", err)
×
909
                        }
×
910
                }
911
        }
912

913
        err = p.pingManager.Start()
3✔
914
        if err != nil {
3✔
915
                return fmt.Errorf("could not start ping manager %w", err)
×
916
        }
×
917

918
        p.cg.WgAdd(4)
3✔
919
        go p.queueHandler()
3✔
920
        go p.writeHandler()
3✔
921
        go p.channelManager()
3✔
922
        go p.readHandler()
3✔
923

3✔
924
        // Signal to any external processes that the peer is now active.
3✔
925
        close(p.activeSignal)
3✔
926

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

3✔
942
        return nil
3✔
943
}
944

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

3✔
953
                if p.cfg.AuthGossiper == nil {
3✔
UNCOV
954
                        // This should only ever be hit in the unit tests.
×
UNCOV
955
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
×
UNCOV
956
                                "gossip sync.")
×
UNCOV
957
                        return
×
UNCOV
958
                }
×
959

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

973
// taprootShutdownAllowed returns true if both parties have negotiated the
974
// shutdown-any-segwit feature.
975
func (p *Brontide) taprootShutdownAllowed() bool {
3✔
976
        return p.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
3✔
977
                p.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
3✔
978
}
3✔
979

980
// rbfCoopCloseAllowed returns true if both parties have negotiated the new RBF
981
// coop close feature.
982
func (p *Brontide) rbfCoopCloseAllowed() bool {
3✔
983
        bothHaveBit := func(bit lnwire.FeatureBit) bool {
6✔
984
                return p.RemoteFeatures().HasFeature(bit) &&
3✔
985
                        p.LocalFeatures().HasFeature(bit)
3✔
986
        }
3✔
987

988
        return bothHaveBit(lnwire.RbfCoopCloseOptional) ||
3✔
989
                bothHaveBit(lnwire.RbfCoopCloseOptionalStaging)
3✔
990
}
991

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

1002
// addrWithInternalKey takes a delivery script, then attempts to supplement it
1003
// with information related to the internal key for the addr, but only if it's
1004
// a taproot addr.
1005
func (p *Brontide) addrWithInternalKey(
1006
        deliveryScript []byte) (*chancloser.DeliveryAddrWithKey, error) {
3✔
1007

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

1019
        return &chancloser.DeliveryAddrWithKey{
3✔
1020
                DeliveryAddress: deliveryScript,
3✔
1021
                InternalKey: fn.MapOption(
3✔
1022
                        func(desc keychain.KeyDescriptor) btcec.PublicKey {
6✔
1023
                                return *desc.PubKey
3✔
1024
                        },
3✔
1025
                )(internalKeyDesc),
1026
        }, nil
1027
}
1028

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

3✔
1036
        // Return a slice of messages to send to the peers in case the channel
3✔
1037
        // cannot be loaded normally.
3✔
1038
        var msgs []lnwire.Message
3✔
1039

3✔
1040
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
3✔
1041

3✔
1042
        for _, dbChan := range chans {
6✔
1043
                hasScidFeature := dbChan.ChanType.HasScidAliasFeature()
3✔
1044
                if scidAliasNegotiated && !hasScidFeature {
6✔
1045
                        // We'll request and store an alias. Once the channel
3✔
1046
                        // gets confirmed any alias entries will be deleted.
3✔
1047
                        // We'll queue a channel_ready message with the new
3✔
1048
                        // alias. This should technically be done *after* the
3✔
1049
                        // reestablish, but this behavior is pre-existing since
3✔
1050
                        // the funding manager may already queue a
3✔
1051
                        // channel_ready before the channel_reestablish.
3✔
1052
                        if !dbChan.IsPending {
6✔
1053
                                aliasScid, err := p.cfg.RequestAlias()
3✔
1054
                                if err != nil {
3✔
1055
                                        return nil, err
×
1056
                                }
×
1057

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

1065
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
1066
                                        dbChan.FundingOutpoint,
3✔
1067
                                )
3✔
1068

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

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

3✔
1081
                                msgs = append(msgs, channelReadyMsg)
3✔
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.
1089
                        err := dbChan.MarkScidAliasNegotiated()
3✔
1090
                        if err != nil {
3✔
1091
                                return nil, err
×
1092
                        }
×
1093
                }
1094

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

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

1118
                chanPoint := dbChan.FundingOutpoint
3✔
1119

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

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

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

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

3✔
1133
                        // To help our peer recover from a potential data loss,
3✔
1134
                        // we resend our channel reestablish message if the
3✔
1135
                        // channel is in a borked state. We won't process any
3✔
1136
                        // channel reestablish message sent from the peer, but
3✔
1137
                        // that's okay since the assumption is that we did when
3✔
1138
                        // marking the channel borked.
3✔
1139
                        chanSync, err := dbChan.ChanSyncMsg()
3✔
1140
                        if err != nil {
3✔
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)
3✔
1148

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

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

1164
                                if shutdownMsg == nil {
6✔
1165
                                        continue
3✔
1166
                                }
1167

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

1173
                        continue
3✔
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.
1179
                graph := p.cfg.ChannelGraph
3✔
1180
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
3✔
1181
                        &chanPoint,
3✔
1182
                )
3✔
1183
                if err != nil && !errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
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.
1194
                var selfPolicy *models.ChannelEdgePolicy
3✔
1195
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
3✔
1196
                        p.cfg.ServerPubKey[:]) {
6✔
1197

3✔
1198
                        selfPolicy = p1
3✔
1199
                } else {
6✔
1200
                        selfPolicy = p2
3✔
1201
                }
3✔
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.
1206
                var forwardingPolicy *models.ForwardingPolicy
3✔
1207
                if selfPolicy != nil {
6✔
1208
                        forwardingPolicy = &models.ForwardingPolicy{
3✔
1209
                                MinHTLCOut:    selfPolicy.MinHTLC,
3✔
1210
                                MaxHTLC:       selfPolicy.MaxHTLC,
3✔
1211
                                BaseFee:       selfPolicy.FeeBaseMSat,
3✔
1212
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
3✔
1213
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
3✔
1214
                        }
3✔
1215
                        selfPolicy.InboundFee.WhenSome(func(fee lnwire.Fee) {
3✔
1216
                                inboundFee := models.NewInboundFeeFromWire(fee)
×
1217
                                forwardingPolicy.InboundFee = inboundFee
×
1218
                        })
×
1219
                } else {
3✔
1220
                        p.log.Warnf("Unable to find our forwarding policy "+
3✔
1221
                                "for channel %v, using default values",
3✔
1222
                                chanPoint)
3✔
1223
                        forwardingPolicy = &p.cfg.RoutingPolicy
3✔
1224
                }
3✔
1225

1226
                p.log.Tracef("Using link policy of: %v",
3✔
1227
                        lnutils.SpewLogClosure(forwardingPolicy))
3✔
1228

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

3✔
1238
                        continue
3✔
1239
                }
1240

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

1246
                isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
1247

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

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

×
1268
                                return
×
1269
                        }
×
1270

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

×
1287
                                return
×
1288
                        }
×
1289

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

3✔
1294
                        p.activeChanCloses.Store(chanID, makeNegotiateCloser(
3✔
1295
                                negotiateChanCloser,
3✔
1296
                        ))
3✔
1297

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

×
1304
                                return
×
1305
                        }
×
1306

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

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

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

1330
                p.activeChannels.Store(chanID, lnChan)
3✔
1331

3✔
1332
                // We're using the old co-op close, so we don't need to init
3✔
1333
                // the new RBF chan closer. If we have a taproot chan, then
3✔
1334
                // we'll also use the legacy type, so we don't need to make the
3✔
1335
                // new closer.
3✔
1336
                if !p.rbfCoopCloseAllowed() || isTaprootChan {
6✔
1337
                        continue
3✔
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.
1346
                if _, err := p.initRbfChanCloser(lnChan); err != nil {
3✔
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.
1356
                restartShutdown := func(s channeldb.ShutdownInfo) error {
6✔
1357
                        return p.startRbfChanCloser(
3✔
1358
                                newRestartShutdownInit(s),
3✔
1359
                                lnChan.ChannelPoint(),
3✔
1360
                        )
3✔
1361
                }
3✔
1362
                err = fn.MapOptionZ(shutdownInfo, restartShutdown)
3✔
1363
                if err != nil {
3✔
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,
1377
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
3✔
1378

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

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

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

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

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

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

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

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

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

3✔
1474
        hasConfirmedPublicChan := false
3✔
1475
        for _, channel := range channels {
6✔
1476
                if channel.IsPending {
6✔
1477
                        continue
3✔
1478
                }
1479
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
6✔
1480
                        continue
3✔
1481
                }
1482

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

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

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

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

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

1511
        maybeSendUpd := func(cid lnwire.ChannelID,
3✔
1512
                lnChan *lnwallet.LightningChannel) error {
6✔
1513

3✔
1514
                // Nil channels are pending, so we'll skip them.
3✔
1515
                if lnChan == nil {
6✔
1516
                        return nil
3✔
1517
                }
3✔
1518

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

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

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

3✔
1543
                        return nil
3✔
1544
                }
3✔
1545

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

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

×
1558
                        return err
×
1559
                }
×
1560

1561
                return nil
3✔
1562
        }
1563

1564
        p.activeChannels.ForEach(maybeSendUpd)
3✔
1565
}
1566

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

1584
        select {
3✔
1585
        case <-ready:
3✔
1586
        case <-p.cg.Done():
3✔
1587
        }
1588

1589
        p.cg.WgWait()
3✔
1590
}
1591

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

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

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

1621
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
3✔
1622
        p.storeError(err)
3✔
1623

3✔
1624
        p.log.Infof(err.Error())
3✔
1625

3✔
1626
        // Stop PingManager before closing TCP connection.
3✔
1627
        p.pingManager.Stop()
3✔
1628

3✔
1629
        // Ensure that the TCP connection is properly closed before continuing.
3✔
1630
        p.cfg.Conn.Close()
3✔
1631

3✔
1632
        p.cg.Quit()
3✔
1633

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

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

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

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

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

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

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

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

1711
        p.logWireMessage(nextMsg, true)
3✔
1712

3✔
1713
        return nextMsg, nil
3✔
1714
}
1715

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

1724
        peer *Brontide
1725

1726
        apply func(lnwire.Message)
1727

1728
        startMsg string
1729
        stopMsg  string
1730

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

1734
        mtx sync.Mutex
1735

1736
        producerSema chan struct{}
1737

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

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

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

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

1768
        return stream
3✔
1769
}
1770

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

1777
// Stop stops the chanMsgStream.
1778
func (ms *msgStream) Stop() {
3✔
1779
        // TODO(roasbeef): signal too?
3✔
1780

3✔
1781
        close(ms.quit)
3✔
1782

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

1790
        ms.wg.Wait()
3✔
1791
}
1792

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

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

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

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

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

3✔
1830
                ms.msgCond.L.Unlock()
3✔
1831

3✔
1832
                ms.apply(msg)
3✔
1833

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

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

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

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

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

3✔
1881
        p.log.Tracef("Waiting for link=%v to be active", cid)
3✔
1882

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

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

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

1922
                        chanPoint := event.ChannelPoint
3✔
1923

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

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

1935
                case <-p.cg.Done():
3✔
1936
                        return nil
3✔
1937
                }
1938
        }
1939
}
1940

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

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

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

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

1974
                chanLink.HandleChannelUpdate(msg)
3✔
1975
        }
1976

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2109
                // No error occurred, and the message was handled by the
2110
                // router.
2111
                if err == nil {
6✔
2112
                        continue
3✔
2113
                }
2114

2115
                var (
3✔
2116
                        targetChan   lnwire.ChannelID
3✔
2117
                        isLinkUpdate bool
3✔
2118
                )
3✔
2119

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

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

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

2136
                case *lnwire.OpenChannel,
2137
                        *lnwire.AcceptChannel,
2138
                        *lnwire.FundingCreated,
2139
                        *lnwire.FundingSigned,
2140
                        *lnwire.ChannelReady:
3✔
2141

3✔
2142
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2143

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

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

2161
                case *lnwire.Error:
3✔
2162
                        targetChan = msg.ChanID
3✔
2163
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
3✔
2164

2165
                case *lnwire.ChannelReestablish:
3✔
2166
                        targetChan = msg.ChanID
3✔
2167
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2168

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

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

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

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

3✔
2211
                        discStream.AddMsg(msg)
3✔
2212

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

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

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

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

2236
                idleTimer.Reset(idleTimeout)
3✔
2237
        }
2238

2239
        p.Disconnect(errors.New("read handler closed"))
3✔
2240

3✔
2241
        p.log.Trace("readHandler for peer done")
3✔
2242
}
2243

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

2252
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
3✔
2253
}
2254

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

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

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

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

3✔
2286
        return channel != nil
3✔
2287
}
3✔
2288

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

2298
        return channel == nil
3✔
2299
}
2300

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

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

3✔
2315
        p.activeChannels.Range(func(_ lnwire.ChannelID,
3✔
2316
                channel *lnwallet.LightningChannel) bool {
6✔
2317

3✔
2318
                // Pending channels will be nil in the activeChannels map.
3✔
2319
                if channel == nil {
6✔
2320
                        // Return true to continue the iteration.
3✔
2321
                        return true
3✔
2322
                }
3✔
2323

2324
                haveChannels = true
3✔
2325

3✔
2326
                // Return false to break the iteration.
3✔
2327
                return false
3✔
2328
        })
2329

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

2337
        p.cfg.ErrorBuffer.Add(
3✔
2338
                &TimestampedError{Timestamp: time.Now(), Error: err},
3✔
2339
        )
3✔
2340
}
2341

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

3✔
2351
        if errMsg, ok := msg.(*lnwire.Error); ok {
6✔
2352
                p.storeError(errMsg)
3✔
2353
        }
3✔
2354

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

2363
                return false
×
2364

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

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

2375
        default:
3✔
2376
                return false
3✔
2377
        }
2378
}
2379

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

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

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

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

2405
        case *lnwire.FundingSigned:
3✔
2406
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
3✔
2407

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

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

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

2420
        case *lnwire.ClosingSig:
3✔
2421
                return fmt.Sprintf("chan_id=%v", msg.ChannelID)
3✔
2422

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

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

3✔
2433
                                blindingPoint = b.Val.SerializeCompressed()
3✔
2434
                        },
3✔
2435
                )
2436

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

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

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

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

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

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

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

2467
        case *lnwire.Error:
3✔
2468
                return fmt.Sprintf("%v", msg.Error())
3✔
2469

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2532
        case *lnwire.Custom:
3✔
2533
                return fmt.Sprintf("type=%d", msg.Type)
3✔
2534
        }
2535

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

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

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

2557
                preposition := "to"
3✔
2558
                if read {
6✔
2559
                        preposition = "from"
3✔
2560
                }
3✔
2561

2562
                var msgType string
3✔
2563
                if msg.MsgType() < lnwire.CustomTypeStart {
6✔
2564
                        msgType = msg.MsgType().String()
3✔
2565
                } else {
6✔
2566
                        msgType = "custom"
3✔
2567
                }
3✔
2568

2569
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
3✔
2570
                        msgType, summary, preposition, p)
3✔
2571
        }))
2572

2573
        prefix := "readMessage from peer"
3✔
2574
        if !read {
6✔
2575
                prefix = "writeMessage to peer"
3✔
2576
        }
3✔
2577

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

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

2598
        noiseConn := p.cfg.Conn
3✔
2599

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

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

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

2621
                return err
3✔
2622
        }
2623

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

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

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

2651
        return flushMsg()
3✔
2652
}
2653

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

2669
        var exitErr error
3✔
2670

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

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

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

×
2700
                                goto retry
×
2701
                        }
2702

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

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

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

2725
                case <-p.cg.Done():
3✔
2726
                        exitErr = lnpeer.ErrPeerExiting
3✔
2727
                        break out
3✔
2728
                }
2729
        }
2730

2731
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2732
        // disconnect.
2733
        p.cg.WgDone()
3✔
2734

3✔
2735
        p.Disconnect(exitErr)
3✔
2736

3✔
2737
        p.log.Trace("writeHandler for peer done")
3✔
2738
}
2739

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

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

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

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

2765
                if elem != nil {
6✔
2766
                        front := elem.Value.(outgoingMsg)
3✔
2767

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

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

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

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

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

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

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

3✔
2850
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2851
                activeChan *lnwallet.LightningChannel) error {
6✔
2852

3✔
2853
                // If the activeChan is nil, then we skip it as the channel is
3✔
2854
                // pending.
3✔
2855
                if activeChan == nil {
6✔
2856
                        return nil
3✔
2857
                }
3✔
2858

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

2865
                snapshot := activeChan.StateSnapshot()
3✔
2866
                snapshots = append(snapshots, snapshot)
3✔
2867

3✔
2868
                return nil
3✔
2869
        })
2870

2871
        return snapshots
3✔
2872
}
2873

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

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

3✔
2893
        return txscript.PayToAddrScript(deliveryAddr)
3✔
2894
}
2895

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

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

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

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

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

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

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

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

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

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

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

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

3✔
2984
                                // Exit if the channel is nil as it's a pending
3✔
2985
                                // channel.
3✔
2986
                                if lc == nil {
6✔
2987
                                        return nil
3✔
2988
                                }
3✔
2989

2990
                                lc.ResetState()
3✔
2991

3✔
2992
                                return nil
3✔
2993
                        })
2994

2995
                        break out
3✔
2996
                }
2997
        }
2998
}
2999

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

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

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

3✔
3018
                switch {
3✔
3019
                // No error occurred, continue to request the next channel.
3020
                case err == nil:
3✔
3021
                        continue
3✔
3022

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

3✔
3029
                        continue
3✔
3030

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

×
3048
                                continue
×
3049
                        }
3050

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

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

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

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

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

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

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

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

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

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

3132
        chanCloser = makeNegotiateCloser(negotiateChanCloser)
3✔
3133

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

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

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

3✔
3145
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
3✔
3146
                lnChan *lnwallet.LightningChannel) bool {
6✔
3147

3✔
3148
                // If the lnChan is nil, continue as this is a pending channel.
3✔
3149
                if lnChan == nil {
4✔
3150
                        return true
1✔
3151
                }
1✔
3152

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

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

3168
                activePublicChans = append(
3✔
3169
                        activePublicChans, dbChan.FundingOutpoint,
3✔
3170
                )
3✔
3171

3✔
3172
                return true
3✔
3173
        })
3174

3175
        return activePublicChans
3✔
3176
}
3177

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

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

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

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

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

3213
                return nil
×
3214
        }
3215

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

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

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

3241
                                continue
×
3242
                        }
3243

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

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

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

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

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

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

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

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

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

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

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

3✔
3311
        isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
3312

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

3332
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
3✔
3333

3✔
3334
        var deliveryScript []byte
3✔
3335

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

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

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

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

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

3373
                shutdownDesc := fn.MapOption(
3✔
3374
                        newRestartShutdownInit,
3✔
3375
                )(shutdownInfo)
3✔
3376

3✔
3377
                err = p.startRbfChanCloser(
3✔
3378
                        fn.FlattenOption(shutdownDesc), lnChan.ChannelPoint(),
3✔
3379
                )
3✔
3380

3✔
3381
                return nil, err
3✔
3382
        }
3383

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

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

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

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

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

3422
        return shutdownMsg, nil
×
3423
}
3424

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

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

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

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

3469
        return chanCloser, nil
3✔
3470
}
3471

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

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

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

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

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

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

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

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

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

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

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

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

3549
        return nil
3✔
3550
}
3551

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

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

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

3✔
3569
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3570
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3571

3✔
3572
        var (
3✔
3573
                lastTxids    lntypes.Dual[chainhash.Hash]
3✔
3574
                lastFeeRates lntypes.Dual[chainfee.SatPerVByte]
3✔
3575
        )
3✔
3576

3✔
3577
        maybeNotifyTxBroadcast := func(state chancloser.AsymmetricPeerState,
3✔
3578
                party lntypes.ChannelParty) {
6✔
3579

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

3✔
3589
                        peerLog.Warnf("ChannelPoint(%v): encountered close "+
3✔
3590
                                "err: %v", closeReq.ChanPoint, err)
3✔
3591

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

3598
                        return
3✔
3599
                }
3600

3601
                closePending, ok := state.(*chancloser.ClosePending)
3✔
3602

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

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

3✔
3618
                        return
3✔
3619
                }
3✔
3620

3621
                feeRate := closePending.FeeRate
3✔
3622
                lastFeeRates.SetForParty(party, feeRate)
3✔
3623

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

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

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

3648
                lastTxids.SetForParty(party, closingTxid)
3✔
3649
        }
3650

3651
        peerLog.Infof("Observing RBF close updates for channel %v",
3✔
3652
                closeReq.ChanPoint)
3✔
3653

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

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

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

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

3✔
3696
                                return
3✔
3697
                        }
3698

3699
                case <-closeReq.Ctx.Done():
3✔
3700
                        return
3✔
3701

3702
                case <-p.cg.Done():
3✔
3703
                        return
3✔
3704
                }
3705
        }
3706
}
3707

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

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

3✔
3720
        return &chanErrorReporter{
3✔
3721
                chanID: chanID,
3✔
3722
                peer:   peer,
3✔
3723
        }
3✔
3724
}
3✔
3725

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

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

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

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

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

×
3764
                return
×
3765
        }
×
3766

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

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

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

3✔
3784
        defer p.cg.WgDone()
3✔
3785

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

3792
        coopCloseStates := chanCloser.RegisterStateEvents()
3✔
3793
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3794

3✔
3795
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3796

3✔
3797
        sendChanFlushed := func() {
6✔
3798
                chanState := channel.StateSnapshot()
3✔
3799

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

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

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

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

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

3✔
3836
                                return
3✔
3837
                        }
3✔
3838

3839
                case <-p.cg.Done():
3✔
3840
                        return
3✔
3841
                }
3842
        }
3843
}
3844

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

3✔
3851
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
3✔
3852

3✔
3853
        link := p.fetchLinkFromKeyAndCid(chanID)
3✔
3854

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

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

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

3872
        peerPub := *p.IdentityKey()
3✔
3873

3✔
3874
        msgMapper := chancloser.NewRbfMsgMapper(
3✔
3875
                uint32(startingHeight), chanID, peerPub,
3✔
3876
        )
3✔
3877

3✔
3878
        initialState := chancloser.ChannelActive{}
3✔
3879

3✔
3880
        scid := channel.ZeroConfRealScid().UnwrapOr(
3✔
3881
                channel.ShortChanID(),
3✔
3882
        )
3✔
3883

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

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

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

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

3✔
3935
        ctx := context.Background()
3✔
3936
        chanCloser := protofsm.NewStateMachine(protoCfg)
3✔
3937
        chanCloser.Start(ctx)
3✔
3938

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

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

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

3953
        p.activeChanCloses.Store(chanID, makeRbfCloser(&chanCloser))
3✔
3954

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

3✔
3961
        return &chanCloser, nil
3✔
3962
}
3963

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

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

3✔
3978
                var feeRate fn.Option[chainfee.SatPerKWeight]
3✔
3979
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
6✔
3980
                        feeRate = fn.Some(req.TargetFeePerKw)
3✔
3981
                })
3✔
3982

3983
                return feeRate
3✔
3984
        })(s)
3985

3986
        return fn.FlattenOption(feeRateOpt)
3✔
3987
}
3988

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

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

4006
                return addr
3✔
4007
        })(s)
4008

4009
        return fn.FlattenOption(addrOpt)
3✔
4010
}
4011

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

3✔
4018
                init.WhenLeft(f)
3✔
4019
        })
3✔
4020
}
4021

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

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

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

3✔
4041
        coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4042
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
4043
        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4044

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

4053
                localState := state.PeerState.GetForParty(lntypes.Local)
3✔
4054

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

3✔
4059
                return ok
3✔
4060
        }
4061

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

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

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

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

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

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

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

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

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

×
4125
                        return
×
4126
                }
×
4127

4128
                coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4129

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

3✔
4137
                        p.cg.WgAdd(1)
3✔
4138
                        go func() {
6✔
4139
                                defer p.cg.WgDone()
3✔
4140

3✔
4141
                                p.observeRbfCloseUpdates(
3✔
4142
                                        rbfCloser, req, coopCloseStates,
3✔
4143
                                )
3✔
4144
                        }()
3✔
4145
                })
4146

4147
                if !rpcShutdown {
6✔
4148
                        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4149
                }
3✔
4150

4151
                ctx, _ := p.cg.Create(context.Background())
3✔
4152
                feeRate := defaultFeePerKw.FeePerVByte()
3✔
4153

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

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

×
4184
                                return
×
4185
                        }
×
4186

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

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

4200
        return nil
3✔
4201
}
4202

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

3✔
4208
        channel, ok := p.activeChannels.Load(chanID)
3✔
4209

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

4220
        isTaprootChan := channel.ChanType().IsTaproot()
3✔
4221

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

4244
                if err != nil {
3✔
UNCOV
4245
                        p.log.Errorf(err.Error())
×
UNCOV
4246
                        req.Err <- err
×
UNCOV
4247
                }
×
4248

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
4362
        var chanLink htlcswitch.ChannelUpdateHandler
3✔
4363

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

4374
        return chanLink
3✔
4375
}
4376

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

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

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

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

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

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

4414
        closingTxid := closingTx.TxHash()
3✔
4415

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

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

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

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

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

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

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

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

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

3✔
4490
        p.activeChannels.Delete(chanID)
3✔
4491

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

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

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

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

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

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

4535
        return nil
3✔
4536
}
4537

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

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

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

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

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

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

×
UNCOV
4586
                features.Set(lnwire.StaticRemoteKeyOptional)
×
UNCOV
4587
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
×
UNCOV
4588
        }
×
4589

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

3✔
4595
        return p.writeMessage(msg)
3✔
4596
}
4597

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

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

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

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

4624
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
3✔
4625
                "peer", cid)
3✔
4626

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

4632
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
3✔
4633
                cid)
3✔
4634

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

3✔
4639
        return nil
3✔
4640
}
4641

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

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

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

4683
                if priority {
6✔
4684
                        p.queueMsg(msg, errChan)
3✔
4685
                } else {
6✔
4686
                        p.queueMsgLazy(msg, errChan)
3✔
4687
                }
3✔
4688
        }
4689

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

4703
        return nil
3✔
4704
}
4705

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

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

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

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

3✔
4734
        errChan := make(chan error, 1)
3✔
4735
        newChanMsg := &newChannelMsg{
3✔
4736
                channel: newChan,
3✔
4737
                err:     errChan,
3✔
4738
        }
3✔
4739

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

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

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

3✔
4765
        errChan := make(chan error, 1)
3✔
4766
        newChanMsg := &newChannelMsg{
3✔
4767
                channelID: cid,
3✔
4768
                err:       errChan,
3✔
4769
        }
3✔
4770

3✔
4771
        select {
3✔
4772
        case p.newPendingChannel <- newChanMsg:
3✔
4773

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4881
                p.activeChanCloses.Delete(msg.cid)
1✔
4882

1✔
4883
                p.Disconnect(err)
1✔
4884
        }
4885

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

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

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

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

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

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

4933
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
6✔
4934
                                p.queueMsg(&msg, nil)
3✔
4935
                        })
3✔
4936
                }
4937

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

4951
        case *lnwire.ClosingSigned:
3✔
4952
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
3✔
4953
                if err != nil {
4✔
4954
                        handleErr(err)
1✔
4955
                        return
1✔
4956
                }
1✔
4957

4958
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
6✔
4959
                        p.queueMsg(&msg, nil)
3✔
4960
                })
3✔
4961

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5050
        return pingBytes
×
5051
}
5052

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

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

5074
        p.channelEventClient = sub
3✔
5075

3✔
5076
        return nil
3✔
5077
}
5078

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

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

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

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

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

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

3✔
5112
        nextRevoke := c.RemoteNextRevocation
3✔
5113

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

5119
        return nil
3✔
5120
}
5121

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

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

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

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

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

5164
        // Store the channel in the activeChannels map.
5165
        p.activeChannels.Store(chanID, lnChan)
3✔
5166

3✔
5167
        p.log.Infof("New channel active ChannelPoint(%v) with peer", chanPoint)
3✔
5168

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

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

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

5195
        isTaprootChan := c.ChanType.IsTaproot()
3✔
5196

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

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

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

5217
        return nil
3✔
5218
}
5219

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

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

3✔
5235
                // Handle it and close the err chan on the request.
3✔
5236
                close(req.err)
3✔
5237

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

5244
                return
3✔
5245
        }
5246

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

×
5253
                return
×
5254
        }
×
5255

5256
        // Close the err chan if everything went fine.
5257
        close(req.err)
3✔
5258
}
5259

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

3✔
5267
        chanID := req.channelID
3✔
5268

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

×
UNCOV
5277
                return
×
UNCOV
5278
        }
×
5279

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

×
UNCOV
5285
                return
×
UNCOV
5286
        }
×
5287

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

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

3✔
5301
        chanID := req.channelID
3✔
5302

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

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

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

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

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

3✔
5336
                // Stop the stream when quit.
3✔
5337
                go func() {
6✔
5338
                        <-p.cg.Done()
3✔
5339
                        chanStream.Stop()
3✔
5340
                }()
3✔
5341
        }
5342

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

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

UNCOV
5357
        return timeout
×
5358
}
5359

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

5365
        ErrChan chan error
5366
}
5367

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

5377
        return chanCloser.IsRight()
3✔
5378
}
5379

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

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

5394
        closeUpdates := &CoopCloseUpdates{
3✔
5395
                UpdateChan: make(chan interface{}, 1),
3✔
5396
                ErrChan:    make(chan error, 1),
3✔
5397
        }
3✔
5398

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

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

5416
        return closeUpdates, nil
3✔
5417
}
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