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

lightningnetwork / lnd / 16170852573

09 Jul 2025 01:36PM UTC coverage: 68.199% (+10.6%) from 57.62%
16170852573

Pull #9868

github

web-flow
Merge e5726a7be into ea32aac77
Pull Request #9868: PoC Onion messaging using `msgmux`

169 of 228 new or added lines in 10 files covered. (74.12%)

17 existing lines in 3 files now uncovered.

137361 of 201411 relevant lines covered (68.2%)

21720.74 hits per line

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

78.66
/peer/brontide.go
1
package peer
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

127
        err chan error
128
}
129

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

455
        // OnionMessageServer is an instance of a message server that dispatches
456
        // onion messages to subscribers.
457
        OnionMessageServer *subscribe.Server
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
        onionMessageEndpoint := onion_message.NewOnionEndpoint(
6✔
895
                p.cfg.OnionMessageServer,
6✔
896
        )
6✔
897

6✔
898
        // We register the onion message endpoint with the message router.
6✔
899
        err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
12✔
900
                _ = r.UnregisterEndpoint(onionMessageEndpoint.Name())
6✔
901

6✔
902
                return r.RegisterEndpoint(onionMessageEndpoint)
6✔
903
        })
6✔
904
        if err != nil {
6✔
NEW
905
                return fmt.Errorf("unable to register endpoint for onion "+
×
NEW
906
                        "messaging: %w", err)
×
NEW
907
        }
×
908

909
        p.startTime = time.Now()
6✔
910

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

5✔
918
                // Send the messages directly via writeMessage and bypass the
5✔
919
                // writeHandler goroutine.
5✔
920
                for _, msg := range msgs {
10✔
921
                        if err := p.writeMessage(msg); err != nil {
5✔
922
                                return fmt.Errorf("unable to send "+
×
923
                                        "reestablish msg: %v", err)
×
924
                        }
×
925
                }
926
        }
927

928
        err = p.pingManager.Start()
6✔
929
        if err != nil {
6✔
930
                return fmt.Errorf("could not start ping manager %w", err)
×
931
        }
×
932

933
        p.cg.WgAdd(4)
6✔
934
        go p.queueHandler()
6✔
935
        go p.writeHandler()
6✔
936
        go p.channelManager()
6✔
937
        go p.readHandler()
6✔
938

6✔
939
        // Signal to any external processes that the peer is now active.
6✔
940
        close(p.activeSignal)
6✔
941

6✔
942
        // Node announcements don't propagate very well throughout the network
6✔
943
        // as there isn't a way to efficiently query for them through their
6✔
944
        // timestamp, mostly affecting nodes that were offline during the time
6✔
945
        // of broadcast. We'll resend our node announcement to the remote peer
6✔
946
        // as a best-effort delivery such that it can also propagate to their
6✔
947
        // peers. To ensure they can successfully process it in most cases,
6✔
948
        // we'll only resend it as long as we have at least one confirmed
6✔
949
        // advertised channel with the remote peer.
6✔
950
        //
6✔
951
        // TODO(wilmer): Remove this once we're able to query for node
6✔
952
        // announcements through their timestamps.
6✔
953
        p.cg.WgAdd(2)
6✔
954
        go p.maybeSendNodeAnn(activeChans)
6✔
955
        go p.maybeSendChannelUpdates()
6✔
956

6✔
957
        return nil
6✔
958
}
959

960
// initGossipSync initializes either a gossip syncer or an initial routing
961
// dump, depending on the negotiated synchronization method.
962
func (p *Brontide) initGossipSync() {
6✔
963
        // If the remote peer knows of the new gossip queries feature, then
6✔
964
        // we'll create a new gossipSyncer in the AuthenticatedGossiper for it.
6✔
965
        if p.remoteFeatures.HasFeature(lnwire.GossipQueriesOptional) {
12✔
966
                p.log.Info("Negotiated chan series queries")
6✔
967

6✔
968
                if p.cfg.AuthGossiper == nil {
9✔
969
                        // This should only ever be hit in the unit tests.
3✔
970
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
3✔
971
                                "gossip sync.")
3✔
972
                        return
3✔
973
                }
3✔
974

975
                // Register the peer's gossip syncer with the gossiper.
976
                // This blocks synchronously to ensure the gossip syncer is
977
                // registered with the gossiper before attempting to read
978
                // messages from the remote peer.
979
                //
980
                // TODO(wilmer): Only sync updates from non-channel peers. This
981
                // requires an improved version of the current network
982
                // bootstrapper to ensure we can find and connect to non-channel
983
                // peers.
984
                p.cfg.AuthGossiper.InitSyncState(p)
3✔
985
        }
986
}
987

988
// taprootShutdownAllowed returns true if both parties have negotiated the
989
// shutdown-any-segwit feature.
990
func (p *Brontide) taprootShutdownAllowed() bool {
9✔
991
        return p.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
9✔
992
                p.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
9✔
993
}
9✔
994

995
// rbfCoopCloseAllowed returns true if both parties have negotiated the new RBF
996
// coop close feature.
997
func (p *Brontide) rbfCoopCloseAllowed() bool {
10✔
998
        bothHaveBit := func(bit lnwire.FeatureBit) bool {
27✔
999
                return p.RemoteFeatures().HasFeature(bit) &&
17✔
1000
                        p.LocalFeatures().HasFeature(bit)
17✔
1001
        }
17✔
1002

1003
        return bothHaveBit(lnwire.RbfCoopCloseOptional) ||
10✔
1004
                bothHaveBit(lnwire.RbfCoopCloseOptionalStaging)
10✔
1005
}
1006

1007
// QuitSignal is a method that should return a channel which will be sent upon
1008
// or closed once the backing peer exits. This allows callers using the
1009
// interface to cancel any processing in the event the backing implementation
1010
// exits.
1011
//
1012
// NOTE: Part of the lnpeer.Peer interface.
1013
func (p *Brontide) QuitSignal() <-chan struct{} {
3✔
1014
        return p.cg.Done()
3✔
1015
}
3✔
1016

1017
// addrWithInternalKey takes a delivery script, then attempts to supplement it
1018
// with information related to the internal key for the addr, but only if it's
1019
// a taproot addr.
1020
func (p *Brontide) addrWithInternalKey(
1021
        deliveryScript []byte) (*chancloser.DeliveryAddrWithKey, error) {
12✔
1022

12✔
1023
        // Currently, custom channels cannot be created with external upfront
12✔
1024
        // shutdown addresses, so this shouldn't be an issue. We only require
12✔
1025
        // the internal key for taproot addresses to be able to provide a non
12✔
1026
        // inclusion proof of any scripts.
12✔
1027
        internalKeyDesc, err := lnwallet.InternalKeyForAddr(
12✔
1028
                p.cfg.Wallet, &p.cfg.Wallet.Cfg.NetParams, deliveryScript,
12✔
1029
        )
12✔
1030
        if err != nil {
12✔
1031
                return nil, fmt.Errorf("unable to fetch internal key: %w", err)
×
1032
        }
×
1033

1034
        return &chancloser.DeliveryAddrWithKey{
12✔
1035
                DeliveryAddress: deliveryScript,
12✔
1036
                InternalKey: fn.MapOption(
12✔
1037
                        func(desc keychain.KeyDescriptor) btcec.PublicKey {
15✔
1038
                                return *desc.PubKey
3✔
1039
                        },
3✔
1040
                )(internalKeyDesc),
1041
        }, nil
1042
}
1043

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

6✔
1051
        // Return a slice of messages to send to the peers in case the channel
6✔
1052
        // cannot be loaded normally.
6✔
1053
        var msgs []lnwire.Message
6✔
1054

6✔
1055
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
6✔
1056

6✔
1057
        for _, dbChan := range chans {
11✔
1058
                hasScidFeature := dbChan.ChanType.HasScidAliasFeature()
5✔
1059
                if scidAliasNegotiated && !hasScidFeature {
8✔
1060
                        // We'll request and store an alias, making sure that a
3✔
1061
                        // gossiper mapping is not created for the alias to the
3✔
1062
                        // real SCID. This is done because the peer and funding
3✔
1063
                        // manager are not aware of each other's states and if
3✔
1064
                        // we did not do this, we would accept alias channel
3✔
1065
                        // updates after 6 confirmations, which would be buggy.
3✔
1066
                        // We'll queue a channel_ready message with the new
3✔
1067
                        // alias. This should technically be done *after* the
3✔
1068
                        // reestablish, but this behavior is pre-existing since
3✔
1069
                        // the funding manager may already queue a
3✔
1070
                        // channel_ready before the channel_reestablish.
3✔
1071
                        if !dbChan.IsPending {
6✔
1072
                                aliasScid, err := p.cfg.RequestAlias()
3✔
1073
                                if err != nil {
3✔
1074
                                        return nil, err
×
1075
                                }
×
1076

1077
                                err = p.cfg.AddLocalAlias(
3✔
1078
                                        aliasScid, dbChan.ShortChanID(), false,
3✔
1079
                                        false,
3✔
1080
                                )
3✔
1081
                                if err != nil {
3✔
1082
                                        return nil, err
×
1083
                                }
×
1084

1085
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
1086
                                        dbChan.FundingOutpoint,
3✔
1087
                                )
3✔
1088

3✔
1089
                                // Fetch the second commitment point to send in
3✔
1090
                                // the channel_ready message.
3✔
1091
                                second, err := dbChan.SecondCommitmentPoint()
3✔
1092
                                if err != nil {
3✔
1093
                                        return nil, err
×
1094
                                }
×
1095

1096
                                channelReadyMsg := lnwire.NewChannelReady(
3✔
1097
                                        chanID, second,
3✔
1098
                                )
3✔
1099
                                channelReadyMsg.AliasScid = &aliasScid
3✔
1100

3✔
1101
                                msgs = append(msgs, channelReadyMsg)
3✔
1102
                        }
1103

1104
                        // If we've negotiated the option-scid-alias feature
1105
                        // and this channel does not have ScidAliasFeature set
1106
                        // to true due to an upgrade where the feature bit was
1107
                        // turned on, we'll update the channel's database
1108
                        // state.
1109
                        err := dbChan.MarkScidAliasNegotiated()
3✔
1110
                        if err != nil {
3✔
1111
                                return nil, err
×
1112
                        }
×
1113
                }
1114

1115
                var chanOpts []lnwallet.ChannelOpt
5✔
1116
                p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
5✔
1117
                        chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
1118
                })
×
1119
                p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
5✔
1120
                        chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
1121
                })
×
1122
                p.cfg.AuxResolver.WhenSome(
5✔
1123
                        func(s lnwallet.AuxContractResolver) {
5✔
1124
                                chanOpts = append(
×
1125
                                        chanOpts, lnwallet.WithAuxResolver(s),
×
1126
                                )
×
1127
                        },
×
1128
                )
1129

1130
                lnChan, err := lnwallet.NewLightningChannel(
5✔
1131
                        p.cfg.Signer, dbChan, p.cfg.SigPool, chanOpts...,
5✔
1132
                )
5✔
1133
                if err != nil {
5✔
1134
                        return nil, fmt.Errorf("unable to create channel "+
×
1135
                                "state machine: %w", err)
×
1136
                }
×
1137

1138
                chanPoint := dbChan.FundingOutpoint
5✔
1139

5✔
1140
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
5✔
1141

5✔
1142
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
5✔
1143
                        chanPoint, lnChan.IsPending())
5✔
1144

5✔
1145
                // Skip adding any permanently irreconcilable channels to the
5✔
1146
                // htlcswitch.
5✔
1147
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
5✔
1148
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
10✔
1149

5✔
1150
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
5✔
1151
                                "start.", chanPoint, dbChan.ChanStatus())
5✔
1152

5✔
1153
                        // To help our peer recover from a potential data loss,
5✔
1154
                        // we resend our channel reestablish message if the
5✔
1155
                        // channel is in a borked state. We won't process any
5✔
1156
                        // channel reestablish message sent from the peer, but
5✔
1157
                        // that's okay since the assumption is that we did when
5✔
1158
                        // marking the channel borked.
5✔
1159
                        chanSync, err := dbChan.ChanSyncMsg()
5✔
1160
                        if err != nil {
5✔
1161
                                p.log.Errorf("Unable to create channel "+
×
1162
                                        "reestablish message for channel %v: "+
×
1163
                                        "%v", chanPoint, err)
×
1164
                                continue
×
1165
                        }
1166

1167
                        msgs = append(msgs, chanSync)
5✔
1168

5✔
1169
                        // Check if this channel needs to have the cooperative
5✔
1170
                        // close process restarted. If so, we'll need to send
5✔
1171
                        // the Shutdown message that is returned.
5✔
1172
                        if dbChan.HasChanStatus(
5✔
1173
                                channeldb.ChanStatusCoopBroadcasted,
5✔
1174
                        ) {
8✔
1175

3✔
1176
                                shutdownMsg, err := p.restartCoopClose(lnChan)
3✔
1177
                                if err != nil {
3✔
1178
                                        p.log.Errorf("Unable to restart "+
×
1179
                                                "coop close for channel: %v",
×
1180
                                                err)
×
1181
                                        continue
×
1182
                                }
1183

1184
                                if shutdownMsg == nil {
6✔
1185
                                        continue
3✔
1186
                                }
1187

1188
                                // Append the message to the set of messages to
1189
                                // send.
1190
                                msgs = append(msgs, shutdownMsg)
×
1191
                        }
1192

1193
                        continue
5✔
1194
                }
1195

1196
                // Before we register this new link with the HTLC Switch, we'll
1197
                // need to fetch its current link-layer forwarding policy from
1198
                // the database.
1199
                graph := p.cfg.ChannelGraph
3✔
1200
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
3✔
1201
                        &chanPoint,
3✔
1202
                )
3✔
1203
                if err != nil && !errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1204
                        return nil, err
×
1205
                }
×
1206

1207
                // We'll filter out our policy from the directional channel
1208
                // edges based whom the edge connects to. If it doesn't connect
1209
                // to us, then we know that we were the one that advertised the
1210
                // policy.
1211
                //
1212
                // TODO(roasbeef): can add helper method to get policy for
1213
                // particular channel.
1214
                var selfPolicy *models.ChannelEdgePolicy
3✔
1215
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
3✔
1216
                        p.cfg.ServerPubKey[:]) {
6✔
1217

3✔
1218
                        selfPolicy = p1
3✔
1219
                } else {
6✔
1220
                        selfPolicy = p2
3✔
1221
                }
3✔
1222

1223
                // If we don't yet have an advertised routing policy, then
1224
                // we'll use the current default, otherwise we'll translate the
1225
                // routing policy into a forwarding policy.
1226
                var forwardingPolicy *models.ForwardingPolicy
3✔
1227
                if selfPolicy != nil {
6✔
1228
                        forwardingPolicy = &models.ForwardingPolicy{
3✔
1229
                                MinHTLCOut:    selfPolicy.MinHTLC,
3✔
1230
                                MaxHTLC:       selfPolicy.MaxHTLC,
3✔
1231
                                BaseFee:       selfPolicy.FeeBaseMSat,
3✔
1232
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
3✔
1233
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
3✔
1234
                        }
3✔
1235
                        selfPolicy.InboundFee.WhenSome(func(fee lnwire.Fee) {
3✔
1236
                                inboundFee := models.NewInboundFeeFromWire(fee)
×
1237
                                forwardingPolicy.InboundFee = inboundFee
×
1238
                        })
×
1239
                } else {
3✔
1240
                        p.log.Warnf("Unable to find our forwarding policy "+
3✔
1241
                                "for channel %v, using default values",
3✔
1242
                                chanPoint)
3✔
1243
                        forwardingPolicy = &p.cfg.RoutingPolicy
3✔
1244
                }
3✔
1245

1246
                p.log.Tracef("Using link policy of: %v",
3✔
1247
                        spew.Sdump(forwardingPolicy))
3✔
1248

3✔
1249
                // If the channel is pending, set the value to nil in the
3✔
1250
                // activeChannels map. This is done to signify that the channel
3✔
1251
                // is pending. We don't add the link to the switch here - it's
3✔
1252
                // the funding manager's responsibility to spin up pending
3✔
1253
                // channels. Adding them here would just be extra work as we'll
3✔
1254
                // tear them down when creating + adding the final link.
3✔
1255
                if lnChan.IsPending() {
6✔
1256
                        p.activeChannels.Store(chanID, nil)
3✔
1257

3✔
1258
                        continue
3✔
1259
                }
1260

1261
                shutdownInfo, err := lnChan.State().ShutdownInfo()
3✔
1262
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
3✔
1263
                        return nil, err
×
1264
                }
×
1265

1266
                isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
1267

3✔
1268
                var (
3✔
1269
                        shutdownMsg     fn.Option[lnwire.Shutdown]
3✔
1270
                        shutdownInfoErr error
3✔
1271
                )
3✔
1272
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
6✔
1273
                        // If we can use the new RBF close feature, we don't
3✔
1274
                        // need to create the legacy closer. However for taproot
3✔
1275
                        // channels, we'll continue to use the legacy closer.
3✔
1276
                        if p.rbfCoopCloseAllowed() && !isTaprootChan {
6✔
1277
                                return
3✔
1278
                        }
3✔
1279

1280
                        // Compute an ideal fee.
1281
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
1282
                                p.cfg.CoopCloseTargetConfs,
3✔
1283
                        )
3✔
1284
                        if err != nil {
3✔
1285
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1286
                                        "estimate fee: %w", err)
×
1287

×
1288
                                return
×
1289
                        }
×
1290

1291
                        addr, err := p.addrWithInternalKey(
3✔
1292
                                info.DeliveryScript.Val,
3✔
1293
                        )
3✔
1294
                        if err != nil {
3✔
1295
                                shutdownInfoErr = fmt.Errorf("unable to make "+
×
1296
                                        "delivery addr: %w", err)
×
1297
                                return
×
1298
                        }
×
1299
                        negotiateChanCloser, err := p.createChanCloser(
3✔
1300
                                lnChan, addr, feePerKw, nil,
3✔
1301
                                info.Closer(),
3✔
1302
                        )
3✔
1303
                        if err != nil {
3✔
1304
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1305
                                        "create chan closer: %w", err)
×
1306

×
1307
                                return
×
1308
                        }
×
1309

1310
                        chanID := lnwire.NewChanIDFromOutPoint(
3✔
1311
                                lnChan.State().FundingOutpoint,
3✔
1312
                        )
3✔
1313

3✔
1314
                        p.activeChanCloses.Store(chanID, makeNegotiateCloser(
3✔
1315
                                negotiateChanCloser,
3✔
1316
                        ))
3✔
1317

3✔
1318
                        // Create the Shutdown message.
3✔
1319
                        shutdown, err := negotiateChanCloser.ShutdownChan()
3✔
1320
                        if err != nil {
3✔
1321
                                p.activeChanCloses.Delete(chanID)
×
1322
                                shutdownInfoErr = err
×
1323

×
1324
                                return
×
1325
                        }
×
1326

1327
                        shutdownMsg = fn.Some(*shutdown)
3✔
1328
                })
1329
                if shutdownInfoErr != nil {
3✔
1330
                        return nil, shutdownInfoErr
×
1331
                }
×
1332

1333
                // Subscribe to the set of on-chain events for this channel.
1334
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
3✔
1335
                        chanPoint,
3✔
1336
                )
3✔
1337
                if err != nil {
3✔
1338
                        return nil, err
×
1339
                }
×
1340

1341
                err = p.addLink(
3✔
1342
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
3✔
1343
                        true, shutdownMsg,
3✔
1344
                )
3✔
1345
                if err != nil {
3✔
1346
                        return nil, fmt.Errorf("unable to add link %v to "+
×
1347
                                "switch: %v", chanPoint, err)
×
1348
                }
×
1349

1350
                p.activeChannels.Store(chanID, lnChan)
3✔
1351

3✔
1352
                // We're using the old co-op close, so we don't need to init
3✔
1353
                // the new RBF chan closer. If we have a taproot chan, then
3✔
1354
                // we'll also use the legacy type, so we don't need to make the
3✔
1355
                // new closer.
3✔
1356
                if !p.rbfCoopCloseAllowed() || isTaprootChan {
6✔
1357
                        continue
3✔
1358
                }
1359

1360
                // Now that the link has been added above, we'll also init an
1361
                // RBF chan closer for this channel, but only if the new close
1362
                // feature is negotiated.
1363
                //
1364
                // Creating this here ensures that any shutdown messages sent
1365
                // will be automatically routed by the msg router.
1366
                if _, err := p.initRbfChanCloser(lnChan); err != nil {
3✔
1367
                        p.activeChanCloses.Delete(chanID)
×
1368

×
1369
                        return nil, fmt.Errorf("unable to init RBF chan "+
×
1370
                                "closer during peer connect: %w", err)
×
1371
                }
×
1372

1373
                // If the shutdown info isn't blank, then we should kick things
1374
                // off by sending a shutdown message to the remote party to
1375
                // continue the old shutdown flow.
1376
                restartShutdown := func(s channeldb.ShutdownInfo) error {
6✔
1377
                        return p.startRbfChanCloser(
3✔
1378
                                newRestartShutdownInit(s),
3✔
1379
                                lnChan.ChannelPoint(),
3✔
1380
                        )
3✔
1381
                }
3✔
1382
                err = fn.MapOptionZ(shutdownInfo, restartShutdown)
3✔
1383
                if err != nil {
3✔
1384
                        return nil, fmt.Errorf("unable to start RBF "+
×
1385
                                "chan closer: %w", err)
×
1386
                }
×
1387
        }
1388

1389
        return msgs, nil
6✔
1390
}
1391

1392
// addLink creates and adds a new ChannelLink from the specified channel.
1393
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1394
        lnChan *lnwallet.LightningChannel,
1395
        forwardingPolicy *models.ForwardingPolicy,
1396
        chainEvents *contractcourt.ChainEventSubscription,
1397
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
3✔
1398

3✔
1399
        // onChannelFailure will be called by the link in case the channel
3✔
1400
        // fails for some reason.
