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

lightningnetwork / lnd / 17741595272

15 Sep 2025 05:34PM UTC coverage: 66.653% (+0.008%) from 66.645%
17741595272

Pull #10221

github

web-flow
Merge e7ff1981e into 6b279fb24
Pull Request #10221: Update bbolt + grpc dependencies

136302 of 204494 relevant lines covered (66.65%)

21378.23 hits per line

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

78.63
/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
                gossip, 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 {
12✔
480
        return fn.NewLeft[*chancloser.ChanCloser, *chancloser.RbfChanCloser](
12✔
481
                chanCloser,
12✔
482
        )
12✔
483
}
12✔
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 {
28✔
649
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
28✔
650

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

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

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

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

28✔
690
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
31✔
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 (
28✔
697
                lastBlockHeader           *wire.BlockHeader
28✔
698
                lastSerializedBlockHeader [wire.MaxBlockHeaderPayload]byte
28✔
699
        )
28✔
700
        newPingPayload := func() []byte {
28✔
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 {
28✔
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{
28✔
740
                NewPingPayload:   newPingPayload,
28✔
741
                NewPongSize:      randPongSize,
28✔
742
                IntervalDuration: p.scaleTimeout(pingInterval),
28✔
743
                TimeoutDuration:  p.scaleTimeout(pingTimeout),
28✔
744
                SendPing: func(ping *lnwire.Ping) {
28✔
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
28✔
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 {
6✔
777
        if atomic.AddInt32(&p.started, 1) != 1 {
6✔
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)
6✔
785

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

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

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

804
        // Quickly check if we have any existing legacy channels with this
805
        // peer.
806
        haveLegacyChan := false
6✔
807
        for _, c := range activeChans {
11✔
808
                if c.ChanType.IsTweakless() {
10✔
809
                        continue
5✔
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 {
9✔
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)
6✔
826
        msgChan := make(chan lnwire.Message, 1)
6✔
827
        p.cg.WgAdd(1)
6✔
828
        go func() {
12✔
829
                defer p.cg.WgDone()
6✔
830

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

841
        select {
6✔
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:
6✔
848
                if err != nil {
9✔
849
                        return fmt.Errorf("unable to read init msg: %w", err)
3✔
850
                }
3✔
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
6✔
856
        if msg, ok := msg.(*lnwire.Init); ok {
12✔
857
                if err := p.handleInitMsg(msg); err != nil {
6✔
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",
6✔
870
                len(activeChans))
6✔
871

6✔
872
        // Conditionally subscribe to channel events before loading channels so
6✔
873
        // we won't miss events. This subscription is used to listen to active
6✔
874
        // channel event when reenabling channels. Once the reenabling process
6✔
875
        // is finished, this subscription will be canceled.
6✔
876
        //
6✔
877
        // NOTE: ChannelNotifier must be started before subscribing events
6✔
878
        // otherwise we'd panic here.
6✔
879
        if err := p.attachChannelEventSubscription(); err != nil {
6✔
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) {
12✔
886
                router.Start(context.Background())
6✔
887
        })
6✔
888

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

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

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

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

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

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

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

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

6✔
942
        return nil
6✔
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() {
6✔
948
        // If the remote peer knows of the new gossip queries feature, then
6✔
949
        // we'll create a new gossipSyncer in the AuthenticatedGossiper for it.
6✔
950
        if p.remoteFeatures.HasFeature(lnwire.GossipQueriesOptional) {
12✔
951
                p.log.Info("Negotiated chan series queries")
6✔
952

6✔
953
                if p.cfg.AuthGossiper == nil {
9✔
954
                        // This should only ever be hit in the unit tests.
3✔
955
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
3✔
956
                                "gossip sync.")
3✔
957
                        return
3✔
958
                }
3✔
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 {
9✔
976
        return p.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
9✔
977
                p.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
9✔
978
}
9✔
979

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

988
        return bothHaveBit(lnwire.RbfCoopCloseOptional) ||
10✔
989
                bothHaveBit(lnwire.RbfCoopCloseOptionalStaging)
10✔
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) {
12✔
1007

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

1019
        return &chancloser.DeliveryAddrWithKey{
12✔
1020
                DeliveryAddress: deliveryScript,
12✔
1021
                InternalKey: fn.MapOption(
12✔
1022
                        func(desc keychain.KeyDescriptor) btcec.PublicKey {
15✔
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) {
6✔
1035

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

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

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

1062
                                err = p.cfg.AddLocalAlias(
3✔
1063
                                        aliasScid, dbChan.ShortChanID(), false,
3✔
1064
                                        false,
3✔
1065
                                )
3✔
1066
                                if err != nil {
3✔
1067
                                        return nil, err
×
1068
                                }
×
1069

1070
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
1071
                                        dbChan.FundingOutpoint,
3✔
1072
                                )
3✔
1073

3✔
1074
                                // Fetch the second commitment point to send in
3✔
1075
                                // the channel_ready message.
3✔
1076
                                second, err := dbChan.SecondCommitmentPoint()
3✔
1077
                                if err != nil {
3✔
1078
                                        return nil, err
×
1079
                                }
×
1080

1081
                                channelReadyMsg := lnwire.NewChannelReady(
3✔
1082
                                        chanID, second,
3✔
1083
                                )
3✔
1084
                                channelReadyMsg.AliasScid = &aliasScid
3✔
1085

3✔
1086
                                msgs = append(msgs, channelReadyMsg)
3✔
1087
                        }
1088

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

1100
                var chanOpts []lnwallet.ChannelOpt
5✔
1101
                p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
5✔
1102
                        chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
1103
                })
×
1104
                p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
5✔
1105
                        chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
1106
                })
×
1107
                p.cfg.AuxResolver.WhenSome(
5✔
1108
                        func(s lnwallet.AuxContractResolver) {
5✔
1109
                                chanOpts = append(
×
1110
                                        chanOpts, lnwallet.WithAuxResolver(s),
×
1111
                                )
×
1112
                        },
×
1113
                )
1114

1115
                lnChan, err := lnwallet.NewLightningChannel(
5✔
1116
                        p.cfg.Signer, dbChan, p.cfg.SigPool, chanOpts...,
5✔
1117
                )
5✔
1118
                if err != nil {
5✔
1119
                        return nil, fmt.Errorf("unable to create channel "+
×
1120
                                "state machine: %w", err)
×
1121
                }
×
1122

1123
                chanPoint := dbChan.FundingOutpoint
5✔
1124

5✔
1125
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
5✔
1126

5✔
1127
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
5✔
1128
                        chanPoint, lnChan.IsPending())
5✔
1129

5✔
1130
                // Skip adding any permanently irreconcilable channels to the
5✔
1131
                // htlcswitch.
5✔
1132
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
5✔
1133
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
10✔
1134

5✔
1135
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
5✔
1136
                                "start.", chanPoint, dbChan.ChanStatus())
5✔
1137

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

1152
                        msgs = append(msgs, chanSync)
5✔
1153

5✔
1154
                        // Check if this channel needs to have the cooperative
5✔
1155
                        // close process restarted. If so, we'll need to send
5✔
1156
                        // the Shutdown message that is returned.
5✔
1157
                        if dbChan.HasChanStatus(
5✔
1158
                                channeldb.ChanStatusCoopBroadcasted,
5✔
1159
                        ) {
8✔
1160

3✔
1161
                                shutdownMsg, err := p.restartCoopClose(lnChan)
3✔
1162
                                if err != nil {
3✔
1163
                                        p.log.Errorf("Unable to restart "+
×
1164
                                                "coop close for channel: %v",
×
1165
                                                err)
×
1166
                                        continue
×
1167
                                }
1168

1169
                                if shutdownMsg == nil {
6✔
1170
                                        continue
3✔
1171
                                }
1172

1173
                                // Append the message to the set of messages to
1174
                                // send.
1175
                                msgs = append(msgs, shutdownMsg)
×
1176
                        }
1177

1178
                        continue
5✔
1179
                }
1180

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

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

3✔
1203
                        selfPolicy = p1
3✔
1204
                } else {
6✔
1205
                        selfPolicy = p2
3✔
1206
                }
3✔
1207

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

1231
                p.log.Tracef("Using link policy of: %v",
3✔
1232
                        lnutils.SpewLogClosure(forwardingPolicy))
3✔
1233

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

3✔
1243
                        continue
3✔
1244
                }
1245

1246
                shutdownInfo, err := lnChan.State().ShutdownInfo()
3✔
1247
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
3✔
1248
                        return nil, err
×
1249
                }
×
1250

1251
                isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
1252

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

1265
                        // Compute an ideal fee.
1266
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
1267
                                p.cfg.CoopCloseTargetConfs,
3✔
1268
                        )
3✔
1269
                        if err != nil {
3✔
1270
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1271
                                        "estimate fee: %w", err)
×
1272

×
1273
                                return
×
1274
                        }
×
1275

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

×
1292
                                return
×
1293
                        }
×
1294

1295
                        chanID := lnwire.NewChanIDFromOutPoint(
3✔
1296
                                lnChan.State().FundingOutpoint,
3✔
1297
                        )
3✔
1298

3✔
1299
                        p.activeChanCloses.Store(chanID, makeNegotiateCloser(
3✔
1300
                                negotiateChanCloser,
3✔
1301
                        ))
3✔
1302

3✔
1303
                        // Create the Shutdown message.
3✔
1304
                        shutdown, err := negotiateChanCloser.ShutdownChan()
3✔
1305
                        if err != nil {
3✔
1306
                                p.activeChanCloses.Delete(chanID)
×
1307
                                shutdownInfoErr = err
×
1308

×
1309
                                return
×
1310
                        }
×
1311

1312
                        shutdownMsg = fn.Some(*shutdown)
3✔
1313
                })
1314
                if shutdownInfoErr != nil {
3✔
1315
                        return nil, shutdownInfoErr
×
1316
                }
×
1317

1318
                // Subscribe to the set of on-chain events for this channel.
1319
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
3✔
1320
                        chanPoint,
3✔
1321
                )
3✔
1322
                if err != nil {
3✔
1323
                        return nil, err
×
1324
                }
×
1325

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

1335
                p.activeChannels.Store(chanID, lnChan)
3✔
1336

3✔
1337
                // We're using the old co-op close, so we don't need to init
3✔
1338
                // the new RBF chan closer. If we have a taproot chan, then
3✔
1339
                // we'll also use the legacy type, so we don't need to make the
3✔
1340
                // new closer.
3✔
1341
                if !p.rbfCoopCloseAllowed() || isTaprootChan {
6✔
1342
                        continue
3✔
1343
                }
1344

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

×
1354
                        return nil, fmt.Errorf("unable to init RBF chan "+
×
1355
                                "closer during peer connect: %w", err)
×
1356
                }
×
1357

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

1374
        return msgs, nil
6✔
1375
}
1376

1377
// addLink creates and adds a new ChannelLink from the specified channel.
1378
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1379
        lnChan *lnwallet.LightningChannel,
1380
        forwardingPolicy *models.ForwardingPolicy,
1381
        chainEvents *contractcourt.ChainEventSubscription,
1382
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
3✔
1383

3✔
1384
        // onChannelFailure will be called by the link in case the channel
3✔
1385
        // fails for some reason.
3✔
1386
        onChannelFailure := func(chanID lnwire.ChannelID,
3✔
1387
                shortChanID lnwire.ShortChannelID,
3✔
1388
                linkErr htlcswitch.LinkFailureError) {
6✔
1389

3✔
1390
                failure := linkFailureReport{
3✔
1391
                        chanPoint:   *chanPoint,
3✔
1392
                        chanID:      chanID,
3✔
1393
                        shortChanID: shortChanID,
3✔
1394
                        linkErr:     linkErr,
3✔
1395
                }
3✔
1396

3✔
1397
                select {
3✔
1398
                case p.linkFailures <- failure:
3✔
1399
                case <-p.cg.Done():
×
1400
                case <-p.cfg.Quit:
×
1401
                }
1402
        }
