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

lightningnetwork / lnd / 16673052227

01 Aug 2025 10:44AM UTC coverage: 67.016% (-0.03%) from 67.047%
16673052227

Pull #9888

github

web-flow
Merge 1dd8765d7 into 37523b6cb
Pull Request #9888: Attributable failures

325 of 384 new or added lines in 16 files covered. (84.64%)

131 existing lines in 24 files now uncovered.

135611 of 202355 relevant lines covered (67.02%)

21613.83 hits per line

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

78.43
/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
        sphinx "github.com/lightningnetwork/lightning-onion"
24
        "github.com/lightningnetwork/lnd/buffer"
25
        "github.com/lightningnetwork/lnd/chainntnfs"
26
        "github.com/lightningnetwork/lnd/channeldb"
27
        "github.com/lightningnetwork/lnd/channelnotifier"
28
        "github.com/lightningnetwork/lnd/contractcourt"
29
        "github.com/lightningnetwork/lnd/discovery"
30
        "github.com/lightningnetwork/lnd/feature"
31
        "github.com/lightningnetwork/lnd/fn/v2"
32
        "github.com/lightningnetwork/lnd/funding"
33
        graphdb "github.com/lightningnetwork/lnd/graph/db"
34
        "github.com/lightningnetwork/lnd/graph/db/models"
35
        "github.com/lightningnetwork/lnd/htlcswitch"
36
        "github.com/lightningnetwork/lnd/htlcswitch/hodl"
37
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
38
        "github.com/lightningnetwork/lnd/input"
39
        "github.com/lightningnetwork/lnd/invoices"
40
        "github.com/lightningnetwork/lnd/keychain"
41
        "github.com/lightningnetwork/lnd/lnpeer"
42
        "github.com/lightningnetwork/lnd/lntypes"
43
        "github.com/lightningnetwork/lnd/lnutils"
44
        "github.com/lightningnetwork/lnd/lnwallet"
45
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
46
        "github.com/lightningnetwork/lnd/lnwallet/chancloser"
47
        "github.com/lightningnetwork/lnd/lnwire"
48
        "github.com/lightningnetwork/lnd/msgmux"
49
        "github.com/lightningnetwork/lnd/netann"
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
        // QuiescenceTimeout is the max duration that the channel can be
443
        // quiesced. Any dependent protocols (dynamic commitments, splicing,
444
        // etc.) must finish their operations under this timeout value,
445
        // otherwise the node will disconnect.
446
        QuiescenceTimeout time.Duration
447

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

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

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

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

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

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

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

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

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

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

504
        // MUST be used atomically.
505
        bytesReceived uint64
506
        bytesSent     uint64
507

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

525
        pingManager *PingManager
526

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

534
        cfg Config
535

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

634
        startReady chan struct{}
635

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

641
        // log is a peer-specific logging instance.
642
        log btclog.Logger
643
}
644

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

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

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

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

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

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

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

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

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

725
                return lastSerializedBlockHeader[:]
×
726
        }
727

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

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

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

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

767
                        p.log.Warnf("%s -- disconnecting", logMsg)
×
768

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

773
        return p
28✔
774
}
775

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

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

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

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

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

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

814
                haveLegacyChan = true
3✔
815
                break
3✔
816
        }
817

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

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

6✔
833
                msg, err := p.readNextMessage()
6✔
834
                if err != nil {
8✔
835
                        readErr <- err
2✔
836
                        msgChan <- nil
2✔
837
                        return
2✔
838
                }
2✔
839
                readErr <- nil
6✔
840
                msgChan <- msg
6✔
841
        }()
842

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

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

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

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

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

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

896
        p.startTime = time.Now()
6✔
897

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

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

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

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

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

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

6✔
944
        return nil
6✔
945
}
946

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

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

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

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

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

990
        return bothHaveBit(lnwire.RbfCoopCloseOptional) ||
10✔
991
                bothHaveBit(lnwire.RbfCoopCloseOptionalStaging)
10✔
992
}
993

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

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

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

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

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

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

6✔
1042
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
6✔
1043

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

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

1072
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
1073
                                        dbChan.FundingOutpoint,
3✔
1074
                                )
3✔
1075

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

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

3✔
1088
                                msgs = append(msgs, channelReadyMsg)
3✔
1089
                        }
1090

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

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

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

1125
                chanPoint := dbChan.FundingOutpoint
5✔
1126

5✔
1127
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
5✔
1128

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

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

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

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

1154
                        msgs = append(msgs, chanSync)
5✔
1155

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

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

1171
                                if shutdownMsg == nil {
6✔
1172
                                        continue
3✔
1173
                                }
1174

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

1180
                        continue
5✔
1181
                }
1182

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

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

3✔
1205
                        selfPolicy = p1
3✔
1206
                } else {
6✔
1207
                        selfPolicy = p2
3✔
1208
                }
3✔
1209

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

1233
                p.log.Tracef("Using link policy of: %v",
3✔
1234
                        spew.Sdump(forwardingPolicy))
3✔
1235

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

3✔
1245
                        continue
3✔
1246
                }
1247

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

1253
                isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
1254

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

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

×
1275
                                return
×
1276
                        }
×
1277

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

×
1294
                                return
×
1295
                        }
×
1296

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

3✔
1301
                        p.activeChanCloses.Store(chanID, makeNegotiateCloser(
3✔
1302
                                negotiateChanCloser,
3✔
1303
                        ))
3✔
1304

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

×
1311
                                return
×
1312
                        }
×
1313

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

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

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

1337
                p.activeChannels.Store(chanID, lnChan)
3✔
1338

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

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

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

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

1376
        return msgs, nil
6✔
1377
}
1378

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

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

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

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

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

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

1414
        //nolint:ll
1415
        linkCfg := htlcswitch.ChannelLinkConfig{
3✔
1416
                Peer:                p,
3✔
1417
                DecodeHopIterators:  p.cfg.Sphinx.DecodeHopIterators,
3✔
1418
                ExtractSharedSecret: p.cfg.Sphinx.ExtractSharedSecret,
3✔
1419
                CreateErrorEncrypter: func(ephemeralKey *btcec.PublicKey,
3✔
1420
                        sharedSecret sphinx.Hash256, isIntroduction,
3✔
1421
                        hasBlindingPoint bool) hop.ErrorEncrypter {
6✔
1422

3✔
1423
                        switch {
3✔
1424
                        case isIntroduction:
3✔
1425
                                return hop.NewIntroductionErrorEncrypter(
3✔
1426
                                        ephemeralKey, sharedSecret,
3✔
1427
                                )
3✔
1428

1429
                        case hasBlindingPoint:
3✔
1430
                                return hop.NewRelayingErrorEncrypter(
3✔
1431
                                        ephemeralKey, sharedSecret,
3✔
1432
                                )
3✔
1433

1434
                        default:
3✔
1435
                                return hop.NewSphinxErrorEncrypter(
3✔
1436
                                        ephemeralKey, sharedSecret,
3✔
1437
                                )
3✔
1438
                        }
1439
                }, FetchLastChannelUpdate: p.cfg.FetchLastChanUpdate,
1440
                HodlMask:              p.cfg.Hodl.Mask(),
1441
                Registry:              p.cfg.Invoices,
1442
                BestHeight:            p.cfg.Switch.BestHeight,
1443
                Circuits:              p.cfg.Switch.CircuitModifier(),
1444
                ForwardPackets:        p.cfg.InterceptSwitch.ForwardPackets,
1445
                FwrdingPolicy:         *forwardingPolicy,
1446
                FeeEstimator:          p.cfg.FeeEstimator,
1447
                PreimageCache:         p.cfg.WitnessBeacon,
1448
                ChainEvents:           chainEvents,
1449
                UpdateContractSignals: updateContractSignals,
1450
                NotifyContractUpdate:  notifyContractUpdate,
1451
                OnChannelFailure:      onChannelFailure,
1452
                SyncStates:            syncStates,
1453
                BatchTicker:           ticker.New(p.cfg.ChannelCommitInterval),
1454
                FwdPkgGCTicker:        ticker.New(time.Hour),
1455
                PendingCommitTicker: ticker.New(
1456
                        p.cfg.PendingCommitInterval,
1457
                ),
1458
                BatchSize:               p.cfg.ChannelCommitBatchSize,
1459
                UnsafeReplay:            p.cfg.UnsafeReplay,
1460
                MinUpdateTimeout:        htlcswitch.DefaultMinLinkFeeUpdateTimeout,
1461
                MaxUpdateTimeout:        htlcswitch.DefaultMaxLinkFeeUpdateTimeout,
1462
                OutgoingCltvRejectDelta: p.cfg.OutgoingCltvRejectDelta,
1463
                TowerClient:             p.cfg.TowerClient,
1464
                MaxOutgoingCltvExpiry:   p.cfg.MaxOutgoingCltvExpiry,
1465
                MaxFeeAllocation:        p.cfg.MaxChannelFeeAllocation,
1466
                MaxAnchorsCommitFeeRate: p.cfg.MaxAnchorsCommitFeeRate,
1467
                NotifyActiveLink:        p.cfg.ChannelNotifier.NotifyActiveLinkEvent,
1468
                NotifyActiveChannel:     p.cfg.ChannelNotifier.NotifyActiveChannelEvent,
1469
                NotifyInactiveChannel:   p.cfg.ChannelNotifier.NotifyInactiveChannelEvent,
1470
                NotifyInactiveLinkEvent: p.cfg.ChannelNotifier.NotifyInactiveLinkEvent,
1471
                HtlcNotifier:            p.cfg.HtlcNotifier,
1472
                GetAliases:              p.cfg.GetAliases,
1473
                PreviouslySentShutdown:  shutdownMsg,
1474
                DisallowRouteBlinding:   p.cfg.DisallowRouteBlinding,
1475
                MaxFeeExposure:          p.cfg.MaxFeeExposure,
1476
                ShouldFwdExpEndorsement: p.cfg.ShouldFwdExpEndorsement,
1477
                DisallowQuiescence: p.cfg.DisallowQuiescence ||
1478
                        !p.remoteFeatures.HasFeature(lnwire.QuiescenceOptional),
1479
                AuxTrafficShaper:  p.cfg.AuxTrafficShaper,
1480
                QuiescenceTimeout: p.cfg.QuiescenceTimeout,
1481
        }
1482

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

3✔
1490
        // With the channel link created, we'll now notify the htlc switch so
3✔
1491
        // this channel can be used to dispatch local payments and also
3✔
1492
        // passively forward payments.
3✔
1493
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
3✔
1494
}
1495

1496
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1497
// one confirmed public channel exists with them.
1498
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
6✔
1499
        defer p.cg.WgDone()
6✔
1500

6✔
1501
        hasConfirmedPublicChan := false
6✔
1502
        for _, channel := range channels {
11✔
1503
                if channel.IsPending {
8✔
1504
                        continue
3✔
1505
                }
1506
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
10✔
1507
                        continue
5✔
1508
                }
1509

1510
                hasConfirmedPublicChan = true
3✔
1511
                break
3✔
1512
        }
1513
        if !hasConfirmedPublicChan {
12✔
1514
                return
6✔
1515
        }
6✔
1516

1517
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
3✔
1518
        if err != nil {
3✔
1519
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1520
                return
×
1521
        }
×
1522

1523
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
3✔
1524
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1525
        }
×
1526
}
1527

1528
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1529
// have any active channels with them.
1530
func (p *Brontide) maybeSendChannelUpdates() {
6✔
1531
        defer p.cg.WgDone()
6✔
1532

6✔
1533
        // If we don't have any active channels, then we can exit early.
6✔
1534
        if p.activeChannels.Len() == 0 {
10✔
1535
                return
4✔
1536
        }
4✔
1537

1538
        maybeSendUpd := func(cid lnwire.ChannelID,
5✔
1539
                lnChan *lnwallet.LightningChannel) error {
10✔
1540

5✔
1541
                // Nil channels are pending, so we'll skip them.
5✔
1542
                if lnChan == nil {
8✔
1543
                        return nil
3✔
1544
                }
3✔
1545

1546
                dbChan := lnChan.State()
5✔
1547
                scid := func() lnwire.ShortChannelID {
10✔
1548
                        switch {
5✔
1549
                        // Otherwise if it's a zero conf channel and confirmed,
1550
                        // then we need to use the "real" scid.
1551
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
3✔
1552
                                return dbChan.ZeroConfRealScid()
3✔
1553

1554
                        // Otherwise, we can use the normal scid.
1555
                        default:
5✔
1556
                                return dbChan.ShortChanID()
5✔
1557
                        }
1558
                }()
1559

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

3✔
1570
                        return nil
3✔
1571
                }
3✔
1572

1573
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
5✔
1574
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
5✔
1575

5✔
1576
                // We'll send it as a normal message instead of using the lazy
5✔
1577
                // queue to prioritize transmission of the fresh update.
5✔
1578
                if err := p.SendMessage(false, chanUpd); err != nil {
5✔
1579
                        err := fmt.Errorf("unable to send channel update for "+
×
1580
                                "ChannelPoint(%v), scid=%v: %w",
×
1581
                                dbChan.FundingOutpoint, dbChan.ShortChanID(),
×
1582
                                err)
×
1583
                        p.log.Errorf(err.Error())
×
1584

×
1585
                        return err
×
1586
                }
×
1587

1588
                return nil
5✔
1589
        }
1590

1591
        p.activeChannels.ForEach(maybeSendUpd)
5✔
1592
}
1593

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

1611
        select {
3✔
1612
        case <-ready:
3✔
1613
        case <-p.cg.Done():
3✔
1614
        }
1615

1616
        p.cg.WgWait()
3✔
1617
}
1618

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

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

3✔
1641
                select {
3✔
1642
                case <-p.startReady:
3✔
1643
                case <-p.cg.Done():
×
1644
                        return
×
1645
                }
1646
        }
1647

1648
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
3✔
1649
        p.storeError(err)
3✔
1650

3✔
1651
        p.log.Infof(err.Error())
3✔
1652

3✔
1653
        // Stop PingManager before closing TCP connection.
3✔
1654
        p.pingManager.Stop()
3✔
1655

3✔
1656
        // Ensure that the TCP connection is properly closed before continuing.
3✔
1657
        p.cfg.Conn.Close()
3✔
1658

3✔
1659
        p.cg.Quit()
3✔
1660

3✔
1661
        // If our msg router isn't global (local to this instance), then we'll
3✔
1662
        // stop it. Otherwise, we'll leave it running.
3✔
1663
        if !p.globalMsgRouter {
6✔
1664
                p.msgRouter.WhenSome(func(router msgmux.Router) {
6✔
1665
                        router.Stop()
3✔
1666
                })
3✔
1667
        }
1668
}
1669

1670
// String returns the string representation of this peer.
1671
func (p *Brontide) String() string {
3✔
1672
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
3✔
1673
}
3✔
1674

1675
// readNextMessage reads, and returns the next message on the wire along with
1676
// any additional raw payload.
1677
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
10✔
1678
        noiseConn := p.cfg.Conn
10✔
1679
        err := noiseConn.SetReadDeadline(time.Time{})
10✔
1680
        if err != nil {
10✔
1681
                return nil, err
×
1682
        }
×
1683

1684
        pktLen, err := noiseConn.ReadNextHeader()
10✔
1685
        if err != nil {
13✔
1686
                return nil, fmt.Errorf("read next header: %w", err)
3✔
1687
        }
3✔
1688

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

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

7✔
1721
                // Next, create a new io.Reader implementation from the raw
7✔
1722
                // message, and use this to decode the message directly from.
7✔
1723
                msgReader := bytes.NewReader(rawMsg)
7✔
1724
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
7✔
1725
                if err != nil {
10✔
1726
                        return err
3✔
1727
                }
3✔
1728

1729
                // At this point, rawMsg and buf will be returned back to the
1730
                // buffer pool for re-use.
1731
                return nil
7✔
1732
        })
1733
        atomic.AddUint64(&p.bytesReceived, msgLen)
7✔
1734
        if err != nil {
10✔
1735
                return nil, err
3✔
1736
        }
3✔
1737

1738
        p.logWireMessage(nextMsg, true)
7✔
1739

7✔
1740
        return nextMsg, nil
7✔
1741
}
1742

1743
// msgStream implements a goroutine-safe, in-order stream of messages to be
1744
// delivered via closure to a receiver. These messages MUST be in order due to
1745
// the nature of the lightning channel commitment and gossiper state machines.
1746
// TODO(conner): use stream handler interface to abstract out stream
1747
// state/logging.
1748
type msgStream struct {
1749
        streamShutdown int32 // To be used atomically.
1750

1751
        peer *Brontide
1752

1753
        apply func(lnwire.Message)
1754

1755
        startMsg string
1756
        stopMsg  string
1757

1758
        msgCond *sync.Cond
1759
        msgs    []lnwire.Message
1760

1761
        mtx sync.Mutex
1762

1763
        producerSema chan struct{}
1764

1765
        wg   sync.WaitGroup
1766
        quit chan struct{}
1767
}
1768

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