3✔
1401
        onChannelFailure := func(chanID lnwire.ChannelID,
3✔
1402
                shortChanID lnwire.ShortChannelID,
3✔
1403
                linkErr htlcswitch.LinkFailureError) {
6✔
1404

3✔
1405
                failure := linkFailureReport{
3✔
1406
                        chanPoint:   *chanPoint,
3✔
1407
                        chanID:      chanID,
3✔
1408
                        shortChanID: shortChanID,
3✔
1409
                        linkErr:     linkErr,
3✔
1410
                }
3✔
1411

3✔
1412
                select {
3✔
1413
                case p.linkFailures <- failure:
3✔
1414
                case <-p.cg.Done():
×
1415
                case <-p.cfg.Quit:
×
1416
                }
1417
        }
1418

1419
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
6✔
1420
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
3✔
1421
        }
3✔
1422

1423
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
6✔
1424
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
3✔
1425
        }
3✔
1426

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

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

3✔
1482
        // With the channel link created, we'll now notify the htlc switch so
3✔
1483
        // this channel can be used to dispatch local payments and also
3✔
1484
        // passively forward payments.
3✔
1485
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
3✔
1486
}
1487

1488
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1489
// one confirmed public channel exists with them.
1490
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
6✔
1491
        defer p.cg.WgDone()
6✔
1492

6✔
1493
        hasConfirmedPublicChan := false
6✔
1494
        for _, channel := range channels {
11✔
1495
                if channel.IsPending {
8✔
1496
                        continue
3✔
1497
                }
1498
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
10✔
1499
                        continue
5✔
1500
                }
1501

1502
                hasConfirmedPublicChan = true
3✔
1503
                break
3✔
1504
        }
1505
        if !hasConfirmedPublicChan {
12✔
1506
                return
6✔
1507
        }
6✔
1508

1509
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
3✔
1510
        if err != nil {
3✔
1511
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1512
                return
×
1513
        }
×
1514

1515
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
3✔
1516
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1517
        }
×
1518
}
1519

1520
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1521
// have any active channels with them.
1522
func (p *Brontide) maybeSendChannelUpdates() {
6✔
1523
        defer p.cg.WgDone()
6✔
1524

6✔
1525
        // If we don't have any active channels, then we can exit early.
6✔
1526
        if p.activeChannels.Len() == 0 {
10✔
1527
                return
4✔
1528
        }
4✔
1529

1530
        maybeSendUpd := func(cid lnwire.ChannelID,
5✔
1531
                lnChan *lnwallet.LightningChannel) error {
10✔
1532

5✔
1533
                // Nil channels are pending, so we'll skip them.
5✔
1534
                if lnChan == nil {
8✔
1535
                        return nil
3✔
1536
                }
3✔
1537

1538
                dbChan := lnChan.State()
5✔
1539
                scid := func() lnwire.ShortChannelID {
10✔
1540
                        switch {
5✔
1541
                        // Otherwise if it's a zero conf channel and confirmed,
1542
                        // then we need to use the "real" scid.
1543
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
3✔
1544
                                return dbChan.ZeroConfRealScid()
3✔
1545

1546
                        // Otherwise, we can use the normal scid.
1547
                        default:
5✔
1548
                                return dbChan.ShortChanID()
5✔
1549
                        }
1550
                }()
1551

1552
                // Now that we know the channel is in a good state, we'll try
1553
                // to fetch the update to send to the remote peer. If the
1554
                // channel is pending, and not a zero conf channel, we'll get
1555
                // an error here which we'll ignore.
1556
                chanUpd, err := p.cfg.FetchLastChanUpdate(scid)
5✔
1557
                if err != nil {
8✔
1558
                        p.log.Debugf("Unable to fetch channel update for "+
3✔
1559
                                "ChannelPoint(%v), scid=%v: %v",
3✔
1560
                                dbChan.FundingOutpoint, dbChan.ShortChanID, err)
3✔
1561

3✔
1562
                        return nil
3✔
1563
                }
3✔
1564

1565
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
5✔
1566
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
5✔
1567

5✔
1568
                // We'll send it as a normal message instead of using the lazy
5✔
1569
                // queue to prioritize transmission of the fresh update.
5✔
1570
                if err := p.SendMessage(false, chanUpd); err != nil {
5✔
1571
                        err := fmt.Errorf("unable to send channel update for "+
×
1572
                                "ChannelPoint(%v), scid=%v: %w",
×
1573
                                dbChan.FundingOutpoint, dbChan.ShortChanID(),
×
1574
                                err)
×
1575
                        p.log.Errorf(err.Error())
×
1576

×
1577
                        return err
×
1578
                }
×
1579

1580
                return nil
5✔
1581
        }
1582

1583
        p.activeChannels.ForEach(maybeSendUpd)
5✔
1584
}
1585

1586
// WaitForDisconnect waits until the peer has disconnected. A peer may be
1587
// disconnected if the local or remote side terminates the connection, or an
1588
// irrecoverable protocol error has been encountered. This method will only
1589
// begin watching the peer's waitgroup after the ready channel or the peer's
1590
// quit channel are signaled. The ready channel should only be signaled if a
1591
// call to Start returns no error. Otherwise, if the peer fails to start,
1592
// calling Disconnect will signal the quit channel and the method will not
1593
// block, since no goroutines were spawned.
1594
func (p *Brontide) WaitForDisconnect(ready chan struct{}) {
3✔
1595
        // Before we try to call the `Wait` goroutine, we'll make sure the main
3✔
1596
        // set of goroutines are already active.
3✔
1597
        select {
3✔
1598
        case <-p.startReady:
3✔
1599
        case <-p.cg.Done():
1✔
1600
                return
1✔
1601
        }
1602

1603
        select {
3✔
1604
        case <-ready:
3✔
1605
        case <-p.cg.Done():
3✔
1606
        }
1607

1608
        p.cg.WgWait()
3✔
1609
}
1610

1611
// Disconnect terminates the connection with the remote peer. Additionally, a
1612
// signal is sent to the server and htlcSwitch indicating the resources
1613
// allocated to the peer can now be cleaned up.
1614
//
1615
// NOTE: Be aware that this method will block if the peer is still starting up.
1616
// Therefore consider starting it in a goroutine if you cannot guarantee that
1617
// the peer has finished starting up before calling this method.
1618
func (p *Brontide) Disconnect(reason error) {
3✔
1619
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
6✔
1620
                return
3✔
1621
        }
3✔
1622

1623
        // Make sure initialization has completed before we try to tear things
1624
        // down.
1625
        //
1626
        // NOTE: We only read the `startReady` chan if the peer has been
1627
        // started, otherwise we will skip reading it as this chan won't be
1628
        // closed, hence blocks forever.
1629
        if atomic.LoadInt32(&p.started) == 1 {
6✔
1630
                p.log.Debugf("Peer hasn't finished starting up yet, waiting " +
3✔
1631
                        "on startReady signal before closing connection")
3✔
1632

3✔
1633
                select {
3✔
1634
                case <-p.startReady:
3✔
1635
                case <-p.cg.Done():
×
1636
                        return
×
1637
                }
1638
        }
1639

1640
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
3✔
1641
        p.storeError(err)
3✔
1642

3✔
1643
        p.log.Infof(err.Error())
3✔
1644

3✔
1645
        // Stop PingManager before closing TCP connection.
3✔
1646
        p.pingManager.Stop()
3✔
1647

3✔
1648
        // Ensure that the TCP connection is properly closed before continuing.
3✔
1649
        p.cfg.Conn.Close()
3✔
1650

3✔
1651
        p.cg.Quit()
3✔
1652

3✔
1653
        // If our msg router isn't global (local to this instance), then we'll
3✔
1654
        // stop it. Otherwise, we'll leave it running.
3✔
1655
        if !p.globalMsgRouter {
6✔
1656
                p.msgRouter.WhenSome(func(router msgmux.Router) {
6✔
1657
                        router.Stop()
3✔
1658
                })
3✔
1659
        }
1660
}
1661

1662
// String returns the string representation of this peer.
1663
func (p *Brontide) String() string {
3✔
1664
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
3✔
1665
}
3✔
1666

1667
// readNextMessage reads, and returns the next message on the wire along with
1668
// any additional raw payload.
1669
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
10✔
1670
        noiseConn := p.cfg.Conn
10✔
1671
        err := noiseConn.SetReadDeadline(time.Time{})
10✔
1672
        if err != nil {
10✔
1673
                return nil, err
×
1674
        }
×
1675

1676
        pktLen, err := noiseConn.ReadNextHeader()
10✔
1677
        if err != nil {
13✔
1678
                return nil, fmt.Errorf("read next header: %w", err)
3✔
1679
        }
3✔
1680

1681
        // First we'll read the next _full_ message. We do this rather than
1682
        // reading incrementally from the stream as the Lightning wire protocol
1683
        // is message oriented and allows nodes to pad on additional data to
1684
        // the message stream.
1685
        var (
7✔
1686
                nextMsg lnwire.Message
7✔
1687
                msgLen  uint64
7✔
1688
        )
7✔
1689
        err = p.cfg.ReadPool.Submit(func(buf *buffer.Read) error {
14✔
1690
                // Before reading the body of the message, set the read timeout
7✔
1691
                // accordingly to ensure we don't block other readers using the
7✔
1692
                // pool. We do so only after the task has been scheduled to
7✔
1693
                // ensure the deadline doesn't expire while the message is in
7✔
1694
                // the process of being scheduled.
7✔
1695
                readDeadline := time.Now().Add(
7✔
1696
                        p.scaleTimeout(readMessageTimeout),
7✔
1697
                )
7✔
1698
                readErr := noiseConn.SetReadDeadline(readDeadline)
7✔
1699
                if readErr != nil {
7✔
1700
                        return readErr
×
1701
                }
×
1702

1703
                // The ReadNextBody method will actually end up re-using the
1704
                // buffer, so within this closure, we can continue to use
1705
                // rawMsg as it's just a slice into the buf from the buffer
1706
                // pool.
1707
                rawMsg, readErr := noiseConn.ReadNextBody(buf[:pktLen])
7✔
1708
                if readErr != nil {
7✔
1709
                        return fmt.Errorf("read next body: %w", readErr)
×
1710
                }
×
1711
                msgLen = uint64(len(rawMsg))
7✔
1712

7✔
1713
                // Next, create a new io.Reader implementation from the raw
7✔
1714
                // message, and use this to decode the message directly from.
7✔
1715
                msgReader := bytes.NewReader(rawMsg)
7✔
1716
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
7✔
1717
                if err != nil {
10✔
1718
                        return err
3✔
1719
                }
3✔
1720

1721
                // At this point, rawMsg and buf will be returned back to the
1722
                // buffer pool for re-use.
1723
                return nil
7✔
1724
        })
1725
        atomic.AddUint64(&p.bytesReceived, msgLen)
7✔
1726
        if err != nil {
10✔
1727
                return nil, err
3✔
1728
        }
3✔
1729

1730
        p.logWireMessage(nextMsg, true)
7✔
1731

7✔
1732
        return nextMsg, nil
7✔
1733
}
1734

1735
// msgStream implements a goroutine-safe, in-order stream of messages to be
1736
// delivered via closure to a receiver. These messages MUST be in order due to
1737
// the nature of the lightning channel commitment and gossiper state machines.
1738
// TODO(conner): use stream handler interface to abstract out stream
1739
// state/logging.
1740
type msgStream struct {
1741
        streamShutdown int32 // To be used atomically.
1742

1743
        peer *Brontide
1744

1745
        apply func(lnwire.Message)
1746

1747
        startMsg string
1748
        stopMsg  string
1749

1750
        msgCond *sync.Cond
1751
        msgs    []lnwire.Message
1752

1753
        mtx sync.Mutex
1754

1755
        producerSema chan struct{}
1756

1757
        wg   sync.WaitGroup
1758
        quit chan struct{}
1759
}
1760

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

6✔
1769
        stream := &msgStream{
6✔
1770
                peer:         p,
6✔
1771
                apply:        apply,
6✔
1772
                startMsg:     startMsg,
6✔
1773
                stopMsg:      stopMsg,
6✔
1774
                producerSema: make(chan struct{}, bufSize),
6✔
1775
                quit:         make(chan struct{}),
6✔
1776
        }
6✔
1777
        stream.msgCond = sync.NewCond(&stream.mtx)
6✔
1778

6✔
1779
        // Before we return the active stream, we'll populate the producer's
6✔
1780
        // semaphore channel. We'll use this to ensure that the producer won't
6✔
1781
        // attempt to allocate memory in the queue for an item until it has
6✔
1782
        // sufficient extra space.
6✔
1783
        for i := uint32(0); i < bufSize; i++ {
159✔
1784
                stream.producerSema <- struct{}{}
153✔
1785
        }
153✔
1786

1787
        return stream
6✔
1788
}
1789

1790
// Start starts the chanMsgStream.
1791
func (ms *msgStream) Start() {
6✔
1792
        ms.wg.Add(1)
6✔
1793
        go ms.msgConsumer()
6✔
1794
}
6✔
1795

1796
// Stop stops the chanMsgStream.
1797
func (ms *msgStream) Stop() {
3✔
1798
        // TODO(roasbeef): signal too?
3✔
1799

3✔
1800
        close(ms.quit)
3✔
1801

3✔
1802
        // Now that we've closed the channel, we'll repeatedly signal the msg
3✔
1803
        // consumer until we've detected that it has exited.
3✔
1804
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
6✔
1805
                ms.msgCond.Signal()
3✔
1806
                time.Sleep(time.Millisecond * 100)
3✔
1807
        }
3✔
1808

1809
        ms.wg.Wait()
3✔
1810
}
1811

1812
// msgConsumer is the main goroutine that streams messages from the peer's
1813
// readHandler directly to the target channel.
1814
func (ms *msgStream) msgConsumer() {
6✔
1815
        defer ms.wg.Done()
6✔
1816
        defer peerLog.Tracef(ms.stopMsg)
6✔
1817
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
6✔
1818

6✔
1819
        peerLog.Tracef(ms.startMsg)
6✔
1820

6✔
1821
        for {
12✔
1822
                // First, we'll check our condition. If the queue of messages
6✔
1823
                // is empty, then we'll wait until a new item is added.
6✔
1824
                ms.msgCond.L.Lock()
6✔
1825
                for len(ms.msgs) == 0 {
12✔
1826
                        ms.msgCond.Wait()
6✔
1827

6✔
1828
                        // If we woke up in order to exit, then we'll do so.
6✔
1829
                        // Otherwise, we'll check the message queue for any new
6✔
1830
                        // items.
6✔
1831
                        select {
6✔
1832
                        case <-ms.peer.cg.Done():
3✔
1833
                                ms.msgCond.L.Unlock()
3✔
1834
                                return
3✔
1835
                        case <-ms.quit:
3✔
1836
                                ms.msgCond.L.Unlock()
3✔
1837
                                return
3✔
1838
                        default:
3✔
1839
                        }
1840
                }
1841

1842
                // Grab the message off the front of the queue, shifting the
1843
                // slice's reference down one in order to remove the message
1844
                // from the queue.
1845
                msg := ms.msgs[0]
3✔
1846
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
3✔
1847
                ms.msgs = ms.msgs[1:]
3✔
1848

3✔
1849
                ms.msgCond.L.Unlock()
3✔
1850

3✔
1851
                ms.apply(msg)
3✔
1852

3✔
1853
                // We've just successfully processed an item, so we'll signal
3✔
1854
                // to the producer that a new slot in the buffer. We'll use
3✔
1855
                // this to bound the size of the buffer to avoid allowing it to
3✔
1856
                // grow indefinitely.
3✔
1857
                select {
3✔
1858
                case ms.producerSema <- struct{}{}:
3✔
1859
                case <-ms.peer.cg.Done():
3✔
1860
                        return
3✔
1861
                case <-ms.quit:
2✔
1862
                        return
2✔
1863
                }
1864
        }
1865
}
1866

1867
// AddMsg adds a new message to the msgStream. This function is safe for
1868
// concurrent access.
1869
func (ms *msgStream) AddMsg(msg lnwire.Message) {
3✔
1870
        // First, we'll attempt to receive from the producerSema struct. This
3✔
1871
        // acts as a semaphore to prevent us from indefinitely buffering
3✔
1872
        // incoming items from the wire. Either the msg queue isn't full, and
3✔
1873
        // we'll not block, or the queue is full, and we'll block until either
3✔
1874
        // we're signalled to quit, or a slot is freed up.
3✔
1875
        select {
3✔
1876
        case <-ms.producerSema:
3✔
1877
        case <-ms.peer.cg.Done():
×
1878
                return
×
1879
        case <-ms.quit:
×
1880
                return
×
1881
        }
1882

1883
        // Next, we'll lock the condition, and add the message to the end of
1884
        // the message queue.
1885
        ms.msgCond.L.Lock()
3✔
1886
        ms.msgs = append(ms.msgs, msg)
3✔
1887
        ms.msgCond.L.Unlock()
3✔
1888

3✔
1889
        // With the message added, we signal to the msgConsumer that there are
3✔
1890
        // additional messages to consume.
3✔
1891
        ms.msgCond.Signal()
3✔
1892
}
1893

1894
// waitUntilLinkActive waits until the target link is active and returns a
1895
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1896
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1897
func waitUntilLinkActive(p *Brontide,
1898
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
3✔
1899

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

3✔
1902
        // Subscribe to receive channel events.
3✔
1903
        //
3✔
1904
        // NOTE: If the link is already active by SubscribeChannelEvents, then
3✔
1905
        // GetLink will retrieve the link and we can send messages. If the link
3✔
1906
        // becomes active between SubscribeChannelEvents and GetLink, then GetLink
3✔
1907
        // will retrieve the link. If the link becomes active after GetLink, then
3✔
1908
        // we will get an ActiveLinkEvent notification and retrieve the link. If
3✔
1909
        // the call to GetLink is before SubscribeChannelEvents, however, there
3✔
1910
        // will be a race condition.
3✔
1911
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
3✔
1912
        if err != nil {
6✔
1913
                // If we have a non-nil error, then the server is shutting down and we
3✔
1914
                // can exit here and return nil. This means no message will be delivered
3✔
1915
                // to the link.
3✔
1916
                return nil
3✔
1917
        }
3✔
1918
        defer sub.Cancel()
3✔
1919

3✔
1920
        // The link may already be active by this point, and we may have missed the
3✔
1921
        // ActiveLinkEvent. Check if the link exists.
3✔
1922
        link := p.fetchLinkFromKeyAndCid(cid)
3✔
1923
        if link != nil {
6✔
1924
                return link
3✔
1925
        }
3✔
1926

1927
        // If the link is nil, we must wait for it to be active.
1928
        for {
6✔
1929
                select {
3✔
1930
                // A new event has been sent by the ChannelNotifier. We first check
1931
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1932
                // that the event is for this channel. Otherwise, we discard the
1933
                // message.
1934
                case e := <-sub.Updates():
3✔
1935
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
3✔
1936
                        if !ok {
6✔
1937
                                // Ignore this notification.
3✔
1938
                                continue
3✔
1939
                        }
1940

1941
                        chanPoint := event.ChannelPoint
3✔
1942

3✔
1943
                        // Check whether the retrieved chanPoint matches the target
3✔
1944
                        // channel id.
3✔
1945
                        if !cid.IsChanPoint(chanPoint) {
3✔
1946
                                continue
×
1947
                        }
1948

1949
                        // The link shouldn't be nil as we received an
1950
                        // ActiveLinkEvent. If it is nil, we return nil and the
1951
                        // calling function should catch it.
1952
                        return p.fetchLinkFromKeyAndCid(cid)
3✔
1953

1954
                case <-p.cg.Done():
3✔
1955
                        return nil
3✔
1956
                }
1957
        }
1958
}
1959

1960
// newChanMsgStream is used to create a msgStream between the peer and
1961
// particular channel link in the htlcswitch. We utilize additional
1962
// synchronization with the fundingManager to ensure we don't attempt to
1963
// dispatch a message to a channel before it is fully active. A reference to the
1964
// channel this stream forwards to is held in scope to prevent unnecessary
1965
// lookups.
1966
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
3✔
1967
        var chanLink htlcswitch.ChannelUpdateHandler
3✔
1968

3✔
1969
        apply := func(msg lnwire.Message) {
6✔
1970
                // This check is fine because if the link no longer exists, it will
3✔
1971
                // be removed from the activeChannels map and subsequent messages
3✔
1972
                // shouldn't reach the chan msg stream.
3✔
1973
                if chanLink == nil {
6✔
1974
                        chanLink = waitUntilLinkActive(p, cid)
3✔
1975

3✔
1976
                        // If the link is still not active and the calling function
3✔
1977
                        // errored out, just return.
3✔
1978
                        if chanLink == nil {
6✔
1979
                                p.log.Warnf("Link=%v is not active", cid)
3✔
1980
                                return
3✔
1981
                        }
3✔
1982
                }
1983

1984
                // In order to avoid unnecessarily delivering message
1985
                // as the peer is exiting, we'll check quickly to see
1986
                // if we need to exit.
1987
                select {
3✔
1988
                case <-p.cg.Done():
×
1989
                        return
×
1990
                default:
3✔
1991
                }
1992

1993
                chanLink.HandleChannelUpdate(msg)
3✔
1994
        }
1995

1996
        return newMsgStream(p,
3✔
1997
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
3✔
1998
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
3✔
1999
                msgStreamSize,
3✔
2000
                apply,
3✔
2001
        )
3✔
2002
}
2003

2004
// newDiscMsgStream is used to setup a msgStream between the peer and the
2005
// authenticated gossiper. This stream should be used to forward all remote
2006
// channel announcements.
2007
func newDiscMsgStream(p *Brontide) *msgStream {
6✔
2008
        apply := func(msg lnwire.Message) {
9✔
2009
                // TODO(elle): thread contexts through the peer system properly
3✔
2010
                // so that a parent context can be passed in here.
3✔
2011
                ctx := context.TODO()
3✔
2012

3✔
2013
                // Processing here means we send it to the gossiper which then
3✔
2014
                // decides whether this message is processed immediately or
3✔
2015
                // waits for dependent messages to be processed. It can also
3✔
2016
                // happen that the message is not processed at all if it is
3✔
2017
                // premature and the LRU cache fills up and the message is
3✔
2018
                // deleted.
3✔
2019
                p.log.Debugf("Processing remote msg %T", msg)
3✔
2020

3✔
2021
                // TODO(ziggie): ProcessRemoteAnnouncement returns an error
3✔
2022
                // channel, but we cannot rely on it being written to.
3✔
2023
                // Because some messages might never be processed (e.g.
3✔
2024
                // premature channel updates). We should change the design here
3✔
2025
                // and use the actor model pattern as soon as it is available.
3✔
2026
                // So for now we should NOT use the error channel.
3✔
2027
                // See https://github.com/lightningnetwork/lnd/pull/9820.
3✔
2028
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(ctx, msg, p)
3✔
2029
        }
3✔
2030

2031
        return newMsgStream(
6✔
2032
                p,
6✔
2033
                "Update stream for gossiper created",
6✔
2034
                "Update stream for gossiper exited",
6✔
2035
                msgStreamSize,
6✔
2036
                apply,
6✔
2037
        )
6✔
2038
}
2039