1403

1404
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
6✔
1405
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
3✔
1406
        }
3✔
1407

1408
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
6✔
1409
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
3✔
1410
        }
3✔
1411

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

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

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

1474
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1475
// one confirmed public channel exists with them.
1476
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
6✔
1477
        defer p.cg.WgDone()
6✔
1478

6✔
1479
        hasConfirmedPublicChan := false
6✔
1480
        for _, channel := range channels {
11✔
1481
                if channel.IsPending {
8✔
1482
                        continue
3✔
1483
                }
1484
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
10✔
1485
                        continue
5✔
1486
                }
1487

1488
                hasConfirmedPublicChan = true
3✔
1489
                break
3✔
1490
        }
1491
        if !hasConfirmedPublicChan {
12✔
1492
                return
6✔
1493
        }
6✔
1494

1495
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
3✔
1496
        if err != nil {
3✔
1497
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1498
                return
×
1499
        }
×
1500

1501
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
3✔
1502
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1503
        }
×
1504
}
1505

1506
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1507
// have any active channels with them.
1508
func (p *Brontide) maybeSendChannelUpdates() {
6✔
1509
        defer p.cg.WgDone()
6✔
1510

6✔
1511
        // If we don't have any active channels, then we can exit early.
6✔
1512
        if p.activeChannels.Len() == 0 {
10✔
1513
                return
4✔
1514
        }
4✔
1515

1516
        maybeSendUpd := func(cid lnwire.ChannelID,
5✔
1517
                lnChan *lnwallet.LightningChannel) error {
10✔
1518

5✔
1519
                // Nil channels are pending, so we'll skip them.
5✔
1520
                if lnChan == nil {
8✔
1521
                        return nil
3✔
1522
                }
3✔
1523

1524
                dbChan := lnChan.State()
5✔
1525
                scid := func() lnwire.ShortChannelID {
10✔
1526
                        switch {
5✔
1527
                        // Otherwise if it's a zero conf channel and confirmed,
1528
                        // then we need to use the "real" scid.
1529
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
3✔
1530
                                return dbChan.ZeroConfRealScid()
3✔
1531

1532
                        // Otherwise, we can use the normal scid.
1533
                        default:
5✔
1534
                                return dbChan.ShortChanID()
5✔
1535
                        }
1536
                }()
1537

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

3✔
1548
                        return nil
3✔
1549
                }
3✔
1550

1551
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
5✔
1552
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
5✔
1553

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

×
1563
                        return err
×
1564
                }
×
1565

1566
                return nil
5✔
1567
        }
1568

1569
        p.activeChannels.ForEach(maybeSendUpd)
5✔
1570
}
1571

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

1589
        select {
3✔
1590
        case <-ready:
3✔
1591
        case <-p.cg.Done():
3✔
1592
        }
1593

1594
        p.cg.WgWait()
3✔
1595
}
1596

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

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

3✔
1619
                select {
3✔
1620
                case <-p.startReady:
3✔
1621
                case <-p.cg.Done():
×
1622
                        return
×
1623
                }
1624
        }
1625

1626
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
3✔
1627
        p.storeError(err)
3✔
1628

3✔
1629
        p.log.Infof(err.Error())
3✔
1630

3✔
1631
        // Stop PingManager before closing TCP connection.
3✔
1632
        p.pingManager.Stop()
3✔
1633

3✔
1634
        // Ensure that the TCP connection is properly closed before continuing.
3✔
1635
        p.cfg.Conn.Close()
3✔
1636

3✔
1637
        p.cg.Quit()
3✔
1638

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

1648
// String returns the string representation of this peer.
1649
func (p *Brontide) String() string {
3✔
1650
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
3✔
1651
}
3✔
1652

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

1662
        pktLen, err := noiseConn.ReadNextHeader()
10✔
1663
        if err != nil {
13✔
1664
                return nil, fmt.Errorf("read next header: %w", err)
3✔
1665
        }
3✔
1666

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

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

7✔
1699
                // Next, create a new io.Reader implementation from the raw
7✔
1700
                // message, and use this to decode the message directly from.
7✔
1701
                msgReader := bytes.NewReader(rawMsg)
7✔
1702
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
7✔
1703
                if err != nil {
10✔
1704
                        return err
3✔
1705
                }
3✔
1706

1707
                // At this point, rawMsg and buf will be returned back to the
1708
                // buffer pool for re-use.
1709
                return nil
7✔
1710
        })
1711
        atomic.AddUint64(&p.bytesReceived, msgLen)
7✔
1712
        if err != nil {
10✔
1713
                return nil, err
3✔
1714
        }
3✔
1715

1716
        p.logWireMessage(nextMsg, true)
7✔
1717

7✔
1718
        return nextMsg, nil
7✔
1719
}
1720

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

1729
        peer *Brontide
1730

1731
        apply func(lnwire.Message)
1732

1733
        startMsg string
1734
        stopMsg  string
1735

1736
        msgCond *sync.Cond
1737
        msgs    []lnwire.Message
1738

1739
        mtx sync.Mutex
1740

1741
        producerSema chan struct{}
1742

1743
        wg   sync.WaitGroup
1744
        quit chan struct{}
1745
}
1746

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

6✔
1755
        stream := &msgStream{
6✔
1756
                peer:         p,
6✔
1757
                apply:        apply,
6✔
1758
                startMsg:     startMsg,
6✔
1759
                stopMsg:      stopMsg,
6✔
1760
                producerSema: make(chan struct{}, bufSize),
6✔
1761
                quit:         make(chan struct{}),
6✔
1762
        }
6✔
1763
        stream.msgCond = sync.NewCond(&stream.mtx)
6✔
1764

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

1773
        return stream
6✔
1774
}
1775

1776
// Start starts the chanMsgStream.
1777
func (ms *msgStream) Start() {
6✔
1778
        ms.wg.Add(1)
6✔
1779
        go ms.msgConsumer()
6✔
1780
}
6✔
1781

1782
// Stop stops the chanMsgStream.
1783
func (ms *msgStream) Stop() {
3✔
1784
        // TODO(roasbeef): signal too?
3✔
1785

3✔
1786
        close(ms.quit)
3✔
1787

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

1795
        ms.wg.Wait()
3✔
1796
}
1797

1798
// msgConsumer is the main goroutine that streams messages from the peer's
1799
// readHandler directly to the target channel.
1800
func (ms *msgStream) msgConsumer() {
6✔
1801
        defer ms.wg.Done()
6✔
1802
        defer peerLog.Tracef(ms.stopMsg)
6✔
1803
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
6✔
1804

6✔
1805
        peerLog.Tracef(ms.startMsg)
6✔
1806

6✔
1807
        for {
12✔
1808
                // First, we'll check our condition. If the queue of messages
6✔
1809
                // is empty, then we'll wait until a new item is added.
6✔
1810
                ms.msgCond.L.Lock()
6✔
1811
                for len(ms.msgs) == 0 {
12✔
1812
                        ms.msgCond.Wait()
6✔
1813

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

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

3✔
1835
                ms.msgCond.L.Unlock()
3✔
1836

3✔
1837
                ms.apply(msg)
3✔
1838

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

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

1869
        // Next, we'll lock the condition, and add the message to the end of
1870
        // the message queue.
1871
        ms.msgCond.L.Lock()
3✔
1872
        ms.msgs = append(ms.msgs, msg)
3✔
1873
        ms.msgCond.L.Unlock()
3✔
1874

3✔
1875
        // With the message added, we signal to the msgConsumer that there are
3✔
1876
        // additional messages to consume.
3✔
1877
        ms.msgCond.Signal()
3✔
1878
}
1879

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

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

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

3✔
1906
        // The link may already be active by this point, and we may have missed the
3✔
1907
        // ActiveLinkEvent. Check if the link exists.
3✔
1908
        link := p.fetchLinkFromKeyAndCid(cid)
3✔
1909
        if link != nil {
6✔
1910
                return link
3✔
1911
        }
3✔
1912

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

1927
                        chanPoint := event.ChannelPoint
3✔
1928

3✔
1929
                        // Check whether the retrieved chanPoint matches the target
3✔
1930
                        // channel id.
3✔
1931
                        if !cid.IsChanPoint(chanPoint) {
3✔
1932
                                continue
×
1933
                        }
1934

1935
                        // The link shouldn't be nil as we received an
1936
                        // ActiveLinkEvent. If it is nil, we return nil and the
1937
                        // calling function should catch it.
1938
                        return p.fetchLinkFromKeyAndCid(cid)
3✔
1939

1940
                case <-p.cg.Done():
3✔
1941
                        return nil
3✔
1942
                }
1943
        }
1944
}
1945

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

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

3✔
1962
                        // If the link is still not active and the calling function
3✔
1963
                        // errored out, just return.
3✔
1964
                        if chanLink == nil {
6✔
1965
                                p.log.Warnf("Link=%v is not active", cid)
3✔
1966
                                return
3✔
1967
                        }
3✔
1968
                }
1969

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

1979
                chanLink.HandleChannelUpdate(msg)
3✔
1980
        }
1981

1982
        return newMsgStream(p,
3✔
1983
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
3✔
1984
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
3✔
1985
                msgStreamSize,
3✔
1986
                apply,
3✔
1987
        )
3✔
1988
}
1989

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

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

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

2017
        return newMsgStream(
6✔
2018
                p,
6✔
2019
                "Update stream for gossiper created",
6✔
2020
                "Update stream for gossiper exited",
6✔
2021
                msgStreamSize,
6✔
2022
                apply,
6✔
2023
        )
6✔
2024
}
2025

2026
// readHandler is responsible for reading messages off the wire in series, then
2027
// properly dispatching the handling of the message to the proper subsystem.
2028
//
2029
// NOTE: This method MUST be run as a goroutine.
2030
func (p *Brontide) readHandler() {
6✔
2031
        defer p.cg.WgDone()
6✔
2032

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

2041
        // Initialize our negotiated gossip sync method before reading messages
2042
        // off the wire. When using gossip queries, this ensures a gossip
2043
        // syncer is active by the time query messages arrive.
2044
        //
2045
        // TODO(conner): have peer store gossip syncer directly and bypass
2046
        // gossiper?
2047
        p.initGossipSync()
6✔
2048

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

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

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

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

2096
                        // If the error we encountered wasn't just a message we
2097
                        // didn't recognize, then we'll stop all processing as
2098
                        // this is a fatal error.
2099
                        default:
3✔
2100
                                break out
3✔
2101
                        }
2102
                }
2103

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

2114
                // No error occurred, and the message was handled by the
2115
                // router.
2116
                if err == nil {
7✔
2117
                        continue
3✔
2118
                }
2119

2120
                var (
4✔
2121
                        targetChan   lnwire.ChannelID
4✔
2122
                        isLinkUpdate bool
4✔
2123
                )
4✔
2124