6✔
1777
        stream := &msgStream{
6✔
1778
                peer:         p,
6✔
1779
                apply:        apply,
6✔
1780
                startMsg:     startMsg,
6✔
1781
                stopMsg:      stopMsg,
6✔
1782
                producerSema: make(chan struct{}, bufSize),
6✔
1783
                quit:         make(chan struct{}),
6✔
1784
        }
6✔
1785
        stream.msgCond = sync.NewCond(&stream.mtx)
6✔
1786

6✔
1787
        // Before we return the active stream, we'll populate the producer's
6✔
1788
        // semaphore channel. We'll use this to ensure that the producer won't
6✔
1789
        // attempt to allocate memory in the queue for an item until it has
6✔
1790
        // sufficient extra space.
6✔
1791
        for i := uint32(0); i < bufSize; i++ {
159✔
1792
                stream.producerSema <- struct{}{}
153✔
1793
        }
153✔
1794

1795
        return stream
6✔
1796
}
1797

1798
// Start starts the chanMsgStream.
1799
func (ms *msgStream) Start() {
6✔
1800
        ms.wg.Add(1)
6✔
1801
        go ms.msgConsumer()
6✔
1802
}
6✔
1803

1804
// Stop stops the chanMsgStream.
1805
func (ms *msgStream) Stop() {
3✔
1806
        // TODO(roasbeef): signal too?
3✔
1807

3✔
1808
        close(ms.quit)
3✔
1809

3✔
1810
        // Now that we've closed the channel, we'll repeatedly signal the msg
3✔
1811
        // consumer until we've detected that it has exited.
3✔
1812
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
6✔
1813
                ms.msgCond.Signal()
3✔
1814
                time.Sleep(time.Millisecond * 100)
3✔
1815
        }
3✔
1816

1817
        ms.wg.Wait()
3✔
1818
}
1819

1820
// msgConsumer is the main goroutine that streams messages from the peer's
1821
// readHandler directly to the target channel.
1822
func (ms *msgStream) msgConsumer() {
6✔
1823
        defer ms.wg.Done()
6✔
1824
        defer peerLog.Tracef(ms.stopMsg)
6✔
1825
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
6✔
1826

6✔
1827
        peerLog.Tracef(ms.startMsg)
6✔
1828

6✔
1829
        for {
12✔
1830
                // First, we'll check our condition. If the queue of messages
6✔
1831
                // is empty, then we'll wait until a new item is added.
6✔
1832
                ms.msgCond.L.Lock()
6✔
1833
                for len(ms.msgs) == 0 {
12✔
1834
                        ms.msgCond.Wait()
6✔
1835

6✔
1836
                        // If we woke up in order to exit, then we'll do so.
6✔
1837
                        // Otherwise, we'll check the message queue for any new
6✔
1838
                        // items.
6✔
1839
                        select {
6✔
1840
                        case <-ms.peer.cg.Done():
3✔
1841
                                ms.msgCond.L.Unlock()
3✔
1842
                                return
3✔
1843
                        case <-ms.quit:
3✔
1844
                                ms.msgCond.L.Unlock()
3✔
1845
                                return
3✔
1846
                        default:
3✔
1847
                        }
1848
                }
1849

1850
                // Grab the message off the front of the queue, shifting the
1851
                // slice's reference down one in order to remove the message
1852
                // from the queue.
1853
                msg := ms.msgs[0]
3✔
1854
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
3✔
1855
                ms.msgs = ms.msgs[1:]
3✔
1856

3✔
1857
                ms.msgCond.L.Unlock()
3✔
1858

3✔
1859
                ms.apply(msg)
3✔
1860

3✔
1861
                // We've just successfully processed an item, so we'll signal
3✔
1862
                // to the producer that a new slot in the buffer. We'll use
3✔
1863
                // this to bound the size of the buffer to avoid allowing it to
3✔
1864
                // grow indefinitely.
3✔
1865
                select {
3✔
1866
                case ms.producerSema <- struct{}{}:
3✔
1867
                case <-ms.peer.cg.Done():
3✔
1868
                        return
3✔
1869
                case <-ms.quit:
1✔
1870
                        return
1✔
1871
                }
1872
        }
1873
}
1874

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

1891
        // Next, we'll lock the condition, and add the message to the end of
1892
        // the message queue.
1893
        ms.msgCond.L.Lock()
3✔
1894
        ms.msgs = append(ms.msgs, msg)
3✔
1895
        ms.msgCond.L.Unlock()
3✔
1896

3✔
1897
        // With the message added, we signal to the msgConsumer that there are
3✔
1898
        // additional messages to consume.
3✔
1899
        ms.msgCond.Signal()
3✔
1900
}
1901

1902
// waitUntilLinkActive waits until the target link is active and returns a
1903
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1904
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1905
func waitUntilLinkActive(p *Brontide,
1906
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
3✔
1907

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

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

3✔
1928
        // The link may already be active by this point, and we may have missed the
3✔
1929
        // ActiveLinkEvent. Check if the link exists.
3✔
1930
        link := p.fetchLinkFromKeyAndCid(cid)
3✔
1931
        if link != nil {
6✔
1932
                return link
3✔
1933
        }
3✔
1934

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

1949
                        chanPoint := event.ChannelPoint
3✔
1950

3✔
1951
                        // Check whether the retrieved chanPoint matches the target
3✔
1952
                        // channel id.
3✔
1953
                        if !cid.IsChanPoint(chanPoint) {
3✔
1954
                                continue
×
1955
                        }
1956

1957
                        // The link shouldn't be nil as we received an
1958
                        // ActiveLinkEvent. If it is nil, we return nil and the
1959
                        // calling function should catch it.
1960
                        return p.fetchLinkFromKeyAndCid(cid)
3✔
1961

1962
                case <-p.cg.Done():
3✔
1963
                        return nil
3✔
1964
                }
1965
        }
1966
}
1967

1968
// newChanMsgStream is used to create a msgStream between the peer and
1969
// particular channel link in the htlcswitch. We utilize additional
1970
// synchronization with the fundingManager to ensure we don't attempt to
1971
// dispatch a message to a channel before it is fully active. A reference to the
1972
// channel this stream forwards to is held in scope to prevent unnecessary
1973
// lookups.
1974
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
3✔
1975
        var chanLink htlcswitch.ChannelUpdateHandler
3✔
1976

3✔
1977
        apply := func(msg lnwire.Message) {
6✔
1978
                // This check is fine because if the link no longer exists, it will
3✔
1979
                // be removed from the activeChannels map and subsequent messages
3✔
1980
                // shouldn't reach the chan msg stream.
3✔
1981
                if chanLink == nil {
6✔
1982
                        chanLink = waitUntilLinkActive(p, cid)
3✔
1983

3✔
1984
                        // If the link is still not active and the calling function
3✔
1985
                        // errored out, just return.
3✔
1986
                        if chanLink == nil {
6✔
1987
                                p.log.Warnf("Link=%v is not active", cid)
3✔
1988
                                return
3✔
1989
                        }
3✔
1990
                }
1991

1992
                // In order to avoid unnecessarily delivering message
1993
                // as the peer is exiting, we'll check quickly to see
1994
                // if we need to exit.
1995
                select {
3✔
1996
                case <-p.cg.Done():
×
1997
                        return
×
1998
                default:
3✔
1999
                }
2000

2001
                chanLink.HandleChannelUpdate(msg)
3✔
2002
        }
2003

2004
        return newMsgStream(p,
3✔
2005
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
3✔
2006
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
3✔
2007
                msgStreamSize,
3✔
2008
                apply,
3✔
2009
        )
3✔
2010
}
2011

2012
// newDiscMsgStream is used to setup a msgStream between the peer and the
2013
// authenticated gossiper. This stream should be used to forward all remote
2014
// channel announcements.
2015
func newDiscMsgStream(p *Brontide) *msgStream {
6✔
2016
        apply := func(msg lnwire.Message) {
9✔
2017
                // TODO(elle): thread contexts through the peer system properly
3✔
2018
                // so that a parent context can be passed in here.
3✔
2019
                ctx := context.TODO()
3✔
2020

3✔
2021
                // Processing here means we send it to the gossiper which then
3✔
2022
                // decides whether this message is processed immediately or
3✔
2023
                // waits for dependent messages to be processed. It can also
3✔
2024
                // happen that the message is not processed at all if it is
3✔
2025
                // premature and the LRU cache fills up and the message is
3✔
2026
                // deleted.
3✔
2027
                p.log.Debugf("Processing remote msg %T", msg)
3✔
2028

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

2039
        return newMsgStream(
6✔
2040
                p,
6✔
2041
                "Update stream for gossiper created",
6✔
2042
                "Update stream for gossiper exited",
6✔
2043
                msgStreamSize,
6✔
2044
                apply,
6✔
2045
        )
6✔
2046
}
2047

2048
// readHandler is responsible for reading messages off the wire in series, then
2049
// properly dispatching the handling of the message to the proper subsystem.
2050
//
2051
// NOTE: This method MUST be run as a goroutine.
2052
func (p *Brontide) readHandler() {
6✔
2053
        defer p.cg.WgDone()
6✔
2054

6✔
2055
        // We'll stop the timer after a new messages is received, and also
6✔
2056
        // reset it after we process the next message.
6✔
2057
        idleTimer := time.AfterFunc(idleTimeout, func() {
6✔
2058
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
2059
                        p, idleTimeout)
×
2060
                p.Disconnect(err)
×
2061
        })
×
2062

2063
        // Initialize our negotiated gossip sync method before reading messages
2064
        // off the wire. When using gossip queries, this ensures a gossip
2065
        // syncer is active by the time query messages arrive.
2066
        //
2067
        // TODO(conner): have peer store gossip syncer directly and bypass
2068
        // gossiper?
2069
        p.initGossipSync()
6✔
2070

6✔
2071
        discStream := newDiscMsgStream(p)
6✔
2072
        discStream.Start()
6✔
2073
        defer discStream.Stop()
6✔
2074
out:
6✔
2075
        for atomic.LoadInt32(&p.disconnect) == 0 {
13✔
2076
                nextMsg, err := p.readNextMessage()
7✔
2077
                if !idleTimer.Stop() {
10✔
2078
                        select {
3✔
2079
                        case <-idleTimer.C:
×
2080
                        default:
3✔
2081
                        }
2082
                }
2083
                if err != nil {
7✔
2084
                        p.log.Infof("unable to read message from peer: %v", err)
3✔
2085

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

2100
                        // If they sent us an address type that we don't yet
2101
                        // know of, then this isn't a wire error, so we'll
2102
                        // simply continue parsing the remainder of their
2103
                        // messages.
2104
                        case *lnwire.ErrUnknownAddrType:
×
2105
                                p.storeError(e)
×
2106
                                idleTimer.Reset(idleTimeout)
×
2107
                                continue
×
2108

2109
                        // If the NodeAnnouncement has an invalid alias, then
2110
                        // we'll log that error above and continue so we can
2111
                        // continue to read messages from the peer. We do not
2112
                        // store this error because it is of little debugging
2113
                        // value.
2114
                        case *lnwire.ErrInvalidNodeAlias:
×
2115
                                idleTimer.Reset(idleTimeout)
×
2116
                                continue
×
2117

2118
                        // If the error we encountered wasn't just a message we
2119
                        // didn't recognize, then we'll stop all processing as
2120
                        // this is a fatal error.
2121
                        default:
3✔
2122
                                break out
3✔
2123
                        }
2124
                }
2125

2126
                // If a message router is active, then we'll try to have it
2127
                // handle this message. If it can, then we're able to skip the
2128
                // rest of the message handling logic.
2129
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
8✔
2130
                        return r.RouteMsg(msgmux.PeerMsg{
4✔
2131
                                PeerPub: *p.IdentityKey(),
4✔
2132
                                Message: nextMsg,
4✔
2133
                        })
4✔
2134
                })
4✔
2135

2136
                // No error occurred, and the message was handled by the
2137
                // router.
2138
                if err == nil {
7✔
2139
                        continue
3✔
2140
                }
2141

2142
                var (
4✔
2143
                        targetChan   lnwire.ChannelID
4✔
2144
                        isLinkUpdate bool
4✔
2145
                )
4✔
2146

4✔
2147
                switch msg := nextMsg.(type) {
4✔
2148
                case *lnwire.Pong:
×
2149
                        // When we receive a Pong message in response to our
×
2150
                        // last ping message, we send it to the pingManager
×
2151
                        p.pingManager.ReceivedPong(msg)
×
2152

2153
                case *lnwire.Ping:
×
2154
                        // First, we'll store their latest ping payload within
×
2155
                        // the relevant atomic variable.
×
2156
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
2157

×
2158
                        // Next, we'll send over the amount of specified pong
×
2159
                        // bytes.
×
2160
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
×
2161
                        p.queueMsg(pong, nil)
×
2162

2163
                case *lnwire.OpenChannel,
2164
                        *lnwire.AcceptChannel,
2165
                        *lnwire.FundingCreated,
2166
                        *lnwire.FundingSigned,
2167
                        *lnwire.ChannelReady:
3✔
2168

3✔
2169
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2170

2171
                case *lnwire.Shutdown:
3✔
2172
                        select {
3✔
2173
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
2174
                        case <-p.cg.Done():
×
2175
                                break out
×
2176
                        }
2177
                case *lnwire.ClosingSigned:
3✔
2178
                        select {
3✔
2179
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
2180
                        case <-p.cg.Done():
×
2181
                                break out
×
2182
                        }
2183

2184
                case *lnwire.Warning:
×
2185
                        targetChan = msg.ChanID
×
2186
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2187

2188
                case *lnwire.Error:
3✔
2189
                        targetChan = msg.ChanID
3✔
2190
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
3✔
2191

2192
                case *lnwire.ChannelReestablish:
3✔
2193
                        targetChan = msg.ChanID
3✔
2194
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2195

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

2211
                // For messages that implement the LinkUpdater interface, we
2212
                // will consider them as link updates and send them to
2213
                // chanStream. These messages will be queued inside chanStream
2214
                // if the channel is not active yet.
2215
                case lnwire.LinkUpdater:
3✔
2216
                        targetChan = msg.TargetChanID()
3✔
2217
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2218

3✔
2219
                        // Log an error if we don't have this channel. This
3✔
2220
                        // means the peer has sent us a message with unknown
3✔
2221
                        // channel ID.
3✔
2222
                        if !isLinkUpdate {
6✔
2223
                                p.log.Errorf("Unknown channel ID: %v found "+
3✔
2224
                                        "in received msg=%s", targetChan,
3✔
2225
                                        nextMsg.MsgType())
3✔
2226
                        }
3✔
2227

2228
                case *lnwire.ChannelUpdate1,
2229
                        *lnwire.ChannelAnnouncement1,
2230
                        *lnwire.NodeAnnouncement,
2231
                        *lnwire.AnnounceSignatures1,
2232
                        *lnwire.GossipTimestampRange,
2233
                        *lnwire.QueryShortChanIDs,
2234
                        *lnwire.QueryChannelRange,
2235
                        *lnwire.ReplyChannelRange,
2236
                        *lnwire.ReplyShortChanIDsEnd:
3✔
2237

3✔
2238
                        discStream.AddMsg(msg)
3✔
2239

2240
                case *lnwire.Custom:
4✔
2241
                        err := p.handleCustomMessage(msg)
4✔
2242
                        if err != nil {
4✔
2243
                                p.storeError(err)
×
2244
                                p.log.Errorf("%v", err)
×
2245
                        }
×
2246

2247
                default:
×
2248
                        // If the message we received is unknown to us, store
×
2249
                        // the type to track the failure.
×
2250
                        err := fmt.Errorf("unknown message type %v received",
×
2251
                                uint16(msg.MsgType()))
×
2252
                        p.storeError(err)
×
2253

×
2254
                        p.log.Errorf("%v", err)
×
2255
                }
2256

2257
                if isLinkUpdate {
7✔
2258
                        // If this is a channel update, then we need to feed it
3✔
2259
                        // into the channel's in-order message stream.
3✔
2260
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
3✔
2261
                }
3✔
2262

2263
                idleTimer.Reset(idleTimeout)
4✔
2264
        }
2265

2266
        p.Disconnect(errors.New("read handler closed"))
3✔
2267

3✔
2268
        p.log.Trace("readHandler for peer done")
3✔
2269
}
2270

2271
// handleCustomMessage handles the given custom message if a handler is
2272
// registered.
2273
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
4✔
2274
        if p.cfg.HandleCustomMessage == nil {
4✔
2275
                return fmt.Errorf("no custom message handler for "+
×
2276
                        "message type %v", uint16(msg.MsgType()))
×
2277
        }
×
2278

2279
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
4✔
2280
}
2281