2040
// readHandler is responsible for reading messages off the wire in series, then
2041
// properly dispatching the handling of the message to the proper subsystem.
2042
//
2043
// NOTE: This method MUST be run as a goroutine.
2044
func (p *Brontide) readHandler() {
6✔
2045
        defer p.cg.WgDone()
6✔
2046

6✔
2047
        // We'll stop the timer after a new messages is received, and also
6✔
2048
        // reset it after we process the next message.
6✔
2049
        idleTimer := time.AfterFunc(idleTimeout, func() {
6✔
2050
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
2051
                        p, idleTimeout)
×
2052
                p.Disconnect(err)
×
2053
        })
×
2054

2055
        // Initialize our negotiated gossip sync method before reading messages
2056
        // off the wire. When using gossip queries, this ensures a gossip
2057
        // syncer is active by the time query messages arrive.
2058
        //
2059
        // TODO(conner): have peer store gossip syncer directly and bypass
2060
        // gossiper?
2061
        p.initGossipSync()
6✔
2062

6✔
2063
        discStream := newDiscMsgStream(p)
6✔
2064
        discStream.Start()
6✔
2065
        defer discStream.Stop()
6✔
2066
out:
6✔
2067
        for atomic.LoadInt32(&p.disconnect) == 0 {
13✔
2068
                nextMsg, err := p.readNextMessage()
7✔
2069
                if !idleTimer.Stop() {
10✔
2070
                        select {
3✔
2071
                        case <-idleTimer.C:
×
2072
                        default:
3✔
2073
                        }
2074
                }
2075
                if err != nil {
7✔
2076
                        p.log.Infof("unable to read message from peer: %v", err)
3✔
2077

3✔
2078
                        // If we could not read our peer's message due to an
3✔
2079
                        // unknown type or invalid alias, we continue processing
3✔
2080
                        // as normal. We store unknown message and address
3✔
2081
                        // types, as they may provide debugging insight.
3✔
2082
                        switch e := err.(type) {
3✔
2083
                        // If this is just a message we don't yet recognize,
2084
                        // we'll continue processing as normal as this allows
2085
                        // us to introduce new messages in a forwards
2086
                        // compatible manner.
2087
                        case *lnwire.UnknownMessage:
3✔
2088
                                p.storeError(e)
3✔
2089
                                idleTimer.Reset(idleTimeout)
3✔
2090
                                continue
3✔
2091

2092
                        // If they sent us an address type that we don't yet
2093
                        // know of, then this isn't a wire error, so we'll
2094
                        // simply continue parsing the remainder of their
2095
                        // messages.
2096
                        case *lnwire.ErrUnknownAddrType:
×
2097
                                p.storeError(e)
×
2098
                                idleTimer.Reset(idleTimeout)
×
2099
                                continue
×
2100

2101
                        // If the NodeAnnouncement has an invalid alias, then
2102
                        // we'll log that error above and continue so we can
2103
                        // continue to read messages from the peer. We do not
2104
                        // store this error because it is of little debugging
2105
                        // value.
2106
                        case *lnwire.ErrInvalidNodeAlias:
×
2107
                                idleTimer.Reset(idleTimeout)
×
2108
                                continue
×
2109

2110
                        // If the error we encountered wasn't just a message we
2111
                        // didn't recognize, then we'll stop all processing as
2112
                        // this is a fatal error.
2113
                        default:
3✔
2114
                                break out
3✔
2115
                        }
2116
                }
2117

2118
                // If a message router is active, then we'll try to have it
2119
                // handle this message. If it can, then we're able to skip the
2120
                // rest of the message handling logic.
2121
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
8✔
2122
                        return r.RouteMsg(msgmux.PeerMsg{
4✔
2123
                                PeerPub: *p.IdentityKey(),
4✔
2124
                                Message: nextMsg,
4✔
2125
                        })
4✔
2126
                })
4✔
2127

2128
                // No error occurred, and the message was handled by the
2129
                // router.
2130
                if err == nil {
7✔
2131
                        continue
3✔
2132
                }
2133

2134
                var (
4✔
2135
                        targetChan   lnwire.ChannelID
4✔
2136
                        isLinkUpdate bool
4✔
2137
                )
4✔
2138

4✔
2139
                switch msg := nextMsg.(type) {
4✔
2140
                case *lnwire.Pong:
×
2141
                        // When we receive a Pong message in response to our
×
2142
                        // last ping message, we send it to the pingManager
×
2143
                        p.pingManager.ReceivedPong(msg)
×
2144

2145
                case *lnwire.Ping:
×
2146
                        // First, we'll store their latest ping payload within
×
2147
                        // the relevant atomic variable.
×
2148
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
2149

×
2150
                        // Next, we'll send over the amount of specified pong
×
2151
                        // bytes.
×
2152
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
×
2153
                        p.queueMsg(pong, nil)
×
2154

2155
                case *lnwire.OpenChannel,
2156
                        *lnwire.AcceptChannel,
2157
                        *lnwire.FundingCreated,
2158
                        *lnwire.FundingSigned,
2159
                        *lnwire.ChannelReady:
3✔
2160

3✔
2161
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2162

2163
                case *lnwire.Shutdown:
3✔
2164
                        select {
3✔
2165
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
2166
                        case <-p.cg.Done():
×
2167
                                break out
×
2168
                        }
2169
                case *lnwire.ClosingSigned:
3✔
2170
                        select {
3✔
2171
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
2172
                        case <-p.cg.Done():
×
2173
                                break out
×
2174
                        }
2175

2176
                case *lnwire.Warning:
×
2177
                        targetChan = msg.ChanID
×
2178
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2179

2180
                case *lnwire.Error:
3✔
2181
                        targetChan = msg.ChanID
3✔
2182
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
3✔
2183

2184
                case *lnwire.ChannelReestablish:
3✔
2185
                        targetChan = msg.ChanID
3✔
2186
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2187

3✔
2188
                        // If we failed to find the link in question, and the
3✔
2189
                        // message received was a channel sync message, then
3✔
2190
                        // this might be a peer trying to resync closed channel.
3✔
2191
                        // In this case we'll try to resend our last channel
3✔
2192
                        // sync message, such that the peer can recover funds
3✔
2193
                        // from the closed channel.
3✔
2194
                        if !isLinkUpdate {
6✔
2195
                                err := p.resendChanSyncMsg(targetChan)
3✔
2196
                                if err != nil {
6✔
2197
                                        // TODO(halseth): send error to peer?
3✔
2198
                                        p.log.Errorf("resend failed: %v",
3✔
2199
                                                err)
3✔
2200
                                }
3✔
2201
                        }
2202

2203
                // For messages that implement the LinkUpdater interface, we
2204
                // will consider them as link updates and send them to
2205
                // chanStream. These messages will be queued inside chanStream
2206
                // if the channel is not active yet.
2207
                case lnwire.LinkUpdater:
3✔
2208
                        targetChan = msg.TargetChanID()
3✔
2209
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2210

3✔
2211
                        // Log an error if we don't have this channel. This
3✔
2212
                        // means the peer has sent us a message with unknown
3✔
2213
                        // channel ID.
3✔
2214
                        if !isLinkUpdate {
6✔
2215
                                p.log.Errorf("Unknown channel ID: %v found "+
3✔
2216
                                        "in received msg=%s", targetChan,
3✔
2217
                                        nextMsg.MsgType())
3✔
2218
                        }
3✔
2219

2220
                case *lnwire.ChannelUpdate1,
2221
                        *lnwire.ChannelAnnouncement1,
2222
                        *lnwire.NodeAnnouncement,
2223
                        *lnwire.AnnounceSignatures1,
2224
                        *lnwire.GossipTimestampRange,
2225
                        *lnwire.QueryShortChanIDs,
2226
                        *lnwire.QueryChannelRange,
2227
                        *lnwire.ReplyChannelRange,
2228
                        *lnwire.ReplyShortChanIDsEnd:
3✔
2229

3✔
2230
                        discStream.AddMsg(msg)
3✔
2231

2232
                case *lnwire.Custom:
4✔
2233
                        err := p.handleCustomMessage(msg)
4✔
2234
                        if err != nil {
4✔
2235
                                p.storeError(err)
×
2236
                                p.log.Errorf("%v", err)
×
2237
                        }
×
2238

2239
                default:
×
2240
                        // If the message we received is unknown to us, store
×
2241
                        // the type to track the failure.
×
2242
                        err := fmt.Errorf("unknown message type %v received",
×
2243
                                uint16(msg.MsgType()))
×
2244
                        p.storeError(err)
×
2245

×
2246
                        p.log.Errorf("%v", err)
×
2247
                }
2248

2249
                if isLinkUpdate {
7✔
2250
                        // If this is a channel update, then we need to feed it
3✔
2251
                        // into the channel's in-order message stream.
3✔
2252
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
3✔
2253
                }
3✔
2254

2255
                idleTimer.Reset(idleTimeout)
4✔
2256
        }
2257

2258
        p.Disconnect(errors.New("read handler closed"))
3✔
2259

3✔
2260
        p.log.Trace("readHandler for peer done")
3✔
2261
}
2262

2263
// handleCustomMessage handles the given custom message if a handler is
2264
// registered.
2265
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
4✔
2266
        if p.cfg.HandleCustomMessage == nil {
4✔
2267
                return fmt.Errorf("no custom message handler for "+
×
2268
                        "message type %v", uint16(msg.MsgType()))
×
2269
        }
×
2270

2271
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
4✔
2272
}
2273

2274
// isLoadedFromDisk returns true if the provided channel ID is loaded from
2275
// disk.
2276
//
2277
// NOTE: only returns true for pending channels.
2278
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
3✔
2279
        // If this is a newly added channel, no need to reestablish.
3✔
2280
        _, added := p.addedChannels.Load(chanID)
3✔
2281
        if added {
6✔
2282
                return false
3✔
2283
        }
3✔
2284

2285
        // Return false if the channel is unknown.
2286
        channel, ok := p.activeChannels.Load(chanID)
3✔
2287
        if !ok {
3✔
2288
                return false
×
2289
        }
×
2290

2291
        // During startup, we will use a nil value to mark a pending channel
2292
        // that's loaded from disk.
2293
        return channel == nil
3✔
2294
}
2295

2296
// isActiveChannel returns true if the provided channel id is active, otherwise
2297
// returns false.
2298
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
11✔
2299
        // The channel would be nil if,
11✔
2300
        // - the channel doesn't exist, or,
11✔
2301
        // - the channel exists, but is pending. In this case, we don't
11✔
2302
        //   consider this channel active.
11✔
2303
        channel, _ := p.activeChannels.Load(chanID)
11✔
2304

11✔
2305
        return channel != nil
11✔
2306
}
11✔
2307

2308
// isPendingChannel returns true if the provided channel ID is pending, and
2309
// returns false if the channel is active or unknown.
2310
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
9✔
2311
        // Return false if the channel is unknown.
9✔
2312
        channel, ok := p.activeChannels.Load(chanID)
9✔
2313
        if !ok {
15✔
2314
                return false
6✔
2315
        }
6✔
2316

2317
        return channel == nil
6✔
2318
}
2319

2320
// hasChannel returns true if the peer has a pending/active channel specified
2321
// by the channel ID.
2322
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
3✔
2323
        _, ok := p.activeChannels.Load(chanID)
3✔
2324
        return ok
3✔
2325
}
3✔
2326

2327
// storeError stores an error in our peer's buffer of recent errors with the
2328
// current timestamp. Errors are only stored if we have at least one active
2329
// channel with the peer to mitigate a dos vector where a peer costlessly
2330
// connects to us and spams us with errors.
2331
func (p *Brontide) storeError(err error) {
3✔
2332
        var haveChannels bool
3✔
2333

3✔
2334
        p.activeChannels.Range(func(_ lnwire.ChannelID,
3✔
2335
                channel *lnwallet.LightningChannel) bool {
6✔
2336

3✔
2337
                // Pending channels will be nil in the activeChannels map.
3✔
2338
                if channel == nil {
6✔
2339
                        // Return true to continue the iteration.
3✔
2340
                        return true
3✔
2341
                }
3✔
2342

2343
                haveChannels = true
3✔
2344

3✔
2345
                // Return false to break the iteration.
3✔
2346
                return false
3✔
2347
        })
2348

2349
        // If we do not have any active channels with the peer, we do not store
2350
        // errors as a dos mitigation.
2351
        if !haveChannels {
6✔
2352
                p.log.Trace("no channels with peer, not storing err")
3✔
2353
                return
3✔
2354
        }
3✔
2355

2356
        p.cfg.ErrorBuffer.Add(
3✔
2357
                &TimestampedError{Timestamp: time.Now(), Error: err},
3✔
2358
        )
3✔
2359
}
2360

2361
// handleWarningOrError processes a warning or error msg and returns true if
2362
// msg should be forwarded to the associated channel link. False is returned if
2363
// any necessary forwarding of msg was already handled by this method. If msg is
2364
// an error from a peer with an active channel, we'll store it in memory.
2365
//
2366
// NOTE: This method should only be called from within the readHandler.
2367
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
2368
        msg lnwire.Message) bool {
3✔
2369

3✔
2370
        if errMsg, ok := msg.(*lnwire.Error); ok {
6✔
2371
                p.storeError(errMsg)
3✔
2372
        }
3✔
2373

2374
        switch {
3✔
2375
        // Connection wide messages should be forwarded to all channel links
2376
        // with this peer.
2377
        case chanID == lnwire.ConnectionWideID:
×
2378
                for _, chanStream := range p.activeMsgStreams {
×
2379
                        chanStream.AddMsg(msg)
×
2380
                }
×
2381

2382
                return false
×
2383

2384
        // If the channel ID for the message corresponds to a pending channel,
2385
        // then the funding manager will handle it.
2386
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
3✔
2387
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2388
                return false
3✔
2389

2390
        // If not we hand the message to the channel link for this channel.
2391
        case p.isActiveChannel(chanID):
3✔
2392
                return true
3✔
2393

2394
        default:
3✔
2395
                return false
3✔
2396
        }
2397
}
2398

2399
// messageSummary returns a human-readable string that summarizes a
2400
// incoming/outgoing message. Not all messages will have a summary, only those
2401
// which have additional data that can be informative at a glance.
2402
func messageSummary(msg lnwire.Message) string {
3✔
2403
        switch msg := msg.(type) {
3✔
2404
        case *lnwire.Init:
3✔
2405
                // No summary.
3✔
2406
                return ""
3✔
2407

2408
        case *lnwire.OpenChannel:
3✔
2409
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
3✔
2410
                        "push_amt=%v, reserve=%v, flags=%v",
3✔
2411
                        msg.PendingChannelID[:], msg.ChainHash,
3✔
2412
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
3✔
2413
                        msg.ChannelReserve, msg.ChannelFlags)
3✔
2414

2415
        case *lnwire.AcceptChannel:
3✔
2416
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
3✔
2417
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
3✔
2418
                        msg.MinAcceptDepth)
3✔
2419

2420
        case *lnwire.FundingCreated:
3✔
2421
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
3✔
2422
                        msg.PendingChannelID[:], msg.FundingPoint)
3✔
2423

2424
        case *lnwire.FundingSigned:
3✔
2425
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
3✔
2426

2427
        case *lnwire.ChannelReady:
3✔
2428
                return fmt.Sprintf("chan_id=%v, next_point=%x",
3✔
2429
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
3✔
2430

2431
        case *lnwire.Shutdown:
3✔
2432
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
3✔
2433
                        msg.Address[:])
3✔
2434

2435
        case *lnwire.ClosingComplete:
3✔
2436
                return fmt.Sprintf("chan_id=%v, fee_sat=%v, locktime=%v",
3✔
2437
                        msg.ChannelID, msg.FeeSatoshis, msg.LockTime)
3✔
2438

2439
        case *lnwire.ClosingSig:
3✔
2440
                return fmt.Sprintf("chan_id=%v", msg.ChannelID)
3✔
2441

2442
        case *lnwire.ClosingSigned:
3✔
2443
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
3✔
2444
                        msg.FeeSatoshis)
3✔
2445

2446
        case *lnwire.UpdateAddHTLC:
3✔
2447
                var blindingPoint []byte
3✔
2448
                msg.BlindingPoint.WhenSome(
3✔
2449
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
3✔
2450
                                *btcec.PublicKey]) {
6✔
2451

3✔
2452
                                blindingPoint = b.Val.SerializeCompressed()
3✔
2453
                        },
3✔
2454
                )
2455

2456
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
3✔
2457
                        "hash=%x, blinding_point=%x, custom_records=%v",
3✔
2458
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
3✔
2459
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
3✔
2460

2461
        case *lnwire.UpdateFailHTLC:
3✔
2462
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
3✔
2463
                        msg.ID, msg.Reason)
3✔
2464

2465
        case *lnwire.UpdateFulfillHTLC:
3✔
2466
                return fmt.Sprintf("chan_id=%v, id=%v, preimage=%x, "+
3✔
2467
                        "custom_records=%v", msg.ChanID, msg.ID,
3✔
2468
                        msg.PaymentPreimage[:], msg.CustomRecords)
3✔
2469

2470
        case *lnwire.CommitSig:
3✔
2471
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
3✔
2472
                        len(msg.HtlcSigs))
3✔
2473

2474
        case *lnwire.RevokeAndAck:
3✔
2475
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
3✔
2476
                        msg.ChanID, msg.Revocation[:],
3✔
2477
                        msg.NextRevocationKey.SerializeCompressed())
3✔
2478

2479
        case *lnwire.UpdateFailMalformedHTLC:
3✔
2480
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
3✔
2481
                        msg.ChanID, msg.ID, msg.FailureCode)
3✔
2482

2483
        case *lnwire.Warning:
×
2484
                return fmt.Sprintf("%v", msg.Warning())
×
2485

2486
        case *lnwire.Error:
3✔
2487
                return fmt.Sprintf("%v", msg.Error())
3✔
2488

2489
        case *lnwire.AnnounceSignatures1:
3✔
2490
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
3✔
2491
                        msg.ShortChannelID.ToUint64())
3✔
2492

2493
        case *lnwire.ChannelAnnouncement1:
3✔
2494
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
3✔
2495
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
3✔
2496

2497
        case *lnwire.ChannelUpdate1:
3✔
2498
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
3✔
2499
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
3✔
2500
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
3✔
2501
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
3✔
2502

2503
        case *lnwire.NodeAnnouncement:
3✔
2504
                return fmt.Sprintf("node=%x, update_time=%v",
3✔
2505
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
3✔
2506

2507
        case *lnwire.Ping:
×
2508
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
2509

2510
        case *lnwire.Pong:
×
2511
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
×
2512

2513
        case *lnwire.UpdateFee:
×
2514
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2515
                        msg.ChanID, int64(msg.FeePerKw))
×
2516

2517
        case *lnwire.ChannelReestablish:
3✔
2518
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
3✔
2519
                        "remote_tail_height=%v", msg.ChanID,
3✔
2520
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
3✔
2521

2522
        case *lnwire.ReplyShortChanIDsEnd:
3✔
2523
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
3✔
2524
                        msg.Complete)
3✔
2525

2526
        case *lnwire.ReplyChannelRange:
3✔
2527
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
3✔
2528
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
3✔
2529
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
3✔
2530
                        msg.EncodingType)
3✔
2531

2532
        case *lnwire.QueryShortChanIDs:
3✔
2533
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
3✔
2534
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
3✔
2535

2536
        case *lnwire.QueryChannelRange:
3✔
2537
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
3✔
2538
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
3✔
2539
                        msg.LastBlockHeight())
3✔
2540

2541
        case *lnwire.GossipTimestampRange:
3✔
2542
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
3✔
2543
                        "stamp_range=%v", msg.ChainHash,
3✔
2544
                        time.Unix(int64(msg.FirstTimestamp), 0),
3✔
2545
                        msg.TimestampRange)
3✔
2546

2547
        case *lnwire.Stfu:
3✔
2548
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
3✔
2549
                        msg.Initiator)
3✔
2550

2551
        case *lnwire.Custom:
3✔
2552
                return fmt.Sprintf("type=%d", msg.Type)
3✔
2553
        }
2554

2555
        return fmt.Sprintf("unknown msg type=%T", msg)
3✔
2556
}
2557

2558
// logWireMessage logs the receipt or sending of particular wire message. This
2559
// function is used rather than just logging the message in order to produce
2560
// less spammy log messages in trace mode by setting the 'Curve" parameter to
2561
// nil. Doing this avoids printing out each of the field elements in the curve
2562
// parameters for secp256k1.
2563
func (p *Brontide) logWireMessage(msg lnwire.Message, read bool) {
20✔
2564
        summaryPrefix := "Received"
20✔
2565
        if !read {
36✔
2566
                summaryPrefix = "Sending"
16✔
2567
        }
16✔
2568

2569
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
23✔
2570
                // Debug summary of message.
3✔
2571
                summary := messageSummary(msg)
3✔
2572
                if len(summary) > 0 {
6✔
2573
                        summary = "(" + summary + ")"
3✔
2574
                }
3✔
2575

2576
                preposition := "to"
3✔
2577
                if read {
6✔
2578
                        preposition = "from"
3✔
2579
                }
3✔
2580

2581
                var msgType string
3✔
2582
                if msg.MsgType() < lnwire.CustomTypeStart {
6✔
2583
                        msgType = msg.MsgType().String()
3✔
2584
                } else {
6✔
2585
                        msgType = "custom"
3✔
2586
                }
3✔
2587

2588
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
3✔
2589
                        msgType, summary, preposition, p)
3✔
2590
        }))
2591

2592
        prefix := "readMessage from peer"