4✔
2125
                switch msg := nextMsg.(type) {
4✔
2126
                case *lnwire.Pong:
×
2127
                        // When we receive a Pong message in response to our
×
2128
                        // last ping message, we send it to the pingManager
×
2129
                        p.pingManager.ReceivedPong(msg)
×
2130

2131
                case *lnwire.Ping:
×
2132
                        // First, we'll store their latest ping payload within
×
2133
                        // the relevant atomic variable.
×
2134
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
2135

×
2136
                        // Next, we'll send over the amount of specified pong
×
2137
                        // bytes.
×
2138
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
×
2139
                        p.queueMsg(pong, nil)
×
2140

2141
                case *lnwire.OpenChannel,
2142
                        *lnwire.AcceptChannel,
2143
                        *lnwire.FundingCreated,
2144
                        *lnwire.FundingSigned,
2145
                        *lnwire.ChannelReady:
3✔
2146

3✔
2147
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2148

2149
                case *lnwire.Shutdown:
3✔
2150
                        select {
3✔
2151
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
2152
                        case <-p.cg.Done():
×
2153
                                break out
×
2154
                        }
2155
                case *lnwire.ClosingSigned:
3✔
2156
                        select {
3✔
2157
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
2158
                        case <-p.cg.Done():
×
2159
                                break out
×
2160
                        }
2161

2162
                case *lnwire.Warning:
×
2163
                        targetChan = msg.ChanID
×
2164
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2165

2166
                case *lnwire.Error:
3✔
2167
                        targetChan = msg.ChanID
3✔
2168
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
3✔
2169

2170
                case *lnwire.ChannelReestablish:
3✔
2171
                        targetChan = msg.ChanID
3✔
2172
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2173

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

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

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

2206
                case *lnwire.ChannelUpdate1,
2207
                        *lnwire.ChannelAnnouncement1,
2208
                        *lnwire.NodeAnnouncement,
2209
                        *lnwire.AnnounceSignatures1,
2210
                        *lnwire.GossipTimestampRange,
2211
                        *lnwire.QueryShortChanIDs,
2212
                        *lnwire.QueryChannelRange,
2213
                        *lnwire.ReplyChannelRange,
2214
                        *lnwire.ReplyShortChanIDsEnd:
3✔
2215

3✔
2216
                        discStream.AddMsg(msg)
3✔
2217

2218
                case *lnwire.Custom:
4✔
2219
                        err := p.handleCustomMessage(msg)
4✔
2220
                        if err != nil {
4✔
2221
                                p.storeError(err)
×
2222
                                p.log.Errorf("%v", err)
×
2223
                        }
×
2224

2225
                default:
×
2226
                        // If the message we received is unknown to us, store
×
2227
                        // the type to track the failure.
×
2228
                        err := fmt.Errorf("unknown message type %v received",
×
2229
                                uint16(msg.MsgType()))
×
2230
                        p.storeError(err)
×
2231

×
2232
                        p.log.Errorf("%v", err)
×
2233
                }
2234

2235
                if isLinkUpdate {
7✔
2236
                        // If this is a channel update, then we need to feed it
3✔
2237
                        // into the channel's in-order message stream.
3✔
2238
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
3✔
2239
                }
3✔
2240

2241
                idleTimer.Reset(idleTimeout)
4✔
2242
        }
2243

2244
        p.Disconnect(errors.New("read handler closed"))
3✔
2245

3✔
2246
        p.log.Trace("readHandler for peer done")
3✔
2247
}
2248

2249
// handleCustomMessage handles the given custom message if a handler is
2250
// registered.
2251
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
4✔
2252
        if p.cfg.HandleCustomMessage == nil {
4✔
2253
                return fmt.Errorf("no custom message handler for "+
×
2254
                        "message type %v", uint16(msg.MsgType()))
×
2255
        }
×
2256

2257
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
4✔
2258
}
2259

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

2271
        // Return false if the channel is unknown.
2272
        channel, ok := p.activeChannels.Load(chanID)
3✔
2273
        if !ok {
3✔
2274
                return false
×
2275
        }
×
2276

2277
        // During startup, we will use a nil value to mark a pending channel
2278
        // that's loaded from disk.
2279
        return channel == nil
3✔
2280
}
2281

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

11✔
2291
        return channel != nil
11✔
2292
}
11✔
2293

2294
// isPendingChannel returns true if the provided channel ID is pending, and
2295
// returns false if the channel is active or unknown.
2296
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
9✔
2297
        // Return false if the channel is unknown.
9✔
2298
        channel, ok := p.activeChannels.Load(chanID)
9✔
2299
        if !ok {
15✔
2300
                return false
6✔
2301
        }
6✔
2302

2303
        return channel == nil
6✔
2304
}
2305

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

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

3✔
2320
        p.activeChannels.Range(func(_ lnwire.ChannelID,
3✔
2321
                channel *lnwallet.LightningChannel) bool {
6✔
2322

3✔
2323
                // Pending channels will be nil in the activeChannels map.
3✔
2324
                if channel == nil {
6✔
2325
                        // Return true to continue the iteration.
3✔
2326
                        return true
3✔
2327
                }
3✔
2328

2329
                haveChannels = true
3✔
2330

3✔
2331
                // Return false to break the iteration.
3✔
2332
                return false
3✔
2333
        })
2334

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

2342
        p.cfg.ErrorBuffer.Add(
3✔
2343
                &TimestampedError{Timestamp: time.Now(), Error: err},
3✔
2344
        )
3✔
2345
}
2346

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

3✔
2356
        if errMsg, ok := msg.(*lnwire.Error); ok {
6✔
2357
                p.storeError(errMsg)
3✔
2358
        }
3✔
2359

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

2368
                return false
×
2369

2370
        // If the channel ID for the message corresponds to a pending channel,
2371
        // then the funding manager will handle it.
2372
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
3✔
2373
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2374
                return false
3✔
2375

2376
        // If not we hand the message to the channel link for this channel.
2377
        case p.isActiveChannel(chanID):
3✔
2378
                return true
3✔
2379

2380
        default:
3✔
2381
                return false
3✔
2382
        }
2383
}
2384

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

2394
        case *lnwire.OpenChannel:
3✔
2395
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
3✔
2396
                        "push_amt=%v, reserve=%v, flags=%v",
3✔
2397
                        msg.PendingChannelID[:], msg.ChainHash,
3✔
2398
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
3✔
2399
                        msg.ChannelReserve, msg.ChannelFlags)
3✔
2400

2401
        case *lnwire.AcceptChannel:
3✔
2402
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
3✔
2403
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
3✔
2404
                        msg.MinAcceptDepth)
3✔
2405

2406
        case *lnwire.FundingCreated:
3✔
2407
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
3✔
2408
                        msg.PendingChannelID[:], msg.FundingPoint)
3✔
2409

2410
        case *lnwire.FundingSigned:
3✔
2411
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
3✔
2412

2413
        case *lnwire.ChannelReady:
3✔
2414
                return fmt.Sprintf("chan_id=%v, next_point=%x",
3✔
2415
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
3✔
2416

2417
        case *lnwire.Shutdown:
3✔
2418
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
3✔
2419
                        msg.Address[:])
3✔
2420

2421
        case *lnwire.ClosingComplete:
3✔
2422
                return fmt.Sprintf("chan_id=%v, fee_sat=%v, locktime=%v",
3✔
2423
                        msg.ChannelID, msg.FeeSatoshis, msg.LockTime)
3✔
2424

2425
        case *lnwire.ClosingSig:
3✔
2426
                return fmt.Sprintf("chan_id=%v", msg.ChannelID)
3✔
2427

2428
        case *lnwire.ClosingSigned:
3✔
2429
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
3✔
2430
                        msg.FeeSatoshis)
3✔
2431

2432
        case *lnwire.UpdateAddHTLC:
3✔
2433
                var blindingPoint []byte
3✔
2434
                msg.BlindingPoint.WhenSome(
3✔
2435
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
3✔
2436
                                *btcec.PublicKey]) {
6✔
2437

3✔
2438
                                blindingPoint = b.Val.SerializeCompressed()
3✔
2439
                        },
3✔
2440
                )
2441

2442
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
3✔
2443
                        "hash=%x, blinding_point=%x, custom_records=%v",
3✔
2444
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
3✔
2445
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
3✔
2446

2447
        case *lnwire.UpdateFailHTLC:
3✔
2448
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
3✔
2449
                        msg.ID, msg.Reason)
3✔
2450

2451
        case *lnwire.UpdateFulfillHTLC:
3✔
2452
                return fmt.Sprintf("chan_id=%v, id=%v, preimage=%x, "+
3✔
2453
                        "custom_records=%v", msg.ChanID, msg.ID,
3✔
2454
                        msg.PaymentPreimage[:], msg.CustomRecords)
3✔
2455

2456
        case *lnwire.CommitSig:
3✔
2457
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
3✔
2458
                        len(msg.HtlcSigs))
3✔
2459

2460
        case *lnwire.RevokeAndAck:
3✔
2461
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
3✔
2462
                        msg.ChanID, msg.Revocation[:],
3✔
2463
                        msg.NextRevocationKey.SerializeCompressed())
3✔
2464

2465
        case *lnwire.UpdateFailMalformedHTLC:
3✔
2466
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
3✔
2467
                        msg.ChanID, msg.ID, msg.FailureCode)
3✔
2468

2469
        case *lnwire.Warning:
×
2470
                return fmt.Sprintf("%v", msg.Warning())
×
2471

2472
        case *lnwire.Error:
3✔
2473
                return fmt.Sprintf("%v", msg.Error())
3✔
2474

2475
        case *lnwire.AnnounceSignatures1:
3✔
2476
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
3✔
2477
                        msg.ShortChannelID.ToUint64())
3✔
2478

2479
        case *lnwire.ChannelAnnouncement1:
3✔
2480
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
3✔
2481
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
3✔
2482

2483
        case *lnwire.ChannelUpdate1:
3✔
2484
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
3✔
2485
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
3✔
2486
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
3✔
2487
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
3✔
2488

2489
        case *lnwire.NodeAnnouncement:
3✔
2490
                return fmt.Sprintf("node=%x, update_time=%v",
3✔
2491
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
3✔
2492

2493
        case *lnwire.Ping:
×
2494
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
2495

2496
        case *lnwire.Pong:
×
2497
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
×
2498

2499
        case *lnwire.UpdateFee:
×
2500
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2501
                        msg.ChanID, int64(msg.FeePerKw))
×
2502

2503
        case *lnwire.ChannelReestablish:
3✔
2504
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
3✔
2505
                        "remote_tail_height=%v", msg.ChanID,
3✔
2506
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
3✔
2507

2508
        case *lnwire.ReplyShortChanIDsEnd:
3✔
2509
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
3✔
2510
                        msg.Complete)
3✔
2511

2512
        case *lnwire.ReplyChannelRange:
3✔
2513
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
3✔
2514
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
3✔
2515
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
3✔
2516
                        msg.EncodingType)
3✔
2517

2518
        case *lnwire.QueryShortChanIDs:
3✔
2519
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
3✔
2520
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
3✔
2521

2522
        case *lnwire.QueryChannelRange:
3✔
2523
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
3✔
2524
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
3✔
2525
                        msg.LastBlockHeight())
3✔
2526

2527
        case *lnwire.GossipTimestampRange:
3✔
2528
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
3✔
2529
                        "stamp_range=%v", msg.ChainHash,
3✔
2530
                        time.Unix(int64(msg.FirstTimestamp), 0),
3✔
2531
                        msg.TimestampRange)
3✔
2532

2533
        case *lnwire.Stfu:
3✔
2534
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
3✔
2535
                        msg.Initiator)
3✔
2536

2537
        case *lnwire.Custom:
3✔
2538
                return fmt.Sprintf("type=%d", msg.Type)
3✔
2539
        }
2540

2541
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2542
}
2543

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

2555
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
23✔
2556
                // Debug summary of message.
3✔
2557
                summary := messageSummary(msg)
3✔
2558
                if len(summary) > 0 {
6✔
2559
                        summary = "(" + summary + ")"
3✔
2560
                }
3✔
2561

2562
                preposition := "to"
3✔
2563
                if read {
6✔
2564
                        preposition = "from"
3✔
2565
                }
3✔
2566

2567
                var msgType string
3✔
2568
                if msg.MsgType() < lnwire.CustomTypeStart {
6✔
2569
                        msgType = msg.MsgType().String()
3✔
2570
                } else {
6✔
2571
                        msgType = "custom"
3✔
2572
                }