2282
// isLoadedFromDisk returns true if the provided channel ID is loaded from
2283
// disk.
2284
//
2285
// NOTE: only returns true for pending channels.
2286
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
3✔
2287
        // If this is a newly added channel, no need to reestablish.
3✔
2288
        _, added := p.addedChannels.Load(chanID)
3✔
2289
        if added {
6✔
2290
                return false
3✔
2291
        }
3✔
2292

2293
        // Return false if the channel is unknown.
2294
        channel, ok := p.activeChannels.Load(chanID)
3✔
2295
        if !ok {
3✔
2296
                return false
×
2297
        }
×
2298

2299
        // During startup, we will use a nil value to mark a pending channel
2300
        // that's loaded from disk.
2301
        return channel == nil
3✔
2302
}
2303

2304
// isActiveChannel returns true if the provided channel id is active, otherwise
2305
// returns false.
2306
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
11✔
2307
        // The channel would be nil if,
11✔
2308
        // - the channel doesn't exist, or,
11✔
2309
        // - the channel exists, but is pending. In this case, we don't
11✔
2310
        //   consider this channel active.
11✔
2311
        channel, _ := p.activeChannels.Load(chanID)
11✔
2312

11✔
2313
        return channel != nil
11✔
2314
}
11✔
2315

2316
// isPendingChannel returns true if the provided channel ID is pending, and
2317
// returns false if the channel is active or unknown.
2318
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
9✔
2319
        // Return false if the channel is unknown.
9✔
2320
        channel, ok := p.activeChannels.Load(chanID)
9✔
2321
        if !ok {
15✔
2322
                return false
6✔
2323
        }
6✔
2324

2325
        return channel == nil
6✔
2326
}
2327

2328
// hasChannel returns true if the peer has a pending/active channel specified
2329
// by the channel ID.
2330
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
3✔
2331
        _, ok := p.activeChannels.Load(chanID)
3✔
2332
        return ok
3✔
2333
}
3✔
2334

2335
// storeError stores an error in our peer's buffer of recent errors with the
2336
// current timestamp. Errors are only stored if we have at least one active
2337
// channel with the peer to mitigate a dos vector where a peer costlessly
2338
// connects to us and spams us with errors.
2339
func (p *Brontide) storeError(err error) {
3✔
2340
        var haveChannels bool
3✔
2341

3✔
2342
        p.activeChannels.Range(func(_ lnwire.ChannelID,
3✔
2343
                channel *lnwallet.LightningChannel) bool {
6✔
2344

3✔
2345
                // Pending channels will be nil in the activeChannels map.
3✔
2346
                if channel == nil {
6✔
2347
                        // Return true to continue the iteration.
3✔
2348
                        return true
3✔
2349
                }
3✔
2350

2351
                haveChannels = true
3✔
2352

3✔
2353
                // Return false to break the iteration.
3✔
2354
                return false
3✔
2355
        })
2356

2357
        // If we do not have any active channels with the peer, we do not store
2358
        // errors as a dos mitigation.
2359
        if !haveChannels {
6✔
2360
                p.log.Trace("no channels with peer, not storing err")
3✔
2361
                return
3✔
2362
        }
3✔
2363

2364
        p.cfg.ErrorBuffer.Add(
3✔
2365
                &TimestampedError{Timestamp: time.Now(), Error: err},
3✔
2366
        )
3✔
2367
}
2368

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

3✔
2378
        if errMsg, ok := msg.(*lnwire.Error); ok {
6✔
2379
                p.storeError(errMsg)
3✔
2380
        }
3✔
2381

2382
        switch {
3✔
2383
        // Connection wide messages should be forwarded to all channel links
2384
        // with this peer.
2385
        case chanID == lnwire.ConnectionWideID:
×
2386
                for _, chanStream := range p.activeMsgStreams {
×
2387
                        chanStream.AddMsg(msg)
×
2388
                }
×
2389

2390
                return false
×
2391

2392
        // If the channel ID for the message corresponds to a pending channel,
2393
        // then the funding manager will handle it.
2394
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
3✔
2395
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2396
                return false
3✔
2397

2398
        // If not we hand the message to the channel link for this channel.
2399
        case p.isActiveChannel(chanID):
3✔
2400
                return true
3✔
2401

2402
        default:
3✔
2403
                return false
3✔
2404
        }
2405
}
2406

2407
// messageSummary returns a human-readable string that summarizes a
2408
// incoming/outgoing message. Not all messages will have a summary, only those
2409
// which have additional data that can be informative at a glance.
2410
func messageSummary(msg lnwire.Message) string {
3✔
2411
        switch msg := msg.(type) {
3✔
2412
        case *lnwire.Init:
3✔
2413
                // No summary.
3✔
2414
                return ""
3✔
2415

2416
        case *lnwire.OpenChannel:
3✔
2417
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
3✔
2418
                        "push_amt=%v, reserve=%v, flags=%v",
3✔
2419
                        msg.PendingChannelID[:], msg.ChainHash,
3✔
2420
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
3✔
2421
                        msg.ChannelReserve, msg.ChannelFlags)
3✔
2422

2423
        case *lnwire.AcceptChannel:
3✔
2424
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
3✔
2425
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
3✔
2426
                        msg.MinAcceptDepth)
3✔
2427

2428
        case *lnwire.FundingCreated:
3✔
2429
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
3✔
2430
                        msg.PendingChannelID[:], msg.FundingPoint)
3✔
2431

2432
        case *lnwire.FundingSigned:
3✔
2433
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
3✔
2434

2435
        case *lnwire.ChannelReady:
3✔
2436
                return fmt.Sprintf("chan_id=%v, next_point=%x",
3✔
2437
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
3✔
2438

2439
        case *lnwire.Shutdown:
3✔
2440
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
3✔
2441
                        msg.Address[:])
3✔
2442

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

2447
        case *lnwire.ClosingSig:
3✔
2448
                return fmt.Sprintf("chan_id=%v", msg.ChannelID)
3✔
2449

2450
        case *lnwire.ClosingSigned:
3✔
2451
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
3✔
2452
                        msg.FeeSatoshis)
3✔
2453

2454
        case *lnwire.UpdateAddHTLC:
3✔
2455
                var blindingPoint []byte
3✔
2456
                msg.BlindingPoint.WhenSome(
3✔
2457
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
3✔
2458
                                *btcec.PublicKey]) {
6✔
2459

3✔
2460
                                blindingPoint = b.Val.SerializeCompressed()
3✔
2461
                        },
3✔
2462
                )
2463

2464
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
3✔
2465
                        "hash=%x, blinding_point=%x, custom_records=%v",
3✔
2466
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
3✔
2467
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
3✔
2468

2469
        case *lnwire.UpdateFailHTLC:
3✔
2470
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
3✔
2471
                        msg.ID, msg.Reason)
3✔
2472

2473
        case *lnwire.UpdateFulfillHTLC:
3✔
2474
                return fmt.Sprintf("chan_id=%v, id=%v, preimage=%x, "+
3✔
2475
                        "custom_records=%v", msg.ChanID, msg.ID,
3✔
2476
                        msg.PaymentPreimage[:], msg.CustomRecords)
3✔
2477

2478
        case *lnwire.CommitSig:
3✔
2479
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
3✔
2480
                        len(msg.HtlcSigs))
3✔
2481

2482
        case *lnwire.RevokeAndAck:
3✔
2483
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
3✔
2484
                        msg.ChanID, msg.Revocation[:],
3✔
2485
                        msg.NextRevocationKey.SerializeCompressed())
3✔
2486

2487
        case *lnwire.UpdateFailMalformedHTLC:
3✔
2488
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
3✔
2489
                        msg.ChanID, msg.ID, msg.FailureCode)
3✔
2490

2491
        case *lnwire.Warning:
×
2492
                return fmt.Sprintf("%v", msg.Warning())
×
2493

2494
        case *lnwire.Error:
3✔
2495
                return fmt.Sprintf("%v", msg.Error())
3✔
2496

2497
        case *lnwire.AnnounceSignatures1:
3✔
2498
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
3✔
2499
                        msg.ShortChannelID.ToUint64())
3✔
2500

2501
        case *lnwire.ChannelAnnouncement1:
3✔
2502
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
3✔
2503
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
3✔
2504

2505
        case *lnwire.ChannelUpdate1:
3✔
2506
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
3✔
2507
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
3✔
2508
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
3✔
2509
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
3✔
2510

2511
        case *lnwire.NodeAnnouncement:
3✔
2512
                return fmt.Sprintf("node=%x, update_time=%v",
3✔
2513
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
3✔
2514

2515
        case *lnwire.Ping:
×
2516
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
2517

2518
        case *lnwire.Pong:
×
2519
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
×
2520

2521
        case *lnwire.UpdateFee:
×
2522
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2523
                        msg.ChanID, int64(msg.FeePerKw))
×
2524

2525
        case *lnwire.ChannelReestablish:
3✔
2526
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
3✔
2527
                        "remote_tail_height=%v", msg.ChanID,
3✔
2528
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
3✔
2529

2530
        case *lnwire.ReplyShortChanIDsEnd:
3✔
2531
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
3✔
2532
                        msg.Complete)
3✔
2533

2534
        case *lnwire.ReplyChannelRange:
3✔
2535
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
3✔
2536
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
3✔
2537
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
3✔
2538
                        msg.EncodingType)
3✔
2539

2540
        case *lnwire.QueryShortChanIDs:
3✔
2541
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
3✔
2542
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
3✔
2543

2544
        case *lnwire.QueryChannelRange:
3✔
2545
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
3✔
2546
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
3✔
2547
                        msg.LastBlockHeight())
3✔
2548

2549
        case *lnwire.GossipTimestampRange:
3✔
2550
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
3✔
2551
                        "stamp_range=%v", msg.ChainHash,
3✔
2552
                        time.Unix(int64(msg.FirstTimestamp), 0),
3✔
2553
                        msg.TimestampRange)
3✔
2554

2555
        case *lnwire.Stfu:
3✔
2556
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
3✔
2557
                        msg.Initiator)
3✔
2558

2559
        case *lnwire.Custom:
3✔
2560
                return fmt.Sprintf("type=%d", msg.Type)
3✔
2561
        }
2562

2563
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2564
}
2565

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

2577
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
23✔
2578
                // Debug summary of message.
3✔
2579
                summary := messageSummary(msg)
3✔
2580
                if len(summary) > 0 {
6✔
2581
                        summary = "(" + summary + ")"
3✔
2582
                }
3✔
2583

2584
                preposition := "to"
3✔
2585
                if read {
6✔
2586
                        preposition = "from"
3✔
2587
                }
3✔
2588

2589
                var msgType string
3✔
2590
                if msg.MsgType() < lnwire.CustomTypeStart {
6✔
2591
                        msgType = msg.MsgType().String()
3✔
2592
                } else {
6✔
2593
                        msgType = "custom"
3✔
2594
                }
3✔
2595

2596
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
3✔
2597
                        msgType, summary, preposition, p)
3✔
2598
        }))
2599

2600
        prefix := "readMessage from peer"
20✔
2601
        if !read {
36✔
2602
                prefix = "writeMessage to peer"
16✔
2603
        }
16✔
2604

2605
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
20✔
2606
}
2607

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

2625
        noiseConn := p.cfg.Conn
16✔
2626

16✔
2627
        flushMsg := func() error {
32✔
2628
                // Ensure the write deadline is set before we attempt to send
16✔
2629
                // the message.
16✔
2630
                writeDeadline := time.Now().Add(
16✔
2631
                        p.scaleTimeout(writeMessageTimeout),
16✔
2632
                )
16✔
2633
                err := noiseConn.SetWriteDeadline(writeDeadline)
16✔
2634
                if err != nil {
16✔
2635
                        return err
×
2636
                }
×
2637

2638
                // Flush the pending message to the wire. If an error is
2639
                // encountered, e.g. write timeout, the number of bytes written
2640
                // so far will be returned.
2641
                n, err := noiseConn.Flush()
16✔
2642

16✔
2643
                // Record the number of bytes written on the wire, if any.
16✔
2644
                if n > 0 {
19✔
2645
                        atomic.AddUint64(&p.bytesSent, uint64(n))
3✔
2646
                }
3✔
2647

2648
                return err
16✔
2649
        }
2650

2651
        // If the current message has already been serialized, encrypted, and
2652
        // buffered on the underlying connection we will skip straight to
2653
        // flushing it to the wire.
2654
        if msg == nil {
16✔
2655
                return flushMsg()
×
2656
        }
×
2657

2658
        // Otherwise, this is a new message. We'll acquire a write buffer to
2659
        // serialize the message and buffer the ciphertext on the connection.
2660
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
32✔
2661
                // Using a buffer allocated by the write pool, encode the
16✔
2662
                // message directly into the buffer.
16✔
2663
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
16✔
2664
                if writeErr != nil {
16✔
2665
                        return writeErr
×
2666
                }
×
2667

2668
                // Finally, write the message itself in a single swoop. This
2669
                // will buffer the ciphertext on the underlying connection. We
2670
                // will defer flushing the message until the write pool has been
2671
                // released.
2672
                return noiseConn.WriteMessage(buf.Bytes())
16✔
2673
        })
2674
        if err != nil {
16✔
2675
                return err
×
2676
        }
×
2677

2678
        return flushMsg()
16✔
2679
}
2680

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

2696
        var exitErr error
6✔
2697

6✔
2698
out:
6✔
2699
        for {
16✔
2700
                select {
10✔
2701
                case outMsg := <-p.sendQueue:
7✔
2702
                        // Record the time at which we first attempt to send the
7✔
2703
                        // message.
7✔
2704
                        startTime := time.Now()
7✔
2705

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

×
2718
                                // If we received a timeout error, this implies
×
2719
                                // that the message was buffered on the
×
2720
                                // connection successfully and that a flush was
×
2721
                                // attempted. We'll set the message to nil so
×
2722
                                // that on a subsequent pass we only try to
×
2723
                                // flush the buffered message, and forgo
×
2724
                                // reserializing or reencrypting it.
×
2725
                                outMsg.msg = nil
×
2726

×
2727
                                goto retry
×
2728
                        }
2729

2730
                        // The write succeeded, reset the idle timer to prevent
2731
                        // us from disconnecting the peer.
2732
                        if !idleTimer.Stop() {
7✔
2733
                                select {
×
2734
                                case <-idleTimer.C:
×
2735
                                default:
×
2736
                                }
2737
                        }
2738
                        idleTimer.Reset(idleTimeout)
7✔
2739

7✔
2740
                        // If the peer requested a synchronous write, respond
7✔
2741
                        // with the error.
7✔
2742
                        if outMsg.errChan != nil {
11✔
2743
                                outMsg.errChan <- err
4✔
2744
                        }
4✔
2745

2746
                        if err != nil {
7✔
2747
                                exitErr = fmt.Errorf("unable to write "+
×
2748
                                        "message: %v", err)
×
2749
                                break out
×
2750
                        }
2751

2752
                case <-p.cg.Done():
3✔
2753
                        exitErr = lnpeer.ErrPeerExiting
3✔
2754
                        break out
3✔
2755
                }
2756
        }
2757

2758
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2759
        // disconnect.
2760
        p.cg.WgDone()
3✔
2761

3✔
2762
        p.Disconnect(exitErr)
3✔
2763

3✔
2764
        p.log.Trace("writeHandler for peer done")
3✔
2765
}
2766

2767
// queueHandler is responsible for accepting messages from outside subsystems
2768
// to be eventually sent out on the wire by the writeHandler.
2769
//
2770
// NOTE: This method MUST be run as a goroutine.
2771
func (p *Brontide) queueHandler() {
6✔
2772
        defer p.cg.WgDone()
6✔
2773

6✔
2774
        // priorityMsgs holds an in order list of messages deemed high-priority
6✔
2775
        // to be added to the sendQueue. This predominately includes messages
6✔
2776
        // from the funding manager and htlcswitch.
6✔
2777
        priorityMsgs := list.New()
6✔
2778

6✔
2779
        // lazyMsgs holds an in order list of messages deemed low-priority to be
6✔
2780
        // added to the sendQueue only after all high-priority messages have
6✔
2781
        // been queued. This predominately includes messages from the gossiper.
6✔
2782
        lazyMsgs := list.New()
6✔
2783

6✔
2784
        for {
20✔
2785
                // Examine the front of the priority queue, if it is empty check
14✔
2786
                // the low priority queue.
14✔
2787
                elem := priorityMsgs.Front()
14✔
2788
                if elem == nil {
25✔
2789
                        elem = lazyMsgs.Front()
11✔
2790
                }
11✔
2791

2792
                if elem != nil {
21✔
2793
                        front := elem.Value.(outgoingMsg)
7✔
2794

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

2834
// PingTime returns the estimated ping time to the peer in microseconds.
2835
func (p *Brontide) PingTime() int64 {
3✔
2836
        return p.pingManager.GetPingTimeMicroSeconds()
3✔
2837
}
3✔
2838

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

2846
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2847
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2848
// queue or failed to write, and nil otherwise.
2849
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
4✔
2850
        p.queue(false, msg, errChan)
4✔
2851
}
4✔
2852

2853
// queue sends a given message to the queueHandler using the passed priority. If
2854
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2855
// failed to write, and nil otherwise.
2856
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2857
        errChan chan error) {
29✔
2858

29✔
2859
        select {
29✔
2860
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
28✔
2861
        case <-p.cg.Done():
×
2862
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
×
2863
                        spew.Sdump(msg))
×
2864
                if errChan != nil {
×
2865
                        errChan <- lnpeer.ErrPeerExiting
×
2866
                }
×
2867
        }
2868
}
2869