20✔
2593
        if !read {
36✔
2594
                prefix = "writeMessage to peer"
16✔
2595
        }
16✔
2596

2597
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
20✔
2598
}
2599

2600
// writeMessage writes and flushes the target lnwire.Message to the remote peer.
2601
// If the passed message is nil, this method will only try to flush an existing
2602
// message buffered on the connection. It is safe to call this method again
2603
// with a nil message iff a timeout error is returned. This will continue to
2604
// flush the pending message to the wire.
2605
//
2606
// NOTE:
2607
// Besides its usage in Start, this function should not be used elsewhere
2608
// except in writeHandler. If multiple goroutines call writeMessage at the same
2609
// time, panics can occur because WriteMessage and Flush don't use any locking
2610
// internally.
2611
func (p *Brontide) writeMessage(msg lnwire.Message) error {
16✔
2612
        // Only log the message on the first attempt.
16✔
2613
        if msg != nil {
32✔
2614
                p.logWireMessage(msg, false)
16✔
2615
        }
16✔
2616

2617
        noiseConn := p.cfg.Conn
16✔
2618

16✔
2619
        flushMsg := func() error {
32✔
2620
                // Ensure the write deadline is set before we attempt to send
16✔
2621
                // the message.
16✔
2622
                writeDeadline := time.Now().Add(
16✔
2623
                        p.scaleTimeout(writeMessageTimeout),
16✔
2624
                )
16✔
2625
                err := noiseConn.SetWriteDeadline(writeDeadline)
16✔
2626
                if err != nil {
16✔
2627
                        return err
×
2628
                }
×
2629

2630
                // Flush the pending message to the wire. If an error is
2631
                // encountered, e.g. write timeout, the number of bytes written
2632
                // so far will be returned.
2633
                n, err := noiseConn.Flush()
16✔
2634

16✔
2635
                // Record the number of bytes written on the wire, if any.
16✔
2636
                if n > 0 {
19✔
2637
                        atomic.AddUint64(&p.bytesSent, uint64(n))
3✔
2638
                }
3✔
2639

2640
                return err
16✔
2641
        }
2642

2643
        // If the current message has already been serialized, encrypted, and
2644
        // buffered on the underlying connection we will skip straight to
2645
        // flushing it to the wire.
2646
        if msg == nil {
16✔
2647
                return flushMsg()
×
2648
        }
×
2649

2650
        // Otherwise, this is a new message. We'll acquire a write buffer to
2651
        // serialize the message and buffer the ciphertext on the connection.
2652
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
32✔
2653
                // Using a buffer allocated by the write pool, encode the
16✔
2654
                // message directly into the buffer.
16✔
2655
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
16✔
2656
                if writeErr != nil {
16✔
2657
                        return writeErr
×
2658
                }
×
2659

2660
                // Finally, write the message itself in a single swoop. This
2661
                // will buffer the ciphertext on the underlying connection. We
2662
                // will defer flushing the message until the write pool has been
2663
                // released.
2664
                return noiseConn.WriteMessage(buf.Bytes())
16✔
2665
        })
2666
        if err != nil {
16✔
2667
                return err
×
2668
        }
×
2669

2670
        return flushMsg()
16✔
2671
}
2672

2673
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2674
// queue, and writing them out to the wire. This goroutine coordinates with the
2675
// queueHandler in order to ensure the incoming message queue is quickly
2676
// drained.
2677
//
2678
// NOTE: This method MUST be run as a goroutine.
2679
func (p *Brontide) writeHandler() {
6✔
2680
        // We'll stop the timer after a new messages is sent, and also reset it
6✔
2681
        // after we process the next message.
6✔
2682
        idleTimer := time.AfterFunc(idleTimeout, func() {
6✔
2683
                err := fmt.Errorf("peer %s no write for %s -- disconnecting",
×
2684
                        p, idleTimeout)
×
2685
                p.Disconnect(err)
×
2686
        })
×
2687

2688
        var exitErr error
6✔
2689

6✔
2690
out:
6✔
2691
        for {
16✔
2692
                select {
10✔
2693
                case outMsg := <-p.sendQueue:
7✔
2694
                        // Record the time at which we first attempt to send the
7✔
2695
                        // message.
7✔
2696
                        startTime := time.Now()
7✔
2697

7✔
2698
                retry:
7✔
2699
                        // Write out the message to the socket. If a timeout
2700
                        // error is encountered, we will catch this and retry
2701
                        // after backing off in case the remote peer is just
2702
                        // slow to process messages from the wire.
2703
                        err := p.writeMessage(outMsg.msg)
7✔
2704
                        if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
7✔
2705
                                p.log.Debugf("Write timeout detected for "+
×
2706
                                        "peer, first write for message "+
×
2707
                                        "attempted %v ago",
×
2708
                                        time.Since(startTime))
×
2709

×
2710
                                // If we received a timeout error, this implies
×
2711
                                // that the message was buffered on the
×
2712
                                // connection successfully and that a flush was
×
2713
                                // attempted. We'll set the message to nil so
×
2714
                                // that on a subsequent pass we only try to
×
2715
                                // flush the buffered message, and forgo
×
2716
                                // reserializing or reencrypting it.
×
2717
                                outMsg.msg = nil
×
2718

×
2719
                                goto retry
×
2720
                        }
2721

2722
                        // The write succeeded, reset the idle timer to prevent
2723
                        // us from disconnecting the peer.
2724
                        if !idleTimer.Stop() {
7✔
2725
                                select {
×
2726
                                case <-idleTimer.C:
×
2727
                                default:
×
2728
                                }
2729
                        }
2730
                        idleTimer.Reset(idleTimeout)
7✔
2731

7✔
2732
                        // If the peer requested a synchronous write, respond
7✔
2733
                        // with the error.
7✔
2734
                        if outMsg.errChan != nil {
11✔
2735
                                outMsg.errChan <- err
4✔
2736
                        }
4✔
2737

2738
                        if err != nil {
7✔
2739
                                exitErr = fmt.Errorf("unable to write "+
×
2740
                                        "message: %v", err)
×
2741
                                break out
×
2742
                        }
2743

2744
                case <-p.cg.Done():
3✔
2745
                        exitErr = lnpeer.ErrPeerExiting
3✔
2746
                        break out
3✔
2747
                }
2748
        }
2749

2750
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2751
        // disconnect.
2752
        p.cg.WgDone()
3✔
2753

3✔
2754
        p.Disconnect(exitErr)
3✔
2755

3✔
2756
        p.log.Trace("writeHandler for peer done")
3✔
2757
}
2758

2759
// queueHandler is responsible for accepting messages from outside subsystems
2760
// to be eventually sent out on the wire by the writeHandler.
2761
//
2762
// NOTE: This method MUST be run as a goroutine.
2763
func (p *Brontide) queueHandler() {
6✔
2764
        defer p.cg.WgDone()
6✔
2765

6✔
2766
        // priorityMsgs holds an in order list of messages deemed high-priority
6✔
2767
        // to be added to the sendQueue. This predominately includes messages
6✔
2768
        // from the funding manager and htlcswitch.
6✔
2769
        priorityMsgs := list.New()
6✔
2770

6✔
2771
        // lazyMsgs holds an in order list of messages deemed low-priority to be
6✔
2772
        // added to the sendQueue only after all high-priority messages have
6✔
2773
        // been queued. This predominately includes messages from the gossiper.
6✔
2774
        lazyMsgs := list.New()
6✔
2775

6✔
2776
        for {
20✔
2777
                // Examine the front of the priority queue, if it is empty check
14✔
2778
                // the low priority queue.
14✔
2779
                elem := priorityMsgs.Front()
14✔
2780
                if elem == nil {
25✔
2781
                        elem = lazyMsgs.Front()
11✔
2782
                }
11✔
2783

2784
                if elem != nil {
21✔
2785
                        front := elem.Value.(outgoingMsg)
7✔
2786

7✔
2787
                        // There's an element on the queue, try adding
7✔
2788
                        // it to the sendQueue. We also watch for
7✔
2789
                        // messages on the outgoingQueue, in case the
7✔
2790
                        // writeHandler cannot accept messages on the
7✔
2791
                        // sendQueue.
7✔
2792
                        select {
7✔
2793
                        case p.sendQueue <- front:
7✔
2794
                                if front.priority {
13✔
2795
                                        priorityMsgs.Remove(elem)
6✔
2796
                                } else {
10✔
2797
                                        lazyMsgs.Remove(elem)
4✔
2798
                                }
4✔
2799
                        case msg := <-p.outgoingQueue:
3✔
2800
                                if msg.priority {
6✔
2801
                                        priorityMsgs.PushBack(msg)
3✔
2802
                                } else {
6✔
2803
                                        lazyMsgs.PushBack(msg)
3✔
2804
                                }
3✔
2805
                        case <-p.cg.Done():
×
2806
                                return
×
2807
                        }
2808
                } else {
10✔
2809
                        // If there weren't any messages to send to the
10✔
2810
                        // writeHandler, then we'll accept a new message
10✔
2811
                        // into the queue from outside sub-systems.
10✔
2812
                        select {
10✔
2813
                        case msg := <-p.outgoingQueue:
7✔
2814
                                if msg.priority {
13✔
2815
                                        priorityMsgs.PushBack(msg)
6✔
2816
                                } else {
10✔
2817
                                        lazyMsgs.PushBack(msg)
4✔
2818
                                }
4✔
2819
                        case <-p.cg.Done():
3✔
2820
                                return
3✔
2821
                        }
2822
                }
2823
        }
2824
}
2825

2826
// PingTime returns the estimated ping time to the peer in microseconds.
2827
func (p *Brontide) PingTime() int64 {
3✔
2828
        return p.pingManager.GetPingTimeMicroSeconds()
3✔
2829
}
3✔
2830

2831
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2832
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2833
// or failed to write, and nil otherwise.
2834
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
28✔
2835
        p.queue(true, msg, errChan)
28✔
2836
}
28✔
2837

2838
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2839
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2840
// queue or failed to write, and nil otherwise.
2841
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
4✔
2842
        p.queue(false, msg, errChan)
4✔
2843
}
4✔
2844

2845
// queue sends a given message to the queueHandler using the passed priority. If
2846
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2847
// failed to write, and nil otherwise.
2848
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2849
        errChan chan error) {
29✔
2850

29✔
2851
        select {
29✔
2852
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
28✔
2853
        case <-p.cg.Done():
×
2854
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
×
2855
                        spew.Sdump(msg))
×
2856
                if errChan != nil {
×
2857
                        errChan <- lnpeer.ErrPeerExiting
×
2858
                }
×
2859
        }
2860
}
2861

2862
// ChannelSnapshots returns a slice of channel snapshots detailing all
2863
// currently active channels maintained with the remote peer.
2864
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
3✔
2865
        snapshots := make(
3✔
2866
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
3✔
2867
        )
3✔
2868

3✔
2869
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2870
                activeChan *lnwallet.LightningChannel) error {
6✔
2871

3✔
2872
                // If the activeChan is nil, then we skip it as the channel is
3✔
2873
                // pending.
3✔
2874
                if activeChan == nil {
6✔
2875
                        return nil
3✔
2876
                }
3✔
2877

2878
                // We'll only return a snapshot for channels that are
2879
                // *immediately* available for routing payments over.
2880
                if activeChan.RemoteNextRevocation() == nil {
6✔
2881
                        return nil
3✔
2882
                }
3✔
2883

2884
                snapshot := activeChan.StateSnapshot()
3✔
2885
                snapshots = append(snapshots, snapshot)
3✔
2886

3✔
2887
                return nil
3✔
2888
        })
2889

2890
        return snapshots
3✔
2891
}
2892

2893
// genDeliveryScript returns a new script to be used to send our funds to in
2894
// the case of a cooperative channel close negotiation.
2895
func (p *Brontide) genDeliveryScript() ([]byte, error) {
9✔
2896
        // We'll send a normal p2wkh address unless we've negotiated the
9✔
2897
        // shutdown-any-segwit feature.
9✔
2898
        addrType := lnwallet.WitnessPubKey
9✔
2899
        if p.taprootShutdownAllowed() {
12✔
2900
                addrType = lnwallet.TaprootPubkey
3✔
2901
        }
3✔
2902

2903
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
9✔
2904
                addrType, false, lnwallet.DefaultAccountName,
9✔
2905
        )
9✔
2906
        if err != nil {
9✔
2907
                return nil, err
×
2908
        }
×
2909
        p.log.Infof("Delivery addr for channel close: %v",
9✔
2910
                deliveryAddr)
9✔
2911

9✔
2912
        return txscript.PayToAddrScript(deliveryAddr)
9✔
2913
}
2914

2915
// channelManager is goroutine dedicated to handling all requests/signals
2916
// pertaining to the opening, cooperative closing, and force closing of all
2917
// channels maintained with the remote peer.
2918
//
2919
// NOTE: This method MUST be run as a goroutine.
2920
func (p *Brontide) channelManager() {
20✔
2921
        defer p.cg.WgDone()
20✔
2922

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

20✔
2928
out:
20✔
2929
        for {
61✔
2930
                select {
41✔
2931
                // A new pending channel has arrived which means we are about
2932
                // to complete a funding workflow and is waiting for the final
2933
                // `ChannelReady` messages to be exchanged. We will add this
2934
                // channel to the `activeChannels` with a nil value to indicate
2935
                // this is a pending channel.
2936
                case req := <-p.newPendingChannel:
4✔
2937
                        p.handleNewPendingChannel(req)
4✔
2938

2939
                // A new channel has arrived which means we've just completed a
2940
                // funding workflow. We'll initialize the necessary local
2941
                // state, and notify the htlc switch of a new link.
2942
                case req := <-p.newActiveChannel:
3✔
2943
                        p.handleNewActiveChannel(req)
3✔
2944

2945
                // The funding flow for a pending channel is failed, we will
2946
                // remove it from Brontide.
2947
                case req := <-p.removePendingChannel:
4✔
2948
                        p.handleRemovePendingChannel(req)
4✔
2949

2950
                // We've just received a local request to close an active
2951
                // channel. It will either kick of a cooperative channel
2952
                // closure negotiation, or be a notification of a breached
2953
                // contract that should be abandoned.
2954
                case req := <-p.localCloseChanReqs:
10✔
2955
                        p.handleLocalCloseReq(req)
10✔
2956

2957
                // We've received a link failure from a link that was added to
2958
                // the switch. This will initiate the teardown of the link, and
2959
                // initiate any on-chain closures if necessary.
2960
                case failure := <-p.linkFailures:
3✔
2961
                        p.handleLinkFailure(failure)
3✔
2962

2963
                // We've received a new cooperative channel closure related
2964
                // message from the remote peer, we'll use this message to
2965
                // advance the chan closer state machine.
2966
                case closeMsg := <-p.chanCloseMsgs:
16✔
2967
                        p.handleCloseMsg(closeMsg)
16✔
2968

2969
                // The channel reannounce delay has elapsed, broadcast the
2970
                // reenabled channel updates to the network. This should only
2971
                // fire once, so we set the reenableTimeout channel to nil to
2972
                // mark it for garbage collection. If the peer is torn down
2973
                // before firing, reenabling will not be attempted.
2974
                // TODO(conner): consolidate reenables timers inside chan status
2975
                // manager
2976
                case <-reenableTimeout:
3✔
2977
                        p.reenableActiveChannels()
3✔
2978

3✔
2979
                        // Since this channel will never fire again during the
3✔
2980
                        // lifecycle of the peer, we nil the channel to mark it
3✔
2981
                        // eligible for garbage collection, and make this
3✔
2982
                        // explicitly ineligible to receive in future calls to
3✔
2983
                        // select. This also shaves a few CPU cycles since the
3✔
2984
                        // select will ignore this case entirely.
3✔
2985
                        reenableTimeout = nil
3✔
2986

3✔
2987
                        // Once the reenabling is attempted, we also cancel the
3✔
2988
                        // channel event subscription to free up the overflow
3✔
2989
                        // queue used in channel notifier.
3✔
2990
                        //
3✔
2991
                        // NOTE: channelEventClient will be nil if the
3✔
2992
                        // reenableTimeout is greater than 1 minute.
3✔
2993
                        if p.channelEventClient != nil {
6✔
2994
                                p.channelEventClient.Cancel()
3✔
2995
                        }
3✔
2996

2997
                case <-p.cg.Done():
3✔
2998
                        // As, we've been signalled to exit, we'll reset all
3✔
2999
                        // our active channel back to their default state.
3✔
3000
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
3001
                                lc *lnwallet.LightningChannel) error {
6✔
3002

3✔
3003
                                // Exit if the channel is nil as it's a pending
3✔
3004
                                // channel.
3✔
3005
                                if lc == nil {
6✔
3006
                                        return nil
3✔
3007
                                }
3✔
3008

3009
                                lc.ResetState()
3✔
3010

3✔
3011
                                return nil
3✔
3012
                        })
3013

3014
                        break out
3✔
3015
                }
3016
        }
3017
}
3018

3019
// reenableActiveChannels searches the index of channels maintained with this
3020
// peer, and reenables each public, non-pending channel. This is done at the
3021
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
3022
// No message will be sent if the channel is already enabled.
3023
func (p *Brontide) reenableActiveChannels() {
3✔
3024
        // First, filter all known channels with this peer for ones that are
3✔
3025
        // both public and not pending.
3✔
3026
        activePublicChans := p.filterChannelsToEnable()
3✔
3027

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

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

3✔
3037
                switch {
3✔
3038
                // No error occurred, continue to request the next channel.
3039
                case err == nil:
3✔
3040
                        continue
3✔
3041

3042
                // Cannot auto enable a manually disabled channel so we do
3043
                // nothing but proceed to the next channel.
3044
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
3✔
3045
                        p.log.Debugf("Channel(%v) was manually disabled, "+
3✔
3046
                                "ignoring automatic enable request", chanPoint)
3✔
3047

3✔
3048
                        continue
3✔
3049

3050
                // If the channel is reported as inactive, we will give it
3051
                // another chance. When handling the request, ChanStatusManager
3052
                // will check whether the link is active or not. One of the
3053
                // conditions is whether the link has been marked as
3054
                // reestablished, which happens inside a goroutine(htlcManager)
3055
                // after the link is started. And we may get a false negative
3056
                // saying the link is not active because that goroutine hasn't
3057
                // reached the line to mark the reestablishment. Thus we give
3058
                // it a second chance to send the request.
3059
                case errors.Is(err, netann.ErrEnableInactiveChan):
×
3060
                        // If we don't have a client created, it means we
×
3061
                        // shouldn't retry enabling the channel.
×
3062
                        if p.channelEventClient == nil {
×
3063
                                p.log.Errorf("Channel(%v) request enabling "+
×
3064
                                        "failed due to inactive link",
×
3065
                                        chanPoint)
×
3066

×
3067
                                continue
×
3068
                        }
3069

3070
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
3071
                                "ChanStatusManager reported inactive, retrying")
×
3072

×
3073
                        // Add the channel to the retry map.
×
3074
                        retryChans[chanPoint] = struct{}{}
×
3075
                }
3076
        }
3077

3078
        // Retry the channels if we have any.
3079
        if len(retryChans) != 0 {
3✔
3080
                p.retryRequestEnable(retryChans)
×
3081
        }
×
3082
}
3083

3084
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
3085
// for the target channel ID. If the channel isn't active an error is returned.
3086
// Otherwise, either an existing state machine will be returned, or a new one
3087
// will be created.
3088
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
3089
        *chanCloserFsm, error) {
16✔
3090

16✔
3091
        chanCloser, found := p.activeChanCloses.Load(chanID)
16✔
3092
        if found {
29✔
3093
                // An entry will only be found if the closer has already been
13✔
3094
                // created for a non-pending channel or for a channel that had
13✔
3095
                // previously started the shutdown process but the connection
13✔
3096
                // was restarted.
13✔
3097
                return &chanCloser, nil
13✔
3098
        }
13✔
3099

3100
        // First, we'll ensure that we actually know of the target channel. If
3101
        // not, we'll ignore this message.
3102
        channel, ok := p.activeChannels.Load(chanID)
6✔
3103

6✔
3104
        // If the channel isn't in the map or the channel is nil, return
6✔
3105
        // ErrChannelNotFound as the channel is pending.
6✔
3106
        if !ok || channel == nil {
9✔
3107
                return nil, ErrChannelNotFound
3✔
3108
        }
3✔
3109

3110
        // We'll create a valid closing state machine in order to respond to
3111
        // the initiated cooperative channel closure. First, we set the
3112
        // delivery script that our funds will be paid out to. If an upfront
3113
        // shutdown script was set, we will use it. Otherwise, we get a fresh
3114
        // delivery script.
3115
        //
3116
        // TODO: Expose option to allow upfront shutdown script from watch-only
3117
        // accounts.
3118
        deliveryScript := channel.LocalUpfrontShutdownScript()
6✔
3119
        if len(deliveryScript) == 0 {
12✔
3120
                var err error
6✔
3121
                deliveryScript, err = p.genDeliveryScript()
6✔
3122
                if err != nil {
6✔
3123
                        p.log.Errorf("unable to gen delivery script: %v",
×
3124
                                err)
×
3125
                        return nil, fmt.Errorf("close addr unavailable")
×
3126
                }
×
3127
        }
3128

3129
        // In order to begin fee negotiations, we'll first compute our target
3130
        // ideal fee-per-kw.
3131
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
6✔
3132
                p.cfg.CoopCloseTargetConfs,
6✔
3133
        )
6✔
3134
        if err != nil {
6✔
3135
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3136
                return nil, fmt.Errorf("unable to estimate fee")
×
3137
        }
×
3138

3139
        addr, err := p.addrWithInternalKey(deliveryScript)
6✔
3140
        if err != nil {
6✔
3141
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3142
        }
×
3143
        negotiateChanCloser, err := p.createChanCloser(
6✔
3144
                channel, addr, feePerKw, nil, lntypes.Remote,
6✔
3145
        )
6✔
3146
        if err != nil {
6✔
3147
                p.log.Errorf("unable to create chan closer: %v", err)
×
3148
                return nil, fmt.Errorf("unable to create chan closer")
×
3149
        }
×
3150

3151
        chanCloser = makeNegotiateCloser(negotiateChanCloser)
6✔
3152

6✔
3153
        p.activeChanCloses.Store(chanID, chanCloser)
6✔
3154