3✔
2573

2574
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
3✔
2575
                        msgType, summary, preposition, p)
3✔
2576
        }))
2577

2578
        prefix := "readMessage from peer"
20✔
2579
        if !read {
36✔
2580
                prefix = "writeMessage to peer"
16✔
2581
        }
16✔
2582

2583
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
20✔
2584
}
2585

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

2603
        noiseConn := p.cfg.Conn
16✔
2604

16✔
2605
        flushMsg := func() error {
32✔
2606
                // Ensure the write deadline is set before we attempt to send
16✔
2607
                // the message.
16✔
2608
                writeDeadline := time.Now().Add(
16✔
2609
                        p.scaleTimeout(writeMessageTimeout),
16✔
2610
                )
16✔
2611
                err := noiseConn.SetWriteDeadline(writeDeadline)
16✔
2612
                if err != nil {
16✔
2613
                        return err
×
2614
                }
×
2615

2616
                // Flush the pending message to the wire. If an error is
2617
                // encountered, e.g. write timeout, the number of bytes written
2618
                // so far will be returned.
2619
                n, err := noiseConn.Flush()
16✔
2620

16✔
2621
                // Record the number of bytes written on the wire, if any.
16✔
2622
                if n > 0 {
19✔
2623
                        atomic.AddUint64(&p.bytesSent, uint64(n))
3✔
2624
                }
3✔
2625

2626
                return err
16✔
2627
        }
2628

2629
        // If the current message has already been serialized, encrypted, and
2630
        // buffered on the underlying connection we will skip straight to
2631
        // flushing it to the wire.
2632
        if msg == nil {
16✔
2633
                return flushMsg()
×
2634
        }
×
2635

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

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

2656
        return flushMsg()
16✔
2657
}
2658

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

2674
        var exitErr error
6✔
2675

6✔
2676
out:
6✔
2677
        for {
16✔
2678
                select {
10✔
2679
                case outMsg := <-p.sendQueue:
7✔
2680
                        // Record the time at which we first attempt to send the
7✔
2681
                        // message.
7✔
2682
                        startTime := time.Now()
7✔
2683

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

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

×
2705
                                goto retry
×
2706
                        }
2707

2708
                        // The write succeeded, reset the idle timer to prevent
2709
                        // us from disconnecting the peer.
2710
                        if !idleTimer.Stop() {
7✔
2711
                                select {
×
2712
                                case <-idleTimer.C:
×
2713
                                default:
×
2714
                                }
2715
                        }
2716
                        idleTimer.Reset(idleTimeout)
7✔
2717

7✔
2718
                        // If the peer requested a synchronous write, respond
7✔
2719
                        // with the error.
7✔
2720
                        if outMsg.errChan != nil {
11✔
2721
                                outMsg.errChan <- err
4✔
2722
                        }
4✔
2723

2724
                        if err != nil {
7✔
2725
                                exitErr = fmt.Errorf("unable to write "+
×
2726
                                        "message: %v", err)
×
2727
                                break out
×
2728
                        }
2729

2730
                case <-p.cg.Done():
3✔
2731
                        exitErr = lnpeer.ErrPeerExiting
3✔
2732
                        break out
3✔
2733
                }
2734
        }
2735

2736
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2737
        // disconnect.
2738
        p.cg.WgDone()
3✔
2739

3✔
2740
        p.Disconnect(exitErr)
3✔
2741

3✔
2742
        p.log.Trace("writeHandler for peer done")
3✔
2743
}
2744

2745
// queueHandler is responsible for accepting messages from outside subsystems
2746
// to be eventually sent out on the wire by the writeHandler.
2747
//
2748
// NOTE: This method MUST be run as a goroutine.
2749
func (p *Brontide) queueHandler() {
6✔
2750
        defer p.cg.WgDone()
6✔
2751

6✔
2752
        // priorityMsgs holds an in order list of messages deemed high-priority
6✔
2753
        // to be added to the sendQueue. This predominately includes messages
6✔
2754
        // from the funding manager and htlcswitch.
6✔
2755
        priorityMsgs := list.New()
6✔
2756

6✔
2757
        // lazyMsgs holds an in order list of messages deemed low-priority to be
6✔
2758
        // added to the sendQueue only after all high-priority messages have
6✔
2759
        // been queued. This predominately includes messages from the gossiper.
6✔
2760
        lazyMsgs := list.New()
6✔
2761

6✔
2762
        for {
20✔
2763
                // Examine the front of the priority queue, if it is empty check
14✔
2764
                // the low priority queue.
14✔
2765
                elem := priorityMsgs.Front()
14✔
2766
                if elem == nil {
25✔
2767
                        elem = lazyMsgs.Front()
11✔
2768
                }
11✔
2769

2770
                if elem != nil {
21✔
2771
                        front := elem.Value.(outgoingMsg)
7✔
2772

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

2812
// PingTime returns the estimated ping time to the peer in microseconds.
2813
func (p *Brontide) PingTime() int64 {
3✔
2814
        return p.pingManager.GetPingTimeMicroSeconds()
3✔
2815
}
3✔
2816

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

2824
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2825
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2826
// queue or failed to write, and nil otherwise.
2827
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
4✔
2828
        p.queue(false, msg, errChan)
4✔
2829
}
4✔
2830

2831
// queue sends a given message to the queueHandler using the passed priority. If
2832
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2833
// failed to write, and nil otherwise.
2834
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2835
        errChan chan error) {
29✔
2836

29✔
2837
        select {
29✔
2838
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
28✔
2839
        case <-p.cg.Done():
×
2840
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
×
2841
                        lnutils.SpewLogClosure(msg))
×
2842
                if errChan != nil {
×
2843
                        errChan <- lnpeer.ErrPeerExiting
×
2844
                }
×
2845
        }
2846
}
2847

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

3✔
2855
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2856
                activeChan *lnwallet.LightningChannel) error {
6✔
2857

3✔
2858
                // If the activeChan is nil, then we skip it as the channel is
3✔
2859
                // pending.
3✔
2860
                if activeChan == nil {
6✔
2861
                        return nil
3✔
2862
                }
3✔
2863

2864
                // We'll only return a snapshot for channels that are
2865
                // *immediately* available for routing payments over.
2866
                if activeChan.RemoteNextRevocation() == nil {
6✔
2867
                        return nil
3✔
2868
                }
3✔
2869

2870
                snapshot := activeChan.StateSnapshot()
3✔
2871
                snapshots = append(snapshots, snapshot)
3✔
2872

3✔
2873
                return nil
3✔
2874
        })
2875

2876
        return snapshots
3✔
2877
}
2878

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

2889
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
9✔
2890
                addrType, false, lnwallet.DefaultAccountName,
9✔
2891
        )
9✔
2892
        if err != nil {
9✔
2893
                return nil, err
×
2894
        }
×
2895
        p.log.Infof("Delivery addr for channel close: %v",
9✔
2896
                deliveryAddr)
9✔
2897

9✔
2898
        return txscript.PayToAddrScript(deliveryAddr)
9✔
2899
}
2900

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

20✔
2909
        // reenableTimeout will fire once after the configured channel status
20✔
2910
        // interval has elapsed. This will trigger us to sign new channel
20✔
2911
        // updates and broadcast them with the "disabled" flag unset.
20✔
2912
        reenableTimeout := time.After(p.cfg.ChanActiveTimeout)
20✔
2913

20✔
2914
out:
20✔
2915
        for {
61✔
2916
                select {
41✔
2917
                // A new pending channel has arrived which means we are about
2918
                // to complete a funding workflow and is waiting for the final
2919
                // `ChannelReady` messages to be exchanged. We will add this
2920
                // channel to the `activeChannels` with a nil value to indicate
2921
                // this is a pending channel.
2922
                case req := <-p.newPendingChannel:
4✔
2923
                        p.handleNewPendingChannel(req)
4✔
2924

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

2931
                // The funding flow for a pending channel is failed, we will
2932
                // remove it from Brontide.
2933
                case req := <-p.removePendingChannel:
4✔
2934
                        p.handleRemovePendingChannel(req)
4✔
2935

2936
                // We've just received a local request to close an active
2937
                // channel. It will either kick of a cooperative channel
2938
                // closure negotiation, or be a notification of a breached
2939
                // contract that should be abandoned.
2940
                case req := <-p.localCloseChanReqs:
10✔
2941
                        p.handleLocalCloseReq(req)
10✔
2942

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

2949
                // We've received a new cooperative channel closure related
2950
                // message from the remote peer, we'll use this message to
2951
                // advance the chan closer state machine.
2952
                case closeMsg := <-p.chanCloseMsgs:
16✔
2953
                        p.handleCloseMsg(closeMsg)
16✔
2954

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

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

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

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

3✔
2989
                                // Exit if the channel is nil as it's a pending
3✔
2990
                                // channel.
3✔
2991
                                if lc == nil {
6✔
2992
                                        return nil
3✔
2993
                                }
3✔
2994

2995
                                lc.ResetState()
3✔
2996

3✔
2997
                                return nil
3✔
2998
                        })
2999

3000
                        break out
3✔
3001
                }
3002
        }
3003
}
3004

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

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

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

3✔
3023
                switch {
3✔
3024
                // No error occurred, continue to request the next channel.
3025
                case err == nil:
3✔
3026
                        continue
3✔
3027

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

3✔
3034
                        continue
3✔
3035

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

×
3053
                                continue
×
3054
                        }
3055

3056
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
3057
                                "ChanStatusManager reported inactive, retrying")
×
3058

×
3059
                        // Add the channel to the retry map.
×
3060
                        retryChans[chanPoint] = struct{}{}
×
3061
                }
3062
        }
3063

3064
        // Retry the channels if we have any.
3065
        if len(retryChans) != 0 {
3✔
3066
                p.retryRequestEnable(retryChans)
×
3067
        }
×
3068
}
3069

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

16✔
3077
        chanCloser, found := p.activeChanCloses.Load(chanID)
16✔
3078
        if found {
29✔
3079
                // An entry will only be found if the closer has already been
13✔
3080
                // created for a non-pending channel or for a channel that had
13✔
3081
                // previously started the shutdown process but the connection
13✔
3082
                // was restarted.
13✔
3083
                return &chanCloser, nil
13✔
3084
        }
13✔
3085

3086
        // First, we'll ensure that we actually know of the target channel. If
3087
        // not, we'll ignore this message.
3088
        channel, ok := p.activeChannels.Load(chanID)
6✔
3089

6✔
3090
        // If the channel isn't in the map or the channel is nil, return
6✔
3091
        // ErrChannelNotFound as the channel is pending.
6✔
3092
        if !ok || channel == nil {
9✔
3093
                return nil, ErrChannelNotFound
3✔
3094
        }
3✔
3095

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

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

3125
        addr, err := p.addrWithInternalKey(deliveryScript)
6✔
3126
        if err != nil {
6✔
3127
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3128
        }
×
3129
        negotiateChanCloser, err := p.createChanCloser(
6✔
3130
                channel, addr, feePerKw, nil, lntypes.Remote,
6✔
3131
        )
6✔
3132
        if err != nil {
6✔
3133
                p.log.Errorf("unable to create chan closer: %v", err)
×
3134
                return nil, fmt.Errorf("unable to create chan closer")
×
3135
        }
×
3136

3137
        chanCloser = makeNegotiateCloser(negotiateChanCloser)
6✔
3138

6✔
3139
        p.activeChanCloses.Store(chanID, chanCloser)
6✔
3140

6✔
3141
        return &chanCloser, nil
6✔
3142
}
3143

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