2870
// ChannelSnapshots returns a slice of channel snapshots detailing all
2871
// currently active channels maintained with the remote peer.
2872
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
3✔
2873
        snapshots := make(
3✔
2874
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
3✔
2875
        )
3✔
2876

3✔
2877
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2878
                activeChan *lnwallet.LightningChannel) error {
6✔
2879

3✔
2880
                // If the activeChan is nil, then we skip it as the channel is
3✔
2881
                // pending.
3✔
2882
                if activeChan == nil {
6✔
2883
                        return nil
3✔
2884
                }
3✔
2885

2886
                // We'll only return a snapshot for channels that are
2887
                // *immediately* available for routing payments over.
2888
                if activeChan.RemoteNextRevocation() == nil {
6✔
2889
                        return nil
3✔
2890
                }
3✔
2891

2892
                snapshot := activeChan.StateSnapshot()
3✔
2893
                snapshots = append(snapshots, snapshot)
3✔
2894

3✔
2895
                return nil
3✔
2896
        })
2897

2898
        return snapshots
3✔
2899
}
2900

2901
// genDeliveryScript returns a new script to be used to send our funds to in
2902
// the case of a cooperative channel close negotiation.
2903
func (p *Brontide) genDeliveryScript() ([]byte, error) {
9✔
2904
        // We'll send a normal p2wkh address unless we've negotiated the
9✔
2905
        // shutdown-any-segwit feature.
9✔
2906
        addrType := lnwallet.WitnessPubKey
9✔
2907
        if p.taprootShutdownAllowed() {
12✔
2908
                addrType = lnwallet.TaprootPubkey
3✔
2909
        }
3✔
2910

2911
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
9✔
2912
                addrType, false, lnwallet.DefaultAccountName,
9✔
2913
        )
9✔
2914
        if err != nil {
9✔
2915
                return nil, err
×
2916
        }
×
2917
        p.log.Infof("Delivery addr for channel close: %v",
9✔
2918
                deliveryAddr)
9✔
2919

9✔
2920
        return txscript.PayToAddrScript(deliveryAddr)
9✔
2921
}
2922

2923
// channelManager is goroutine dedicated to handling all requests/signals
2924
// pertaining to the opening, cooperative closing, and force closing of all
2925
// channels maintained with the remote peer.
2926
//
2927
// NOTE: This method MUST be run as a goroutine.
2928
func (p *Brontide) channelManager() {
20✔
2929
        defer p.cg.WgDone()
20✔
2930

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

20✔
2936
out:
20✔
2937
        for {
61✔
2938
                select {
41✔
2939
                // A new pending channel has arrived which means we are about
2940
                // to complete a funding workflow and is waiting for the final
2941
                // `ChannelReady` messages to be exchanged. We will add this
2942
                // channel to the `activeChannels` with a nil value to indicate
2943
                // this is a pending channel.
2944
                case req := <-p.newPendingChannel:
4✔
2945
                        p.handleNewPendingChannel(req)
4✔
2946

2947
                // A new channel has arrived which means we've just completed a
2948
                // funding workflow. We'll initialize the necessary local
2949
                // state, and notify the htlc switch of a new link.
2950
                case req := <-p.newActiveChannel:
3✔
2951
                        p.handleNewActiveChannel(req)
3✔
2952

2953
                // The funding flow for a pending channel is failed, we will
2954
                // remove it from Brontide.
2955
                case req := <-p.removePendingChannel:
4✔
2956
                        p.handleRemovePendingChannel(req)
4✔
2957

2958
                // We've just received a local request to close an active
2959
                // channel. It will either kick of a cooperative channel
2960
                // closure negotiation, or be a notification of a breached
2961
                // contract that should be abandoned.
2962
                case req := <-p.localCloseChanReqs:
10✔
2963
                        p.handleLocalCloseReq(req)
10✔
2964

2965
                // We've received a link failure from a link that was added to
2966
                // the switch. This will initiate the teardown of the link, and
2967
                // initiate any on-chain closures if necessary.
2968
                case failure := <-p.linkFailures:
3✔
2969
                        p.handleLinkFailure(failure)
3✔
2970

2971
                // We've received a new cooperative channel closure related
2972
                // message from the remote peer, we'll use this message to
2973
                // advance the chan closer state machine.
2974
                case closeMsg := <-p.chanCloseMsgs:
16✔
2975
                        p.handleCloseMsg(closeMsg)
16✔
2976

2977
                // The channel reannounce delay has elapsed, broadcast the
2978
                // reenabled channel updates to the network. This should only
2979
                // fire once, so we set the reenableTimeout channel to nil to
2980
                // mark it for garbage collection. If the peer is torn down
2981
                // before firing, reenabling will not be attempted.
2982
                // TODO(conner): consolidate reenables timers inside chan status
2983
                // manager
2984
                case <-reenableTimeout:
3✔
2985
                        p.reenableActiveChannels()
3✔
2986

3✔
2987
                        // Since this channel will never fire again during the
3✔
2988
                        // lifecycle of the peer, we nil the channel to mark it
3✔
2989
                        // eligible for garbage collection, and make this
3✔
2990
                        // explicitly ineligible to receive in future calls to
3✔
2991
                        // select. This also shaves a few CPU cycles since the
3✔
2992
                        // select will ignore this case entirely.
3✔
2993
                        reenableTimeout = nil
3✔
2994

3✔
2995
                        // Once the reenabling is attempted, we also cancel the
3✔
2996
                        // channel event subscription to free up the overflow
3✔
2997
                        // queue used in channel notifier.
3✔
2998
                        //
3✔
2999
                        // NOTE: channelEventClient will be nil if the
3✔
3000
                        // reenableTimeout is greater than 1 minute.
3✔
3001
                        if p.channelEventClient != nil {
6✔
3002
                                p.channelEventClient.Cancel()
3✔
3003
                        }
3✔
3004

3005
                case <-p.cg.Done():
3✔
3006
                        // As, we've been signalled to exit, we'll reset all
3✔
3007
                        // our active channel back to their default state.
3✔
3008
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
3009
                                lc *lnwallet.LightningChannel) error {
6✔
3010

3✔
3011
                                // Exit if the channel is nil as it's a pending
3✔
3012
                                // channel.
3✔
3013
                                if lc == nil {
6✔
3014
                                        return nil
3✔
3015
                                }
3✔
3016

3017
                                lc.ResetState()
3✔
3018

3✔
3019
                                return nil
3✔
3020
                        })
3021

3022
                        break out
3✔
3023
                }
3024
        }
3025
}
3026

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

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

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

3✔
3045
                switch {
3✔
3046
                // No error occurred, continue to request the next channel.
3047
                case err == nil:
3✔
3048
                        continue
3✔
3049

3050
                // Cannot auto enable a manually disabled channel so we do
3051
                // nothing but proceed to the next channel.
3052
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
3✔
3053
                        p.log.Debugf("Channel(%v) was manually disabled, "+
3✔
3054
                                "ignoring automatic enable request", chanPoint)
3✔
3055

3✔
3056
                        continue
3✔
3057

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

×
3075
                                continue
×
3076
                        }
3077

3078
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
3079
                                "ChanStatusManager reported inactive, retrying")
×
3080

×
3081
                        // Add the channel to the retry map.
×
3082
                        retryChans[chanPoint] = struct{}{}
×
3083
                }
3084
        }
3085

3086
        // Retry the channels if we have any.
3087
        if len(retryChans) != 0 {
3✔
3088
                p.retryRequestEnable(retryChans)
×
3089
        }
×
3090
}
3091

3092
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
3093
// for the target channel ID. If the channel isn't active an error is returned.
3094
// Otherwise, either an existing state machine will be returned, or a new one
3095
// will be created.
3096
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
3097
        *chanCloserFsm, error) {
16✔
3098

16✔
3099
        chanCloser, found := p.activeChanCloses.Load(chanID)
16✔
3100
        if found {
29✔
3101
                // An entry will only be found if the closer has already been
13✔
3102
                // created for a non-pending channel or for a channel that had
13✔
3103
                // previously started the shutdown process but the connection
13✔
3104
                // was restarted.
13✔
3105
                return &chanCloser, nil
13✔
3106
        }
13✔
3107

3108
        // First, we'll ensure that we actually know of the target channel. If
3109
        // not, we'll ignore this message.
3110
        channel, ok := p.activeChannels.Load(chanID)
6✔
3111

6✔
3112
        // If the channel isn't in the map or the channel is nil, return
6✔
3113
        // ErrChannelNotFound as the channel is pending.
6✔
3114
        if !ok || channel == nil {
9✔
3115
                return nil, ErrChannelNotFound
3✔
3116
        }
3✔
3117

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

3137
        // In order to begin fee negotiations, we'll first compute our target
3138
        // ideal fee-per-kw.
3139
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
6✔
3140
                p.cfg.CoopCloseTargetConfs,
6✔
3141
        )
6✔
3142
        if err != nil {
6✔
3143
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3144
                return nil, fmt.Errorf("unable to estimate fee")
×
3145
        }
×
3146

3147
        addr, err := p.addrWithInternalKey(deliveryScript)
6✔
3148
        if err != nil {
6✔
3149
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3150
        }
×
3151
        negotiateChanCloser, err := p.createChanCloser(
6✔
3152
                channel, addr, feePerKw, nil, lntypes.Remote,
6✔
3153
        )
6✔
3154
        if err != nil {
6✔
3155
                p.log.Errorf("unable to create chan closer: %v", err)
×
3156
                return nil, fmt.Errorf("unable to create chan closer")
×
3157
        }
×
3158

3159
        chanCloser = makeNegotiateCloser(negotiateChanCloser)
6✔
3160

6✔
3161
        p.activeChanCloses.Store(chanID, chanCloser)
6✔
3162

6✔
3163
        return &chanCloser, nil
6✔
3164
}
3165

3166
// filterChannelsToEnable filters a list of channels to be enabled upon start.
3167
// The filtered channels are active channels that's neither private nor
3168
// pending.
3169
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
3✔
3170
        var activePublicChans []wire.OutPoint
3✔
3171

3✔
3172
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
3✔
3173
                lnChan *lnwallet.LightningChannel) bool {
6✔
3174

3✔
3175
                // If the lnChan is nil, continue as this is a pending channel.
3✔
3176
                if lnChan == nil {
5✔
3177
                        return true
2✔
3178
                }
2✔
3179

3180
                dbChan := lnChan.State()
3✔
3181
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
3182
                if !isPublic || dbChan.IsPending {
3✔
3183
                        return true
×
3184
                }
×
3185

3186
                // We'll also skip any channels added during this peer's
3187
                // lifecycle since they haven't waited out the timeout. Their
3188
                // first announcement will be enabled, and the chan status
3189
                // manager will begin monitoring them passively since they exist
3190
                // in the database.
3191
                if _, ok := p.addedChannels.Load(chanID); ok {
4✔
3192
                        return true
1✔
3193
                }
1✔
3194

3195
                activePublicChans = append(
3✔
3196
                        activePublicChans, dbChan.FundingOutpoint,
3✔
3197
                )
3✔
3198

3✔
3199
                return true
3✔
3200
        })
3201

3202
        return activePublicChans
3✔
3203
}
3204

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

×
3212
        // retryEnable is a helper closure that sends an enable request and
×
3213
        // removes the channel from the map if it's matched.
×
3214
        retryEnable := func(chanPoint wire.OutPoint) error {
×
3215
                // If this is an active channel event, check whether it's in
×
3216
                // our targeted channels map.
×
3217
                _, found := activeChans[chanPoint]
×
3218

×
3219
                // If this channel is irrelevant, return nil so the loop can
×
3220
                // jump to next iteration.
×
3221
                if !found {
×
3222
                        return nil
×
3223
                }
×
3224

3225
                // Otherwise we've just received an active signal for a channel
3226
                // that's previously failed to be enabled, we send the request
3227
                // again.
3228
                //
3229
                // We only give the channel one more shot, so we delete it from
3230
                // our map first to keep it from being attempted again.
3231
                delete(activeChans, chanPoint)
×
3232

×
3233
                // Send the request.
×
3234
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3235
                if err != nil {
×
3236
                        return fmt.Errorf("request enabling channel %v "+
×
3237
                                "failed: %w", chanPoint, err)
×
3238
                }
×
3239

3240
                return nil
×
3241
        }
3242

3243
        for {
×
3244
                // If activeChans is empty, we've done processing all the
×
3245
                // channels.
×
3246
                if len(activeChans) == 0 {
×
3247
                        p.log.Debug("Finished retry enabling channels")
×
3248
                        return
×
3249
                }
×
3250

3251
                select {
×
3252
                // A new event has been sent by the ChannelNotifier. We now
3253
                // check whether it's an active or inactive channel event.
3254
                case e := <-p.channelEventClient.Updates():
×
3255
                        // If this is an active channel event, try enable the
×
3256
                        // channel then jump to the next iteration.
×
3257
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
3258
                        if ok {
×
3259
                                chanPoint := *active.ChannelPoint
×
3260

×
3261
                                // If we received an error for this particular
×
3262
                                // channel, we log an error and won't quit as
×
3263
                                // we still want to retry other channels.
×
3264
                                if err := retryEnable(chanPoint); err != nil {
×
3265
                                        p.log.Errorf("Retry failed: %v", err)
×
3266
                                }
×
3267

3268
                                continue
×
3269
                        }
3270

3271
                        // Otherwise check for inactive link event, and jump to
3272
                        // next iteration if it's not.
3273
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3274
                        if !ok {
×
3275
                                continue
×
3276
                        }
3277

3278
                        // Found an inactive link event, if this is our
3279
                        // targeted channel, remove it from our map.
3280
                        chanPoint := *inactive.ChannelPoint
×
3281
                        _, found := activeChans[chanPoint]
×
3282
                        if !found {
×
3283
                                continue
×
3284
                        }
3285

3286
                        delete(activeChans, chanPoint)
×
3287
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3288
                                "inactive link event", chanPoint)
×
3289

3290
                case <-p.cg.Done():
×
3291
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3292
                        return
×
3293
                }
3294
        }
3295
}
3296

3297
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3298
// a suitable script to close out to. This may be nil if neither script is
3299
// set. If both scripts are set, this function will error if they do not match.
3300
func chooseDeliveryScript(upfront, requested lnwire.DeliveryAddress,
3301
        genDeliveryScript func() ([]byte, error),
3302
) (lnwire.DeliveryAddress, error) {
15✔
3303

15✔
3304
        switch {
15✔
3305
        // If no script was provided, then we'll generate a new delivery script.
3306
        case len(upfront) == 0 && len(requested) == 0:
7✔
3307
                return genDeliveryScript()
7✔
3308

3309
        // If no upfront shutdown script was provided, return the user
3310
        // requested address (which may be nil).
3311
        case len(upfront) == 0:
5✔
3312
                return requested, nil
5✔
3313

3314
        // If an upfront shutdown script was provided, and the user did not
3315
        // request a custom shutdown script, return the upfront address.
3316
        case len(requested) == 0:
5✔
3317
                return upfront, nil
5✔
3318

3319
        // If both an upfront shutdown script and a custom close script were
3320
        // provided, error if the user provided shutdown script does not match
3321
        // the upfront shutdown script (because closing out to a different
3322
        // script would violate upfront shutdown).
3323
        case !bytes.Equal(upfront, requested):
2✔
3324
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
3325

3326
        // The user requested script matches the upfront shutdown script, so we
3327
        // can return it without error.
3328
        default:
2✔
3329
                return upfront, nil
2✔
3330
        }
3331
}
3332

3333
// restartCoopClose checks whether we need to restart the cooperative close
3334
// process for a given channel.
3335
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3336
        *lnwire.Shutdown, error) {
3✔
3337

3✔
3338
        isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
3339

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

3359
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
3✔
3360

3✔
3361
        var deliveryScript []byte
3✔
3362

3✔
3363
        shutdownInfo, err := c.ShutdownInfo()
3✔
3364
        switch {
3✔
3365
        // We have previously stored the delivery script that we need to use
3366
        // in the shutdown message. Re-use this script.
3367
        case err == nil:
3✔
3368
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
6✔
3369
                        deliveryScript = info.DeliveryScript.Val
3✔
3370
                })
3✔
3371

3372
        // An error other than ErrNoShutdownInfo was returned