6✔
3155
        return &chanCloser, nil
6✔
3156
}
3157

3158
// filterChannelsToEnable filters a list of channels to be enabled upon start.
3159
// The filtered channels are active channels that's neither private nor
3160
// pending.
3161
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
3✔
3162
        var activePublicChans []wire.OutPoint
3✔
3163

3✔
3164
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
3✔
3165
                lnChan *lnwallet.LightningChannel) bool {
6✔
3166

3✔
3167
                // If the lnChan is nil, continue as this is a pending channel.
3✔
3168
                if lnChan == nil {
4✔
3169
                        return true
1✔
3170
                }
1✔
3171

3172
                dbChan := lnChan.State()
3✔
3173
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
3174
                if !isPublic || dbChan.IsPending {
3✔
3175
                        return true
×
3176
                }
×
3177

3178
                // We'll also skip any channels added during this peer's
3179
                // lifecycle since they haven't waited out the timeout. Their
3180
                // first announcement will be enabled, and the chan status
3181
                // manager will begin monitoring them passively since they exist
3182
                // in the database.
3183
                if _, ok := p.addedChannels.Load(chanID); ok {
5✔
3184
                        return true
2✔
3185
                }
2✔
3186

3187
                activePublicChans = append(
3✔
3188
                        activePublicChans, dbChan.FundingOutpoint,
3✔
3189
                )
3✔
3190

3✔
3191
                return true
3✔
3192
        })
3193

3194
        return activePublicChans
3✔
3195
}
3196

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

×
3204
        // retryEnable is a helper closure that sends an enable request and
×
3205
        // removes the channel from the map if it's matched.
×
3206
        retryEnable := func(chanPoint wire.OutPoint) error {
×
3207
                // If this is an active channel event, check whether it's in
×
3208
                // our targeted channels map.
×
3209
                _, found := activeChans[chanPoint]
×
3210

×
3211
                // If this channel is irrelevant, return nil so the loop can
×
3212
                // jump to next iteration.
×
3213
                if !found {
×
3214
                        return nil
×
3215
                }
×
3216

3217
                // Otherwise we've just received an active signal for a channel
3218
                // that's previously failed to be enabled, we send the request
3219
                // again.
3220
                //
3221
                // We only give the channel one more shot, so we delete it from
3222
                // our map first to keep it from being attempted again.
3223
                delete(activeChans, chanPoint)
×
3224

×
3225
                // Send the request.
×
3226
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3227
                if err != nil {
×
3228
                        return fmt.Errorf("request enabling channel %v "+
×
3229
                                "failed: %w", chanPoint, err)
×
3230
                }
×
3231

3232
                return nil
×
3233
        }
3234

3235
        for {
×
3236
                // If activeChans is empty, we've done processing all the
×
3237
                // channels.
×
3238
                if len(activeChans) == 0 {
×
3239
                        p.log.Debug("Finished retry enabling channels")
×
3240
                        return
×
3241
                }
×
3242

3243
                select {
×
3244
                // A new event has been sent by the ChannelNotifier. We now
3245
                // check whether it's an active or inactive channel event.
3246
                case e := <-p.channelEventClient.Updates():
×
3247
                        // If this is an active channel event, try enable the
×
3248
                        // channel then jump to the next iteration.
×
3249
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
3250
                        if ok {
×
3251
                                chanPoint := *active.ChannelPoint
×
3252

×
3253
                                // If we received an error for this particular
×
3254
                                // channel, we log an error and won't quit as
×
3255
                                // we still want to retry other channels.
×
3256
                                if err := retryEnable(chanPoint); err != nil {
×
3257
                                        p.log.Errorf("Retry failed: %v", err)
×
3258
                                }
×
3259

3260
                                continue
×
3261
                        }
3262

3263
                        // Otherwise check for inactive link event, and jump to
3264
                        // next iteration if it's not.
3265
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3266
                        if !ok {
×
3267
                                continue
×
3268
                        }
3269

3270
                        // Found an inactive link event, if this is our
3271
                        // targeted channel, remove it from our map.
3272
                        chanPoint := *inactive.ChannelPoint
×
3273
                        _, found := activeChans[chanPoint]
×
3274
                        if !found {
×
3275
                                continue
×
3276
                        }
3277

3278
                        delete(activeChans, chanPoint)
×
3279
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3280
                                "inactive link event", chanPoint)
×
3281

3282
                case <-p.cg.Done():
×
3283
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3284
                        return
×
3285
                }
3286
        }
3287
}
3288

3289
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3290
// a suitable script to close out to. This may be nil if neither script is
3291
// set. If both scripts are set, this function will error if they do not match.
3292
func chooseDeliveryScript(upfront, requested lnwire.DeliveryAddress,
3293
        genDeliveryScript func() ([]byte, error),
3294
) (lnwire.DeliveryAddress, error) {
15✔
3295

15✔
3296
        switch {
15✔
3297
        // If no script was provided, then we'll generate a new delivery script.
3298
        case len(upfront) == 0 && len(requested) == 0:
7✔
3299
                return genDeliveryScript()
7✔
3300

3301
        // If no upfront shutdown script was provided, return the user
3302
        // requested address (which may be nil).
3303
        case len(upfront) == 0:
5✔
3304
                return requested, nil
5✔
3305

3306
        // If an upfront shutdown script was provided, and the user did not
3307
        // request a custom shutdown script, return the upfront address.
3308
        case len(requested) == 0:
5✔
3309
                return upfront, nil
5✔
3310

3311
        // If both an upfront shutdown script and a custom close script were
3312
        // provided, error if the user provided shutdown script does not match
3313
        // the upfront shutdown script (because closing out to a different
3314
        // script would violate upfront shutdown).
3315
        case !bytes.Equal(upfront, requested):
2✔
3316
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
3317

3318
        // The user requested script matches the upfront shutdown script, so we
3319
        // can return it without error.
3320
        default:
2✔
3321
                return upfront, nil
2✔
3322
        }
3323
}
3324

3325
// restartCoopClose checks whether we need to restart the cooperative close
3326
// process for a given channel.
3327
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3328
        *lnwire.Shutdown, error) {
3✔
3329

3✔
3330
        isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
3331

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

3351
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
3✔
3352

3✔
3353
        var deliveryScript []byte
3✔
3354

3✔
3355
        shutdownInfo, err := c.ShutdownInfo()
3✔
3356
        switch {
3✔
3357
        // We have previously stored the delivery script that we need to use
3358
        // in the shutdown message. Re-use this script.
3359
        case err == nil:
3✔
3360
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
6✔
3361
                        deliveryScript = info.DeliveryScript.Val
3✔
3362
                })
3✔
3363

3364
        // An error other than ErrNoShutdownInfo was returned
3365
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3366
                return nil, err
×
3367

3368
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3369
                deliveryScript = c.LocalShutdownScript
×
3370
                if len(deliveryScript) == 0 {
×
3371
                        var err error
×
3372
                        deliveryScript, err = p.genDeliveryScript()
×
3373
                        if err != nil {
×
3374
                                p.log.Errorf("unable to gen delivery script: "+
×
3375
                                        "%v", err)
×
3376

×
3377
                                return nil, fmt.Errorf("close addr unavailable")
×
3378
                        }
×
3379
                }
3380
        }
3381

3382
        // If the new RBF co-op close is negotiated, then we'll init and start
3383
        // that state machine, skipping the steps for the negotiate machine
3384
        // below. We don't support this close type for taproot channels though.
3385
        if p.rbfCoopCloseAllowed() && !isTaprootChan {
6✔
3386
                _, err := p.initRbfChanCloser(lnChan)
3✔
3387
                if err != nil {
3✔
3388
                        return nil, fmt.Errorf("unable to init rbf chan "+
×
3389
                                "closer during restart: %w", err)
×
3390
                }
×
3391

3392
                shutdownDesc := fn.MapOption(
3✔
3393
                        newRestartShutdownInit,
3✔
3394
                )(shutdownInfo)
3✔
3395

3✔
3396
                err = p.startRbfChanCloser(
3✔
3397
                        fn.FlattenOption(shutdownDesc), lnChan.ChannelPoint(),
3✔
3398
                )
3✔
3399

3✔
3400
                return nil, err
3✔
3401
        }
3402

3403
        // Compute an ideal fee.
3404
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
3405
                p.cfg.CoopCloseTargetConfs,
×
3406
        )
×
3407
        if err != nil {
×
3408
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3409
                return nil, fmt.Errorf("unable to estimate fee")
×
3410
        }
×
3411

3412
        // Determine whether we or the peer are the initiator of the coop
3413
        // close attempt by looking at the channel's status.
3414
        closingParty := lntypes.Remote
×
3415
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3416
                closingParty = lntypes.Local
×
3417
        }
×
3418

3419
        addr, err := p.addrWithInternalKey(deliveryScript)
×
3420
        if err != nil {
×
3421
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3422
        }
×
3423
        chanCloser, err := p.createChanCloser(
×
3424
                lnChan, addr, feePerKw, nil, closingParty,
×
3425
        )
×
3426
        if err != nil {
×
3427
                p.log.Errorf("unable to create chan closer: %v", err)
×
3428
                return nil, fmt.Errorf("unable to create chan closer")
×
3429
        }
×
3430

3431
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
×
3432

×
3433
        // Create the Shutdown message.
×
3434
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3435
        if err != nil {
×
3436
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3437
                p.activeChanCloses.Delete(chanID)
×
3438
                return nil, err
×
3439
        }
×
3440

3441
        return shutdownMsg, nil
×
3442
}
3443

3444
// createChanCloser constructs a ChanCloser from the passed parameters and is
3445
// used to de-duplicate code.
3446
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3447
        deliveryScript *chancloser.DeliveryAddrWithKey,
3448
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3449
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
12✔
3450

12✔
3451
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
12✔
3452
        if err != nil {
12✔
3453
                p.log.Errorf("unable to obtain best block: %v", err)
×
3454
                return nil, fmt.Errorf("cannot obtain best block")
×
3455
        }
×
3456

3457
        // The req will only be set if we initiated the co-op closing flow.
3458
        var maxFee chainfee.SatPerKWeight
12✔
3459
        if req != nil {
21✔
3460
                maxFee = req.MaxFee
9✔
3461
        }
9✔
3462

3463
        chanCloser := chancloser.NewChanCloser(
12✔
3464
                chancloser.ChanCloseCfg{
12✔
3465
                        Channel:      channel,
12✔
3466
                        MusigSession: NewMusigChanCloser(channel),
12✔
3467
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
12✔
3468
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
12✔
3469
                        AuxCloser:    p.cfg.AuxChanCloser,
12✔
3470
                        DisableChannel: func(op wire.OutPoint) error {
24✔
3471
                                return p.cfg.ChanStatusMgr.RequestDisable(
12✔
3472
                                        op, false,
12✔
3473
                                )
12✔
3474
                        },
12✔
3475
                        MaxFee: maxFee,
3476
                        Disconnect: func() error {
×
3477
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
3478
                        },
×
3479
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3480
                },
3481
                *deliveryScript,
3482
                fee,
3483
                uint32(startingHeight),
3484
                req,
3485
                closer,
3486
        )
3487

3488
        return chanCloser, nil
12✔
3489
}
3490

3491
// initNegotiateChanCloser initializes the channel closer for a channel that is
3492
// using the original "negotiation" based protocol. This path is used when
3493
// we're the one initiating the channel close.
3494
//
3495
// TODO(roasbeef): can make a MsgEndpoint for existing handling logic to
3496
// further abstract.
3497
func (p *Brontide) initNegotiateChanCloser(req *htlcswitch.ChanClose,
3498
        channel *lnwallet.LightningChannel) error {
10✔
3499

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

10✔
3503
        // An upfront shutdown and user provided script are both optional, but
10✔
3504
        // must be equal if both set  (because we cannot serve a request to
10✔
3505
        // close out to a script which violates upfront shutdown). Get the
10✔
3506
        // appropriate address to close out to (which may be nil if neither are
10✔
3507
        // set) and error if they are both set and do not match.
10✔
3508
        deliveryScript, err := chooseDeliveryScript(
10✔
3509
                channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
10✔
3510
                p.genDeliveryScript,
10✔
3511
        )
10✔
3512
        if err != nil {
11✔
3513
                return fmt.Errorf("cannot close channel %v: %w",
1✔
3514
                        req.ChanPoint, err)
1✔
3515
        }
1✔
3516

3517
        addr, err := p.addrWithInternalKey(deliveryScript)
9✔
3518
        if err != nil {
9✔
3519
                return fmt.Errorf("unable to parse addr for channel "+
×
3520
                        "%v: %w", req.ChanPoint, err)
×
3521
        }
×
3522

3523
        chanCloser, err := p.createChanCloser(
9✔
3524
                channel, addr, req.TargetFeePerKw, req, lntypes.Local,
9✔
3525
        )
9✔
3526
        if err != nil {
9✔
3527
                return fmt.Errorf("unable to make chan closer: %w", err)
×
3528
        }
×
3529

3530
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
9✔
3531
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
9✔
3532

9✔
3533
        // Finally, we'll initiate the channel shutdown within the
9✔
3534
        // chanCloser, and send the shutdown message to the remote
9✔
3535
        // party to kick things off.
9✔
3536
        shutdownMsg, err := chanCloser.ShutdownChan()
9✔
3537
        if err != nil {
9✔
3538
                // As we were unable to shutdown the channel, we'll return it
×
3539
                // back to its normal state.
×
3540
                defer channel.ResetState()
×
3541

×
3542
                p.activeChanCloses.Delete(chanID)
×
3543

×
3544
                return fmt.Errorf("unable to shutdown channel: %w", err)
×
3545
        }
×
3546

3547
        link := p.fetchLinkFromKeyAndCid(chanID)
9✔
3548
        if link == nil {
9✔
3549
                // If the link is nil then it means it was already removed from
×
3550
                // the switch or it never existed in the first place. The
×
3551
                // latter case is handled at the beginning of this function, so
×
3552
                // in the case where it has already been removed, we can skip
×
3553
                // adding the commit hook to queue a Shutdown message.
×
3554
                p.log.Warnf("link not found during attempted closure: "+
×
3555
                        "%v", chanID)
×
3556
                return nil
×
3557
        }
×
3558

3559
        if !link.DisableAdds(htlcswitch.Outgoing) {
9✔
3560
                p.log.Warnf("Outgoing link adds already "+
×
3561
                        "disabled: %v", link.ChanID())
×
3562
        }
×
3563

3564
        link.OnCommitOnce(htlcswitch.Outgoing, func() {
18✔
3565
                p.queueMsg(shutdownMsg, nil)
9✔
3566
        })
9✔
3567

3568
        return nil
9✔
3569
}
3570

3571
// chooseAddr returns the provided address if it is non-zero length, otherwise
3572
// None.
3573
func chooseAddr(addr lnwire.DeliveryAddress) fn.Option[lnwire.DeliveryAddress] {
3✔
3574
        if len(addr) == 0 {
6✔
3575
                return fn.None[lnwire.DeliveryAddress]()
3✔
3576
        }
3✔
3577

3578
        return fn.Some(addr)
×
3579
}
3580

3581
// observeRbfCloseUpdates observes the channel for any updates that may
3582
// indicate that a new txid has been broadcasted, or the channel fully closed
3583
// on chain.
3584
func (p *Brontide) observeRbfCloseUpdates(chanCloser *chancloser.RbfChanCloser,
3585
        closeReq *htlcswitch.ChanClose,
3586
        coopCloseStates chancloser.RbfStateSub) {
3✔
3587

3✔
3588
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3589
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3590

3✔
3591
        var (
3✔
3592
                lastTxids    lntypes.Dual[chainhash.Hash]
3✔
3593
                lastFeeRates lntypes.Dual[chainfee.SatPerVByte]
3✔
3594
        )
3✔
3595

3✔
3596
        maybeNotifyTxBroadcast := func(state chancloser.AsymmetricPeerState,
3✔
3597
                party lntypes.ChannelParty) {
6✔
3598

3✔
3599
                // First, check to see if we have an error to report to the
3✔
3600
                // caller. If so, then we''ll return that error and exit, as the
3✔
3601
                // stream will exit as well.
3✔
3602
                if closeErr, ok := state.(*chancloser.CloseErr); ok {
6✔
3603
                        // We hit an error during the last state transition, so
3✔
3604
                        // we'll extract the error then send it to the
3✔
3605
                        // user.
3✔
3606
                        err := closeErr.Err()
3✔
3607

3✔
3608
                        peerLog.Warnf("ChannelPoint(%v): encountered close "+
3✔
3609
                                "err: %v", closeReq.ChanPoint, err)
3✔
3610

3✔
3611
                        select {
3✔
3612
                        case closeReq.Err <- err:
3✔
3613
                        case <-closeReq.Ctx.Done():
×
3614
                        case <-p.cg.Done():
×
3615
                        }
3616

3617
                        return
3✔
3618
                }
3619

3620
                closePending, ok := state.(*chancloser.ClosePending)
3✔
3621

3✔
3622
                // If this isn't the close pending state, we aren't at the
3✔
3623
                // terminal state yet.
3✔
3624
                if !ok {
6✔
3625
                        return
3✔
3626
                }
3✔
3627

3628
                // Only notify if the fee rate is greater.
3629
                newFeeRate := closePending.FeeRate
3✔
3630
                lastFeeRate := lastFeeRates.GetForParty(party)
3✔
3631
                if newFeeRate <= lastFeeRate {
6✔
3632
                        peerLog.Debugf("ChannelPoint(%v): remote party made "+
3✔
3633
                                "update for fee rate %v, but we already have "+
3✔
3634
                                "a higher fee rate of %v", closeReq.ChanPoint,
3✔
3635
                                newFeeRate, lastFeeRate)
3✔
3636

3✔
3637
                        return
3✔
3638
                }
3✔
3639

3640
                feeRate := closePending.FeeRate
3✔
3641
                lastFeeRates.SetForParty(party, feeRate)
3✔
3642

3✔
3643
                // At this point, we'll have a txid that we can use to notify
3✔
3644
                // the client, but only if it's different from the last one we
3✔
3645
                // sent. If the user attempted to bump, but was rejected due to
3✔
3646
                // RBF, then we'll send a redundant update.
3✔
3647
                closingTxid := closePending.CloseTx.TxHash()
3✔
3648
                lastTxid := lastTxids.GetForParty(party)
3✔
3649
                if closeReq != nil && closingTxid != lastTxid {
6✔
3650
                        select {
3✔
3651
                        case closeReq.Updates <- &PendingUpdate{
3652
                                Txid:        closingTxid[:],
3653
                                FeePerVbyte: fn.Some(closePending.FeeRate),
3654
                                IsLocalCloseTx: fn.Some(
3655
                                        party == lntypes.Local,
3656
                                ),
3657
                        }:
3✔
3658

3659
                        case <-closeReq.Ctx.Done():
×
3660
                                return
×
3661

3662
                        case <-p.cg.Done():
×
3663
                                return
×
3664
                        }
3665
                }
3666

3667
                lastTxids.SetForParty(party, closingTxid)
3✔
3668
        }
3669

3670
        peerLog.Infof("Observing RBF close updates for channel %v",
3✔
3671
                closeReq.ChanPoint)
3✔
3672

3✔
3673
        // We'll consume each new incoming state to send out the appropriate
3✔
3674
        // RPC update.
3✔
3675
        for {
6✔
3676
                select {
3✔
3677
                case newState := <-newStateChan:
3✔
3678

3✔
3679
                        switch closeState := newState.(type) {
3✔
3680
                        // Once we've reached the state of pending close, we
3681
                        // have a txid that we broadcasted.
3682
                        case *chancloser.ClosingNegotiation:
3✔
3683
                                peerState := closeState.PeerState
3✔
3684

3✔
3685
                                // Each side may have gained a new co-op close
3✔
3686
                                // tx, so we'll examine both to see if they've
3✔
3687
                                // changed.
3✔
3688
                                maybeNotifyTxBroadcast(
3✔
3689
                                        peerState.GetForParty(lntypes.Local),
3✔
3690
                                        lntypes.Local,
3✔
3691
                                )
3✔
3692
                                maybeNotifyTxBroadcast(
3✔
3693
                                        peerState.GetForParty(lntypes.Remote),
3✔
3694
                                        lntypes.Remote,
3✔
3695
                                )
3✔
3696

3697
                        // Otherwise, if we're transition to CloseFin, then we
3698
                        // know that we're done.
3699
                        case *chancloser.CloseFin:
3✔
3700
                                // To clean up, we'll remove the chan closer
3✔
3701
                                // from the active map, and send the final
3✔
3702
                                // update to the client.
3✔
3703
                                closingTxid := closeState.ConfirmedTx.TxHash()
3✔
3704
                                if closeReq != nil {
6✔
3705
                                        closeReq.Updates <- &ChannelCloseUpdate{
3✔
3706
                                                ClosingTxid: closingTxid[:],
3✔
3707
                                                Success:     true,
3✔
3708
                                        }
3✔
3709
                                }
3✔
3710
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
3711
                                        *closeReq.ChanPoint,
3✔
3712
                                )
3✔
3713
                                p.activeChanCloses.Delete(chanID)
3✔
3714

3✔
3715
                                return
3✔
3716
                        }
3717

3718
                case <-closeReq.Ctx.Done():
3✔
3719
                        return
3✔
3720

3721
                case <-p.cg.Done():
3✔
3722
                        return
3✔
3723
                }
3724
        }
3725
}
3726

3727
// chanErrorReporter is a simple implementation of the
3728
// chancloser.ErrorReporter. This is bound to a single channel by the channel
3729
// ID.
3730
type chanErrorReporter struct {
3731
        chanID lnwire.ChannelID
3732
        peer   *Brontide
3733
}
3734

3735
// newChanErrorReporter creates a new instance of the chanErrorReporter.
3736
func newChanErrorReporter(chanID lnwire.ChannelID,
3737
        peer *Brontide) *chanErrorReporter {
3✔
3738

3✔
3739
        return &chanErrorReporter{
3✔
3740
                chanID: chanID,
3✔
3741
                peer:   peer,
3✔
3742
        }
3✔
3743
}
3✔
3744