3✔
3150
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
3✔
3151
                lnChan *lnwallet.LightningChannel) bool {
6✔
3152

3✔
3153
                // If the lnChan is nil, continue as this is a pending channel.
3✔
3154
                if lnChan == nil {
5✔
3155
                        return true
2✔
3156
                }
2✔
3157

3158
                dbChan := lnChan.State()
3✔
3159
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
3160
                if !isPublic || dbChan.IsPending {
3✔
3161
                        return true
×
3162
                }
×
3163

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

3173
                activePublicChans = append(
3✔
3174
                        activePublicChans, dbChan.FundingOutpoint,
3✔
3175
                )
3✔
3176

3✔
3177
                return true
3✔
3178
        })
3179

3180
        return activePublicChans
3✔
3181
}
3182

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

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

×
3197
                // If this channel is irrelevant, return nil so the loop can
×
3198
                // jump to next iteration.
×
3199
                if !found {
×
3200
                        return nil
×
3201
                }
×
3202

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

×
3211
                // Send the request.
×
3212
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3213
                if err != nil {
×
3214
                        return fmt.Errorf("request enabling channel %v "+
×
3215
                                "failed: %w", chanPoint, err)
×
3216
                }
×
3217

3218
                return nil
×
3219
        }
3220

3221
        for {
×
3222
                // If activeChans is empty, we've done processing all the
×
3223
                // channels.
×
3224
                if len(activeChans) == 0 {
×
3225
                        p.log.Debug("Finished retry enabling channels")
×
3226
                        return
×
3227
                }
×
3228

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

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

3246
                                continue
×
3247
                        }
3248

3249
                        // Otherwise check for inactive link event, and jump to
3250
                        // next iteration if it's not.
3251
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3252
                        if !ok {
×
3253
                                continue
×
3254
                        }
3255

3256
                        // Found an inactive link event, if this is our
3257
                        // targeted channel, remove it from our map.
3258
                        chanPoint := *inactive.ChannelPoint
×
3259
                        _, found := activeChans[chanPoint]
×
3260
                        if !found {
×
3261
                                continue
×
3262
                        }
3263

3264
                        delete(activeChans, chanPoint)
×
3265
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3266
                                "inactive link event", chanPoint)
×
3267

3268
                case <-p.cg.Done():
×
3269
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3270
                        return
×
3271
                }
3272
        }
3273
}
3274

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

15✔
3282
        switch {
15✔
3283
        // If no script was provided, then we'll generate a new delivery script.
3284
        case len(upfront) == 0 && len(requested) == 0:
7✔
3285
                return genDeliveryScript()
7✔
3286

3287
        // If no upfront shutdown script was provided, return the user
3288
        // requested address (which may be nil).
3289
        case len(upfront) == 0:
5✔
3290
                return requested, nil
5✔
3291

3292
        // If an upfront shutdown script was provided, and the user did not
3293
        // request a custom shutdown script, return the upfront address.
3294
        case len(requested) == 0:
5✔
3295
                return upfront, nil
5✔
3296

3297
        // If both an upfront shutdown script and a custom close script were
3298
        // provided, error if the user provided shutdown script does not match
3299
        // the upfront shutdown script (because closing out to a different
3300
        // script would violate upfront shutdown).
3301
        case !bytes.Equal(upfront, requested):
2✔
3302
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
3303

3304
        // The user requested script matches the upfront shutdown script, so we
3305
        // can return it without error.
3306
        default:
2✔
3307
                return upfront, nil
2✔
3308
        }
3309
}
3310

3311
// restartCoopClose checks whether we need to restart the cooperative close
3312
// process for a given channel.
3313
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3314
        *lnwire.Shutdown, error) {
3✔
3315

3✔
3316
        isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
3317

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

3337
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
3✔
3338

3✔
3339
        var deliveryScript []byte
3✔
3340

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

3350
        // An error other than ErrNoShutdownInfo was returned
3351
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3352
                return nil, err
×
3353

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

×
3363
                                return nil, fmt.Errorf("close addr unavailable")
×
3364
                        }
×
3365
                }
3366
        }
3367

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

3378
                shutdownDesc := fn.MapOption(
3✔
3379
                        newRestartShutdownInit,
3✔
3380
                )(shutdownInfo)
3✔
3381

3✔
3382
                err = p.startRbfChanCloser(
3✔
3383
                        fn.FlattenOption(shutdownDesc), lnChan.ChannelPoint(),
3✔
3384
                )
3✔
3385

3✔
3386
                return nil, err
3✔
3387
        }
3388

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

3398
        // Determine whether we or the peer are the initiator of the coop
3399
        // close attempt by looking at the channel's status.
3400
        closingParty := lntypes.Remote
×
3401
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3402
                closingParty = lntypes.Local
×
3403
        }
×
3404

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

3417
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
×
3418

×
3419
        // Create the Shutdown message.
×
3420
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3421
        if err != nil {
×
3422
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3423
                p.activeChanCloses.Delete(chanID)
×
3424
                return nil, err
×
3425
        }
×
3426

3427
        return shutdownMsg, nil
×
3428
}
3429

3430
// createChanCloser constructs a ChanCloser from the passed parameters and is
3431
// used to de-duplicate code.
3432
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3433
        deliveryScript *chancloser.DeliveryAddrWithKey,
3434
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3435
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
12✔
3436

12✔
3437
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
12✔
3438
        if err != nil {
12✔
3439
                p.log.Errorf("unable to obtain best block: %v", err)
×
3440
                return nil, fmt.Errorf("cannot obtain best block")
×
3441
        }
×
3442

3443
        // The req will only be set if we initiated the co-op closing flow.
3444
        var maxFee chainfee.SatPerKWeight
12✔
3445
        if req != nil {
21✔
3446
                maxFee = req.MaxFee
9✔
3447
        }
9✔
3448

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

3474
        return chanCloser, nil
12✔
3475
}
3476

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

10✔
3486
        // First, we'll choose a delivery address that we'll use to send the
10✔
3487
        // funds to in the case of a successful negotiation.
10✔
3488

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

3503
        addr, err := p.addrWithInternalKey(deliveryScript)
9✔
3504
        if err != nil {
9✔
3505
                return fmt.Errorf("unable to parse addr for channel "+
×
3506
                        "%v: %w", req.ChanPoint, err)
×
3507
        }
×
3508

3509
        chanCloser, err := p.createChanCloser(
9✔
3510
                channel, addr, req.TargetFeePerKw, req, lntypes.Local,
9✔
3511
        )
9✔
3512
        if err != nil {
9✔
3513
                return fmt.Errorf("unable to make chan closer: %w", err)
×
3514
        }
×
3515

3516
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
9✔
3517
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
9✔
3518

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

×
3528
                p.activeChanCloses.Delete(chanID)
×
3529

×
3530
                return fmt.Errorf("unable to shutdown channel: %w", err)
×
3531
        }
×
3532

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

3545
        if !link.DisableAdds(htlcswitch.Outgoing) {
9✔
3546
                p.log.Warnf("Outgoing link adds already "+
×
3547
                        "disabled: %v", link.ChanID())
×
3548
        }
×
3549

3550
        link.OnCommitOnce(htlcswitch.Outgoing, func() {
18✔
3551
                p.queueMsg(shutdownMsg, nil)
9✔
3552
        })
9✔
3553

3554
        return nil
9✔
3555
}
3556

3557
// chooseAddr returns the provided address if it is non-zero length, otherwise
3558
// None.
3559
func chooseAddr(addr lnwire.DeliveryAddress) fn.Option[lnwire.DeliveryAddress] {
3✔
3560
        if len(addr) == 0 {
6✔
3561
                return fn.None[lnwire.DeliveryAddress]()
3✔
3562
        }
3✔
3563

3564
        return fn.Some(addr)
×
3565
}
3566

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

3✔
3574
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3575
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3576

3✔
3577
        var (
3✔
3578
                lastTxids    lntypes.Dual[chainhash.Hash]
3✔
3579
                lastFeeRates lntypes.Dual[chainfee.SatPerVByte]
3✔
3580
        )
3✔
3581

3✔
3582
        maybeNotifyTxBroadcast := func(state chancloser.AsymmetricPeerState,
3✔
3583
                party lntypes.ChannelParty) {
6✔
3584

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

3✔
3594
                        peerLog.Warnf("ChannelPoint(%v): encountered close "+
3✔
3595
                                "err: %v", closeReq.ChanPoint, err)
3✔
3596

3✔
3597
                        select {
3✔
3598
                        case closeReq.Err <- err:
3✔
3599
                        case <-closeReq.Ctx.Done():
×
3600
                        case <-p.cg.Done():
×
3601
                        }
3602

3603
                        return
3✔
3604
                }
3605

3606
                closePending, ok := state.(*chancloser.ClosePending)
3✔
3607

3✔
3608
                // If this isn't the close pending state, we aren't at the
3✔
3609
                // terminal state yet.
3✔
3610
                if !ok {
6✔
3611
                        return
3✔
3612
                }
3✔
3613

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

3✔
3623
                        return
3✔
3624
                }
3✔
3625

3626
                feeRate := closePending.FeeRate
3✔
3627
                lastFeeRates.SetForParty(party, feeRate)
3✔
3628

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

3645
                        case <-closeReq.Ctx.Done():
×
3646
                                return
×
3647

3648
                        case <-p.cg.Done():
×
3649
                                return
×
3650
                        }
3651
                }
3652

3653
                lastTxids.SetForParty(party, closingTxid)
3✔
3654
        }
3655

3656
        peerLog.Infof("Observing RBF close updates for channel %v",
3✔
3657
                closeReq.ChanPoint)
3✔
3658

3✔
3659
        // We'll consume each new incoming state to send out the appropriate
3✔
3660
        // RPC update.
3✔
3661
        for {
6✔
3662
                select {
3✔
3663
                case newState := <-newStateChan:
3✔
3664

3✔
3665
                        switch closeState := newState.(type) {
3✔
3666
                        // Once we've reached the state of pending close, we
3667
                        // have a txid that we broadcasted.
3668
                        case *chancloser.ClosingNegotiation:
3✔
3669
                                peerState := closeState.PeerState
3✔
3670

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

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

3✔
3701
                                return
3✔
3702
                        }
3703

3704
                case <-closeReq.Ctx.Done():
3✔
3705
                        return
3✔
3706

3707
                case <-p.cg.Done():
3✔
3708
                        return
3✔
3709
                }
3710
        }
3711
}
3712

3713
// chanErrorReporter is a simple implementation of the
3714
// chancloser.ErrorReporter. This is bound to a single channel by the channel
3715
// ID.
3716
type chanErrorReporter struct {
3717
        chanID lnwire.ChannelID
3718
        peer   *Brontide
3719
}
3720

3721
// newChanErrorReporter creates a new instance of the chanErrorReporter.
3722
func newChanErrorReporter(chanID lnwire.ChannelID,
3723
        peer *Brontide) *chanErrorReporter {
3✔
3724

3✔
3725
        return &chanErrorReporter{
3✔
3726
                chanID: chanID,
3✔
3727
                peer:   peer,
3✔
3728
        }
3✔
3729
}
3✔
3730

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

×
3740
        var errMsg []byte
×
3741
        if errors.Is(chanErr, chancloser.ErrInvalidStateTransition) {
×
3742
                errMsg = []byte("unexpected protocol message")
×
3743
        } else {
×
3744
                errMsg = []byte(chanErr.Error())
×
3745
        }
×
3746

3747
        err := c.peer.SendMessageLazy(false, &lnwire.Error{
×
3748
                ChanID: c.chanID,
×
3749
                Data:   errMsg,
×
3750
        })
×
3751
        if err != nil {
×
3752
                c.peer.log.Warnf("unable to send error message to peer: %v",
×
3753
                        err)
×
3754
        }
×
3755

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