3373
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3374
                return nil, err
×
3375

3376
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3377
                deliveryScript = c.LocalShutdownScript
×
3378
                if len(deliveryScript) == 0 {
×
3379
                        var err error
×
3380
                        deliveryScript, err = p.genDeliveryScript()
×
3381
                        if err != nil {
×
3382
                                p.log.Errorf("unable to gen delivery script: "+
×
3383
                                        "%v", err)
×
3384

×
3385
                                return nil, fmt.Errorf("close addr unavailable")
×
3386
                        }
×
3387
                }
3388
        }
3389

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

3400
                shutdownDesc := fn.MapOption(
3✔
3401
                        newRestartShutdownInit,
3✔
3402
                )(shutdownInfo)
3✔
3403

3✔
3404
                err = p.startRbfChanCloser(
3✔
3405
                        fn.FlattenOption(shutdownDesc), lnChan.ChannelPoint(),
3✔
3406
                )
3✔
3407

3✔
3408
                return nil, err
3✔
3409
        }
3410

3411
        // Compute an ideal fee.
3412
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
3413
                p.cfg.CoopCloseTargetConfs,
×
3414
        )
×
3415
        if err != nil {
×
3416
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3417
                return nil, fmt.Errorf("unable to estimate fee")
×
3418
        }
×
3419

3420
        // Determine whether we or the peer are the initiator of the coop
3421
        // close attempt by looking at the channel's status.
3422
        closingParty := lntypes.Remote
×
3423
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3424
                closingParty = lntypes.Local
×
3425
        }
×
3426

3427
        addr, err := p.addrWithInternalKey(deliveryScript)
×
3428
        if err != nil {
×
3429
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3430
        }
×
3431
        chanCloser, err := p.createChanCloser(
×
3432
                lnChan, addr, feePerKw, nil, closingParty,
×
3433
        )
×
3434
        if err != nil {
×
3435
                p.log.Errorf("unable to create chan closer: %v", err)
×
3436
                return nil, fmt.Errorf("unable to create chan closer")
×
3437
        }
×
3438

3439
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
×
3440

×
3441
        // Create the Shutdown message.
×
3442
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3443
        if err != nil {
×
3444
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3445
                p.activeChanCloses.Delete(chanID)
×
3446
                return nil, err
×
3447
        }
×
3448

3449
        return shutdownMsg, nil
×
3450
}
3451

3452
// createChanCloser constructs a ChanCloser from the passed parameters and is
3453
// used to de-duplicate code.
3454
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3455
        deliveryScript *chancloser.DeliveryAddrWithKey,
3456
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3457
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
12✔
3458

12✔
3459
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
12✔
3460
        if err != nil {
12✔
3461
                p.log.Errorf("unable to obtain best block: %v", err)
×
3462
                return nil, fmt.Errorf("cannot obtain best block")
×
3463
        }
×
3464

3465
        // The req will only be set if we initiated the co-op closing flow.
3466
        var maxFee chainfee.SatPerKWeight
12✔
3467
        if req != nil {
21✔
3468
                maxFee = req.MaxFee
9✔
3469
        }
9✔
3470

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

3496
        return chanCloser, nil
12✔
3497
}
3498

3499
// initNegotiateChanCloser initializes the channel closer for a channel that is
3500
// using the original "negotiation" based protocol. This path is used when
3501
// we're the one initiating the channel close.
3502
//
3503
// TODO(roasbeef): can make a MsgEndpoint for existing handling logic to
3504
// further abstract.
3505
func (p *Brontide) initNegotiateChanCloser(req *htlcswitch.ChanClose,
3506
        channel *lnwallet.LightningChannel) error {
10✔
3507

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

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

3525
        addr, err := p.addrWithInternalKey(deliveryScript)
9✔
3526
        if err != nil {
9✔
3527
                return fmt.Errorf("unable to parse addr for channel "+
×
3528
                        "%v: %w", req.ChanPoint, err)
×
3529
        }
×
3530

3531
        chanCloser, err := p.createChanCloser(
9✔
3532
                channel, addr, req.TargetFeePerKw, req, lntypes.Local,
9✔
3533
        )
9✔
3534
        if err != nil {
9✔
3535
                return fmt.Errorf("unable to make chan closer: %w", err)
×
3536
        }
×
3537

3538
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
9✔
3539
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
9✔
3540

9✔
3541
        // Finally, we'll initiate the channel shutdown within the
9✔
3542
        // chanCloser, and send the shutdown message to the remote
9✔
3543
        // party to kick things off.
9✔
3544
        shutdownMsg, err := chanCloser.ShutdownChan()
9✔
3545
        if err != nil {
9✔
3546
                // As we were unable to shutdown the channel, we'll return it
×
3547
                // back to its normal state.
×
3548
                defer channel.ResetState()
×
3549

×
3550
                p.activeChanCloses.Delete(chanID)
×
3551

×
3552
                return fmt.Errorf("unable to shutdown channel: %w", err)
×
3553
        }
×
3554

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

3567
        if !link.DisableAdds(htlcswitch.Outgoing) {
9✔
3568
                p.log.Warnf("Outgoing link adds already "+
×
3569
                        "disabled: %v", link.ChanID())
×
3570
        }
×
3571

3572
        link.OnCommitOnce(htlcswitch.Outgoing, func() {
18✔
3573
                p.queueMsg(shutdownMsg, nil)
9✔
3574
        })
9✔
3575

3576
        return nil
9✔
3577
}
3578

3579
// chooseAddr returns the provided address if it is non-zero length, otherwise
3580
// None.
3581
func chooseAddr(addr lnwire.DeliveryAddress) fn.Option[lnwire.DeliveryAddress] {
3✔
3582
        if len(addr) == 0 {
6✔
3583
                return fn.None[lnwire.DeliveryAddress]()
3✔
3584
        }
3✔
3585

3586
        return fn.Some(addr)
×
3587
}
3588

3589
// observeRbfCloseUpdates observes the channel for any updates that may
3590
// indicate that a new txid has been broadcasted, or the channel fully closed
3591
// on chain.
3592
func (p *Brontide) observeRbfCloseUpdates(chanCloser *chancloser.RbfChanCloser,
3593
        closeReq *htlcswitch.ChanClose,
3594
        coopCloseStates chancloser.RbfStateSub) {
3✔
3595

3✔
3596
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3597
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3598

3✔
3599
        var (
3✔
3600
                lastTxids    lntypes.Dual[chainhash.Hash]
3✔
3601
                lastFeeRates lntypes.Dual[chainfee.SatPerVByte]
3✔
3602
        )
3✔
3603

3✔
3604
        maybeNotifyTxBroadcast := func(state chancloser.AsymmetricPeerState,
3✔
3605
                party lntypes.ChannelParty) {
6✔
3606

3✔
3607
                // First, check to see if we have an error to report to the
3✔
3608
                // caller. If so, then we''ll return that error and exit, as the
3✔
3609
                // stream will exit as well.
3✔
3610
                if closeErr, ok := state.(*chancloser.CloseErr); ok {
6✔
3611
                        // We hit an error during the last state transition, so
3✔
3612
                        // we'll extract the error then send it to the
3✔
3613
                        // user.
3✔
3614
                        err := closeErr.Err()
3✔
3615

3✔
3616
                        peerLog.Warnf("ChannelPoint(%v): encountered close "+
3✔
3617
                                "err: %v", closeReq.ChanPoint, err)
3✔
3618

3✔
3619
                        select {
3✔
3620
                        case closeReq.Err <- err:
3✔
3621
                        case <-closeReq.Ctx.Done():
×
3622
                        case <-p.cg.Done():
×
3623
                        }
3624

3625
                        return
3✔
3626
                }
3627

3628
                closePending, ok := state.(*chancloser.ClosePending)
3✔
3629

3✔
3630
                // If this isn't the close pending state, we aren't at the
3✔
3631
                // terminal state yet.
3✔
3632
                if !ok {
6✔
3633
                        return
3✔
3634
                }
3✔
3635

3636
                // Only notify if the fee rate is greater.
3637
                newFeeRate := closePending.FeeRate
3✔
3638
                lastFeeRate := lastFeeRates.GetForParty(party)
3✔
3639
                if newFeeRate <= lastFeeRate {
6✔
3640
                        peerLog.Debugf("ChannelPoint(%v): remote party made "+
3✔
3641
                                "update for fee rate %v, but we already have "+
3✔
3642
                                "a higher fee rate of %v", closeReq.ChanPoint,
3✔
3643
                                newFeeRate, lastFeeRate)
3✔
3644

3✔
3645
                        return
3✔
3646
                }
3✔
3647

3648
                feeRate := closePending.FeeRate
3✔
3649
                lastFeeRates.SetForParty(party, feeRate)
3✔
3650

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

3667
                        case <-closeReq.Ctx.Done():
×
3668
                                return
×
3669

3670
                        case <-p.cg.Done():
×
3671
                                return
×
3672
                        }
3673
                }
3674

3675
                lastTxids.SetForParty(party, closingTxid)
3✔
3676
        }
3677

3678
        peerLog.Infof("Observing RBF close updates for channel %v",
3✔
3679
                closeReq.ChanPoint)
3✔
3680

3✔
3681
        // We'll consume each new incoming state to send out the appropriate
3✔
3682
        // RPC update.
3✔
3683
        for {
6✔
3684
                select {
3✔
3685
                case newState := <-newStateChan:
3✔
3686

3✔
3687
                        switch closeState := newState.(type) {
3✔
3688
                        // Once we've reached the state of pending close, we
3689
                        // have a txid that we broadcasted.
3690
                        case *chancloser.ClosingNegotiation:
3✔
3691
                                peerState := closeState.PeerState
3✔
3692

3✔
3693
                                // Each side may have gained a new co-op close
3✔
3694
                                // tx, so we'll examine both to see if they've
3✔
3695
                                // changed.
3✔
3696
                                maybeNotifyTxBroadcast(
3✔
3697
                                        peerState.GetForParty(lntypes.Local),
3✔
3698
                                        lntypes.Local,
3✔
3699
                                )
3✔
3700
                                maybeNotifyTxBroadcast(
3✔
3701
                                        peerState.GetForParty(lntypes.Remote),
3✔
3702
                                        lntypes.Remote,
3✔
3703
                                )
3✔
3704

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

3✔
3723
                                return
3✔
3724
                        }
3725

3726
                case <-closeReq.Ctx.Done():
3✔
3727
                        return
3✔
3728

3729
                case <-p.cg.Done():
3✔
3730
                        return
3✔
3731
                }
3732
        }
3733
}
3734

3735
// chanErrorReporter is a simple implementation of the
3736
// chancloser.ErrorReporter. This is bound to a single channel by the channel
3737
// ID.
3738
type chanErrorReporter struct {
3739
        chanID lnwire.ChannelID
3740
        peer   *Brontide
3741
}
3742

3743
// newChanErrorReporter creates a new instance of the chanErrorReporter.
3744
func newChanErrorReporter(chanID lnwire.ChannelID,
3745
        peer *Brontide) *chanErrorReporter {
3✔
3746

3✔
3747
        return &chanErrorReporter{
3✔
3748
                chanID: chanID,
3✔
3749
                peer:   peer,
3✔
3750
        }
3✔
3751
}
3✔
3752

3753
// ReportError is a method that's used to report an error that occurred during
3754
// state machine execution. This is used by the RBF close state machine to
3755
// terminate the state machine and send an error to the remote peer.
3756
//
3757
// This is a part of the chancloser.ErrorReporter interface.
UNCOV
3758
func (c *chanErrorReporter) ReportError(chanErr error) {
×
UNCOV
3759
        c.peer.log.Errorf("coop close error for channel %v: %v",
×
UNCOV
3760
                c.chanID, chanErr)
×
UNCOV
3761

×
UNCOV
3762
        var errMsg []byte
×
UNCOV
3763
        if errors.Is(chanErr, chancloser.ErrInvalidStateTransition) {
×
3764
                errMsg = []byte("unexpected protocol message")
×
UNCOV
3765
        } else {
×
UNCOV
3766
                errMsg = []byte(chanErr.Error())
×
UNCOV
3767
        }
×
3768

UNCOV
3769
        err := c.peer.SendMessageLazy(false, &lnwire.Error{
×
UNCOV
3770
                ChanID: c.chanID,
×
UNCOV
3771
                Data:   errMsg,
×
UNCOV
3772
        })
×
UNCOV
3773
        if err != nil {
×
3774
                c.peer.log.Warnf("unable to send error message to peer: %v",
×
3775
                        err)
×
3776
        }
×
3777

3778
        // After we send the error message to the peer, we'll re-initialize the
3779
        // coop close state machine as they may send a shutdown message to
3780
        // retry the coop close.
UNCOV
3781
        lnChan, ok := c.peer.activeChannels.Load(c.chanID)
×
UNCOV
3782
        if !ok {
×
3783
                return
×
3784
        }
×
3785

UNCOV
3786
        if lnChan == nil {
×
3787
                c.peer.log.Debugf("channel %v is pending, not "+
×
3788
                        "re-initializing coop close state machine",
×
3789
                        c.chanID)
×
3790

×
3791
                return
×
3792
        }
×
3793

UNCOV
3794
        if _, err := c.peer.initRbfChanCloser(lnChan); err != nil {
×
3795
                c.peer.activeChanCloses.Delete(c.chanID)
×
3796

×
3797
                c.peer.log.Errorf("unable to init RBF chan closer after "+
×
3798
                        "error case: %v", err)
×
3799
        }
×
3800
}
3801

3802
// chanFlushEventSentinel is used to send the RBF coop close state machine the
3803
// channel flushed event. We'll wait until the state machine enters the
3804
// ChannelFlushing state, then request the link to send the event once flushed.
3805
//
3806
// NOTE: This MUST be run as a goroutine.
3807
func (p *Brontide) chanFlushEventSentinel(chanCloser *chancloser.RbfChanCloser,
3808
        link htlcswitch.ChannelUpdateHandler,
3809
        channel *lnwallet.LightningChannel) {
3✔
3810

3✔
3811
        defer p.cg.WgDone()
3✔
3812

3✔
3813
        // If there's no link, then the channel has already been flushed, so we
3✔
3814
        // don't need to continue.
3✔
3815
        if link == nil {
6✔
3816
                return
3✔
3817
        }
3✔
3818

3819
        coopCloseStates := chanCloser.RegisterStateEvents()
3✔
3820
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3821

3✔
3822
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3823

3✔
3824
        sendChanFlushed := func() {
6✔
3825
                chanState := channel.StateSnapshot()
3✔
3826

3✔
3827
                peerLog.Infof("ChannelPoint(%v) has been flushed for co-op "+
3✔
3828
                        "close, sending event to chan closer",
3✔
3829
                        channel.ChannelPoint())
3✔
3830

3✔
3831
                chanBalances := chancloser.ShutdownBalances{
3✔
3832
                        LocalBalance:  chanState.LocalBalance,
3✔
3833
                        RemoteBalance: chanState.RemoteBalance,
3✔
3834
                }
3✔
3835
                ctx := context.Background()
3✔
3836
                chanCloser.SendEvent(ctx, &chancloser.ChannelFlushed{
3✔
3837
                        ShutdownBalances: chanBalances,
3✔
3838
                        FreshFlush:       true,
3✔
3839
                })
3✔
3840
        }
3✔
3841

3842
        // We'll wait until the channel enters the ChannelFlushing state. We
3843
        // exit after a success loop. As after the first RBF iteration, the
3844
        // channel will always be flushed.
3845
        for {
6✔
3846
                select {
3✔
3847
                case newState, ok := <-newStateChan:
3✔
3848
                        if !ok {
3✔
3849
                                return
×
3850
                        }
×
3851

3852
                        if _, ok := newState.(*chancloser.ChannelFlushing); ok {
6✔
3853
                                peerLog.Infof("ChannelPoint(%v): rbf coop "+
3✔
3854
                                        "close is awaiting a flushed state, "+
3✔
3855
                                        "registering with link..., ",
3✔
3856
                                        channel.ChannelPoint())
3✔
3857

3✔
3858
                                // Request the link to send the event once the
3✔
3859
                                // channel is flushed. We only need this event
3✔
3860
                                // sent once, so we can exit now.
3✔
3861
                                link.OnFlushedOnce(sendChanFlushed)
3✔
3862

3✔
3863
                                return
3✔
3864
                        }
3✔
3865

3866
                case <-p.cg.Done():
3✔
3867
                        return
3✔
3868
                }
3869
        }
3870
}
3871

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

3✔
3878
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
3✔
3879

3✔
3880
        link := p.fetchLinkFromKeyAndCid(chanID)
3✔
3881

3✔
3882
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
3✔
3883
        if err != nil {
3✔
3884
                return nil, fmt.Errorf("cannot obtain best block: %w", err)
×
3885
        }
×
3886

3887
        defaultFeePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
3888
                p.cfg.CoopCloseTargetConfs,