3745
// ReportError is a method that's used to report an error that occurred during
3746
// state machine execution. This is used by the RBF close state machine to
3747
// terminate the state machine and send an error to the remote peer.
3748
//
3749
// This is a part of the chancloser.ErrorReporter interface.
3750
func (c *chanErrorReporter) ReportError(chanErr error) {
×
3751
        c.peer.log.Errorf("coop close error for channel %v: %v",
×
3752
                c.chanID, chanErr)
×
3753

×
3754
        var errMsg []byte
×
3755
        if errors.Is(chanErr, chancloser.ErrInvalidStateTransition) {
×
3756
                errMsg = []byte("unexpected protocol message")
×
3757
        } else {
×
3758
                errMsg = []byte(chanErr.Error())
×
3759
        }
×
3760

3761
        err := c.peer.SendMessageLazy(false, &lnwire.Error{
×
3762
                ChanID: c.chanID,
×
3763
                Data:   errMsg,
×
3764
        })
×
3765
        if err != nil {
×
3766
                c.peer.log.Warnf("unable to send error message to peer: %v",
×
3767
                        err)
×
3768
        }
×
3769

3770
        // After we send the error message to the peer, we'll re-initialize the
3771
        // coop close state machine as they may send a shutdown message to
3772
        // retry the coop close.
3773
        lnChan, ok := c.peer.activeChannels.Load(c.chanID)
×
3774
        if !ok {
×
3775
                return
×
3776
        }
×
3777

3778
        if lnChan == nil {
×
3779
                c.peer.log.Debugf("channel %v is pending, not "+
×
3780
                        "re-initializing coop close state machine",
×
3781
                        c.chanID)
×
3782

×
3783
                return
×
3784
        }
×
3785

3786
        if _, err := c.peer.initRbfChanCloser(lnChan); err != nil {
×
3787
                c.peer.activeChanCloses.Delete(c.chanID)
×
3788

×
3789
                c.peer.log.Errorf("unable to init RBF chan closer after "+
×
3790
                        "error case: %v", err)
×
3791
        }
×
3792
}
3793

3794
// chanFlushEventSentinel is used to send the RBF coop close state machine the
3795
// channel flushed event. We'll wait until the state machine enters the
3796
// ChannelFlushing state, then request the link to send the event once flushed.
3797
//
3798
// NOTE: This MUST be run as a goroutine.
3799
func (p *Brontide) chanFlushEventSentinel(chanCloser *chancloser.RbfChanCloser,
3800
        link htlcswitch.ChannelUpdateHandler,
3801
        channel *lnwallet.LightningChannel) {
3✔
3802

3✔
3803
        defer p.cg.WgDone()
3✔
3804

3✔
3805
        // If there's no link, then the channel has already been flushed, so we
3✔
3806
        // don't need to continue.
3✔
3807
        if link == nil {
6✔
3808
                return
3✔
3809
        }
3✔
3810

3811
        coopCloseStates := chanCloser.RegisterStateEvents()
3✔
3812
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3813

3✔
3814
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3815

3✔
3816
        sendChanFlushed := func() {
6✔
3817
                chanState := channel.StateSnapshot()
3✔
3818

3✔
3819
                peerLog.Infof("ChannelPoint(%v) has been flushed for co-op "+
3✔
3820
                        "close, sending event to chan closer",
3✔
3821
                        channel.ChannelPoint())
3✔
3822

3✔
3823
                chanBalances := chancloser.ShutdownBalances{
3✔
3824
                        LocalBalance:  chanState.LocalBalance,
3✔
3825
                        RemoteBalance: chanState.RemoteBalance,
3✔
3826
                }
3✔
3827
                ctx := context.Background()
3✔
3828
                chanCloser.SendEvent(ctx, &chancloser.ChannelFlushed{
3✔
3829
                        ShutdownBalances: chanBalances,
3✔
3830
                        FreshFlush:       true,
3✔
3831
                })
3✔
3832
        }
3✔
3833

3834
        // We'll wait until the channel enters the ChannelFlushing state. We
3835
        // exit after a success loop. As after the first RBF iteration, the
3836
        // channel will always be flushed.
3837
        for {
6✔
3838
                select {
3✔
3839
                case newState, ok := <-newStateChan:
3✔
3840
                        if !ok {
3✔
3841
                                return
×
3842
                        }
×
3843

3844
                        if _, ok := newState.(*chancloser.ChannelFlushing); ok {
6✔
3845
                                peerLog.Infof("ChannelPoint(%v): rbf coop "+
3✔
3846
                                        "close is awaiting a flushed state, "+
3✔
3847
                                        "registering with link..., ",
3✔
3848
                                        channel.ChannelPoint())
3✔
3849

3✔
3850
                                // Request the link to send the event once the
3✔
3851
                                // channel is flushed. We only need this event
3✔
3852
                                // sent once, so we can exit now.
3✔
3853
                                link.OnFlushedOnce(sendChanFlushed)
3✔
3854

3✔
3855
                                return
3✔
3856
                        }
3✔
3857

3858
                case <-p.cg.Done():
3✔
3859
                        return
3✔
3860
                }
3861
        }
3862
}
3863

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

3✔
3870
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
3✔
3871

3✔
3872
        link := p.fetchLinkFromKeyAndCid(chanID)
3✔
3873

3✔
3874
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
3✔
3875
        if err != nil {
3✔
3876
                return nil, fmt.Errorf("cannot obtain best block: %w", err)
×
3877
        }
×
3878

3879
        defaultFeePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
3880
                p.cfg.CoopCloseTargetConfs,
3✔
3881
        )
3✔
3882
        if err != nil {
3✔
3883
                return nil, fmt.Errorf("unable to estimate fee: %w", err)
×
3884
        }
×
3885

3886
        thawHeight, err := channel.AbsoluteThawHeight()
3✔
3887
        if err != nil {
3✔
3888
                return nil, fmt.Errorf("unable to get thaw height: %w", err)
×
3889
        }
×
3890

3891
        peerPub := *p.IdentityKey()
3✔
3892

3✔
3893
        msgMapper := chancloser.NewRbfMsgMapper(
3✔
3894
                uint32(startingHeight), chanID, peerPub,
3✔
3895
        )
3✔
3896

3✔
3897
        initialState := chancloser.ChannelActive{}
3✔
3898

3✔
3899
        scid := channel.ZeroConfRealScid().UnwrapOr(
3✔
3900
                channel.ShortChanID(),
3✔
3901
        )
3✔
3902

3✔
3903
        env := chancloser.Environment{
3✔
3904
                ChainParams:    p.cfg.Wallet.Cfg.NetParams,
3✔
3905
                ChanPeer:       peerPub,
3✔
3906
                ChanPoint:      channel.ChannelPoint(),
3✔
3907
                ChanID:         chanID,
3✔
3908
                Scid:           scid,
3✔
3909
                ChanType:       channel.ChanType(),
3✔
3910
                DefaultFeeRate: defaultFeePerKw.FeePerVByte(),
3✔
3911
                ThawHeight:     fn.Some(thawHeight),
3✔
3912
                RemoteUpfrontShutdown: chooseAddr(
3✔
3913
                        channel.RemoteUpfrontShutdownScript(),
3✔
3914
                ),
3✔
3915
                LocalUpfrontShutdown: chooseAddr(
3✔
3916
                        channel.LocalUpfrontShutdownScript(),
3✔
3917
                ),
3✔
3918
                NewDeliveryScript: func() (lnwire.DeliveryAddress, error) {
6✔
3919
                        return p.genDeliveryScript()
3✔
3920
                },
3✔
3921
                FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
3922
                CloseSigner:  channel,
3923
                ChanObserver: newChanObserver(
3924
                        channel, link, p.cfg.ChanStatusMgr,
3925
                ),
3926
        }
3927

3928
        spendEvent := protofsm.RegisterSpend[chancloser.ProtocolEvent]{
3✔
3929
                OutPoint:   channel.ChannelPoint(),
3✔
3930
                PkScript:   channel.FundingTxOut().PkScript,
3✔
3931
                HeightHint: channel.DeriveHeightHint(),
3✔
3932
                PostSpendEvent: fn.Some[chancloser.RbfSpendMapper](
3✔
3933
                        chancloser.SpendMapper,
3✔
3934
                ),
3✔
3935
        }
3✔
3936

3✔
3937
        daemonAdapters := NewLndDaemonAdapters(LndAdapterCfg{
3✔
3938
                MsgSender:     newPeerMsgSender(peerPub, p),
3✔
3939
                TxBroadcaster: p.cfg.Wallet,
3✔
3940
                ChainNotifier: p.cfg.ChainNotifier,
3✔
3941
        })
3✔
3942

3✔
3943
        protoCfg := chancloser.RbfChanCloserCfg{
3✔
3944
                Daemon:        daemonAdapters,
3✔
3945
                InitialState:  &initialState,
3✔
3946
                Env:           &env,
3✔
3947
                InitEvent:     fn.Some[protofsm.DaemonEvent](&spendEvent),
3✔
3948
                ErrorReporter: newChanErrorReporter(chanID, p),
3✔
3949
                MsgMapper: fn.Some[protofsm.MsgMapper[chancloser.ProtocolEvent]]( //nolint:ll
3✔
3950
                        msgMapper,
3✔
3951
                ),
3✔
3952
        }
3✔
3953

3✔
3954
        ctx := context.Background()
3✔
3955
        chanCloser := protofsm.NewStateMachine(protoCfg)
3✔
3956
        chanCloser.Start(ctx)
3✔
3957

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

3✔
3963
                return r.RegisterEndpoint(&chanCloser)
3✔
3964
        })
3✔
3965
        if err != nil {
3✔
3966
                chanCloser.Stop()
×
3967

×
3968
                return nil, fmt.Errorf("unable to register endpoint for co-op "+
×
3969
                        "close: %w", err)
×
3970
        }
×
3971

3972
        p.activeChanCloses.Store(chanID, makeRbfCloser(&chanCloser))
3✔
3973

3✔
3974
        // Now that we've created the rbf closer state machine, we'll launch a
3✔
3975
        // new goroutine to eventually send in the ChannelFlushed event once
3✔
3976
        // needed.
3✔
3977
        p.cg.WgAdd(1)
3✔
3978
        go p.chanFlushEventSentinel(&chanCloser, link, channel)
3✔
3979

3✔
3980
        return &chanCloser, nil
3✔
3981
}
3982

3983
// shutdownInit describes the two ways we can initiate a new shutdown. Either we
3984
// got an RPC request to do so (left), or we sent a shutdown message to the
3985
// party (for w/e reason), but crashed before the close was complete.
3986
//
3987
//nolint:ll
3988
type shutdownInit = fn.Option[fn.Either[*htlcswitch.ChanClose, channeldb.ShutdownInfo]]
3989

3990
// shutdownStartFeeRate returns the fee rate that should be used for the
3991
// shutdown.  This returns a doubly wrapped option as the shutdown info might
3992
// be none, and the fee rate is only defined for the user initiated shutdown.
3993
func shutdownStartFeeRate(s shutdownInit) fn.Option[chainfee.SatPerKWeight] {
3✔
3994
        feeRateOpt := fn.MapOption(func(init fn.Either[*htlcswitch.ChanClose,
3✔
3995
                channeldb.ShutdownInfo]) fn.Option[chainfee.SatPerKWeight] {
6✔
3996

3✔
3997
                var feeRate fn.Option[chainfee.SatPerKWeight]
3✔
3998
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
6✔
3999
                        feeRate = fn.Some(req.TargetFeePerKw)
3✔
4000
                })
3✔
4001

4002
                return feeRate
3✔
4003
        })(s)
4004

4005
        return fn.FlattenOption(feeRateOpt)
3✔
4006
}
4007

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

3✔
4015
                var addr fn.Option[lnwire.DeliveryAddress]
3✔
4016
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
6✔
4017
                        if len(req.DeliveryScript) != 0 {
6✔
4018
                                addr = fn.Some(req.DeliveryScript)
3✔
4019
                        }
3✔
4020
                })
4021
                init.WhenRight(func(info channeldb.ShutdownInfo) {
6✔
4022
                        addr = fn.Some(info.DeliveryScript.Val)
3✔
4023
                })
3✔
4024

4025
                return addr
3✔
4026
        })(s)
4027

4028
        return fn.FlattenOption(addrOpt)
3✔
4029
}
4030

4031
// whenRPCShutdown registers a callback to be executed when the shutdown init
4032
// type is and RPC request.
4033
func whenRPCShutdown(s shutdownInit, f func(r *htlcswitch.ChanClose)) {
3✔
4034
        s.WhenSome(func(init fn.Either[*htlcswitch.ChanClose,
3✔
4035
                channeldb.ShutdownInfo]) {
6✔
4036

3✔
4037
                init.WhenLeft(f)
3✔
4038
        })
3✔
4039
}
4040

4041
// newRestartShutdownInit creates a new shutdownInit for the case where we need
4042
// to restart the shutdown flow after a restart.
4043
func newRestartShutdownInit(info channeldb.ShutdownInfo) shutdownInit {
3✔
4044
        return fn.Some(fn.NewRight[*htlcswitch.ChanClose](info))
3✔
4045
}
3✔
4046

4047
// newRPCShutdownInit creates a new shutdownInit for the case where we
4048
// initiated the shutdown via an RPC client.
4049
func newRPCShutdownInit(req *htlcswitch.ChanClose) shutdownInit {
3✔
4050
        return fn.Some(
3✔
4051
                fn.NewLeft[*htlcswitch.ChanClose, channeldb.ShutdownInfo](req),
3✔
4052
        )
3✔
4053
}
3✔
4054

4055
// waitUntilRbfCoastClear waits until the RBF co-op close state machine has
4056
// advanced to a terminal state before attempting another fee bump.
4057
func waitUntilRbfCoastClear(ctx context.Context,
4058
        rbfCloser *chancloser.RbfChanCloser) error {
3✔
4059

3✔
4060
        coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4061
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
4062
        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4063

3✔
4064
        isTerminalState := func(newState chancloser.RbfState) bool {
6✔
4065
                // If we're not in the negotiation sub-state, then we aren't at
3✔
4066
                // the terminal state yet.
3✔
4067
                state, ok := newState.(*chancloser.ClosingNegotiation)
3✔
4068
                if !ok {
3✔
4069
                        return false
×
4070
                }
×
4071

4072
                localState := state.PeerState.GetForParty(lntypes.Local)
3✔
4073

3✔
4074
                // If this isn't the close pending state, we aren't at the
3✔
4075
                // terminal state yet.
3✔
4076
                _, ok = localState.(*chancloser.ClosePending)
3✔
4077

3✔
4078
                return ok
3✔
4079
        }
4080

4081
        // Before we enter the subscription loop below, check to see if we're
4082
        // already in the terminal state.
4083
        rbfState, err := rbfCloser.CurrentState()
3✔
4084
        if err != nil {
3✔
4085
                return err
×
4086
        }
×
4087
        if isTerminalState(rbfState) {
6✔
4088
                return nil
3✔
4089
        }
3✔
4090

4091
        peerLog.Debugf("Waiting for RBF iteration to complete...")
×
4092

×
4093
        for {
×
4094
                select {
×
4095
                case newState := <-newStateChan:
×
4096
                        if isTerminalState(newState) {
×
4097
                                return nil
×
4098
                        }
×
4099

4100
                case <-ctx.Done():
×
4101
                        return fmt.Errorf("context canceled")
×
4102
                }
4103
        }
4104
}
4105

4106
// startRbfChanCloser kicks off the co-op close process using the new RBF based
4107
// co-op close protocol. This is called when we're the one that's initiating
4108
// the cooperative channel close.
4109
//
4110
// TODO(roasbeef): just accept the two shutdown pointer params instead??
4111
func (p *Brontide) startRbfChanCloser(shutdown shutdownInit,
4112
        chanPoint wire.OutPoint) error {
3✔
4113

3✔
4114
        // Unlike the old negotiate chan closer, we'll always create the RBF
3✔
4115
        // chan closer on startup, so we can skip init here.
3✔
4116
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4117
        chanCloser, found := p.activeChanCloses.Load(chanID)
3✔
4118
        if !found {
3✔
4119
                return fmt.Errorf("rbf chan closer not found for channel %v",
×
4120
                        chanPoint)
×
4121
        }
×
4122

4123
        defaultFeePerKw, err := shutdownStartFeeRate(
3✔
4124
                shutdown,
3✔
4125
        ).UnwrapOrFuncErr(func() (chainfee.SatPerKWeight, error) {
6✔
4126
                return p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
4127
                        p.cfg.CoopCloseTargetConfs,
3✔
4128
                )
3✔
4129
        })
3✔
4130
        if err != nil {
3✔
4131
                return fmt.Errorf("unable to estimate fee: %w", err)
×
4132
        }
×
4133

4134
        chanCloser.WhenRight(func(rbfCloser *chancloser.RbfChanCloser) {
6✔
4135
                peerLog.Infof("ChannelPoint(%v): rbf-coop close requested, "+
3✔
4136
                        "sending shutdown", chanPoint)
3✔
4137

3✔
4138
                rbfState, err := rbfCloser.CurrentState()
3✔
4139
                if err != nil {
3✔
4140
                        peerLog.Warnf("ChannelPoint(%v): unable to get "+
×
4141
                                "current state for rbf-coop close: %v",
×
4142
                                chanPoint, err)
×
4143

×
4144
                        return
×
4145
                }
×
4146

4147
                coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4148

3✔
4149
                // Before we send our event below, we'll launch a goroutine to
3✔
4150
                // watch for the final terminal state to send updates to the RPC
3✔
4151
                // client. We only need to do this if there's an RPC caller.
3✔
4152
                var rpcShutdown bool
3✔
4153
                whenRPCShutdown(shutdown, func(req *htlcswitch.ChanClose) {
6✔
4154
                        rpcShutdown = true
3✔
4155

3✔
4156
                        p.cg.WgAdd(1)
3✔
4157
                        go func() {
6✔
4158
                                defer p.cg.WgDone()
3✔
4159

3✔
4160
                                p.observeRbfCloseUpdates(
3✔
4161
                                        rbfCloser, req, coopCloseStates,
3✔
4162
                                )
3✔
4163
                        }()
3✔
4164
                })
4165

4166
                if !rpcShutdown {
6✔
4167
                        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4168
                }
3✔
4169

4170
                ctx, _ := p.cg.Create(context.Background())
3✔
4171
                feeRate := defaultFeePerKw.FeePerVByte()
3✔
4172

3✔
4173
                // Depending on the state of the state machine, we'll either
3✔
4174
                // kick things off by sending shutdown, or attempt to send a new
3✔
4175
                // offer to the remote party.
3✔
4176
                switch rbfState.(type) {
3✔
4177
                // The channel is still active, so we'll now kick off the co-op
4178
                // close process by instructing it to send a shutdown message to
4179
                // the remote party.
4180
                case *chancloser.ChannelActive:
3✔
4181
                        rbfCloser.SendEvent(
3✔
4182
                                context.Background(),
3✔
4183
                                &chancloser.SendShutdown{
3✔
4184
                                        IdealFeeRate: feeRate,
3✔
4185
                                        DeliveryAddr: shutdownStartAddr(
3✔
4186
                                                shutdown,
3✔
4187
                                        ),
3✔
4188
                                },
3✔
4189
                        )
3✔
4190

4191
                // If we haven't yet sent an offer (didn't have enough funds at
4192
                // the prior fee rate), or we've sent an offer, then we'll
4193
                // trigger a new offer event.
4194
                case *chancloser.ClosingNegotiation:
3✔
4195
                        // Before we send the event below, we'll wait until
3✔
4196
                        // we're in a semi-terminal state.
3✔
4197
                        err := waitUntilRbfCoastClear(ctx, rbfCloser)
3✔
4198
                        if err != nil {
3✔
4199
                                peerLog.Warnf("ChannelPoint(%v): unable to "+
×
4200
                                        "wait for coast to clear: %v",
×
4201
                                        chanPoint, err)
×
4202

×
4203
                                return
×
4204
                        }
×
4205

4206
                        event := chancloser.ProtocolEvent(
3✔
4207
                                &chancloser.SendOfferEvent{
3✔
4208
                                        TargetFeeRate: feeRate,
3✔
4209
                                },
3✔
4210
                        )
3✔
4211
                        rbfCloser.SendEvent(ctx, event)
3✔
4212

4213
                default:
×
4214
                        peerLog.Warnf("ChannelPoint(%v): unexpected state "+
×
4215
                                "for rbf-coop close: %T", chanPoint, rbfState)
×
4216
                }
4217
        })
4218

4219
        return nil
3✔
4220
}
4221

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

10✔
4227
        channel, ok := p.activeChannels.Load(chanID)
10✔
4228

10✔
4229
        // Though this function can't be called for pending channels, we still
10✔
4230
        // check whether channel is nil for safety.
10✔
4231
        if !ok || channel == nil {
10✔
4232
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
×
4233
                        "unknown", chanID)
×
4234
                p.log.Errorf(err.Error())
×
4235
                req.Err <- err
×
4236
                return
×
4237
        }
×
4238

4239
        isTaprootChan := channel.ChanType().IsTaproot()
10✔
4240

10✔
4241
        switch req.CloseType {
10✔
4242
        // A type of CloseRegular indicates that the user has opted to close
4243
        // out this channel on-chain, so we execute the cooperative channel
4244
        // closure workflow.
4245
        case contractcourt.CloseRegular:
10✔
4246
                var err error
10✔
4247
                switch {
10✔
4248
                // If this is the RBF coop state machine, then we'll instruct
4249
                // it to send the shutdown message. This also might be an RBF
4250
                // iteration, in which case we'll be obtaining a new
4251
                // transaction w/ a higher fee rate.
4252
                //
4253
                // We don't support this close type for taproot channels yet
4254
                // however.
4255
                case !isTaprootChan && p.rbfCoopCloseAllowed():
3✔
4256
                        err = p.startRbfChanCloser(
3✔
4257
                                newRPCShutdownInit(req), channel.ChannelPoint(),
3✔
4258
                        )
3✔
4259
                default:
10✔
4260
                        err = p.initNegotiateChanCloser(req, channel)
10✔
4261
                }
4262

4263
                if err != nil {
11✔
4264
                        p.log.Errorf(err.Error())
1✔
4265
                        req.Err <- err
1✔
4266
                }
1✔
4267

4268
        // A type of CloseBreach indicates that the counterparty has breached
4269
        // the channel therefore we need to clean up our local state.
4270
        case contractcourt.CloseBreach:
×
4271
                // TODO(roasbeef): no longer need with newer beach logic?
×
4272
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
×
4273
                        "channel", req.ChanPoint)