3764
        if lnChan == nil {
×
3765
                c.peer.log.Debugf("channel %v is pending, not "+
×
3766
                        "re-initializing coop close state machine",
×
3767
                        c.chanID)
×
3768

×
3769
                return
×
3770
        }
×
3771

3772
        if _, err := c.peer.initRbfChanCloser(lnChan); err != nil {
×
3773
                c.peer.activeChanCloses.Delete(c.chanID)
×
3774

×
3775
                c.peer.log.Errorf("unable to init RBF chan closer after "+
×
3776
                        "error case: %v", err)
×
3777
        }
×
3778
}
3779

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

3✔
3789
        defer p.cg.WgDone()
3✔
3790

3✔
3791
        // If there's no link, then the channel has already been flushed, so we
3✔
3792
        // don't need to continue.
3✔
3793
        if link == nil {
6✔
3794
                return
3✔
3795
        }
3✔
3796

3797
        coopCloseStates := chanCloser.RegisterStateEvents()
3✔
3798
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3799

3✔
3800
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3801

3✔
3802
        sendChanFlushed := func() {
6✔
3803
                chanState := channel.StateSnapshot()
3✔
3804

3✔
3805
                peerLog.Infof("ChannelPoint(%v) has been flushed for co-op "+
3✔
3806
                        "close, sending event to chan closer",
3✔
3807
                        channel.ChannelPoint())
3✔
3808

3✔
3809
                chanBalances := chancloser.ShutdownBalances{
3✔
3810
                        LocalBalance:  chanState.LocalBalance,
3✔
3811
                        RemoteBalance: chanState.RemoteBalance,
3✔
3812
                }
3✔
3813
                ctx := context.Background()
3✔
3814
                chanCloser.SendEvent(ctx, &chancloser.ChannelFlushed{
3✔
3815
                        ShutdownBalances: chanBalances,
3✔
3816
                        FreshFlush:       true,
3✔
3817
                })
3✔
3818
        }
3✔
3819

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

3830
                        if _, ok := newState.(*chancloser.ChannelFlushing); ok {
6✔
3831
                                peerLog.Infof("ChannelPoint(%v): rbf coop "+
3✔
3832
                                        "close is awaiting a flushed state, "+
3✔
3833
                                        "registering with link..., ",
3✔
3834
                                        channel.ChannelPoint())
3✔
3835

3✔
3836
                                // Request the link to send the event once the
3✔
3837
                                // channel is flushed. We only need this event
3✔
3838
                                // sent once, so we can exit now.
3✔
3839
                                link.OnFlushedOnce(sendChanFlushed)
3✔
3840

3✔
3841
                                return
3✔
3842
                        }
3✔
3843

3844
                case <-p.cg.Done():
3✔
3845
                        return
3✔
3846
                }
3847
        }
3848
}
3849

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

3✔
3856
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
3✔
3857

3✔
3858
        link := p.fetchLinkFromKeyAndCid(chanID)
3✔
3859

3✔
3860
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
3✔
3861
        if err != nil {
3✔
3862
                return nil, fmt.Errorf("cannot obtain best block: %w", err)
×
3863
        }
×
3864

3865
        defaultFeePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
3866
                p.cfg.CoopCloseTargetConfs,
3✔
3867
        )
3✔
3868
        if err != nil {
3✔
3869
                return nil, fmt.Errorf("unable to estimate fee: %w", err)
×
3870
        }
×
3871

3872
        thawHeight, err := channel.AbsoluteThawHeight()
3✔
3873
        if err != nil {
3✔
3874
                return nil, fmt.Errorf("unable to get thaw height: %w", err)
×
3875
        }
×
3876

3877
        peerPub := *p.IdentityKey()
3✔
3878

3✔
3879
        msgMapper := chancloser.NewRbfMsgMapper(
3✔
3880
                uint32(startingHeight), chanID, peerPub,
3✔
3881
        )
3✔
3882

3✔
3883
        initialState := chancloser.ChannelActive{}
3✔
3884

3✔
3885
        scid := channel.ZeroConfRealScid().UnwrapOr(
3✔
3886
                channel.ShortChanID(),
3✔
3887
        )
3✔
3888

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

3914
        spendEvent := protofsm.RegisterSpend[chancloser.ProtocolEvent]{
3✔
3915
                OutPoint:   channel.ChannelPoint(),
3✔
3916
                PkScript:   channel.FundingTxOut().PkScript,
3✔
3917
                HeightHint: channel.DeriveHeightHint(),
3✔
3918
                PostSpendEvent: fn.Some[chancloser.RbfSpendMapper](
3✔
3919
                        chancloser.SpendMapper,
3✔
3920
                ),
3✔
3921
        }
3✔
3922

3✔
3923
        daemonAdapters := NewLndDaemonAdapters(LndAdapterCfg{
3✔
3924
                MsgSender:     newPeerMsgSender(peerPub, p),
3✔
3925
                TxBroadcaster: p.cfg.Wallet,
3✔
3926
                ChainNotifier: p.cfg.ChainNotifier,
3✔
3927
        })
3✔
3928

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

3✔
3940
        ctx := context.Background()
3✔
3941
        chanCloser := protofsm.NewStateMachine(protoCfg)
3✔
3942
        chanCloser.Start(ctx)
3✔
3943

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

3✔
3949
                return r.RegisterEndpoint(&chanCloser)
3✔
3950
        })
3✔
3951
        if err != nil {
3✔
3952
                chanCloser.Stop()
×
3953

×
3954
                return nil, fmt.Errorf("unable to register endpoint for co-op "+
×
3955
                        "close: %w", err)
×
3956
        }
×
3957

3958
        p.activeChanCloses.Store(chanID, makeRbfCloser(&chanCloser))
3✔
3959

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

3✔
3966
        return &chanCloser, nil
3✔
3967
}
3968

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

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

3✔
3983
                var feeRate fn.Option[chainfee.SatPerKWeight]
3✔
3984
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
6✔
3985
                        feeRate = fn.Some(req.TargetFeePerKw)
3✔
3986
                })
3✔
3987

3988
                return feeRate
3✔
3989
        })(s)
3990

3991
        return fn.FlattenOption(feeRateOpt)
3✔
3992
}
3993

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

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

4011
                return addr
3✔
4012
        })(s)
4013

4014
        return fn.FlattenOption(addrOpt)
3✔
4015
}
4016

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

3✔
4023
                init.WhenLeft(f)
3✔
4024
        })
3✔
4025
}
4026

4027
// newRestartShutdownInit creates a new shutdownInit for the case where we need
4028
// to restart the shutdown flow after a restart.
4029
func newRestartShutdownInit(info channeldb.ShutdownInfo) shutdownInit {
3✔
4030
        return fn.Some(fn.NewRight[*htlcswitch.ChanClose](info))
3✔
4031
}
3✔
4032

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

4041
// waitUntilRbfCoastClear waits until the RBF co-op close state machine has
4042
// advanced to a terminal state before attempting another fee bump.
4043
func waitUntilRbfCoastClear(ctx context.Context,
4044
        rbfCloser *chancloser.RbfChanCloser) error {
3✔
4045

3✔
4046
        coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4047
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
4048
        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4049

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

4058
                localState := state.PeerState.GetForParty(lntypes.Local)
3✔
4059

3✔
4060
                // If this isn't the close pending state, we aren't at the
3✔
4061
                // terminal state yet.
3✔
4062
                _, ok = localState.(*chancloser.ClosePending)
3✔
4063

3✔
4064
                return ok
3✔
4065
        }
4066

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

4077
        peerLog.Debugf("Waiting for RBF iteration to complete...")
×
4078

×
4079
        for {
×
4080
                select {
×
4081
                case newState := <-newStateChan:
×
4082
                        if isTerminalState(newState) {
×
4083
                                return nil
×
4084
                        }
×
4085

4086
                case <-ctx.Done():
×
4087
                        return fmt.Errorf("context canceled")
×
4088
                }
4089
        }
4090
}
4091

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

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

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

4120
        chanCloser.WhenRight(func(rbfCloser *chancloser.RbfChanCloser) {
6✔
4121
                peerLog.Infof("ChannelPoint(%v): rbf-coop close requested, "+
3✔
4122
                        "sending shutdown", chanPoint)
3✔
4123

3✔
4124
                rbfState, err := rbfCloser.CurrentState()
3✔
4125
                if err != nil {
3✔
4126
                        peerLog.Warnf("ChannelPoint(%v): unable to get "+
×
4127
                                "current state for rbf-coop close: %v",
×
4128
                                chanPoint, err)
×
4129

×
4130
                        return
×
4131
                }
×
4132

4133
                coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4134

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

3✔
4142
                        p.cg.WgAdd(1)
3✔
4143
                        go func() {
6✔
4144
                                defer p.cg.WgDone()
3✔
4145

3✔
4146
                                p.observeRbfCloseUpdates(
3✔
4147
                                        rbfCloser, req, coopCloseStates,
3✔
4148
                                )
3✔
4149
                        }()
3✔
4150
                })
4151

4152
                if !rpcShutdown {
6✔
4153
                        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4154
                }
3✔
4155

4156
                ctx, _ := p.cg.Create(context.Background())
3✔
4157
                feeRate := defaultFeePerKw.FeePerVByte()
3✔
4158

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

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

×
4189
                                return
×
4190
                        }
×
4191

4192
                        event := chancloser.ProtocolEvent(
3✔
4193
                                &chancloser.SendOfferEvent{
3✔
4194
                                        TargetFeeRate: feeRate,
3✔
4195
                                },
3✔
4196
                        )
3✔
4197
                        rbfCloser.SendEvent(ctx, event)
3✔
4198

4199
                default:
×
4200
                        peerLog.Warnf("ChannelPoint(%v): unexpected state "+
×
4201
                                "for rbf-coop close: %T", chanPoint, rbfState)
×
4202
                }
4203
        })
4204

4205
        return nil
3✔
4206
}
4207

4208
// handleLocalCloseReq kicks-off the workflow to execute a cooperative or
4209
// forced unilateral closure of the channel initiated by a local subsystem.
4210
func (p *Brontide) handleLocalCloseReq(req *htlcswitch.ChanClose) {
10✔
4211
        chanID := lnwire.NewChanIDFromOutPoint(*req.ChanPoint)
10✔
4212

10✔
4213
        channel, ok := p.activeChannels.Load(chanID)
10✔
4214

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

4225
        isTaprootChan := channel.ChanType().IsTaproot()
10✔
4226

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

4249
                if err != nil {
11✔
4250
                        p.log.Errorf(err.Error())
1✔
4251
                        req.Err <- err
1✔
4252
                }
1✔
4253

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

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

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

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

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

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

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

×
4317
                if err := lnChan.State().MarkBorked(); err != nil {
×
4318
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
4319
                                failure.shortChanID, err)
×
4320
                }
×
4321
        }
4322

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

4334
                var networkMsg lnwire.Message
3✔
4335
                if failure.linkErr.Warning {
3✔
4336
                        networkMsg = &lnwire.Warning{
×
4337
                                ChanID: failure.chanID,
×
4338
                                Data:   data,
×
4339
                        }
×
4340
                } else {
3✔
4341
                        networkMsg = &lnwire.Error{
3✔
4342
                                ChanID: failure.chanID,
3✔
4343
                                Data:   data,
3✔
4344
                        }
3✔
4345
                }
3✔
4346

4347
                err := p.SendMessage(true, networkMsg)
3✔
4348
                if err != nil {
3✔
4349
                        p.log.Errorf("unable to send msg to "+
×
4350
                                "remote peer: %v", err)
×
4351
                }
×
4352
        }
4353

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