3✔
3889
        )
3✔
3890
        if err != nil {
3✔
3891
                return nil, fmt.Errorf("unable to estimate fee: %w", err)
×
3892
        }
×
3893

3894
        thawHeight, err := channel.AbsoluteThawHeight()
3✔
3895
        if err != nil {
3✔
3896
                return nil, fmt.Errorf("unable to get thaw height: %w", err)
×
3897
        }
×
3898

3899
        peerPub := *p.IdentityKey()
3✔
3900

3✔
3901
        msgMapper := chancloser.NewRbfMsgMapper(
3✔
3902
                uint32(startingHeight), chanID, peerPub,
3✔
3903
        )
3✔
3904

3✔
3905
        initialState := chancloser.ChannelActive{}
3✔
3906

3✔
3907
        scid := channel.ZeroConfRealScid().UnwrapOr(
3✔
3908
                channel.ShortChanID(),
3✔
3909
        )
3✔
3910

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

3936
        spendEvent := protofsm.RegisterSpend[chancloser.ProtocolEvent]{
3✔
3937
                OutPoint:   channel.ChannelPoint(),
3✔
3938
                PkScript:   channel.FundingTxOut().PkScript,
3✔
3939
                HeightHint: channel.DeriveHeightHint(),
3✔
3940
                PostSpendEvent: fn.Some[chancloser.RbfSpendMapper](
3✔
3941
                        chancloser.SpendMapper,
3✔
3942
                ),
3✔
3943
        }
3✔
3944

3✔
3945
        daemonAdapters := NewLndDaemonAdapters(LndAdapterCfg{
3✔
3946
                MsgSender:     newPeerMsgSender(peerPub, p),
3✔
3947
                TxBroadcaster: p.cfg.Wallet,
3✔
3948
                ChainNotifier: p.cfg.ChainNotifier,
3✔
3949
        })
3✔
3950

3✔
3951
        protoCfg := chancloser.RbfChanCloserCfg{
3✔
3952
                Daemon:        daemonAdapters,
3✔
3953
                InitialState:  &initialState,
3✔
3954
                Env:           &env,
3✔
3955
                InitEvent:     fn.Some[protofsm.DaemonEvent](&spendEvent),
3✔
3956
                ErrorReporter: newChanErrorReporter(chanID, p),
3✔
3957
                MsgMapper: fn.Some[protofsm.MsgMapper[chancloser.ProtocolEvent]]( //nolint:ll
3✔
3958
                        msgMapper,
3✔
3959
                ),
3✔
3960
        }
3✔
3961

3✔
3962
        ctx := context.Background()
3✔
3963
        chanCloser := protofsm.NewStateMachine(protoCfg)
3✔
3964
        chanCloser.Start(ctx)
3✔
3965

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

3✔
3971
                return r.RegisterEndpoint(&chanCloser)
3✔
3972
        })
3✔
3973
        if err != nil {
3✔
3974
                chanCloser.Stop()
×
3975

×
3976
                return nil, fmt.Errorf("unable to register endpoint for co-op "+
×
3977
                        "close: %w", err)
×
3978
        }
×
3979

3980
        p.activeChanCloses.Store(chanID, makeRbfCloser(&chanCloser))
3✔
3981

3✔
3982
        // Now that we've created the rbf closer state machine, we'll launch a
3✔
3983
        // new goroutine to eventually send in the ChannelFlushed event once
3✔
3984
        // needed.
3✔
3985
        p.cg.WgAdd(1)
3✔
3986
        go p.chanFlushEventSentinel(&chanCloser, link, channel)
3✔
3987

3✔
3988
        return &chanCloser, nil
3✔
3989
}
3990

3991
// shutdownInit describes the two ways we can initiate a new shutdown. Either we
3992
// got an RPC request to do so (left), or we sent a shutdown message to the
3993
// party (for w/e reason), but crashed before the close was complete.
3994
//
3995
//nolint:ll
3996
type shutdownInit = fn.Option[fn.Either[*htlcswitch.ChanClose, channeldb.ShutdownInfo]]
3997

3998
// shutdownStartFeeRate returns the fee rate that should be used for the
3999
// shutdown.  This returns a doubly wrapped option as the shutdown info might
4000
// be none, and the fee rate is only defined for the user initiated shutdown.
4001
func shutdownStartFeeRate(s shutdownInit) fn.Option[chainfee.SatPerKWeight] {
3✔
4002
        feeRateOpt := fn.MapOption(func(init fn.Either[*htlcswitch.ChanClose,
3✔
4003
                channeldb.ShutdownInfo]) fn.Option[chainfee.SatPerKWeight] {
6✔
4004

3✔
4005
                var feeRate fn.Option[chainfee.SatPerKWeight]
3✔
4006
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
6✔
4007
                        feeRate = fn.Some(req.TargetFeePerKw)
3✔
4008
                })
3✔
4009

4010
                return feeRate
3✔
4011
        })(s)
4012

4013
        return fn.FlattenOption(feeRateOpt)
3✔
4014
}
4015

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

3✔
4023
                var addr fn.Option[lnwire.DeliveryAddress]
3✔
4024
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
6✔
4025
                        if len(req.DeliveryScript) != 0 {
6✔
4026
                                addr = fn.Some(req.DeliveryScript)
3✔
4027
                        }
3✔
4028
                })
4029
                init.WhenRight(func(info channeldb.ShutdownInfo) {
6✔
4030
                        addr = fn.Some(info.DeliveryScript.Val)
3✔
4031
                })
3✔
4032

4033
                return addr
3✔
4034
        })(s)
4035

4036
        return fn.FlattenOption(addrOpt)
3✔
4037
}
4038

4039
// whenRPCShutdown registers a callback to be executed when the shutdown init
4040
// type is and RPC request.
4041
func whenRPCShutdown(s shutdownInit, f func(r *htlcswitch.ChanClose)) {
3✔
4042
        s.WhenSome(func(init fn.Either[*htlcswitch.ChanClose,
3✔
4043
                channeldb.ShutdownInfo]) {
6✔
4044

3✔
4045
                init.WhenLeft(f)
3✔
4046
        })
3✔
4047
}
4048

4049
// newRestartShutdownInit creates a new shutdownInit for the case where we need
4050
// to restart the shutdown flow after a restart.
4051
func newRestartShutdownInit(info channeldb.ShutdownInfo) shutdownInit {
3✔
4052
        return fn.Some(fn.NewRight[*htlcswitch.ChanClose](info))
3✔
4053
}
3✔
4054

4055
// newRPCShutdownInit creates a new shutdownInit for the case where we
4056
// initiated the shutdown via an RPC client.
4057
func newRPCShutdownInit(req *htlcswitch.ChanClose) shutdownInit {
3✔
4058
        return fn.Some(
3✔
4059
                fn.NewLeft[*htlcswitch.ChanClose, channeldb.ShutdownInfo](req),
3✔
4060
        )
3✔
4061
}
3✔
4062

4063
// waitUntilRbfCoastClear waits until the RBF co-op close state machine has
4064
// advanced to a terminal state before attempting another fee bump.
4065
func waitUntilRbfCoastClear(ctx context.Context,
4066
        rbfCloser *chancloser.RbfChanCloser) error {
3✔
4067

3✔
4068
        coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4069
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
4070
        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4071

3✔
4072
        isTerminalState := func(newState chancloser.RbfState) bool {
6✔
4073
                // If we're not in the negotiation sub-state, then we aren't at
3✔
4074
                // the terminal state yet.
3✔
4075
                state, ok := newState.(*chancloser.ClosingNegotiation)
3✔
4076
                if !ok {
3✔
4077
                        return false
×
4078
                }
×
4079

4080
                localState := state.PeerState.GetForParty(lntypes.Local)
3✔
4081

3✔
4082
                // If this isn't the close pending state, we aren't at the
3✔
4083
                // terminal state yet.
3✔
4084
                _, ok = localState.(*chancloser.ClosePending)
3✔
4085

3✔
4086
                return ok
3✔
4087
        }
4088

4089
        // Before we enter the subscription loop below, check to see if we're
4090
        // already in the terminal state.
4091
        rbfState, err := rbfCloser.CurrentState()
3✔
4092
        if err != nil {
3✔
4093
                return err
×
4094
        }
×
4095
        if isTerminalState(rbfState) {
6✔
4096
                return nil
3✔
4097
        }
3✔
4098

4099
        peerLog.Debugf("Waiting for RBF iteration to complete...")
×
4100

×
4101
        for {
×
4102
                select {
×
4103
                case newState := <-newStateChan:
×
4104
                        if isTerminalState(newState) {
×
4105
                                return nil
×
4106
                        }
×
4107

4108
                case <-ctx.Done():
×
4109
                        return fmt.Errorf("context canceled")
×
4110
                }
4111
        }
4112
}
4113

4114
// startRbfChanCloser kicks off the co-op close process using the new RBF based
4115
// co-op close protocol. This is called when we're the one that's initiating
4116
// the cooperative channel close.
4117
//
4118
// TODO(roasbeef): just accept the two shutdown pointer params instead??
4119
func (p *Brontide) startRbfChanCloser(shutdown shutdownInit,
4120
        chanPoint wire.OutPoint) error {
3✔
4121

3✔
4122
        // Unlike the old negotiate chan closer, we'll always create the RBF
3✔
4123
        // chan closer on startup, so we can skip init here.
3✔
4124
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4125
        chanCloser, found := p.activeChanCloses.Load(chanID)
3✔
4126
        if !found {
3✔
4127
                return fmt.Errorf("rbf chan closer not found for channel %v",
×
4128
                        chanPoint)
×
4129
        }
×
4130

4131
        defaultFeePerKw, err := shutdownStartFeeRate(
3✔
4132
                shutdown,
3✔
4133
        ).UnwrapOrFuncErr(func() (chainfee.SatPerKWeight, error) {
6✔
4134
                return p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
4135
                        p.cfg.CoopCloseTargetConfs,
3✔
4136
                )
3✔
4137
        })
3✔
4138
        if err != nil {
3✔
4139
                return fmt.Errorf("unable to estimate fee: %w", err)
×
4140
        }
×
4141

4142
        chanCloser.WhenRight(func(rbfCloser *chancloser.RbfChanCloser) {
6✔
4143
                peerLog.Infof("ChannelPoint(%v): rbf-coop close requested, "+
3✔
4144
                        "sending shutdown", chanPoint)
3✔
4145

3✔
4146
                rbfState, err := rbfCloser.CurrentState()
3✔
4147
                if err != nil {
3✔
4148
                        peerLog.Warnf("ChannelPoint(%v): unable to get "+
×
4149
                                "current state for rbf-coop close: %v",
×
4150
                                chanPoint, err)
×
4151

×
4152
                        return
×
4153
                }
×
4154

4155
                coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4156

3✔
4157
                // Before we send our event below, we'll launch a goroutine to
3✔
4158
                // watch for the final terminal state to send updates to the RPC
3✔
4159
                // client. We only need to do this if there's an RPC caller.
3✔
4160
                var rpcShutdown bool
3✔
4161
                whenRPCShutdown(shutdown, func(req *htlcswitch.ChanClose) {
6✔
4162
                        rpcShutdown = true
3✔
4163

3✔
4164
                        p.cg.WgAdd(1)
3✔
4165
                        go func() {
6✔
4166
                                defer p.cg.WgDone()
3✔
4167

3✔
4168
                                p.observeRbfCloseUpdates(
3✔
4169
                                        rbfCloser, req, coopCloseStates,
3✔
4170
                                )
3✔
4171
                        }()
3✔
4172
                })
4173

4174
                if !rpcShutdown {
6✔
4175
                        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4176
                }
3✔
4177

4178
                ctx, _ := p.cg.Create(context.Background())
3✔
4179
                feeRate := defaultFeePerKw.FeePerVByte()
3✔
4180

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

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

×
4211
                                return
×
4212
                        }
×
4213

4214
                        event := chancloser.ProtocolEvent(
3✔
4215
                                &chancloser.SendOfferEvent{
3✔
4216
                                        TargetFeeRate: feeRate,
3✔
4217
                                },
3✔
4218
                        )
3✔
4219
                        rbfCloser.SendEvent(ctx, event)
3✔
4220

4221
                default:
×
4222
                        peerLog.Warnf("ChannelPoint(%v): unexpected state "+
×
4223
                                "for rbf-coop close: %T", chanPoint, rbfState)
×
4224
                }
4225
        })
4226

4227
        return nil
3✔
4228
}
4229

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

10✔
4235
        channel, ok := p.activeChannels.Load(chanID)
10✔
4236

10✔
4237
        // Though this function can't be called for pending channels, we still
10✔
4238
        // check whether channel is nil for safety.
10✔
4239
        if !ok || channel == nil {
10✔
4240
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
×
4241
                        "unknown", chanID)
×
4242
                p.log.Errorf(err.Error())
×
4243
                req.Err <- err
×
4244
                return
×
4245
        }
×
4246

4247
        isTaprootChan := channel.ChanType().IsTaproot()
10✔
4248

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

4271
                if err != nil {
11✔
4272
                        p.log.Errorf(err.Error())
1✔
4273
                        req.Err <- err
1✔
4274
                }
1✔
4275

4276
        // A type of CloseBreach indicates that the counterparty has breached
4277
        // the channel therefore we need to clean up our local state.
4278
        case contractcourt.CloseBreach:
×
4279
                // TODO(roasbeef): no longer need with newer beach logic?
×
4280
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
×
4281
                        "channel", req.ChanPoint)
×
4282
                p.WipeChannel(req.ChanPoint)
×
4283
        }
4284
}
4285

4286
// linkFailureReport is sent to the channelManager whenever a link reports a
4287
// link failure, and is forced to exit. The report houses the necessary
4288
// information to clean up the channel state, send back the error message, and
4289
// force close if necessary.
4290
type linkFailureReport struct {
4291
        chanPoint   wire.OutPoint
4292
        chanID      lnwire.ChannelID
4293
        shortChanID lnwire.ShortChannelID
4294
        linkErr     htlcswitch.LinkFailureError
4295
}
4296

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

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

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

3✔
4321
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
3✔
4322
                        failure.chanPoint,
3✔
4323
                )
3✔
4324
                if err != nil {
6✔
4325
                        p.log.Errorf("unable to force close "+
3✔
4326
                                "link(%v): %v", failure.shortChanID, err)
3✔
4327
                } else {
6✔
4328
                        p.log.Infof("channel(%v) force "+
3✔
4329
                                "closed with txid %v",
3✔
4330
                                failure.shortChanID, closeTx.TxHash())
3✔
4331
                }
3✔
4332
        }
4333

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

×
4339
                if err := lnChan.State().MarkBorked(); err != nil {
×
4340
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
4341
                                failure.shortChanID, err)
×
4342
                }
×
4343
        }
4344

4345
        // Send an error to the peer, why we failed the channel.
4346
        if failure.linkErr.ShouldSendToPeer() {
6✔
4347
                // If SendData is set, send it to the peer. If not, we'll use
3✔
4348
                // the standard error messages in the payload. We only include
3✔
4349
                // sendData in the cases where the error data does not contain
3✔
4350
                // sensitive information.
3✔
4351
                data := []byte(failure.linkErr.Error())
3✔
4352
                if failure.linkErr.SendData != nil {
3✔
4353
                        data = failure.linkErr.SendData
×
4354
                }
×
4355

4356
                var networkMsg lnwire.Message
3✔
4357
                if failure.linkErr.Warning {
3✔
4358
                        networkMsg = &lnwire.Warning{
×
4359
                                ChanID: failure.chanID,
×
4360
                                Data:   data,
×
4361
                        }
×
4362
                } else {
3✔
4363
                        networkMsg = &lnwire.Error{
3✔
4364
                                ChanID: failure.chanID,
3✔
4365
                                Data:   data,
3✔
4366
                        }
3✔
4367
                }
3✔
4368

4369
                err := p.SendMessage(true, networkMsg)
3✔
4370
                if err != nil {
3✔
4371
                        p.log.Errorf("unable to send msg to "+
×
4372
                                "remote peer: %v", err)
×
4373
                }
×
4374
        }
4375

4376
        // If the failure action is disconnect, then we'll execute that now. If
4377
        // we had to send an error above, it was a sync call, so we expect the
4378
        // message to be flushed on the wire by now.
4379
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
3✔
4380
                p.Disconnect(fmt.Errorf("link requested disconnect"))
×
4381
        }
×
4382
}
4383

4384
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
4385
// public key and the channel id.
4386
func (p *Brontide) fetchLinkFromKeyAndCid(
4387
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
22✔
4388

22✔
4389
        var chanLink htlcswitch.ChannelUpdateHandler
22✔
4390

22✔
4391
        // We don't need to check the error here, and can instead just loop
22✔
4392
        // over the slice and return nil.
22✔
4393
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
22✔
4394
        for _, link := range links {
43✔
4395
                if link.ChanID() == cid {
42✔
4396
                        chanLink = link
21✔
4397
                        break
21✔
4398
                }
4399
        }
4400

4401
        return chanLink
22✔
4402
}
4403