×
4274
                p.WipeChannel(req.ChanPoint)
×
4275
        }
4276
}
4277

4278
// linkFailureReport is sent to the channelManager whenever a link reports a
4279
// link failure, and is forced to exit. The report houses the necessary
4280
// information to clean up the channel state, send back the error message, and
4281
// force close if necessary.
4282
type linkFailureReport struct {
4283
        chanPoint   wire.OutPoint
4284
        chanID      lnwire.ChannelID
4285
        shortChanID lnwire.ShortChannelID
4286
        linkErr     htlcswitch.LinkFailureError
4287
}
4288

4289
// handleLinkFailure processes a link failure report when a link in the switch
4290
// fails. It facilitates the removal of all channel state within the peer,
4291
// force closing the channel depending on severity, and sending the error
4292
// message back to the remote party.
4293
func (p *Brontide) handleLinkFailure(failure linkFailureReport) {
3✔
4294
        // Retrieve the channel from the map of active channels. We do this to
3✔
4295
        // have access to it even after WipeChannel remove it from the map.
3✔
4296
        chanID := lnwire.NewChanIDFromOutPoint(failure.chanPoint)
3✔
4297
        lnChan, _ := p.activeChannels.Load(chanID)
3✔
4298

3✔
4299
        // We begin by wiping the link, which will remove it from the switch,
3✔
4300
        // such that it won't be attempted used for any more updates.
3✔
4301
        //
3✔
4302
        // TODO(halseth): should introduce a way to atomically stop/pause the
3✔
4303
        // link and cancel back any adds in its mailboxes such that we can
3✔
4304
        // safely force close without the link being added again and updates
3✔
4305
        // being applied.
3✔
4306
        p.WipeChannel(&failure.chanPoint)
3✔
4307

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

3✔
4313
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
3✔
4314
                        failure.chanPoint,
3✔
4315
                )
3✔
4316
                if err != nil {
6✔
4317
                        p.log.Errorf("unable to force close "+
3✔
4318
                                "link(%v): %v", failure.shortChanID, err)
3✔
4319
                } else {
6✔
4320
                        p.log.Infof("channel(%v) force "+
3✔
4321
                                "closed with txid %v",
3✔
4322
                                failure.shortChanID, closeTx.TxHash())
3✔
4323
                }
3✔
4324
        }
4325

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

×
4331
                if err := lnChan.State().MarkBorked(); err != nil {
×
4332
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
4333
                                failure.shortChanID, err)
×
4334
                }
×
4335
        }
4336

4337
        // Send an error to the peer, why we failed the channel.
4338
        if failure.linkErr.ShouldSendToPeer() {
6✔
4339
                // If SendData is set, send it to the peer. If not, we'll use
3✔
4340
                // the standard error messages in the payload. We only include
3✔
4341
                // sendData in the cases where the error data does not contain
3✔
4342
                // sensitive information.
3✔
4343
                data := []byte(failure.linkErr.Error())
3✔
4344
                if failure.linkErr.SendData != nil {
3✔
4345
                        data = failure.linkErr.SendData
×
4346
                }
×
4347

4348
                var networkMsg lnwire.Message
3✔
4349
                if failure.linkErr.Warning {
3✔
4350
                        networkMsg = &lnwire.Warning{
×
4351
                                ChanID: failure.chanID,
×
4352
                                Data:   data,
×
4353
                        }
×
4354
                } else {
3✔
4355
                        networkMsg = &lnwire.Error{
3✔
4356
                                ChanID: failure.chanID,
3✔
4357
                                Data:   data,
3✔
4358
                        }
3✔
4359
                }
3✔
4360

4361
                err := p.SendMessage(true, networkMsg)
3✔
4362
                if err != nil {
3✔
4363
                        p.log.Errorf("unable to send msg to "+
×
4364
                                "remote peer: %v", err)
×
4365
                }
×
4366
        }
4367

4368
        // If the failure action is disconnect, then we'll execute that now. If
4369
        // we had to send an error above, it was a sync call, so we expect the
4370
        // message to be flushed on the wire by now.
4371
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
3✔
4372
                p.Disconnect(fmt.Errorf("link requested disconnect"))
×
4373
        }
×
4374
}
4375

4376
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
4377
// public key and the channel id.
4378
func (p *Brontide) fetchLinkFromKeyAndCid(
4379
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
22✔
4380

22✔
4381
        var chanLink htlcswitch.ChannelUpdateHandler
22✔
4382

22✔
4383
        // We don't need to check the error here, and can instead just loop
22✔
4384
        // over the slice and return nil.
22✔
4385
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
22✔
4386
        for _, link := range links {
43✔
4387
                if link.ChanID() == cid {
42✔
4388
                        chanLink = link
21✔
4389
                        break
21✔
4390
                }
4391
        }
4392

4393
        return chanLink
22✔
4394
}
4395

4396
// finalizeChanClosure performs the final clean up steps once the cooperative
4397
// closure transaction has been fully broadcast. The finalized closing state
4398
// machine should be passed in. Once the transaction has been sufficiently
4399
// confirmed, the channel will be marked as fully closed within the database,
4400
// and any clients will be notified of updates to the closing state.
4401
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
7✔
4402
        closeReq := chanCloser.CloseRequest()
7✔
4403

7✔
4404
        // First, we'll clear all indexes related to the channel in question.
7✔
4405
        chanPoint := chanCloser.Channel().ChannelPoint()
7✔
4406
        p.WipeChannel(&chanPoint)
7✔
4407

7✔
4408
        // Also clear the activeChanCloses map of this channel.
7✔
4409
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
7✔
4410
        p.activeChanCloses.Delete(cid) // TODO(roasbeef): existing race
7✔
4411

7✔
4412
        // Next, we'll launch a goroutine which will request to be notified by
7✔
4413
        // the ChainNotifier once the closure transaction obtains a single
7✔
4414
        // confirmation.
7✔
4415
        notifier := p.cfg.ChainNotifier
7✔
4416

7✔
4417
        // If any error happens during waitForChanToClose, forward it to
7✔
4418
        // closeReq. If this channel closure is not locally initiated, closeReq
7✔
4419
        // will be nil, so just ignore the error.
7✔
4420
        errChan := make(chan error, 1)
7✔
4421
        if closeReq != nil {
12✔
4422
                errChan = closeReq.Err
5✔
4423
        }
5✔
4424

4425
        closingTx, err := chanCloser.ClosingTx()
7✔
4426
        if err != nil {
7✔
4427
                if closeReq != nil {
×
4428
                        p.log.Error(err)
×
4429
                        closeReq.Err <- err
×
4430
                }
×
4431
        }
4432

4433
        closingTxid := closingTx.TxHash()
7✔
4434

7✔
4435
        // If this is a locally requested shutdown, update the caller with a
7✔
4436
        // new event detailing the current pending state of this request.
7✔
4437
        if closeReq != nil {
12✔
4438
                closeReq.Updates <- &PendingUpdate{
5✔
4439
                        Txid: closingTxid[:],
5✔
4440
                }
5✔
4441
        }
5✔
4442

4443
        localOut := chanCloser.LocalCloseOutput()
7✔
4444
        remoteOut := chanCloser.RemoteCloseOutput()
7✔
4445
        auxOut := chanCloser.AuxOutputs()
7✔
4446
        go WaitForChanToClose(
7✔
4447
                chanCloser.NegotiationHeight(), notifier, errChan,
7✔
4448
                &chanPoint, &closingTxid, closingTx.TxOut[0].PkScript, func() {
14✔
4449
                        // Respond to the local subsystem which requested the
7✔
4450
                        // channel closure.
7✔
4451
                        if closeReq != nil {
12✔
4452
                                closeReq.Updates <- &ChannelCloseUpdate{
5✔
4453
                                        ClosingTxid:       closingTxid[:],
5✔
4454
                                        Success:           true,
5✔
4455
                                        LocalCloseOutput:  localOut,
5✔
4456
                                        RemoteCloseOutput: remoteOut,
5✔
4457
                                        AuxOutputs:        auxOut,
5✔
4458
                                }
5✔
4459
                        }
5✔
4460
                },
4461
        )
4462
}
4463

4464
// WaitForChanToClose uses the passed notifier to wait until the channel has
4465
// been detected as closed on chain and then concludes by executing the
4466
// following actions: the channel point will be sent over the settleChan, and
4467
// finally the callback will be executed. If any error is encountered within
4468
// the function, then it will be sent over the errChan.
4469
func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
4470
        errChan chan error, chanPoint *wire.OutPoint,
4471
        closingTxID *chainhash.Hash, closeScript []byte, cb func()) {
7✔
4472

7✔
4473
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
7✔
4474
                "with txid: %v", chanPoint, closingTxID)
7✔
4475

7✔
4476
        // TODO(roasbeef): add param for num needed confs
7✔
4477
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
7✔
4478
                closingTxID, closeScript, 1, bestHeight,
7✔
4479
        )
7✔
4480
        if err != nil {
7✔
4481
                if errChan != nil {
×
4482
                        errChan <- err
×
4483
                }
×
4484
                return
×
4485
        }
4486

4487
        // In the case that the ChainNotifier is shutting down, all subscriber
4488
        // notification channels will be closed, generating a nil receive.
4489
        height, ok := <-confNtfn.Confirmed
7✔
4490
        if !ok {
10✔
4491
                return
3✔
4492
        }
3✔
4493

4494
        // The channel has been closed, remove it from any active indexes, and
4495
        // the database state.
4496
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
7✔
4497
                "height %v", chanPoint, height.BlockHeight)
7✔
4498

7✔
4499
        // Finally, execute the closure call back to mark the confirmation of
7✔
4500
        // the transaction closing the contract.
7✔
4501
        cb()
7✔
4502
}
4503

4504
// WipeChannel removes the passed channel point from all indexes associated with
4505
// the peer and the switch.
4506
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
7✔
4507
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
7✔
4508

7✔
4509
        p.activeChannels.Delete(chanID)
7✔
4510

7✔
4511
        // Instruct the HtlcSwitch to close this link as the channel is no
7✔
4512
        // longer active.
7✔
4513
        p.cfg.Switch.RemoveLink(chanID)
7✔
4514
}
7✔
4515

4516
// handleInitMsg handles the incoming init message which contains global and
4517
// local feature vectors. If feature vectors are incompatible then disconnect.
4518
func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
6✔
4519
        // First, merge any features from the legacy global features field into
6✔
4520
        // those presented in the local features fields.
6✔
4521
        err := msg.Features.Merge(msg.GlobalFeatures)
6✔
4522
        if err != nil {
6✔
4523
                return fmt.Errorf("unable to merge legacy global features: %w",
×
4524
                        err)
×
4525
        }
×
4526

4527
        // Then, finalize the remote feature vector providing the flattened
4528
        // feature bit namespace.
4529
        p.remoteFeatures = lnwire.NewFeatureVector(
6✔
4530
                msg.Features, lnwire.Features,
6✔
4531
        )
6✔
4532

6✔
4533
        // Now that we have their features loaded, we'll ensure that they
6✔
4534
        // didn't set any required bits that we don't know of.
6✔
4535
        err = feature.ValidateRequired(p.remoteFeatures)
6✔
4536
        if err != nil {
6✔
4537
                return fmt.Errorf("invalid remote features: %w", err)
×
4538
        }
×
4539

4540
        // Ensure the remote party's feature vector contains all transitive
4541
        // dependencies. We know ours are correct since they are validated
4542
        // during the feature manager's instantiation.
4543
        err = feature.ValidateDeps(p.remoteFeatures)
6✔
4544
        if err != nil {
6✔
4545
                return fmt.Errorf("invalid remote features: %w", err)
×
4546
        }
×
4547

4548
        // Now that we know we understand their requirements, we'll check to
4549
        // see if they don't support anything that we deem to be mandatory.
4550
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
6✔
4551
                return fmt.Errorf("data loss protection required")
×
4552
        }
×
4553

4554
        return nil
6✔
4555
}
4556

4557
// LocalFeatures returns the set of global features that has been advertised by
4558
// the local node. This allows sub-systems that use this interface to gate their
4559
// behavior off the set of negotiated feature bits.
4560
//
4561
// NOTE: Part of the lnpeer.Peer interface.
4562
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
3✔
4563
        return p.cfg.Features
3✔
4564
}
3✔
4565

4566
// RemoteFeatures returns the set of global features that has been advertised by
4567
// the remote node. This allows sub-systems that use this interface to gate
4568
// their behavior off the set of negotiated feature bits.
4569
//
4570
// NOTE: Part of the lnpeer.Peer interface.
4571
func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector {
23✔
4572
        return p.remoteFeatures
23✔
4573
}
23✔
4574

4575
// hasNegotiatedScidAlias returns true if we've negotiated the
4576
// option-scid-alias feature bit with the peer.
4577
func (p *Brontide) hasNegotiatedScidAlias() bool {
6✔
4578
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
6✔
4579
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
6✔
4580
        return peerHas && localHas
6✔
4581
}
6✔
4582

4583
// sendInitMsg sends the Init message to the remote peer. This message contains
4584
// our currently supported local and global features.
4585
func (p *Brontide) sendInitMsg(legacyChan bool) error {
10✔
4586
        features := p.cfg.Features.Clone()
10✔
4587
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
10✔
4588

10✔
4589
        // If we have a legacy channel open with a peer, we downgrade static
10✔
4590
        // remote required to optional in case the peer does not understand the
10✔
4591
        // required feature bit. If we do not do this, the peer will reject our
10✔
4592
        // connection because it does not understand a required feature bit, and
10✔
4593
        // our channel will be unusable.
10✔
4594
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
11✔
4595
                p.log.Infof("Legacy channel open with peer, " +
1✔
4596
                        "downgrading static remote required feature bit to " +
1✔
4597
                        "optional")
1✔
4598

1✔
4599
                // Unset and set in both the local and global features to
1✔
4600
                // ensure both sets are consistent and merge able by old and
1✔
4601
                // new nodes.
1✔
4602
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4603
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4604

1✔
4605
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
4606
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
4607
        }
1✔
4608

4609
        msg := lnwire.NewInitMessage(
10✔
4610
                legacyFeatures.RawFeatureVector,
10✔
4611
                features.RawFeatureVector,
10✔
4612
        )
10✔
4613

10✔
4614
        return p.writeMessage(msg)
10✔
4615
}
4616

4617
// resendChanSyncMsg will attempt to find a channel sync message for the closed
4618
// channel and resend it to our peer.
4619
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
3✔
4620
        // If we already re-sent the mssage for this channel, we won't do it
3✔
4621
        // again.
3✔
4622
        if _, ok := p.resentChanSyncMsg[cid]; ok {
3✔
4623
                return nil
×
4624
        }
×
4625

4626
        // Check if we have any channel sync messages stored for this channel.
4627
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
3✔
4628
        if err != nil {
6✔
4629
                return fmt.Errorf("unable to fetch channel sync messages for "+
3✔
4630
                        "peer %v: %v", p, err)
3✔
4631
        }
3✔
4632

4633
        if c.LastChanSyncMsg == nil {
3✔
4634
                return fmt.Errorf("no chan sync message stored for channel %v",
×
4635
                        cid)
×
4636
        }
×
4637

4638
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
3✔
4639
                return fmt.Errorf("ignoring channel reestablish from "+
×
4640
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
4641
        }
×
4642

4643
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
3✔
4644
                "peer", cid)
3✔
4645

3✔
4646
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
3✔
4647
                return fmt.Errorf("failed resending channel sync "+
×
4648
                        "message to peer %v: %v", p, err)
×
4649
        }
×
4650

4651
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
3✔
4652
                cid)
3✔
4653

3✔
4654
        // Note down that we sent the message, so we won't resend it again for
3✔
4655
        // this connection.
3✔
4656
        p.resentChanSyncMsg[cid] = struct{}{}
3✔
4657

3✔
4658
        return nil
3✔
4659
}
4660

4661
// SendMessage sends a variadic number of high-priority messages to the remote
4662
// peer. The first argument denotes if the method should block until the
4663
// messages have been sent to the remote peer or an error is returned,
4664
// otherwise it returns immediately after queuing.
4665
//
4666
// NOTE: Part of the lnpeer.Peer interface.
4667
func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error {
6✔
4668
        return p.sendMessage(sync, true, msgs...)
6✔
4669
}
6✔
4670

4671
// SendMessageLazy sends a variadic number of low-priority messages to the
4672
// remote peer. The first argument denotes if the method should block until
4673
// the messages have been sent to the remote peer or an error is returned,
4674
// otherwise it returns immediately after queueing.
4675
//
4676
// NOTE: Part of the lnpeer.Peer interface.
4677
func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
4✔
4678
        return p.sendMessage(sync, false, msgs...)
4✔
4679
}
4✔
4680

4681
// sendMessage queues a variadic number of messages using the passed priority
4682
// to the remote peer. If sync is true, this method will block until the
4683
// messages have been sent to the remote peer or an error is returned, otherwise
4684
// it returns immediately after queueing.
4685
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
7✔
4686
        // Add all incoming messages to the outgoing queue. A list of error
7✔
4687
        // chans is populated for each message if the caller requested a sync
7✔
4688
        // send.
7✔
4689
        var errChans []chan error
7✔
4690
        if sync {
11✔
4691
                errChans = make([]chan error, 0, len(msgs))
4✔
4692
        }
4✔
4693
        for _, msg := range msgs {
14✔
4694
                // If a sync send was requested, create an error chan to listen
7✔
4695
                // for an ack from the writeHandler.
7✔
4696
                var errChan chan error
7✔
4697
                if sync {
11✔
4698
                        errChan = make(chan error, 1)
4✔
4699
                        errChans = append(errChans, errChan)
4✔
4700
                }
4✔
4701

4702
                if priority {
13✔
4703
                        p.queueMsg(msg, errChan)
6✔
4704
                } else {
10✔
4705
                        p.queueMsgLazy(msg, errChan)
4✔
4706
                }
4✔
4707
        }
4708

4709
        // Wait for all replies from the writeHandler. For async sends, this
4710
        // will be a NOP as the list of error chans is nil.
4711
        for _, errChan := range errChans {
11✔
4712
                select {
4✔
4713
                case err := <-errChan:
4✔
4714
                        return err
4✔
4715
                case <-p.cg.Done():
×
4716
                        return lnpeer.ErrPeerExiting
×
4717
                case <-p.cfg.Quit:
×
4718
                        return lnpeer.ErrPeerExiting
×
4719
                }
4720
        }
4721

4722
        return nil
6✔
4723
}
4724

4725
// PubKey returns the pubkey of the peer in compressed serialized format.
4726
//
4727
// NOTE: Part of the lnpeer.Peer interface.
4728
func (p *Brontide) PubKey() [33]byte {
5✔
4729
        return p.cfg.PubKeyBytes
5✔
4730
}
5✔
4731

4732
// IdentityKey returns the public key of the remote peer.
4733
//
4734
// NOTE: Part of the lnpeer.Peer interface.
4735
func (p *Brontide) IdentityKey() *btcec.PublicKey {
18✔
4736
        return p.cfg.Addr.IdentityKey
18✔
4737
}
18✔
4738

4739
// Address returns the network address of the remote peer.
4740
//
4741
// NOTE: Part of the lnpeer.Peer interface.
4742
func (p *Brontide) Address() net.Addr {
3✔
4743
        return p.cfg.Addr.Address
3✔
4744
}
3✔
4745

4746
// AddNewChannel adds a new channel to the peer. The channel should fail to be
4747
// added if the cancel channel is closed.
4748
//
4749
// NOTE: Part of the lnpeer.Peer interface.
4750
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
4751
        cancel <-chan struct{}) error {
3✔
4752

3✔
4753
        errChan := make(chan error, 1)
3✔
4754
        newChanMsg := &newChannelMsg{
3✔
4755
                channel: newChan,
3✔
4756
                err:     errChan,
3✔
4757
        }
3✔
4758

3✔
4759
        select {
3✔
4760
        case p.newActiveChannel <- newChanMsg:
3✔
4761
        case <-cancel:
×
4762
                return errors.New("canceled adding new channel")
×
4763
        case <-p.cg.Done():
×
4764
                return lnpeer.ErrPeerExiting
×
4765
        }
4766

4767
        // We pause here to wait for the peer to recognize the new channel
4768
        // before we close the channel barrier corresponding to the channel.
4769
        select {
3✔
4770
        case err := <-errChan:
3✔
4771
                return err
3✔
4772
        case <-p.cg.Done():
×
4773
                return lnpeer.ErrPeerExiting
×
4774
        }
4775
}
4776

4777
// AddPendingChannel adds a pending open channel to the peer. The channel
4778
// should fail to be added if the cancel channel is closed.
4779
//
4780
// NOTE: Part of the lnpeer.Peer interface.
4781
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
4782
        cancel <-chan struct{}) error {
3✔
4783

3✔
4784
        errChan := make(chan error, 1)
3✔
4785
        newChanMsg := &newChannelMsg{
3✔
4786
                channelID: cid,
3✔
4787
                err:       errChan,
3✔
4788
        }
3✔
4789

3✔
4790
        select {
3✔
4791
        case p.newPendingChannel <- newChanMsg:
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
        // We pause here to wait for the peer to recognize the new pending
4801
        // channel before we close the channel barrier corresponding to the
4802
        // channel.
4803
        select {
3✔
4804
        case err := <-errChan:
3✔
4805
                return err
3✔
4806

4807
        case <-cancel:
×
4808
                return errors.New("canceled adding pending channel")
×
4809

4810
        case <-p.cg.Done():
×
4811
                return lnpeer.ErrPeerExiting
×
4812
        }
4813
}
4814

4815
// RemovePendingChannel removes a pending open channel from the peer.
4816
//
4817
// NOTE: Part of the lnpeer.Peer interface.
4818
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
3✔
4819
        errChan := make(chan error, 1)
3✔
4820
        newChanMsg := &newChannelMsg{
3✔
4821
                channelID: cid,
3✔
4822
                err:       errChan,
3✔
4823
        }
3✔
4824

3✔
4825
        select {
3✔
4826
        case p.removePendingChannel <- newChanMsg:
3✔
4827
        case <-p.cg.Done():
×
4828
                return lnpeer.ErrPeerExiting
×
4829
        }
4830

4831
        // We pause here to wait for the peer to respond to the cancellation of
4832
        // the pending channel before we close the channel barrier
4833
        // corresponding to the channel.
4834
        select {
3✔
4835
        case err := <-errChan:
3✔
4836
                return err
3✔
4837

4838
        case <-p.cg.Done():
×
4839
                return lnpeer.ErrPeerExiting
×
4840
        }
4841
}
4842