4362
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
4363
// public key and the channel id.
4364
func (p *Brontide) fetchLinkFromKeyAndCid(
4365
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
22✔
4366

22✔
4367
        var chanLink htlcswitch.ChannelUpdateHandler
22✔
4368

22✔
4369
        // We don't need to check the error here, and can instead just loop
22✔
4370
        // over the slice and return nil.
22✔
4371
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
22✔
4372
        for _, link := range links {
43✔
4373
                if link.ChanID() == cid {
42✔
4374
                        chanLink = link
21✔
4375
                        break
21✔
4376
                }
4377
        }
4378

4379
        return chanLink
22✔
4380
}
4381

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

7✔
4390
        // First, we'll clear all indexes related to the channel in question.
7✔
4391
        chanPoint := chanCloser.Channel().ChannelPoint()
7✔
4392
        p.WipeChannel(&chanPoint)
7✔
4393

7✔
4394
        // Also clear the activeChanCloses map of this channel.
7✔
4395
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
7✔
4396
        p.activeChanCloses.Delete(cid) // TODO(roasbeef): existing race
7✔
4397

7✔
4398
        // Next, we'll launch a goroutine which will request to be notified by
7✔
4399
        // the ChainNotifier once the closure transaction obtains a single
7✔
4400
        // confirmation.
7✔
4401
        notifier := p.cfg.ChainNotifier
7✔
4402

7✔
4403
        // If any error happens during waitForChanToClose, forward it to
7✔
4404
        // closeReq. If this channel closure is not locally initiated, closeReq
7✔
4405
        // will be nil, so just ignore the error.
7✔
4406
        errChan := make(chan error, 1)
7✔
4407
        if closeReq != nil {
12✔
4408
                errChan = closeReq.Err
5✔
4409
        }
5✔
4410

4411
        closingTx, err := chanCloser.ClosingTx()
7✔
4412
        if err != nil {
7✔
4413
                if closeReq != nil {
×
4414
                        p.log.Error(err)
×
4415
                        closeReq.Err <- err
×
4416
                }
×
4417
        }
4418

4419
        closingTxid := closingTx.TxHash()
7✔
4420

7✔
4421
        // If this is a locally requested shutdown, update the caller with a
7✔
4422
        // new event detailing the current pending state of this request.
7✔
4423
        if closeReq != nil {
12✔
4424
                closeReq.Updates <- &PendingUpdate{
5✔
4425
                        Txid: closingTxid[:],
5✔
4426
                }
5✔
4427
        }
5✔
4428

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

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

7✔
4459
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
7✔
4460
                "with txid: %v", chanPoint, closingTxID)
7✔
4461

7✔
4462
        // TODO(roasbeef): add param for num needed confs
7✔
4463
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
7✔
4464
                closingTxID, closeScript, 1, bestHeight,
7✔
4465
        )
7✔
4466
        if err != nil {
7✔
4467
                if errChan != nil {
×
4468
                        errChan <- err
×
4469
                }
×
4470
                return
×
4471
        }
4472

4473
        // In the case that the ChainNotifier is shutting down, all subscriber
4474
        // notification channels will be closed, generating a nil receive.
4475
        height, ok := <-confNtfn.Confirmed
7✔
4476
        if !ok {
10✔
4477
                return
3✔
4478
        }
3✔
4479

4480
        // The channel has been closed, remove it from any active indexes, and
4481
        // the database state.
4482
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
7✔
4483
                "height %v", chanPoint, height.BlockHeight)
7✔
4484

7✔
4485
        // Finally, execute the closure call back to mark the confirmation of
7✔
4486
        // the transaction closing the contract.
7✔
4487
        cb()
7✔
4488
}
4489

4490
// WipeChannel removes the passed channel point from all indexes associated with
4491
// the peer and the switch.
4492
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
7✔
4493
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
7✔
4494

7✔
4495
        p.activeChannels.Delete(chanID)
7✔
4496

7✔
4497
        // Instruct the HtlcSwitch to close this link as the channel is no
7✔
4498
        // longer active.
7✔
4499
        p.cfg.Switch.RemoveLink(chanID)
7✔
4500
}
7✔
4501

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

4513
        // Then, finalize the remote feature vector providing the flattened
4514
        // feature bit namespace.
4515
        p.remoteFeatures = lnwire.NewFeatureVector(
6✔
4516
                msg.Features, lnwire.Features,
6✔
4517
        )
6✔
4518

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

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

4534
        // Now that we know we understand their requirements, we'll check to
4535
        // see if they don't support anything that we deem to be mandatory.
4536
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
6✔
4537
                return fmt.Errorf("data loss protection required")
×
4538
        }
×
4539

4540
        return nil
6✔
4541
}
4542

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

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

4561
// hasNegotiatedScidAlias returns true if we've negotiated the
4562
// option-scid-alias feature bit with the peer.
4563
func (p *Brontide) hasNegotiatedScidAlias() bool {
6✔
4564
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
6✔
4565
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
6✔
4566
        return peerHas && localHas
6✔
4567
}
6✔
4568

4569
// sendInitMsg sends the Init message to the remote peer. This message contains
4570
// our currently supported local and global features.
4571
func (p *Brontide) sendInitMsg(legacyChan bool) error {
10✔
4572
        features := p.cfg.Features.Clone()
10✔
4573
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
10✔
4574

10✔
4575
        // If we have a legacy channel open with a peer, we downgrade static
10✔
4576
        // remote required to optional in case the peer does not understand the
10✔
4577
        // required feature bit. If we do not do this, the peer will reject our
10✔
4578
        // connection because it does not understand a required feature bit, and
10✔
4579
        // our channel will be unusable.
10✔
4580
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
11✔
4581
                p.log.Infof("Legacy channel open with peer, " +
1✔
4582
                        "downgrading static remote required feature bit to " +
1✔
4583
                        "optional")
1✔
4584

1✔
4585
                // Unset and set in both the local and global features to
1✔
4586
                // ensure both sets are consistent and merge able by old and
1✔
4587
                // new nodes.
1✔
4588
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4589
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4590

1✔
4591
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
4592
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
4593
        }
1✔
4594

4595
        msg := lnwire.NewInitMessage(
10✔
4596
                legacyFeatures.RawFeatureVector,
10✔
4597
                features.RawFeatureVector,
10✔
4598
        )
10✔
4599

10✔
4600
        return p.writeMessage(msg)
10✔
4601
}
4602

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

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

4619
        if c.LastChanSyncMsg == nil {
3✔
4620
                return fmt.Errorf("no chan sync message stored for channel %v",
×
4621
                        cid)
×
4622
        }
×
4623

4624
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
3✔
4625
                return fmt.Errorf("ignoring channel reestablish from "+
×
4626
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
4627
        }
×
4628

4629
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
3✔
4630
                "peer", cid)
3✔
4631

3✔
4632
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
3✔
4633
                return fmt.Errorf("failed resending channel sync "+
×
4634
                        "message to peer %v: %v", p, err)
×
4635
        }
×
4636

4637
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
3✔
4638
                cid)
3✔
4639

3✔
4640
        // Note down that we sent the message, so we won't resend it again for
3✔
4641
        // this connection.
3✔
4642
        p.resentChanSyncMsg[cid] = struct{}{}
3✔
4643

3✔
4644
        return nil
3✔
4645
}
4646

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

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

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

4688
                if priority {
13✔
4689
                        p.queueMsg(msg, errChan)
6✔
4690
                } else {
10✔
4691
                        p.queueMsgLazy(msg, errChan)
4✔
4692
                }
4✔
4693
        }
4694

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

4708
        return nil
6✔
4709
}
4710

4711
// PubKey returns the pubkey of the peer in compressed serialized format.
4712
//
4713
// NOTE: Part of the lnpeer.Peer interface.
4714
func (p *Brontide) PubKey() [33]byte {
5✔
4715
        return p.cfg.PubKeyBytes
5✔
4716
}
5✔
4717

4718
// IdentityKey returns the public key of the remote peer.
4719
//
4720
// NOTE: Part of the lnpeer.Peer interface.
4721
func (p *Brontide) IdentityKey() *btcec.PublicKey {
18✔
4722
        return p.cfg.Addr.IdentityKey
18✔
4723
}
18✔
4724

4725
// Address returns the network address of the remote peer.
4726
//
4727
// NOTE: Part of the lnpeer.Peer interface.
4728
func (p *Brontide) Address() net.Addr {
3✔
4729
        return p.cfg.Addr.Address
3✔
4730
}
3✔
4731

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

3✔
4739
        errChan := make(chan error, 1)
3✔
4740
        newChanMsg := &newChannelMsg{
3✔
4741
                channel: newChan,
3✔
4742
                err:     errChan,
3✔
4743
        }
3✔
4744

3✔
4745
        select {
3✔
4746
        case p.newActiveChannel <- newChanMsg:
3✔
4747
        case <-cancel:
×
4748
                return errors.New("canceled adding new channel")
×
4749
        case <-p.cg.Done():
×
4750
                return lnpeer.ErrPeerExiting
×
4751
        }
4752

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

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

3✔
4770
        errChan := make(chan error, 1)
3✔
4771
        newChanMsg := &newChannelMsg{
3✔
4772
                channelID: cid,
3✔
4773
                err:       errChan,
3✔
4774
        }
3✔
4775

3✔
4776
        select {
3✔
4777
        case p.newPendingChannel <- newChanMsg:
3✔
4778

4779
        case <-cancel:
×
4780
                return errors.New("canceled adding pending channel")
×
4781

4782
        case <-p.cg.Done():
×
4783
                return lnpeer.ErrPeerExiting
×
4784
        }
4785

4786
        // We pause here to wait for the peer to recognize the new pending
4787
        // channel before we close the channel barrier corresponding to the
4788
        // channel.
4789
        select {
3✔
4790
        case err := <-errChan:
3✔
4791
                return err
3✔
4792

4793
        case <-cancel:
×
4794
                return errors.New("canceled adding pending channel")
×
4795

4796
        case <-p.cg.Done():
×
4797
                return lnpeer.ErrPeerExiting
×
4798
        }
4799
}
4800

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

3✔
4811
        select {
3✔
4812
        case p.removePendingChannel <- newChanMsg:
3✔
4813
        case <-p.cg.Done():
×
4814
                return lnpeer.ErrPeerExiting
×
4815
        }
4816

4817
        // We pause here to wait for the peer to respond to the cancellation of
4818
        // the pending channel before we close the channel barrier
4819
        // corresponding to the channel.
4820
        select {
3✔
4821
        case err := <-errChan:
3✔
4822
                return err
3✔
4823

4824
        case <-p.cg.Done():
×
4825
                return lnpeer.ErrPeerExiting
×
4826
        }
4827
}
4828

4829
// StartTime returns the time at which the connection was established if the
4830
// peer started successfully, and zero otherwise.
4831
func (p *Brontide) StartTime() time.Time {
3✔
4832
        return p.startTime
3✔
4833
}
3✔
4834

4835
// handleCloseMsg is called when a new cooperative channel closure related
4836
// message is received from the remote peer. We'll use this message to advance
4837
// the chan closer state machine.
4838
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
16✔
4839
        link := p.fetchLinkFromKeyAndCid(msg.cid)
16✔
4840

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

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

×
4853
                errMsg := &lnwire.Error{
×
4854
                        ChanID: msg.cid,
×
4855
                        Data:   lnwire.ErrorData(err.Error()),
×
4856
                }
×
4857
                p.queueMsg(errMsg, nil)
×
4858
                return
×
4859
        }
4860

4861
        if chanCloserE.IsRight() {
16✔
4862
                // TODO(roasbeef): assert?
×
4863
                return
×
4864
        }
×
4865

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

4875
        handleErr := func(err error) {
17✔
4876
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
4877
                p.log.Error(err)
1✔
4878

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

4886
                p.activeChanCloses.Delete(msg.cid)
1✔
4887

1✔
4888
                p.Disconnect(err)
1✔
4889
        }