4404
// finalizeChanClosure performs the final clean up steps once the cooperative
4405
// closure transaction has been fully broadcast. The finalized closing state
4406
// machine should be passed in. Once the transaction has been sufficiently
4407
// confirmed, the channel will be marked as fully closed within the database,
4408
// and any clients will be notified of updates to the closing state.
4409
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
7✔
4410
        closeReq := chanCloser.CloseRequest()
7✔
4411

7✔
4412
        // First, we'll clear all indexes related to the channel in question.
7✔
4413
        chanPoint := chanCloser.Channel().ChannelPoint()
7✔
4414
        p.WipeChannel(&chanPoint)
7✔
4415

7✔
4416
        // Also clear the activeChanCloses map of this channel.
7✔
4417
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
7✔
4418
        p.activeChanCloses.Delete(cid) // TODO(roasbeef): existing race
7✔
4419

7✔
4420
        // Next, we'll launch a goroutine which will request to be notified by
7✔
4421
        // the ChainNotifier once the closure transaction obtains a single
7✔
4422
        // confirmation.
7✔
4423
        notifier := p.cfg.ChainNotifier
7✔
4424

7✔
4425
        // If any error happens during waitForChanToClose, forward it to
7✔
4426
        // closeReq. If this channel closure is not locally initiated, closeReq
7✔
4427
        // will be nil, so just ignore the error.
7✔
4428
        errChan := make(chan error, 1)
7✔
4429
        if closeReq != nil {
12✔
4430
                errChan = closeReq.Err
5✔
4431
        }
5✔
4432

4433
        closingTx, err := chanCloser.ClosingTx()
7✔
4434
        if err != nil {
7✔
4435
                if closeReq != nil {
×
4436
                        p.log.Error(err)
×
4437
                        closeReq.Err <- err
×
4438
                }
×
4439
        }
4440

4441
        closingTxid := closingTx.TxHash()
7✔
4442

7✔
4443
        // If this is a locally requested shutdown, update the caller with a
7✔
4444
        // new event detailing the current pending state of this request.
7✔
4445
        if closeReq != nil {
12✔
4446
                closeReq.Updates <- &PendingUpdate{
5✔
4447
                        Txid: closingTxid[:],
5✔
4448
                }
5✔
4449
        }
5✔
4450

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

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

7✔
4481
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
7✔
4482
                "with txid: %v", chanPoint, closingTxID)
7✔
4483

7✔
4484
        // TODO(roasbeef): add param for num needed confs
7✔
4485
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
7✔
4486
                closingTxID, closeScript, 1, bestHeight,
7✔
4487
        )
7✔
4488
        if err != nil {
7✔
4489
                if errChan != nil {
×
4490
                        errChan <- err
×
4491
                }
×
4492
                return
×
4493
        }
4494

4495
        // In the case that the ChainNotifier is shutting down, all subscriber
4496
        // notification channels will be closed, generating a nil receive.
4497
        height, ok := <-confNtfn.Confirmed
7✔
4498
        if !ok {
10✔
4499
                return
3✔
4500
        }
3✔
4501

4502
        // The channel has been closed, remove it from any active indexes, and
4503
        // the database state.
4504
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
7✔
4505
                "height %v", chanPoint, height.BlockHeight)
7✔
4506

7✔
4507
        // Finally, execute the closure call back to mark the confirmation of
7✔
4508
        // the transaction closing the contract.
7✔
4509
        cb()
7✔
4510
}
4511

4512
// WipeChannel removes the passed channel point from all indexes associated with
4513
// the peer and the switch.
4514
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
7✔
4515
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
7✔
4516

7✔
4517
        p.activeChannels.Delete(chanID)
7✔
4518

7✔
4519
        // Instruct the HtlcSwitch to close this link as the channel is no
7✔
4520
        // longer active.
7✔
4521
        p.cfg.Switch.RemoveLink(chanID)
7✔
4522
}
7✔
4523

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

4535
        // Then, finalize the remote feature vector providing the flattened
4536
        // feature bit namespace.
4537
        p.remoteFeatures = lnwire.NewFeatureVector(
6✔
4538
                msg.Features, lnwire.Features,
6✔
4539
        )
6✔
4540

6✔
4541
        // Now that we have their features loaded, we'll ensure that they
6✔
4542
        // didn't set any required bits that we don't know of.
6✔
4543
        err = feature.ValidateRequired(p.remoteFeatures)
6✔
4544
        if err != nil {
6✔
4545
                return fmt.Errorf("invalid remote features: %w", err)
×
4546
        }
×
4547

4548
        // Ensure the remote party's feature vector contains all transitive
4549
        // dependencies. We know ours are correct since they are validated
4550
        // during the feature manager's instantiation.
4551
        err = feature.ValidateDeps(p.remoteFeatures)
6✔
4552
        if err != nil {
6✔
4553
                return fmt.Errorf("invalid remote features: %w", err)
×
4554
        }
×
4555

4556
        // Now that we know we understand their requirements, we'll check to
4557
        // see if they don't support anything that we deem to be mandatory.
4558
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
6✔
4559
                return fmt.Errorf("data loss protection required")
×
4560
        }
×
4561

4562
        return nil
6✔
4563
}
4564

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

4574
// RemoteFeatures returns the set of global features that has been advertised by
4575
// the remote node. This allows sub-systems that use this interface to gate
4576
// their behavior off the set of negotiated feature bits.
4577
//
4578
// NOTE: Part of the lnpeer.Peer interface.
4579
func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector {
23✔
4580
        return p.remoteFeatures
23✔
4581
}
23✔
4582

4583
// hasNegotiatedScidAlias returns true if we've negotiated the
4584
// option-scid-alias feature bit with the peer.
4585
func (p *Brontide) hasNegotiatedScidAlias() bool {
6✔
4586
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
6✔
4587
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
6✔
4588
        return peerHas && localHas
6✔
4589
}
6✔
4590

4591
// sendInitMsg sends the Init message to the remote peer. This message contains
4592
// our currently supported local and global features.
4593
func (p *Brontide) sendInitMsg(legacyChan bool) error {
10✔
4594
        features := p.cfg.Features.Clone()
10✔
4595
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
10✔
4596

10✔
4597
        // If we have a legacy channel open with a peer, we downgrade static
10✔
4598
        // remote required to optional in case the peer does not understand the
10✔
4599
        // required feature bit. If we do not do this, the peer will reject our
10✔
4600
        // connection because it does not understand a required feature bit, and
10✔
4601
        // our channel will be unusable.
10✔
4602
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
11✔
4603
                p.log.Infof("Legacy channel open with peer, " +
1✔
4604
                        "downgrading static remote required feature bit to " +
1✔
4605
                        "optional")
1✔
4606

1✔
4607
                // Unset and set in both the local and global features to
1✔
4608
                // ensure both sets are consistent and merge able by old and
1✔
4609
                // new nodes.
1✔
4610
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4611
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4612

1✔
4613
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
4614
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
4615
        }
1✔
4616

4617
        msg := lnwire.NewInitMessage(
10✔
4618
                legacyFeatures.RawFeatureVector,
10✔
4619
                features.RawFeatureVector,
10✔
4620
        )
10✔
4621

10✔
4622
        return p.writeMessage(msg)
10✔
4623
}
4624

4625
// resendChanSyncMsg will attempt to find a channel sync message for the closed
4626
// channel and resend it to our peer.
4627
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
3✔
4628
        // If we already re-sent the mssage for this channel, we won't do it
3✔
4629
        // again.
3✔
4630
        if _, ok := p.resentChanSyncMsg[cid]; ok {
3✔
UNCOV
4631
                return nil
×
UNCOV
4632
        }
×
4633

4634
        // Check if we have any channel sync messages stored for this channel.
4635
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
3✔
4636
        if err != nil {
6✔
4637
                return fmt.Errorf("unable to fetch channel sync messages for "+
3✔
4638
                        "peer %v: %v", p, err)
3✔
4639
        }
3✔
4640

4641
        if c.LastChanSyncMsg == nil {
3✔
4642
                return fmt.Errorf("no chan sync message stored for channel %v",
×
4643
                        cid)
×
4644
        }
×
4645

4646
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
3✔
4647
                return fmt.Errorf("ignoring channel reestablish from "+
×
4648
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
4649
        }
×
4650

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

3✔
4654
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
3✔
4655
                return fmt.Errorf("failed resending channel sync "+
×
4656
                        "message to peer %v: %v", p, err)
×
4657
        }
×
4658

4659
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
3✔
4660
                cid)
3✔
4661

3✔
4662
        // Note down that we sent the message, so we won't resend it again for
3✔
4663
        // this connection.
3✔
4664
        p.resentChanSyncMsg[cid] = struct{}{}
3✔
4665

3✔
4666
        return nil
3✔
4667
}
4668

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

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

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

4710
                if priority {
13✔
4711
                        p.queueMsg(msg, errChan)
6✔
4712
                } else {
10✔
4713
                        p.queueMsgLazy(msg, errChan)
4✔
4714
                }
4✔
4715
        }
4716

4717
        // Wait for all replies from the writeHandler. For async sends, this
4718
        // will be a NOP as the list of error chans is nil.
4719
        for _, errChan := range errChans {
11✔
4720
                select {
4✔
4721
                case err := <-errChan:
4✔
4722
                        return err
4✔
4723
                case <-p.cg.Done():
×
4724
                        return lnpeer.ErrPeerExiting
×
4725
                case <-p.cfg.Quit:
×
4726
                        return lnpeer.ErrPeerExiting
×
4727
                }
4728
        }
4729

4730
        return nil
6✔
4731
}
4732

4733
// PubKey returns the pubkey of the peer in compressed serialized format.
4734
//
4735
// NOTE: Part of the lnpeer.Peer interface.
4736
func (p *Brontide) PubKey() [33]byte {
5✔
4737
        return p.cfg.PubKeyBytes
5✔
4738
}
5✔
4739

4740
// IdentityKey returns the public key of the remote peer.
4741
//
4742
// NOTE: Part of the lnpeer.Peer interface.
4743
func (p *Brontide) IdentityKey() *btcec.PublicKey {
18✔
4744
        return p.cfg.Addr.IdentityKey
18✔
4745
}
18✔
4746

4747
// Address returns the network address of the remote peer.
4748
//
4749
// NOTE: Part of the lnpeer.Peer interface.
4750
func (p *Brontide) Address() net.Addr {
3✔
4751
        return p.cfg.Addr.Address
3✔
4752
}
3✔
4753

4754
// AddNewChannel adds a new channel to the peer. The channel should fail to be
4755
// added if the cancel channel is closed.
4756
//
4757
// NOTE: Part of the lnpeer.Peer interface.
4758
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
4759
        cancel <-chan struct{}) error {
3✔
4760

3✔
4761
        errChan := make(chan error, 1)
3✔
4762
        newChanMsg := &newChannelMsg{
3✔
4763
                channel: newChan,
3✔
4764
                err:     errChan,
3✔
4765
        }
3✔
4766

3✔
4767
        select {
3✔
4768
        case p.newActiveChannel <- newChanMsg:
3✔
4769
        case <-cancel:
×
4770
                return errors.New("canceled adding new channel")
×
4771
        case <-p.cg.Done():
×
4772
                return lnpeer.ErrPeerExiting
×
4773
        }
4774

4775
        // We pause here to wait for the peer to recognize the new channel
4776
        // before we close the channel barrier corresponding to the channel.
4777
        select {
3✔
4778
        case err := <-errChan:
3✔
4779
                return err
3✔
4780
        case <-p.cg.Done():
×
4781
                return lnpeer.ErrPeerExiting
×
4782
        }
4783
}
4784

4785
// AddPendingChannel adds a pending open channel to the peer. The channel
4786
// should fail to be added if the cancel channel is closed.
4787
//
4788
// NOTE: Part of the lnpeer.Peer interface.
4789
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
4790
        cancel <-chan struct{}) error {
3✔
4791

3✔
4792
        errChan := make(chan error, 1)
3✔
4793
        newChanMsg := &newChannelMsg{
3✔
4794
                channelID: cid,
3✔
4795
                err:       errChan,
3✔
4796
        }
3✔
4797

3✔
4798
        select {
3✔
4799
        case p.newPendingChannel <- newChanMsg:
3✔
4800

4801
        case <-cancel:
×
4802
                return errors.New("canceled adding pending channel")
×
4803

4804
        case <-p.cg.Done():
×
4805
                return lnpeer.ErrPeerExiting
×
4806
        }
4807

4808
        // We pause here to wait for the peer to recognize the new pending
4809
        // channel before we close the channel barrier corresponding to the
4810
        // channel.
4811
        select {
3✔
4812
        case err := <-errChan:
3✔
4813
                return err
3✔
4814

4815
        case <-cancel:
×
4816
                return errors.New("canceled adding pending channel")
×
4817

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

4823
// RemovePendingChannel removes a pending open channel from the peer.
4824
//
4825
// NOTE: Part of the lnpeer.Peer interface.
4826
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
3✔
4827
        errChan := make(chan error, 1)
3✔
4828
        newChanMsg := &newChannelMsg{
3✔
4829
                channelID: cid,
3✔
4830
                err:       errChan,
3✔
4831
        }
3✔
4832

3✔
4833
        select {
3✔
4834
        case p.removePendingChannel <- newChanMsg:
3✔
4835
        case <-p.cg.Done():
×
4836
                return lnpeer.ErrPeerExiting
×
4837
        }
4838

4839
        // We pause here to wait for the peer to respond to the cancellation of
4840
        // the pending channel before we close the channel barrier
4841
        // corresponding to the channel.
4842
        select {
3✔
4843
        case err := <-errChan:
3✔
4844
                return err
3✔
4845

4846
        case <-p.cg.Done():
×
4847
                return lnpeer.ErrPeerExiting
×
4848
        }
4849
}
4850

4851
// StartTime returns the time at which the connection was established if the
4852
// peer started successfully, and zero otherwise.
4853
func (p *Brontide) StartTime() time.Time {
3✔
4854
        return p.startTime
3✔
4855
}
3✔
4856

4857
// handleCloseMsg is called when a new cooperative channel closure related
4858
// message is received from the remote peer. We'll use this message to advance
4859
// the chan closer state machine.
4860
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
16✔
4861
        link := p.fetchLinkFromKeyAndCid(msg.cid)
16✔
4862

16✔
4863
        // We'll now fetch the matching closing state machine in order to
16✔
4864
        // continue, or finalize the channel closure process.
16✔
4865
        chanCloserE, err := p.fetchActiveChanCloser(msg.cid)
16✔
4866
        if err != nil {
19✔
4867
                // If the channel is not known to us, we'll simply ignore this
3✔
4868
                // message.
3✔
4869
                if err == ErrChannelNotFound {
6✔
4870
                        return
3✔
4871
                }
3✔
4872

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

×
4875
                errMsg := &lnwire.Error{
×
4876
                        ChanID: msg.cid,
×
4877
                        Data:   lnwire.ErrorData(err.Error()),
×
4878
                }
×
4879
                p.queueMsg(errMsg, nil)
×
4880
                return
×
4881
        }
4882

4883
        if chanCloserE.IsRight() {
16✔
4884
                // TODO(roasbeef): assert?
×
4885
                return
×
4886
        }
×
4887

4888
        // At this point, we'll only enter this call path if a negotiate chan
4889
        // closer was used. So we'll extract that from the either now.
4890
        //
4891
        // TODO(roabeef): need extra helper func for either to make cleaner
4892
        var chanCloser *chancloser.ChanCloser
16✔
4893
        chanCloserE.WhenLeft(func(c *chancloser.ChanCloser) {
32✔
4894
                chanCloser = c
16✔
4895
        })
16✔
4896

4897
        handleErr := func(err error) {
17✔
4898
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
4899
                p.log.Error(err)
1✔
4900

1✔
4901
                // As the negotiations failed, we'll reset the channel state
1✔
4902
                // machine to ensure we act to on-chain events as normal.
1✔
4903
                chanCloser.Channel().ResetState()
1✔
4904
                if chanCloser.CloseRequest() != nil {
1✔
4905
                        chanCloser.CloseRequest().Err <- err
×
4906
                }
×
4907

4908
                p.activeChanCloses.Delete(msg.cid)
1✔
4909

1✔
4910
                p.Disconnect(err)
1✔
4911
        }
4912

4913
        // Next, we'll process the next message using the target state machine.
4914
        // We'll either continue negotiation, or halt.
4915
        switch typed := msg.msg.(type) {
16✔
4916
        case *lnwire.Shutdown:
8✔
4917
                // Disable incoming adds immediately.
8✔
4918
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
8✔
4919
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
4920
                                link.ChanID())
×
4921
                }
×
4922

4923
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
8✔
4924
                if err != nil {
8✔
4925
                        handleErr(err)
×
4926
                        return
×
4927
                }