4843
// StartTime returns the time at which the connection was established if the
4844
// peer started successfully, and zero otherwise.
4845
func (p *Brontide) StartTime() time.Time {
3✔
4846
        return p.startTime
3✔
4847
}
3✔
4848

4849
// handleCloseMsg is called when a new cooperative channel closure related
4850
// message is received from the remote peer. We'll use this message to advance
4851
// the chan closer state machine.
4852
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
16✔
4853
        link := p.fetchLinkFromKeyAndCid(msg.cid)
16✔
4854

16✔
4855
        // We'll now fetch the matching closing state machine in order to
16✔
4856
        // continue, or finalize the channel closure process.
16✔
4857
        chanCloserE, err := p.fetchActiveChanCloser(msg.cid)
16✔
4858
        if err != nil {
19✔
4859
                // If the channel is not known to us, we'll simply ignore this
3✔
4860
                // message.
3✔
4861
                if err == ErrChannelNotFound {
6✔
4862
                        return
3✔
4863
                }
3✔
4864

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

×
4867
                errMsg := &lnwire.Error{
×
4868
                        ChanID: msg.cid,
×
4869
                        Data:   lnwire.ErrorData(err.Error()),
×
4870
                }
×
4871
                p.queueMsg(errMsg, nil)
×
4872
                return
×
4873
        }
4874

4875
        if chanCloserE.IsRight() {
16✔
4876
                // TODO(roasbeef): assert?
×
4877
                return
×
4878
        }
×
4879

4880
        // At this point, we'll only enter this call path if a negotiate chan
4881
        // closer was used. So we'll extract that from the either now.
4882
        //
4883
        // TODO(roabeef): need extra helper func for either to make cleaner
4884
        var chanCloser *chancloser.ChanCloser
16✔
4885
        chanCloserE.WhenLeft(func(c *chancloser.ChanCloser) {
32✔
4886
                chanCloser = c
16✔
4887
        })
16✔
4888

4889
        handleErr := func(err error) {
17✔
4890
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
4891
                p.log.Error(err)
1✔
4892

1✔
4893
                // As the negotiations failed, we'll reset the channel state
1✔
4894
                // machine to ensure we act to on-chain events as normal.
1✔
4895
                chanCloser.Channel().ResetState()
1✔
4896
                if chanCloser.CloseRequest() != nil {
1✔
4897
                        chanCloser.CloseRequest().Err <- err
×
4898
                }
×
4899

4900
                p.activeChanCloses.Delete(msg.cid)
1✔
4901

1✔
4902
                p.Disconnect(err)
1✔
4903
        }
4904

4905
        // Next, we'll process the next message using the target state machine.
4906
        // We'll either continue negotiation, or halt.
4907
        switch typed := msg.msg.(type) {
16✔
4908
        case *lnwire.Shutdown:
8✔
4909
                // Disable incoming adds immediately.
8✔
4910
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
8✔
4911
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
4912
                                link.ChanID())
×
4913
                }
×
4914

4915
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
8✔
4916
                if err != nil {
8✔
4917
                        handleErr(err)
×
4918
                        return
×
4919
                }
×
4920

4921
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
14✔
4922
                        // If the link is nil it means we can immediately queue
6✔
4923
                        // the Shutdown message since we don't have to wait for
6✔
4924
                        // commitment transaction synchronization.
6✔
4925
                        if link == nil {
7✔
4926
                                p.queueMsg(&msg, nil)
1✔
4927
                                return
1✔
4928
                        }
1✔
4929

4930
                        // Immediately disallow any new HTLC's from being added
4931
                        // in the outgoing direction.
4932
                        if !link.DisableAdds(htlcswitch.Outgoing) {
5✔
4933
                                p.log.Warnf("Outgoing link adds already "+
×
4934
                                        "disabled: %v", link.ChanID())
×
4935
                        }
×
4936

4937
                        // When we have a Shutdown to send, we defer it till the
4938
                        // next time we send a CommitSig to remain spec
4939
                        // compliant.
4940
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
10✔
4941
                                p.queueMsg(&msg, nil)
5✔
4942
                        })
5✔
4943
                })
4944

4945
                beginNegotiation := func() {
16✔
4946
                        oClosingSigned, err := chanCloser.BeginNegotiation()
8✔
4947
                        if err != nil {
8✔
4948
                                handleErr(err)
×
4949
                                return
×
4950
                        }
×
4951

4952
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
16✔
4953
                                p.queueMsg(&msg, nil)
8✔
4954
                        })
8✔
4955
                }
4956

4957
                if link == nil {
9✔
4958
                        beginNegotiation()
1✔
4959
                } else {
8✔
4960
                        // Now we register a flush hook to advance the
7✔
4961
                        // ChanCloser and possibly send out a ClosingSigned
7✔
4962
                        // when the link finishes draining.
7✔
4963
                        link.OnFlushedOnce(func() {
14✔
4964
                                // Remove link in goroutine to prevent deadlock.
7✔
4965
                                go p.cfg.Switch.RemoveLink(msg.cid)
7✔
4966
                                beginNegotiation()
7✔
4967
                        })
7✔
4968
                }
4969

4970
        case *lnwire.ClosingSigned:
11✔
4971
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
11✔
4972
                if err != nil {
12✔
4973
                        handleErr(err)
1✔
4974
                        return
1✔
4975
                }
1✔
4976

4977
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
22✔
4978
                        p.queueMsg(&msg, nil)
11✔
4979
                })
11✔
4980

4981
        default:
×
4982
                panic("impossible closeMsg type")
×
4983
        }
4984

4985
        // If we haven't finished close negotiations, then we'll continue as we
4986
        // can't yet finalize the closure.
4987
        if _, err := chanCloser.ClosingTx(); err != nil {
26✔
4988
                return
11✔
4989
        }
11✔
4990

4991
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
4992
        // the channel closure by notifying relevant sub-systems and launching a
4993
        // goroutine to wait for close tx conf.
4994
        p.finalizeChanClosure(chanCloser)
7✔
4995
}
4996

4997
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
4998
// the channelManager goroutine, which will shut down the link and possibly
4999
// close the channel.
5000
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
3✔
5001
        select {
3✔
5002
        case p.localCloseChanReqs <- req:
3✔
5003
                p.log.Info("Local close channel request is going to be " +
3✔
5004
                        "delivered to the peer")
3✔
5005
        case <-p.cg.Done():
×
5006
                p.log.Info("Unable to deliver local close channel request " +
×
5007
                        "to peer")
×
5008
        }
5009
}
5010

5011
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
5012
func (p *Brontide) NetAddress() *lnwire.NetAddress {
3✔
5013
        return p.cfg.Addr
3✔
5014
}
3✔
5015

5016
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
5017
func (p *Brontide) Inbound() bool {
3✔
5018
        return p.cfg.Inbound
3✔
5019
}
3✔
5020

5021
// ConnReq is a getter for the Brontide's connReq in cfg.
5022
func (p *Brontide) ConnReq() *connmgr.ConnReq {
3✔
5023
        return p.cfg.ConnReq
3✔
5024
}
3✔
5025

5026
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
5027
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
3✔
5028
        return p.cfg.ErrorBuffer
3✔
5029
}
3✔
5030

5031
// SetAddress sets the remote peer's address given an address.
5032
func (p *Brontide) SetAddress(address net.Addr) {
×
5033
        p.cfg.Addr.Address = address
×
5034
}
×
5035

5036
// ActiveSignal returns the peer's active signal.
5037
func (p *Brontide) ActiveSignal() chan struct{} {
3✔
5038
        return p.activeSignal
3✔
5039
}
3✔
5040

5041
// Conn returns a pointer to the peer's connection struct.
5042
func (p *Brontide) Conn() net.Conn {
3✔
5043
        return p.cfg.Conn
3✔
5044
}
3✔
5045

5046
// BytesReceived returns the number of bytes received from the peer.
5047
func (p *Brontide) BytesReceived() uint64 {
3✔
5048
        return atomic.LoadUint64(&p.bytesReceived)
3✔
5049
}
3✔
5050

5051
// BytesSent returns the number of bytes sent to the peer.
5052
func (p *Brontide) BytesSent() uint64 {
3✔
5053
        return atomic.LoadUint64(&p.bytesSent)
3✔
5054
}
3✔
5055

5056
// LastRemotePingPayload returns the last payload the remote party sent as part
5057
// of their ping.
5058
func (p *Brontide) LastRemotePingPayload() []byte {
3✔
5059
        pingPayload := p.lastPingPayload.Load()
3✔
5060
        if pingPayload == nil {
6✔
5061
                return []byte{}
3✔
5062
        }
3✔
5063

5064
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
5065
        if !ok {
×
5066
                return nil
×
5067
        }
×
5068

5069
        return pingBytes
×
5070
}
5071

5072
// attachChannelEventSubscription creates a channel event subscription and
5073
// attaches to client to Brontide if the reenableTimeout is no greater than 1
5074
// minute.
5075
func (p *Brontide) attachChannelEventSubscription() error {
6✔
5076
        // If the timeout is greater than 1 minute, it's unlikely that the link
6✔
5077
        // hasn't yet finished its reestablishment. Return a nil without
6✔
5078
        // creating the client to specify that we don't want to retry.
6✔
5079
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
9✔
5080
                return nil
3✔
5081
        }
3✔
5082

5083
        // When the reenable timeout is less than 1 minute, it's likely the
5084
        // channel link hasn't finished its reestablishment yet. In that case,
5085
        // we'll give it a second chance by subscribing to the channel update
5086
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
5087
        // enabling the channel again.
5088
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
6✔
5089
        if err != nil {
6✔
5090
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
5091
        }
×
5092

5093
        p.channelEventClient = sub
6✔
5094

6✔
5095
        return nil
6✔
5096
}
5097

5098
// updateNextRevocation updates the existing channel's next revocation if it's
5099
// nil.
5100
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
6✔
5101
        chanPoint := c.FundingOutpoint
6✔
5102
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
6✔
5103

6✔
5104
        // Read the current channel.
6✔
5105
        currentChan, loaded := p.activeChannels.Load(chanID)
6✔
5106

6✔
5107
        // currentChan should exist, but we perform a check anyway to avoid nil
6✔
5108
        // pointer dereference.
6✔
5109
        if !loaded {
7✔
5110
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
5111
                        chanID)
1✔
5112
        }
1✔
5113

5114
        // currentChan should not be nil, but we perform a check anyway to
5115
        // avoid nil pointer dereference.
5116
        if currentChan == nil {
6✔
5117
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
5118
                        chanID)
1✔
5119
        }
1✔
5120

5121
        // If we're being sent a new channel, and our existing channel doesn't
5122
        // have the next revocation, then we need to update the current
5123
        // existing channel.
5124
        if currentChan.RemoteNextRevocation() != nil {
4✔
5125
                return nil
×
5126
        }
×
5127

5128
        p.log.Infof("Processing retransmitted ChannelReady for "+
4✔
5129
                "ChannelPoint(%v)", chanPoint)
4✔
5130

4✔
5131
        nextRevoke := c.RemoteNextRevocation
4✔
5132

4✔
5133
        err := currentChan.InitNextRevocation(nextRevoke)
4✔
5134
        if err != nil {
4✔
5135
                return fmt.Errorf("unable to init next revocation: %w", err)
×
5136
        }
×
5137

5138
        return nil
4✔
5139
}
5140

5141
// addActiveChannel adds a new active channel to the `activeChannels` map. It
5142
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
5143
// it and assembles it with a channel link.
5144
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
3✔
5145
        chanPoint := c.FundingOutpoint
3✔
5146
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5147

3✔
5148
        // If we've reached this point, there are two possible scenarios.  If
3✔
5149
        // the channel was in the active channels map as nil, then it was
3✔
5150
        // loaded from disk and we need to send reestablish. Else, it was not
3✔
5151
        // loaded from disk and we don't need to send reestablish as this is a
3✔
5152
        // fresh channel.
3✔
5153
        shouldReestablish := p.isLoadedFromDisk(chanID)
3✔
5154

3✔
5155
        chanOpts := c.ChanOpts
3✔
5156
        if shouldReestablish {
6✔
5157
                // If we have to do the reestablish dance for this channel,
3✔
5158
                // ensure that we don't try to call InitRemoteMusigNonces twice
3✔
5159
                // by calling SkipNonceInit.
3✔
5160
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
3✔
5161
        }
3✔
5162

5163
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
3✔
5164
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
5165
        })
×
5166
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
3✔
5167
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
5168
        })
×
5169
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
3✔
5170
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
5171
        })
×
5172

5173
        // If not already active, we'll add this channel to the set of active
5174
        // channels, so we can look it up later easily according to its channel
5175
        // ID.
5176
        lnChan, err := lnwallet.NewLightningChannel(
3✔
5177
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
3✔
5178
        )
3✔
5179
        if err != nil {
3✔
5180
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
5181
        }
×
5182

5183
        // Store the channel in the activeChannels map.
5184
        p.activeChannels.Store(chanID, lnChan)
3✔
5185

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

3✔
5188
        // Next, we'll assemble a ChannelLink along with the necessary items it
3✔
5189
        // needs to function.
3✔
5190
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
3✔
5191
        if err != nil {
3✔
5192
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
5193
                        err)
×
5194
        }
×
5195

5196
        // We'll query the channel DB for the new channel's initial forwarding
5197
        // policies to determine the policy we start out with.
5198
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
3✔
5199
        if err != nil {
3✔
5200
                return fmt.Errorf("unable to query for initial forwarding "+
×
5201
                        "policy: %v", err)
×
5202
        }
×
5203

5204
        // Create the link and add it to the switch.
5205
        err = p.addLink(
3✔
5206
                &chanPoint, lnChan, initialPolicy, chainEvents,
3✔
5207
                shouldReestablish, fn.None[lnwire.Shutdown](),
3✔
5208
        )
3✔
5209
        if err != nil {
3✔
5210
                return fmt.Errorf("can't register new channel link(%v) with "+
×
5211
                        "peer", chanPoint)
×
5212
        }
×
5213

5214
        isTaprootChan := c.ChanType.IsTaproot()
3✔
5215

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

5223
        // Now that the link has been added above, we'll also init an RBF chan
5224
        // closer for this channel, but only if the new close feature is
5225
        // negotiated.
5226
        //
5227
        // Creating this here ensures that any shutdown messages sent will be
5228
        // automatically routed by the msg router.
5229
        if _, err := p.initRbfChanCloser(lnChan); err != nil {
3✔
5230
                p.activeChanCloses.Delete(chanID)
×
5231

×
5232
                return fmt.Errorf("unable to init RBF chan closer for new "+
×
5233
                        "chan: %w", err)
×
5234
        }
×
5235

5236
        return nil
3✔
5237
}
5238

5239
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
5240
// know this channel ID or not, we'll either add it to the `activeChannels` map
5241
// or init the next revocation for it.
5242
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
3✔
5243
        newChan := req.channel
3✔
5244
        chanPoint := newChan.FundingOutpoint
3✔
5245
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5246

3✔
5247
        // Only update RemoteNextRevocation if the channel is in the
3✔
5248
        // activeChannels map and if we added the link to the switch. Only
3✔
5249
        // active channels will be added to the switch.
3✔
5250
        if p.isActiveChannel(chanID) {
6✔
5251
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
3✔
5252
                        chanPoint)
3✔
5253

3✔
5254
                // Handle it and close the err chan on the request.
3✔
5255
                close(req.err)
3✔
5256

3✔
5257
                // Update the next revocation point.
3✔
5258
                err := p.updateNextRevocation(newChan.OpenChannel)
3✔
5259
                if err != nil {
3✔
5260
                        p.log.Errorf(err.Error())
×
5261
                }
×
5262

5263
                return
3✔
5264
        }
5265

5266
        // This is a new channel, we now add it to the map.
5267
        if err := p.addActiveChannel(req.channel); err != nil {
3✔
5268
                // Log and send back the error to the request.
×
5269
                p.log.Errorf(err.Error())
×
5270
                req.err <- err
×
5271

×
5272
                return
×
5273
        }
×
5274

5275
        // Close the err chan if everything went fine.
5276
        close(req.err)
3✔
5277
}
5278

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

7✔
5286
        chanID := req.channelID
7✔
5287

7✔
5288
        // If we already have this channel, something is wrong with the funding
7✔
5289
        // flow as it will only be marked as active after `ChannelReady` is
7✔
5290
        // handled. In this case, we will do nothing but log an error, just in
7✔
5291
        // case this is a legit channel.
7✔
5292
        if p.isActiveChannel(chanID) {
8✔
5293
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
5294
                        "pending channel request", chanID)
1✔
5295

1✔
5296
                return
1✔
5297
        }
1✔
5298

5299
        // The channel has already been added, we will do nothing and return.
5300
        if p.isPendingChannel(chanID) {
7✔
5301
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
5302
                        "pending channel request", chanID)
1✔
5303

1✔
5304
                return
1✔
5305
        }
1✔
5306

5307
        // This is a new channel, we now add it to the map `activeChannels`
5308
        // with nil value and mark it as a newly added channel in
5309
        // `addedChannels`.
5310
        p.activeChannels.Store(chanID, nil)
5✔
5311
        p.addedChannels.Store(chanID, struct{}{})
5✔
5312
}
5313

5314
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
5315
// from `activeChannels` map. The request will be ignored if the channel is
5316
// considered active by Brontide. Noop if the channel ID cannot be found.
5317
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
7✔
5318
        defer close(req.err)
7✔
5319

7✔
5320
        chanID := req.channelID
7✔
5321

7✔
5322
        // If we already have this channel, something is wrong with the funding
7✔
5323
        // flow as it will only be marked as active after `ChannelReady` is
7✔
5324
        // handled. In this case, we will log an error and exit.
7✔
5325
        if p.isActiveChannel(chanID) {
8✔
5326
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
5327
                        chanID)
1✔
5328
                return
1✔
5329
        }
1✔
5330

5331
        // The channel has not been added yet, we will log a warning as there
5332
        // is an unexpected call from funding manager.
5333
        if !p.isPendingChannel(chanID) {
10✔
5334
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
4✔
5335
        }
4✔
5336

5337
        // Remove the record of this pending channel.
5338
        p.activeChannels.Delete(chanID)
6✔
5339
        p.addedChannels.Delete(chanID)
6✔
5340
}
5341

5342
// sendLinkUpdateMsg sends a message that updates the channel to the
5343
// channel's message stream.
5344
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
3✔
5345
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
3✔
5346

3✔
5347
        chanStream, ok := p.activeMsgStreams[cid]
3✔
5348
        if !ok {
6✔
5349
                // If a stream hasn't yet been created, then we'll do so, add
3✔
5350
                // it to the map, and finally start it.
3✔
5351
                chanStream = newChanMsgStream(p, cid)
3✔
5352
                p.activeMsgStreams[cid] = chanStream
3✔
5353
                chanStream.Start()
3✔
5354

3✔
5355
                // Stop the stream when quit.
3✔
5356
                go func() {
6✔
5357
                        <-p.cg.Done()
3✔
5358
                        chanStream.Stop()
3✔
5359
                }()
3✔
5360
        }
5361

5362
        // With the stream obtained, add the message to the stream so we can
5363
        // continue processing message.
5364
        chanStream.AddMsg(msg)
3✔
5365
}
5366

5367
// scaleTimeout multiplies the argument duration by a constant factor depending
5368
// on variious heuristics. Currently this is only used to check whether our peer
5369
// appears to be connected over Tor and relaxes the timout deadline. However,
5370
// this is subject to change and should be treated as opaque.
5371
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
70✔
5372
        if p.isTorConnection {
73✔
5373
                return timeout * time.Duration(torTimeoutMultiplier)
3✔
5374
        }
3✔
5375

5376
        return timeout
67✔
5377
}
5378

5379
// CoopCloseUpdates is a struct used to communicate updates for an active close
5380
// to the caller.
5381
type CoopCloseUpdates struct {
5382
        UpdateChan chan interface{}
5383

5384
        ErrChan chan error
5385
}
5386

5387
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5388
// point has an active RBF chan closer.
5389
func (p *Brontide) ChanHasRbfCoopCloser(chanPoint wire.OutPoint) bool {
3✔
5390
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5391
        chanCloser, found := p.activeChanCloses.Load(chanID)
3✔
5392
        if !found {
6✔
5393
                return false
3✔
5394
        }
3✔
5395

5396
        return chanCloser.IsRight()
3✔
5397
}
5398

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

3✔
5407
        // If RBF coop close isn't permitted, then we'll an error.
3✔
5408
        if !p.rbfCoopCloseAllowed() {
3✔
5409
                return nil, fmt.Errorf("rbf coop close not enabled for " +
×
5410
                        "channel")
×
5411
        }
×
5412

5413
        closeUpdates := &CoopCloseUpdates{
3✔
5414
                UpdateChan: make(chan interface{}, 1),
3✔
5415
                ErrChan:    make(chan error, 1),
3✔
5416
        }
3✔
5417

3✔
5418
        // We'll re-use the existing switch struct here, even though we're
3✔
5419
        // bypassing the switch entirely.
3✔
5420
        closeReq := htlcswitch.ChanClose{
3✔
5421
                CloseType:      contractcourt.CloseRegular,
3✔
5422
                ChanPoint:      &chanPoint,
3✔
5423
                TargetFeePerKw: feeRate,
3✔
5424
                DeliveryScript: deliveryScript,
3✔
5425
                Updates:        closeUpdates.UpdateChan,
3✔
5426
                Err:            closeUpdates.ErrChan,
3✔
5427
                Ctx:            ctx,
3✔
5428
        }
3✔
5429

3✔
5430
        err := p.startRbfChanCloser(newRPCShutdownInit(&closeReq), chanPoint)
3✔
5431
        if err != nil {
3✔
5432
                return nil, err
×
5433
        }
×
5434

5435
        return closeUpdates, nil
3✔
5436
}
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