4890

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

4901
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
8✔
4902
                if err != nil {
8✔
4903
                        handleErr(err)
×
4904
                        return
×
4905
                }
×
4906

4907
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
14✔
4908
                        // If the link is nil it means we can immediately queue
6✔
4909
                        // the Shutdown message since we don't have to wait for
6✔
4910
                        // commitment transaction synchronization.
6✔
4911
                        if link == nil {
7✔
4912
                                p.queueMsg(&msg, nil)
1✔
4913
                                return
1✔
4914
                        }
1✔
4915

4916
                        // Immediately disallow any new HTLC's from being added
4917
                        // in the outgoing direction.
4918
                        if !link.DisableAdds(htlcswitch.Outgoing) {
5✔
4919
                                p.log.Warnf("Outgoing link adds already "+
×
4920
                                        "disabled: %v", link.ChanID())
×
4921
                        }
×
4922

4923
                        // When we have a Shutdown to send, we defer it till the
4924
                        // next time we send a CommitSig to remain spec
4925
                        // compliant.
4926
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
10✔
4927
                                p.queueMsg(&msg, nil)
5✔
4928
                        })
5✔
4929
                })
4930

4931
                beginNegotiation := func() {
16✔
4932
                        oClosingSigned, err := chanCloser.BeginNegotiation()
8✔
4933
                        if err != nil {
8✔
4934
                                handleErr(err)
×
4935
                                return
×
4936
                        }
×
4937

4938
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
16✔
4939
                                p.queueMsg(&msg, nil)
8✔
4940
                        })
8✔
4941
                }
4942

4943
                if link == nil {
9✔
4944
                        beginNegotiation()
1✔
4945
                } else {
8✔
4946
                        // Now we register a flush hook to advance the
7✔
4947
                        // ChanCloser and possibly send out a ClosingSigned
7✔
4948
                        // when the link finishes draining.
7✔
4949
                        link.OnFlushedOnce(func() {
14✔
4950
                                // Remove link in goroutine to prevent deadlock.
7✔
4951
                                go p.cfg.Switch.RemoveLink(msg.cid)
7✔
4952
                                beginNegotiation()
7✔
4953
                        })
7✔
4954
                }
4955

4956
        case *lnwire.ClosingSigned:
11✔
4957
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
11✔
4958
                if err != nil {
12✔
4959
                        handleErr(err)
1✔
4960
                        return
1✔
4961
                }
1✔
4962

4963
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
22✔
4964
                        p.queueMsg(&msg, nil)
11✔
4965
                })
11✔
4966

4967
        default:
×
4968
                panic("impossible closeMsg type")
×
4969
        }
4970

4971
        // If we haven't finished close negotiations, then we'll continue as we
4972
        // can't yet finalize the closure.
4973
        if _, err := chanCloser.ClosingTx(); err != nil {
26✔
4974
                return
11✔
4975
        }
11✔
4976

4977
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
4978
        // the channel closure by notifying relevant sub-systems and launching a
4979
        // goroutine to wait for close tx conf.
4980
        p.finalizeChanClosure(chanCloser)
7✔
4981
}
4982

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

4997
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
4998
func (p *Brontide) NetAddress() *lnwire.NetAddress {
3✔
4999
        return p.cfg.Addr
3✔
5000
}
3✔
5001

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

5007
// ConnReq is a getter for the Brontide's connReq in cfg.
5008
func (p *Brontide) ConnReq() *connmgr.ConnReq {
3✔
5009
        return p.cfg.ConnReq
3✔
5010
}
3✔
5011

5012
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
5013
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
3✔
5014
        return p.cfg.ErrorBuffer
3✔
5015
}
3✔
5016

5017
// SetAddress sets the remote peer's address given an address.
5018
func (p *Brontide) SetAddress(address net.Addr) {
×
5019
        p.cfg.Addr.Address = address
×
5020
}
×
5021

5022
// ActiveSignal returns the peer's active signal.
5023
func (p *Brontide) ActiveSignal() chan struct{} {
3✔
5024
        return p.activeSignal
3✔
5025
}
3✔
5026

5027
// Conn returns a pointer to the peer's connection struct.
5028
func (p *Brontide) Conn() net.Conn {
3✔
5029
        return p.cfg.Conn
3✔
5030
}
3✔
5031

5032
// BytesReceived returns the number of bytes received from the peer.
5033
func (p *Brontide) BytesReceived() uint64 {
3✔
5034
        return atomic.LoadUint64(&p.bytesReceived)
3✔
5035
}
3✔
5036

5037
// BytesSent returns the number of bytes sent to the peer.
5038
func (p *Brontide) BytesSent() uint64 {
3✔
5039
        return atomic.LoadUint64(&p.bytesSent)
3✔
5040
}
3✔
5041

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

5050
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
5051
        if !ok {
×
5052
                return nil
×
5053
        }
×
5054

5055
        return pingBytes
×
5056
}
5057

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

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

5079
        p.channelEventClient = sub
6✔
5080

6✔
5081
        return nil
6✔
5082
}
5083

5084
// updateNextRevocation updates the existing channel's next revocation if it's
5085
// nil.
5086
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
6✔
5087
        chanPoint := c.FundingOutpoint
6✔
5088
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
6✔
5089

6✔
5090
        // Read the current channel.
6✔
5091
        currentChan, loaded := p.activeChannels.Load(chanID)
6✔
5092

6✔
5093
        // currentChan should exist, but we perform a check anyway to avoid nil
6✔
5094
        // pointer dereference.
6✔
5095
        if !loaded {
7✔
5096
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
5097
                        chanID)
1✔
5098
        }
1✔
5099

5100
        // currentChan should not be nil, but we perform a check anyway to
5101
        // avoid nil pointer dereference.
5102
        if currentChan == nil {
6✔
5103
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
5104
                        chanID)
1✔
5105
        }
1✔
5106

5107
        // If we're being sent a new channel, and our existing channel doesn't
5108
        // have the next revocation, then we need to update the current
5109
        // existing channel.
5110
        if currentChan.RemoteNextRevocation() != nil {
4✔
5111
                return nil
×
5112
        }
×
5113

5114
        p.log.Infof("Processing retransmitted ChannelReady for "+
4✔
5115
                "ChannelPoint(%v)", chanPoint)
4✔
5116

4✔
5117
        nextRevoke := c.RemoteNextRevocation
4✔
5118

4✔
5119
        err := currentChan.InitNextRevocation(nextRevoke)
4✔
5120
        if err != nil {
4✔
5121
                return fmt.Errorf("unable to init next revocation: %w", err)
×
5122
        }
×
5123

5124
        return nil
4✔
5125
}
5126

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

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

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

5149
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
3✔
5150
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
5151
        })
×
5152
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
3✔
5153
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
5154
        })
×
5155
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
3✔
5156
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
5157
        })
×
5158

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

5169
        // Store the channel in the activeChannels map.
5170
        p.activeChannels.Store(chanID, lnChan)
3✔
5171

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

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

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

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

5200
        isTaprootChan := c.ChanType.IsTaproot()
3✔
5201

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

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

×
5218
                return fmt.Errorf("unable to init RBF chan closer for new "+
×
5219
                        "chan: %w", err)
×
5220
        }
×
5221

5222
        return nil
3✔
5223
}
5224

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

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

3✔
5240
                // Handle it and close the err chan on the request.
3✔
5241
                close(req.err)
3✔
5242

3✔
5243
                // Update the next revocation point.
3✔
5244
                err := p.updateNextRevocation(newChan.OpenChannel)
3✔
5245
                if err != nil {
3✔
5246
                        p.log.Errorf(err.Error())
×
5247
                }
×
5248

5249
                return
3✔
5250
        }
5251

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

×
5258
                return
×
5259
        }
×
5260

5261
        // Close the err chan if everything went fine.
5262
        close(req.err)
3✔
5263
}
5264

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

7✔
5272
        chanID := req.channelID
7✔
5273

7✔
5274
        // If we already have this channel, something is wrong with the funding
7✔
5275
        // flow as it will only be marked as active after `ChannelReady` is
7✔
5276
        // handled. In this case, we will do nothing but log an error, just in
7✔
5277
        // case this is a legit channel.
7✔
5278
        if p.isActiveChannel(chanID) {
8✔
5279
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
5280
                        "pending channel request", chanID)
1✔
5281

1✔
5282
                return
1✔
5283
        }
1✔
5284

5285
        // The channel has already been added, we will do nothing and return.
5286
        if p.isPendingChannel(chanID) {
7✔
5287
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
5288
                        "pending channel request", chanID)
1✔
5289

1✔
5290
                return
1✔
5291
        }
1✔
5292

5293
        // This is a new channel, we now add it to the map `activeChannels`
5294
        // with nil value and mark it as a newly added channel in
5295
        // `addedChannels`.
5296
        p.activeChannels.Store(chanID, nil)
5✔
5297
        p.addedChannels.Store(chanID, struct{}{})
5✔
5298
}
5299

5300
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
5301
// from `activeChannels` map. The request will be ignored if the channel is
5302
// considered active by Brontide. Noop if the channel ID cannot be found.
5303
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
7✔
5304
        defer close(req.err)
7✔
5305

7✔
5306
        chanID := req.channelID
7✔
5307

7✔
5308
        // If we already have this channel, something is wrong with the funding
7✔
5309
        // flow as it will only be marked as active after `ChannelReady` is
7✔
5310
        // handled. In this case, we will log an error and exit.
7✔
5311
        if p.isActiveChannel(chanID) {
8✔
5312
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
5313
                        chanID)
1✔
5314
                return
1✔
5315
        }
1✔
5316

5317
        // The channel has not been added yet, we will log a warning as there
5318
        // is an unexpected call from funding manager.
5319
        if !p.isPendingChannel(chanID) {
10✔
5320
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
4✔
5321
        }
4✔
5322

5323
        // Remove the record of this pending channel.
5324
        p.activeChannels.Delete(chanID)
6✔
5325
        p.addedChannels.Delete(chanID)
6✔
5326
}
5327

5328
// sendLinkUpdateMsg sends a message that updates the channel to the
5329
// channel's message stream.
5330
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
3✔
5331
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
3✔
5332

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

3✔
5341
                // Stop the stream when quit.
3✔
5342
                go func() {
6✔
5343
                        <-p.cg.Done()
3✔
5344
                        chanStream.Stop()
3✔
5345
                }()
3✔
5346
        }
5347

5348
        // With the stream obtained, add the message to the stream so we can
5349
        // continue processing message.
5350
        chanStream.AddMsg(msg)
3✔
5351
}
5352

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

5362
        return timeout
67✔
5363
}
5364

5365
// CoopCloseUpdates is a struct used to communicate updates for an active close
5366
// to the caller.
5367
type CoopCloseUpdates struct {
5368
        UpdateChan chan interface{}
5369

5370
        ErrChan chan error
5371
}
5372

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

5382
        return chanCloser.IsRight()
3✔
5383
}
5384

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

3✔
5393
        // If RBF coop close isn't permitted, then we'll an error.
3✔
5394
        if !p.rbfCoopCloseAllowed() {
3✔
5395
                return nil, fmt.Errorf("rbf coop close not enabled for " +
×
5396
                        "channel")
×
5397
        }
×
5398

5399
        closeUpdates := &CoopCloseUpdates{
3✔
5400
                UpdateChan: make(chan interface{}, 1),
3✔
5401
                ErrChan:    make(chan error, 1),
3✔
5402
        }
3✔
5403

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

3✔
5416
        err := p.startRbfChanCloser(newRPCShutdownInit(&closeReq), chanPoint)
3✔
5417
        if err != nil {
3✔
5418
                return nil, err
×
5419
        }
×
5420

5421
        return closeUpdates, nil
3✔
5422
}
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