×
4928

4929
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
14✔
4930
                        // If the link is nil it means we can immediately queue
6✔
4931
                        // the Shutdown message since we don't have to wait for
6✔
4932
                        // commitment transaction synchronization.
6✔
4933
                        if link == nil {
7✔
4934
                                p.queueMsg(&msg, nil)
1✔
4935
                                return
1✔
4936
                        }
1✔
4937

4938
                        // Immediately disallow any new HTLC's from being added
4939
                        // in the outgoing direction.
4940
                        if !link.DisableAdds(htlcswitch.Outgoing) {
5✔
4941
                                p.log.Warnf("Outgoing link adds already "+
×
4942
                                        "disabled: %v", link.ChanID())
×
4943
                        }
×
4944

4945
                        // When we have a Shutdown to send, we defer it till the
4946
                        // next time we send a CommitSig to remain spec
4947
                        // compliant.
4948
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
10✔
4949
                                p.queueMsg(&msg, nil)
5✔
4950
                        })
5✔
4951
                })
4952

4953
                beginNegotiation := func() {
16✔
4954
                        oClosingSigned, err := chanCloser.BeginNegotiation()
8✔
4955
                        if err != nil {
8✔
4956
                                handleErr(err)
×
4957
                                return
×
4958
                        }
×
4959

4960
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
16✔
4961
                                p.queueMsg(&msg, nil)
8✔
4962
                        })
8✔
4963
                }
4964

4965
                if link == nil {
9✔
4966
                        beginNegotiation()
1✔
4967
                } else {
8✔
4968
                        // Now we register a flush hook to advance the
7✔
4969
                        // ChanCloser and possibly send out a ClosingSigned
7✔
4970
                        // when the link finishes draining.
7✔
4971
                        link.OnFlushedOnce(func() {
14✔
4972
                                // Remove link in goroutine to prevent deadlock.
7✔
4973
                                go p.cfg.Switch.RemoveLink(msg.cid)
7✔
4974
                                beginNegotiation()
7✔
4975
                        })
7✔
4976
                }
4977

4978
        case *lnwire.ClosingSigned:
11✔
4979
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
11✔
4980
                if err != nil {
12✔
4981
                        handleErr(err)
1✔
4982
                        return
1✔
4983
                }
1✔
4984

4985
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
22✔
4986
                        p.queueMsg(&msg, nil)
11✔
4987
                })
11✔
4988

4989
        default:
×
4990
                panic("impossible closeMsg type")
×
4991
        }
4992

4993
        // If we haven't finished close negotiations, then we'll continue as we
4994
        // can't yet finalize the closure.
4995
        if _, err := chanCloser.ClosingTx(); err != nil {
26✔
4996
                return
11✔
4997
        }
11✔
4998

4999
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
5000
        // the channel closure by notifying relevant sub-systems and launching a
5001
        // goroutine to wait for close tx conf.
5002
        p.finalizeChanClosure(chanCloser)
7✔
5003
}
5004

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

5019
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
5020
func (p *Brontide) NetAddress() *lnwire.NetAddress {
3✔
5021
        return p.cfg.Addr
3✔
5022
}
3✔
5023

5024
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
5025
func (p *Brontide) Inbound() bool {
3✔
5026
        return p.cfg.Inbound
3✔
5027
}
3✔
5028

5029
// ConnReq is a getter for the Brontide's connReq in cfg.
5030
func (p *Brontide) ConnReq() *connmgr.ConnReq {
3✔
5031
        return p.cfg.ConnReq
3✔
5032
}
3✔
5033

5034
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
5035
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
3✔
5036
        return p.cfg.ErrorBuffer
3✔
5037
}
3✔
5038

5039
// SetAddress sets the remote peer's address given an address.
5040
func (p *Brontide) SetAddress(address net.Addr) {
×
5041
        p.cfg.Addr.Address = address
×
5042
}
×
5043

5044
// ActiveSignal returns the peer's active signal.
5045
func (p *Brontide) ActiveSignal() chan struct{} {
3✔
5046
        return p.activeSignal
3✔
5047
}
3✔
5048

5049
// Conn returns a pointer to the peer's connection struct.
5050
func (p *Brontide) Conn() net.Conn {
3✔
5051
        return p.cfg.Conn
3✔
5052
}
3✔
5053

5054
// BytesReceived returns the number of bytes received from the peer.
5055
func (p *Brontide) BytesReceived() uint64 {
3✔
5056
        return atomic.LoadUint64(&p.bytesReceived)
3✔
5057
}
3✔
5058

5059
// BytesSent returns the number of bytes sent to the peer.
5060
func (p *Brontide) BytesSent() uint64 {
3✔
5061
        return atomic.LoadUint64(&p.bytesSent)
3✔
5062
}
3✔
5063

5064
// LastRemotePingPayload returns the last payload the remote party sent as part
5065
// of their ping.
5066
func (p *Brontide) LastRemotePingPayload() []byte {
3✔
5067
        pingPayload := p.lastPingPayload.Load()
3✔
5068
        if pingPayload == nil {
6✔
5069
                return []byte{}
3✔
5070
        }
3✔
5071

5072
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
5073
        if !ok {
×
5074
                return nil
×
5075
        }
×
5076

5077
        return pingBytes
×
5078
}
5079

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

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

5101
        p.channelEventClient = sub
6✔
5102

6✔
5103
        return nil
6✔
5104
}
5105

5106
// updateNextRevocation updates the existing channel's next revocation if it's
5107
// nil.
5108
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
6✔
5109
        chanPoint := c.FundingOutpoint
6✔
5110
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
6✔
5111

6✔
5112
        // Read the current channel.
6✔
5113
        currentChan, loaded := p.activeChannels.Load(chanID)
6✔
5114

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

5122
        // currentChan should not be nil, but we perform a check anyway to
5123
        // avoid nil pointer dereference.
5124
        if currentChan == nil {
6✔
5125
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
5126
                        chanID)
1✔
5127
        }
1✔
5128

5129
        // If we're being sent a new channel, and our existing channel doesn't
5130
        // have the next revocation, then we need to update the current
5131
        // existing channel.
5132
        if currentChan.RemoteNextRevocation() != nil {
4✔
5133
                return nil
×
5134
        }
×
5135

5136
        p.log.Infof("Processing retransmitted ChannelReady for "+
4✔
5137
                "ChannelPoint(%v)", chanPoint)
4✔
5138

4✔
5139
        nextRevoke := c.RemoteNextRevocation
4✔
5140

4✔
5141
        err := currentChan.InitNextRevocation(nextRevoke)
4✔
5142
        if err != nil {
4✔
5143
                return fmt.Errorf("unable to init next revocation: %w", err)
×
5144
        }
×
5145

5146
        return nil
4✔
5147
}
5148

5149
// addActiveChannel adds a new active channel to the `activeChannels` map. It
5150
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
5151
// it and assembles it with a channel link.
5152
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
3✔
5153
        chanPoint := c.FundingOutpoint
3✔
5154
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5155

3✔
5156
        // If we've reached this point, there are two possible scenarios.  If
3✔
5157
        // the channel was in the active channels map as nil, then it was
3✔
5158
        // loaded from disk and we need to send reestablish. Else, it was not
3✔
5159
        // loaded from disk and we don't need to send reestablish as this is a
3✔
5160
        // fresh channel.
3✔
5161
        shouldReestablish := p.isLoadedFromDisk(chanID)
3✔
5162

3✔
5163
        chanOpts := c.ChanOpts
3✔
5164
        if shouldReestablish {
6✔
5165
                // If we have to do the reestablish dance for this channel,
3✔
5166
                // ensure that we don't try to call InitRemoteMusigNonces twice
3✔
5167
                // by calling SkipNonceInit.
3✔
5168
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
3✔
5169
        }
3✔
5170

5171
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
3✔
5172
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
5173
        })
×
5174
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
3✔
5175
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
5176
        })
×
5177
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
3✔
5178
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
5179
        })
×
5180

5181
        // If not already active, we'll add this channel to the set of active
5182
        // channels, so we can look it up later easily according to its channel
5183
        // ID.
5184
        lnChan, err := lnwallet.NewLightningChannel(
3✔
5185
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
3✔
5186
        )
3✔
5187
        if err != nil {
3✔
5188
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
5189
        }
×
5190

5191
        // Store the channel in the activeChannels map.
5192
        p.activeChannels.Store(chanID, lnChan)
3✔
5193

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

3✔
5196
        // Next, we'll assemble a ChannelLink along with the necessary items it
3✔
5197
        // needs to function.
3✔
5198
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
3✔
5199
        if err != nil {
3✔
5200
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
5201
                        err)
×
5202
        }
×
5203

5204
        // We'll query the channel DB for the new channel's initial forwarding
5205
        // policies to determine the policy we start out with.
5206
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
3✔
5207
        if err != nil {
3✔
5208
                return fmt.Errorf("unable to query for initial forwarding "+
×
5209
                        "policy: %v", err)
×
5210
        }
×
5211

5212
        // Create the link and add it to the switch.
5213
        err = p.addLink(
3✔
5214
                &chanPoint, lnChan, initialPolicy, chainEvents,
3✔
5215
                shouldReestablish, fn.None[lnwire.Shutdown](),
3✔
5216
        )
3✔
5217
        if err != nil {
3✔
5218
                return fmt.Errorf("can't register new channel link(%v) with "+
×
5219
                        "peer", chanPoint)
×
5220
        }
×
5221

5222
        isTaprootChan := c.ChanType.IsTaproot()
3✔
5223

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

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

×
5240
                return fmt.Errorf("unable to init RBF chan closer for new "+
×
5241
                        "chan: %w", err)
×
5242
        }
×
5243

5244
        return nil
3✔
5245
}
5246

5247
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
5248
// know this channel ID or not, we'll either add it to the `activeChannels` map
5249
// or init the next revocation for it.
5250
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
3✔
5251
        newChan := req.channel
3✔
5252
        chanPoint := newChan.FundingOutpoint
3✔
5253
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5254

3✔
5255
        // Only update RemoteNextRevocation if the channel is in the
3✔
5256
        // activeChannels map and if we added the link to the switch. Only
3✔
5257
        // active channels will be added to the switch.
3✔
5258
        if p.isActiveChannel(chanID) {
6✔
5259
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
3✔
5260
                        chanPoint)
3✔
5261

3✔
5262
                // Handle it and close the err chan on the request.
3✔
5263
                close(req.err)
3✔
5264

3✔
5265
                // Update the next revocation point.
3✔
5266
                err := p.updateNextRevocation(newChan.OpenChannel)
3✔
5267
                if err != nil {
3✔
5268
                        p.log.Errorf(err.Error())
×
5269
                }
×
5270

5271
                return
3✔
5272
        }
5273

5274
        // This is a new channel, we now add it to the map.
5275
        if err := p.addActiveChannel(req.channel); err != nil {
3✔
5276
                // Log and send back the error to the request.
×
5277
                p.log.Errorf(err.Error())
×
5278
                req.err <- err
×
5279

×
5280
                return
×
5281
        }
×
5282

5283
        // Close the err chan if everything went fine.
5284
        close(req.err)
3✔
5285
}
5286

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

7✔
5294
        chanID := req.channelID
7✔
5295

7✔
5296
        // If we already have this channel, something is wrong with the funding
7✔
5297
        // flow as it will only be marked as active after `ChannelReady` is
7✔
5298
        // handled. In this case, we will do nothing but log an error, just in
7✔
5299
        // case this is a legit channel.
7✔
5300
        if p.isActiveChannel(chanID) {
8✔
5301
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
5302
                        "pending channel request", chanID)
1✔
5303

1✔
5304
                return
1✔
5305
        }
1✔
5306

5307
        // The channel has already been added, we will do nothing and return.
5308
        if p.isPendingChannel(chanID) {
7✔
5309
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
5310
                        "pending channel request", chanID)
1✔
5311

1✔
5312
                return
1✔
5313
        }
1✔
5314

5315
        // This is a new channel, we now add it to the map `activeChannels`
5316
        // with nil value and mark it as a newly added channel in
5317
        // `addedChannels`.
5318
        p.activeChannels.Store(chanID, nil)
5✔
5319
        p.addedChannels.Store(chanID, struct{}{})
5✔
5320
}
5321

5322
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
5323
// from `activeChannels` map. The request will be ignored if the channel is
5324
// considered active by Brontide. Noop if the channel ID cannot be found.
5325
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
7✔
5326
        defer close(req.err)
7✔
5327

7✔
5328
        chanID := req.channelID
7✔
5329

7✔
5330
        // If we already have this channel, something is wrong with the funding
7✔
5331
        // flow as it will only be marked as active after `ChannelReady` is
7✔
5332
        // handled. In this case, we will log an error and exit.
7✔
5333
        if p.isActiveChannel(chanID) {
8✔
5334
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
5335
                        chanID)
1✔
5336
                return
1✔
5337
        }
1✔
5338

5339
        // The channel has not been added yet, we will log a warning as there
5340
        // is an unexpected call from funding manager.
5341
        if !p.isPendingChannel(chanID) {
10✔
5342
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
4✔
5343
        }
4✔
5344

5345
        // Remove the record of this pending channel.
5346
        p.activeChannels.Delete(chanID)
6✔
5347
        p.addedChannels.Delete(chanID)
6✔
5348
}
5349

5350
// sendLinkUpdateMsg sends a message that updates the channel to the
5351
// channel's message stream.
5352
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
3✔
5353
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
3✔
5354

3✔
5355
        chanStream, ok := p.activeMsgStreams[cid]
3✔
5356
        if !ok {
6✔
5357
                // If a stream hasn't yet been created, then we'll do so, add
3✔
5358
                // it to the map, and finally start it.
3✔
5359
                chanStream = newChanMsgStream(p, cid)
3✔
5360
                p.activeMsgStreams[cid] = chanStream
3✔
5361
                chanStream.Start()
3✔
5362

3✔
5363
                // Stop the stream when quit.
3✔
5364
                go func() {
6✔
5365
                        <-p.cg.Done()
3✔
5366
                        chanStream.Stop()
3✔
5367
                }()
3✔
5368
        }
5369

5370
        // With the stream obtained, add the message to the stream so we can
5371
        // continue processing message.
5372
        chanStream.AddMsg(msg)
3✔
5373
}
5374

5375
// scaleTimeout multiplies the argument duration by a constant factor depending
5376
// on variious heuristics. Currently this is only used to check whether our peer
5377
// appears to be connected over Tor and relaxes the timout deadline. However,
5378
// this is subject to change and should be treated as opaque.
5379
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
70✔
5380
        if p.isTorConnection {
73✔
5381
                return timeout * time.Duration(torTimeoutMultiplier)
3✔
5382
        }
3✔
5383

5384
        return timeout
67✔
5385
}
5386

5387
// CoopCloseUpdates is a struct used to communicate updates for an active close
5388
// to the caller.
5389
type CoopCloseUpdates struct {
5390
        UpdateChan chan interface{}
5391

5392
        ErrChan chan error
5393
}
5394

5395
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5396
// point has an active RBF chan closer.
5397
func (p *Brontide) ChanHasRbfCoopCloser(chanPoint wire.OutPoint) bool {
3✔
5398
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5399
        chanCloser, found := p.activeChanCloses.Load(chanID)
3✔
5400
        if !found {
6✔
5401
                return false
3✔
5402
        }
3✔
5403

5404
        return chanCloser.IsRight()
3✔
5405
}
5406

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

3✔
5415
        // If RBF coop close isn't permitted, then we'll an error.
3✔
5416
        if !p.rbfCoopCloseAllowed() {
3✔
5417
                return nil, fmt.Errorf("rbf coop close not enabled for " +
×
5418
                        "channel")
×
5419
        }
×
5420

5421
        closeUpdates := &CoopCloseUpdates{
3✔
5422
                UpdateChan: make(chan interface{}, 1),
3✔
5423
                ErrChan:    make(chan error, 1),
3✔
5424
        }
3✔
5425

3✔
5426
        // We'll re-use the existing switch struct here, even though we're
3✔
5427
        // bypassing the switch entirely.
3✔
5428
        closeReq := htlcswitch.ChanClose{
3✔
5429
                CloseType:      contractcourt.CloseRegular,
3✔
5430
                ChanPoint:      &chanPoint,
3✔
5431
                TargetFeePerKw: feeRate,
3✔
5432
                DeliveryScript: deliveryScript,
3✔
5433
                Updates:        closeUpdates.UpdateChan,
3✔
5434
                Err:            closeUpdates.ErrChan,
3✔
5435
                Ctx:            ctx,
3✔
5436
        }
3✔
5437

3✔
5438
        err := p.startRbfChanCloser(newRPCShutdownInit(&closeReq), chanPoint)
3✔
5439
        if err != nil {
3✔
5440
                return nil, err
×
5441
        }
×
5442

5443
        return closeUpdates, nil
3✔
5444
}
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