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

lightningnetwork / lnd / 15981023574

30 Jun 2025 06:42PM UTC coverage: 57.785% (-9.8%) from 67.608%
15981023574

Pull #10012

github

web-flow
Merge 65fb58f85 into e54206f8c
Pull Request #10012: multi: prevent goroutine leak in brontide

7 of 12 new or added lines in 2 files covered. (58.33%)

28438 existing lines in 456 files now uncovered.

98421 of 170324 relevant lines covered (57.78%)

1.79 hits per line

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

77.19
/peer/brontide.go
1
package peer
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

126
        err chan error
127
}
128

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

518
        pingManager *PingManager
519

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

527
        cfg Config
528

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

627
        startReady chan struct{}
628

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

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

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

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

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

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

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

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

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

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

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

718
                return lastSerializedBlockHeader[:]
×
719
        }
720

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

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

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

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

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

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

766
        return p
3✔
767
}
768

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

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

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

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

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

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

807
                haveLegacyChan = true
3✔
808
                break
3✔
809
        }
810

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
937
        return nil
3✔
938
}
939

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
1081
                                msgs = append(msgs, channelReadyMsg)
3✔
1082
                        }
1083

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

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

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

1118
                chanPoint := dbChan.FundingOutpoint
3✔
1119

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

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

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

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

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

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

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

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

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

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

1173
                        continue
3✔
1174
                }
1175

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

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

3✔
1198
                        selfPolicy = p1
3✔
1199
                } else {
6✔
1200
                        selfPolicy = p2
3✔
1201
                }
3✔
1202

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

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

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

3✔
1238
                        continue
3✔
1239
                }
1240

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

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

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

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

×
1268
                                return
×
1269
                        }
×
1270

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

×
1287
                                return
×
1288
                        }
×
1289

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

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

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

×
1304
                                return
×
1305
                        }
×
1306

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

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

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

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

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

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

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

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

1369
        return msgs, nil
3✔
1370
}
1371

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
1542
                        return nil
3✔
1543
                }
3✔
1544

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

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

×
1557
                        return err
×
1558
                }
×
1559

1560
                return nil
3✔
1561
        }
1562

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1723
        peer *Brontide
1724

1725
        apply func(lnwire.Message)
1726

1727
        startMsg string
1728
        stopMsg  string
1729

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

1733
        mtx sync.Mutex
1734

1735
        producerSema chan struct{}
1736

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

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

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

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

1767
        return stream
3✔
1768
}
1769

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1921
                        chanPoint := event.ChannelPoint
3✔
1922

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

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

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

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

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

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

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

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

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

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

3✔
1993
                p.log.Debugf("Processing remote msg %T", msg)
3✔
1994

3✔
1995
                errChan := p.cfg.AuthGossiper.ProcessRemoteAnnouncement(
3✔
1996
                        ctx, msg, p,
3✔
1997
                )
3✔
1998

3✔
1999
                // Exit early because the msg was never delivered to the
3✔
2000
                // gossiper.
3✔
2001
                if errChan == nil {
3✔
NEW
UNCOV
2002
                        return
×
NEW
UNCOV
2003
                }
×
2004

2005
                // Start a goroutine to process the error channel for logging
2006
                // purposes.
2007
                //
2008
                // TODO(ziggie): Maybe use the error to potentially punish the
2009
                // peer depending on the error ?
2010
                go func() {
6✔
2011
                        select {
3✔
UNCOV
2012
                        case <-p.cg.Done():
×
UNCOV
2013
                                return
×
2014

2015
                        case err := <-errChan:
3✔
2016
                                if err != nil {
6✔
2017
                                        p.log.Warnf("Error processing remote "+
3✔
2018
                                                "msg %T: %v", msg,
3✔
2019
                                                err)
3✔
2020
                                }
3✔
2021

2022
                        // This timeout is a safeguard to prevent goroutine
2023
                        // leaks, normally the errChan should trigger before
2024
                        // this timeout or the peer is exiting. We log a warning
2025
                        // with the particular message which is not processed
2026
                        // in time.
UNCOV
2027
                        case <-time.After(5 * time.Second):
×
UNCOV
2028
                                p.log.Warnf("Timeout waiting for error "+
×
UNCOV
2029
                                        "channel response for msg %T", msg)
×
2030
                        }
2031

2032
                        p.log.Debugf("Processed remote msg %T", msg)
3✔
2033
                }()
2034
        }
2035

2036
        return newMsgStream(
3✔
2037
                p,
3✔
2038
                "Update stream for gossiper created",
3✔
2039
                "Update stream for gossiper exited",
3✔
2040
                msgStreamSize,
3✔
2041
                apply,
3✔
2042
        )
3✔
2043
}
2044

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

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

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

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

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

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

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

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

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

2133
                // No error occurred, and the message was handled by the
2134
                // router.
2135
                if err == nil {
6✔
2136
                        continue
3✔
2137
                }
2138

2139
                var (
3✔
2140
                        targetChan   lnwire.ChannelID
3✔
2141
                        isLinkUpdate bool
3✔
2142
                )
3✔
2143

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

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

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

2160
                case *lnwire.OpenChannel,
2161
                        *lnwire.AcceptChannel,
2162
                        *lnwire.FundingCreated,
2163
                        *lnwire.FundingSigned,
2164
                        *lnwire.ChannelReady:
3✔
2165

3✔
2166
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2167

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

2181
                case *lnwire.Warning:
×
2182
                        targetChan = msg.ChanID
×
2183
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2184

2185
                case *lnwire.Error:
3✔
2186
                        targetChan = msg.ChanID
3✔
2187
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
3✔
2188

2189
                case *lnwire.ChannelReestablish:
3✔
2190
                        targetChan = msg.ChanID
3✔
2191
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2192

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

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

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

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

3✔
2235
                        discStream.AddMsg(msg)
3✔
2236

2237
                case *lnwire.Custom:
3✔
2238
                        err := p.handleCustomMessage(msg)
3✔
2239
                        if err != nil {
3✔
2240
                                p.storeError(err)
×
2241
                                p.log.Errorf("%v", err)
×
2242
                        }
×
2243

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

×
2251
                        p.log.Errorf("%v", err)
×
2252
                }
2253

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

2260
                idleTimer.Reset(idleTimeout)
3✔
2261
        }
2262

2263
        p.Disconnect(errors.New("read handler closed"))
3✔
2264

3✔
2265
        p.log.Trace("readHandler for peer done")
3✔
2266
}
2267

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

2276
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
3✔
2277
}
2278

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

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

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

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

3✔
2310
        return channel != nil
3✔
2311
}
3✔
2312

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

2322
        return channel == nil
3✔
2323
}
2324

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

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

3✔
2339
        p.activeChannels.Range(func(_ lnwire.ChannelID,
3✔
2340
                channel *lnwallet.LightningChannel) bool {
6✔
2341

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

2348
                haveChannels = true
3✔
2349

3✔
2350
                // Return false to break the iteration.
3✔
2351
                return false
3✔
2352
        })
2353

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

2361
        p.cfg.ErrorBuffer.Add(
3✔
2362
                &TimestampedError{Timestamp: time.Now(), Error: err},
3✔
2363
        )
3✔
2364
}
2365

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

3✔
2375
        if errMsg, ok := msg.(*lnwire.Error); ok {
6✔
2376
                p.storeError(errMsg)
3✔
2377
        }
3✔
2378

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

2387
                return false
×
2388

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

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

2399
        default:
3✔
2400
                return false
3✔
2401
        }
2402
}
2403

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

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

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

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

2429
        case *lnwire.FundingSigned:
3✔
2430
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
3✔
2431

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

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

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

2444
        case *lnwire.ClosingSig:
3✔
2445
                return fmt.Sprintf("chan_id=%v", msg.ChannelID)
3✔
2446

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

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

3✔
2457
                                blindingPoint = b.Val.SerializeCompressed()
3✔
2458
                        },
3✔
2459
                )
2460

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

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

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

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

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

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

2488
        case *lnwire.Warning:
×
2489
                return fmt.Sprintf("%v", msg.Warning())
×
2490

2491
        case *lnwire.Error:
3✔
2492
                return fmt.Sprintf("%v", msg.Error())
3✔
2493

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

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

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

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

2512
        case *lnwire.Ping:
×
2513
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
2514

2515
        case *lnwire.Pong:
×
2516
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
×
2517

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

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

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

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

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

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

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

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

2556
        case *lnwire.Custom:
3✔
2557
                return fmt.Sprintf("type=%d", msg.Type)
3✔
2558
        }
2559

2560
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2561
}
2562

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

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

2581
                preposition := "to"
3✔
2582
                if read {
6✔
2583
                        preposition = "from"
3✔
2584
                }
3✔
2585

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

2593
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
3✔
2594
                        msgType, summary, preposition, p)
3✔
2595
        }))
2596

2597
        prefix := "readMessage from peer"
3✔
2598
        if !read {
6✔
2599
                prefix = "writeMessage to peer"
3✔
2600
        }
3✔
2601

2602
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
3✔
2603
}
2604

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

2622
        noiseConn := p.cfg.Conn
3✔
2623

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

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

3✔
2640
                // Record the number of bytes written on the wire, if any.
3✔
2641
                if n > 0 {
6✔
2642
                        atomic.AddUint64(&p.bytesSent, uint64(n))
3✔
2643
                }
3✔
2644

2645
                return err
3✔
2646
        }
2647

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

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

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

2675
        return flushMsg()
3✔
2676
}
2677

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

2693
        var exitErr error
3✔
2694

3✔
2695
out:
3✔
2696
        for {
6✔
2697
                select {
3✔
2698
                case outMsg := <-p.sendQueue:
3✔
2699
                        // Record the time at which we first attempt to send the
3✔
2700
                        // message.
3✔
2701
                        startTime := time.Now()
3✔
2702

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

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

×
2724
                                goto retry
×
2725
                        }
2726

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

3✔
2737
                        // If the peer requested a synchronous write, respond
3✔
2738
                        // with the error.
3✔
2739
                        if outMsg.errChan != nil {
6✔
2740
                                outMsg.errChan <- err
3✔
2741
                        }
3✔
2742

2743
                        if err != nil {
3✔
2744
                                exitErr = fmt.Errorf("unable to write "+
×
2745
                                        "message: %v", err)
×
2746
                                break out
×
2747
                        }
2748

2749
                case <-p.cg.Done():
3✔
2750
                        exitErr = lnpeer.ErrPeerExiting
3✔
2751
                        break out
3✔
2752
                }
2753
        }
2754

2755
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2756
        // disconnect.
2757
        p.cg.WgDone()
3✔
2758

3✔
2759
        p.Disconnect(exitErr)
3✔
2760

3✔
2761
        p.log.Trace("writeHandler for peer done")
3✔
2762
}
2763

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

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

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

3✔
2781
        for {
6✔
2782
                // Examine the front of the priority queue, if it is empty check
3✔
2783
                // the low priority queue.
3✔
2784
                elem := priorityMsgs.Front()
3✔
2785
                if elem == nil {
6✔
2786
                        elem = lazyMsgs.Front()
3✔
2787
                }
3✔
2788

2789
                if elem != nil {
6✔
2790
                        front := elem.Value.(outgoingMsg)
3✔
2791

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

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

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

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

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

3✔
2856
        select {
3✔
2857
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
3✔
2858
        case <-p.cg.Done():
1✔
2859
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
1✔
2860
                        spew.Sdump(msg))
1✔
2861
                if errChan != nil {
2✔
2862
                        errChan <- lnpeer.ErrPeerExiting
1✔
2863
                }
1✔
2864
        }
2865
}
2866

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

3✔
2874
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2875
                activeChan *lnwallet.LightningChannel) error {
6✔
2876

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

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

2889
                snapshot := activeChan.StateSnapshot()
3✔
2890
                snapshots = append(snapshots, snapshot)
3✔
2891

3✔
2892
                return nil
3✔
2893
        })
2894

2895
        return snapshots
3✔
2896
}
2897

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

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

3✔
2917
        return txscript.PayToAddrScript(deliveryAddr)
3✔
2918
}
2919

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

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

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

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

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

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

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

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

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

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

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

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

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

3014
                                lc.ResetState()
3✔
3015

3✔
3016
                                return nil
3✔
3017
                        })
3018

3019
                        break out
3✔
3020
                }
3021
        }
3022
}
3023

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

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

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

3✔
3042
                switch {
3✔
3043
                // No error occurred, continue to request the next channel.
3044
                case err == nil:
3✔
3045
                        continue
3✔
3046

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

3✔
3053
                        continue
3✔
3054

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

×
3072
                                continue
×
3073
                        }
3074

3075
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
3076
                                "ChanStatusManager reported inactive, retrying")
×
3077

×
3078
                        // Add the channel to the retry map.
×
3079
                        retryChans[chanPoint] = struct{}{}
×
3080
                }
3081
        }
3082

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

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

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

3105
        // First, we'll ensure that we actually know of the target channel. If
3106
        // not, we'll ignore this message.
3107
        channel, ok := p.activeChannels.Load(chanID)
3✔
3108

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

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

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

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

3156
        chanCloser = makeNegotiateCloser(negotiateChanCloser)
3✔
3157

3✔
3158
        p.activeChanCloses.Store(chanID, chanCloser)
3✔
3159

3✔
3160
        return &chanCloser, nil
3✔
3161
}
3162

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

3✔
3169
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
3✔
3170
                lnChan *lnwallet.LightningChannel) bool {
6✔
3171

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

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

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

3192
                activePublicChans = append(
3✔
3193
                        activePublicChans, dbChan.FundingOutpoint,
3✔
3194
                )
3✔
3195

3✔
3196
                return true
3✔
3197
        })
3198

3199
        return activePublicChans
3✔
3200
}
3201

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

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

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

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

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

3237
                return nil
×
3238
        }
3239

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

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

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

3265
                                continue
×
3266
                        }
3267

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

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

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

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

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

3✔
3301
        switch {
3✔
3302
        // If no script was provided, then we'll generate a new delivery script.
3303
        case len(upfront) == 0 && len(requested) == 0:
3✔
3304
                return genDeliveryScript()
3✔
3305

3306
        // If no upfront shutdown script was provided, return the user
3307
        // requested address (which may be nil).
3308
        case len(upfront) == 0:
3✔
3309
                return requested, nil
3✔
3310

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

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

3323
        // The user requested script matches the upfront shutdown script, so we
3324
        // can return it without error.
UNCOV
3325
        default:
×
UNCOV
3326
                return upfront, nil
×
3327
        }
3328
}
3329

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

3✔
3335
        isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
3336

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

3356
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
3✔
3357

3✔
3358
        var deliveryScript []byte
3✔
3359

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

3369
        // An error other than ErrNoShutdownInfo was returned
3370
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3371
                return nil, err
×
3372

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

×
3382
                                return nil, fmt.Errorf("close addr unavailable")
×
3383
                        }
×
3384
                }
3385
        }
3386

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

3397
                shutdownDesc := fn.MapOption(
3✔
3398
                        newRestartShutdownInit,
3✔
3399
                )(shutdownInfo)
3✔
3400

3✔
3401
                err = p.startRbfChanCloser(
3✔
3402
                        fn.FlattenOption(shutdownDesc), lnChan.ChannelPoint(),
3✔
3403
                )
3✔
3404

3✔
3405
                return nil, err
3✔
3406
        }
3407

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

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

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

3436
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
×
3437

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

3446
        return shutdownMsg, nil
×
3447
}
3448

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

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

3462
        // The req will only be set if we initiated the co-op closing flow.
3463
        var maxFee chainfee.SatPerKWeight
3✔
3464
        if req != nil {
6✔
3465
                maxFee = req.MaxFee
3✔
3466
        }
3✔
3467

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

3493
        return chanCloser, nil
3✔
3494
}
3495

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

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

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

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

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

3535
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
3✔
3536
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
3✔
3537

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

×
3547
                p.activeChanCloses.Delete(chanID)
×
3548

×
3549
                return fmt.Errorf("unable to shutdown channel: %w", err)
×
3550
        }
×
3551

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

3564
        if !link.DisableAdds(htlcswitch.Outgoing) {
3✔
3565
                p.log.Warnf("Outgoing link adds already "+
×
3566
                        "disabled: %v", link.ChanID())
×
3567
        }
×
3568

3569
        link.OnCommitOnce(htlcswitch.Outgoing, func() {
6✔
3570
                p.queueMsg(shutdownMsg, nil)
3✔
3571
        })
3✔
3572

3573
        return nil
3✔
3574
}
3575

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

3583
        return fn.Some(addr)
×
3584
}
3585

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

3✔
3593
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3594
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3595

3✔
3596
        var (
3✔
3597
                lastTxids    lntypes.Dual[chainhash.Hash]
3✔
3598
                lastFeeRates lntypes.Dual[chainfee.SatPerVByte]
3✔
3599
        )
3✔
3600

3✔
3601
        maybeNotifyTxBroadcast := func(state chancloser.AsymmetricPeerState,
3✔
3602
                party lntypes.ChannelParty) {
6✔
3603

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

3✔
3613
                        peerLog.Warnf("ChannelPoint(%v): encountered close "+
3✔
3614
                                "err: %v", closeReq.ChanPoint, err)
3✔
3615

3✔
3616
                        select {
3✔
3617
                        case closeReq.Err <- err:
3✔
3618
                        case <-closeReq.Ctx.Done():
×
3619
                        case <-p.cg.Done():
×
3620
                        }
3621

3622
                        return
3✔
3623
                }
3624

3625
                closePending, ok := state.(*chancloser.ClosePending)
3✔
3626

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

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

3✔
3642
                        return
3✔
3643
                }
3✔
3644

3645
                feeRate := closePending.FeeRate
3✔
3646
                lastFeeRates.SetForParty(party, feeRate)
3✔
3647

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

3664
                        case <-closeReq.Ctx.Done():
×
3665
                                return
×
3666

3667
                        case <-p.cg.Done():
×
3668
                                return
×
3669
                        }
3670
                }
3671

3672
                lastTxids.SetForParty(party, closingTxid)
3✔
3673
        }
3674

3675
        peerLog.Infof("Observing RBF close updates for channel %v",
3✔
3676
                closeReq.ChanPoint)
3✔
3677

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

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

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

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

3✔
3720
                                return
3✔
3721
                        }
3722

3723
                case <-closeReq.Ctx.Done():
3✔
3724
                        return
3✔
3725

3726
                case <-p.cg.Done():
3✔
3727
                        return
3✔
3728
                }
3729
        }
3730
}
3731

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

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

3✔
3744
        return &chanErrorReporter{
3✔
3745
                chanID: chanID,
3✔
3746
                peer:   peer,
3✔
3747
        }
3✔
3748
}
3✔
3749

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

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

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

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

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

×
3788
                return
×
3789
        }
×
3790

3791
        if _, err := c.peer.initRbfChanCloser(lnChan); err != nil {
×
3792
                c.peer.activeChanCloses.Delete(c.chanID)
×
3793

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

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

3✔
3808
        defer p.cg.WgDone()
3✔
3809

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

3816
        coopCloseStates := chanCloser.RegisterStateEvents()
3✔
3817
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3818

3✔
3819
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3820

3✔
3821
        sendChanFlushed := func() {
6✔
3822
                chanState := channel.StateSnapshot()
3✔
3823

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

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

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

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

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

3✔
3860
                                return
3✔
3861
                        }
3✔
3862

3863
                case <-p.cg.Done():
3✔
3864
                        return
3✔
3865
                }
3866
        }
3867
}
3868

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

3✔
3875
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
3✔
3876

3✔
3877
        link := p.fetchLinkFromKeyAndCid(chanID)
3✔
3878

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

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

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

3896
        peerPub := *p.IdentityKey()
3✔
3897

3✔
3898
        msgMapper := chancloser.NewRbfMsgMapper(
3✔
3899
                uint32(startingHeight), chanID, peerPub,
3✔
3900
        )
3✔
3901

3✔
3902
        initialState := chancloser.ChannelActive{}
3✔
3903

3✔
3904
        scid := channel.ZeroConfRealScid().UnwrapOr(
3✔
3905
                channel.ShortChanID(),
3✔
3906
        )
3✔
3907

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

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

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

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

3✔
3959
        ctx := context.Background()
3✔
3960
        chanCloser := protofsm.NewStateMachine(protoCfg)
3✔
3961
        chanCloser.Start(ctx)
3✔
3962

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

3✔
3968
                return r.RegisterEndpoint(&chanCloser)
3✔
3969
        })
3✔
3970
        if err != nil {
3✔
3971
                chanCloser.Stop()
×
3972

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

3977
        p.activeChanCloses.Store(chanID, makeRbfCloser(&chanCloser))
3✔
3978

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

3✔
3985
        return &chanCloser, nil
3✔
3986
}
3987

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

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

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

4007
                return feeRate
3✔
4008
        })(s)
4009

4010
        return fn.FlattenOption(feeRateOpt)
3✔
4011
}
4012

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

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

4030
                return addr
3✔
4031
        })(s)
4032

4033
        return fn.FlattenOption(addrOpt)
3✔
4034
}
4035

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

3✔
4042
                init.WhenLeft(f)
3✔
4043
        })
3✔
4044
}
4045

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

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

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

3✔
4065
        coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4066
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
4067
        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4068

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

4077
                localState := state.PeerState.GetForParty(lntypes.Local)
3✔
4078

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

3✔
4083
                return ok
3✔
4084
        }
4085

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

4096
        peerLog.Debugf("Waiting for RBF iteration to complete...")
×
4097

×
4098
        for {
×
4099
                select {
×
4100
                case newState := <-newStateChan:
×
4101
                        if isTerminalState(newState) {
×
4102
                                return nil
×
4103
                        }
×
4104

4105
                case <-ctx.Done():
×
4106
                        return fmt.Errorf("context canceled")
×
4107
                }
4108
        }
4109
}
4110

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

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

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

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

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

×
4149
                        return
×
4150
                }
×
4151

4152
                coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4153

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

3✔
4161
                        p.cg.WgAdd(1)
3✔
4162
                        go func() {
6✔
4163
                                defer p.cg.WgDone()
3✔
4164

3✔
4165
                                p.observeRbfCloseUpdates(
3✔
4166
                                        rbfCloser, req, coopCloseStates,
3✔
4167
                                )
3✔
4168
                        }()
3✔
4169
                })
4170

4171
                if !rpcShutdown {
6✔
4172
                        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4173
                }
3✔
4174

4175
                ctx, _ := p.cg.Create(context.Background())
3✔
4176
                feeRate := defaultFeePerKw.FeePerVByte()
3✔
4177

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

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

×
4208
                                return
×
4209
                        }
×
4210

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

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

4224
        return nil
3✔
4225
}
4226

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

3✔
4232
        channel, ok := p.activeChannels.Load(chanID)
3✔
4233

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

4244
        isTaprootChan := channel.ChanType().IsTaproot()
3✔
4245

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

4268
                if err != nil {
3✔
UNCOV
4269
                        p.log.Errorf(err.Error())
×
UNCOV
4270
                        req.Err <- err
×
UNCOV
4271
                }
×
4272

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

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

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

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

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

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

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

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

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

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

4366
                err := p.SendMessage(true, networkMsg)
3✔
4367
                if err != nil {
4✔
4368
                        p.log.Errorf("unable to send msg to "+
1✔
4369
                                "remote peer: %v", err)
1✔
4370
                }
1✔
4371
        }
4372

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

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

3✔
4386
        var chanLink htlcswitch.ChannelUpdateHandler
3✔
4387

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

4398
        return chanLink
3✔
4399
}
4400

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

3✔
4409
        // First, we'll clear all indexes related to the channel in question.
3✔
4410
        chanPoint := chanCloser.Channel().ChannelPoint()
3✔
4411
        p.WipeChannel(&chanPoint)
3✔
4412

3✔
4413
        // Also clear the activeChanCloses map of this channel.
3✔
4414
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4415
        p.activeChanCloses.Delete(cid) // TODO(roasbeef): existing race
3✔
4416

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

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

4430
        closingTx, err := chanCloser.ClosingTx()
3✔
4431
        if err != nil {
3✔
4432
                if closeReq != nil {
×
4433
                        p.log.Error(err)
×
4434
                        closeReq.Err <- err
×
4435
                }
×
4436
        }
4437

4438
        closingTxid := closingTx.TxHash()
3✔
4439

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

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

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

3✔
4478
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
3✔
4479
                "with txid: %v", chanPoint, closingTxID)
3✔
4480

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

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

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

3✔
4504
        // Finally, execute the closure call back to mark the confirmation of
3✔
4505
        // the transaction closing the contract.
3✔
4506
        cb()
3✔
4507
}
4508

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

3✔
4514
        p.activeChannels.Delete(chanID)
3✔
4515

3✔
4516
        // Instruct the HtlcSwitch to close this link as the channel is no
3✔
4517
        // longer active.
3✔
4518
        p.cfg.Switch.RemoveLink(chanID)
3✔
4519
}
3✔
4520

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

4532
        // Then, finalize the remote feature vector providing the flattened
4533
        // feature bit namespace.
4534
        p.remoteFeatures = lnwire.NewFeatureVector(
3✔
4535
                msg.Features, lnwire.Features,
3✔
4536
        )
3✔
4537

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

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

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

4559
        return nil
3✔
4560
}
4561

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

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

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

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

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

×
UNCOV
4604
                // Unset and set in both the local and global features to
×
UNCOV
4605
                // ensure both sets are consistent and merge able by old and
×
UNCOV
4606
                // new nodes.
×
UNCOV
4607
                features.Unset(lnwire.StaticRemoteKeyRequired)
×
UNCOV
4608
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
×
UNCOV
4609

×
UNCOV
4610
                features.Set(lnwire.StaticRemoteKeyOptional)
×
UNCOV
4611
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
×
UNCOV
4612
        }
×
4613

4614
        msg := lnwire.NewInitMessage(
3✔
4615
                legacyFeatures.RawFeatureVector,
3✔
4616
                features.RawFeatureVector,
3✔
4617
        )
3✔
4618

3✔
4619
        return p.writeMessage(msg)
3✔
4620
}
4621

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

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

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

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

4648
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
3✔
4649
                "peer", cid)
3✔
4650

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

4656
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
3✔
4657
                cid)
3✔
4658

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

3✔
4663
        return nil
3✔
4664
}
4665

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

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

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

4707
                if priority {
6✔
4708
                        p.queueMsg(msg, errChan)
3✔
4709
                } else {
6✔
4710
                        p.queueMsgLazy(msg, errChan)
3✔
4711
                }
3✔
4712
        }
4713

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

4727
        return nil
3✔
4728
}
4729

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

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

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

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

3✔
4758
        errChan := make(chan error, 1)
3✔
4759
        newChanMsg := &newChannelMsg{
3✔
4760
                channel: newChan,
3✔
4761
                err:     errChan,
3✔
4762
        }
3✔
4763

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

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

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

3✔
4789
        errChan := make(chan error, 1)
3✔
4790
        newChanMsg := &newChannelMsg{
3✔
4791
                channelID: cid,
3✔
4792
                err:       errChan,
3✔
4793
        }
3✔
4794

3✔
4795
        select {
3✔
4796
        case p.newPendingChannel <- newChanMsg:
3✔
4797

4798
        case <-cancel:
×
4799
                return errors.New("canceled adding pending channel")
×
4800

4801
        case <-p.cg.Done():
×
4802
                return lnpeer.ErrPeerExiting
×
4803
        }
4804

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

4812
        case <-cancel:
×
4813
                return errors.New("canceled adding pending channel")
×
4814

4815
        case <-p.cg.Done():
×
4816
                return lnpeer.ErrPeerExiting
×
4817
        }
4818
}
4819

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

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

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

4843
        case <-p.cg.Done():
×
4844
                return lnpeer.ErrPeerExiting
×
4845
        }
4846
}
4847

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

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

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

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

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

4880
        if chanCloserE.IsRight() {
3✔
4881
                // TODO(roasbeef): assert?
×
4882
                return
×
4883
        }
×
4884

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

4894
        handleErr := func(err error) {
4✔
4895
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
4896
                p.log.Error(err)
1✔
4897

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

4905
                p.activeChanCloses.Delete(msg.cid)
1✔
4906

1✔
4907
                p.Disconnect(err)
1✔
4908
        }
4909

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

4920
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
3✔
4921
                if err != nil {
3✔
4922
                        handleErr(err)
×
4923
                        return
×
4924
                }
×
4925

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

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

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

4950
                beginNegotiation := func() {
6✔
4951
                        oClosingSigned, err := chanCloser.BeginNegotiation()
3✔
4952
                        if err != nil {
3✔
UNCOV
4953
                                handleErr(err)
×
UNCOV
4954
                                return
×
UNCOV
4955
                        }
×
4956

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

4962
                if link == nil {
3✔
UNCOV
4963
                        beginNegotiation()
×
4964
                } else {
3✔
4965
                        // Now we register a flush hook to advance the
3✔
4966
                        // ChanCloser and possibly send out a ClosingSigned
3✔
4967
                        // when the link finishes draining.
3✔
4968
                        link.OnFlushedOnce(func() {
6✔
4969
                                // Remove link in goroutine to prevent deadlock.
3✔
4970
                                go p.cfg.Switch.RemoveLink(msg.cid)
3✔
4971
                                beginNegotiation()
3✔
4972
                        })
3✔
4973
                }
4974

4975
        case *lnwire.ClosingSigned:
3✔
4976
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
3✔
4977
                if err != nil {
4✔
4978
                        handleErr(err)
1✔
4979
                        return
1✔
4980
                }
1✔
4981

4982
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
6✔
4983
                        p.queueMsg(&msg, nil)
3✔
4984
                })
3✔
4985

4986
        default:
×
4987
                panic("impossible closeMsg type")
×
4988
        }
4989

4990
        // If we haven't finished close negotiations, then we'll continue as we
4991
        // can't yet finalize the closure.
4992
        if _, err := chanCloser.ClosingTx(); err != nil {
6✔
4993
                return
3✔
4994
        }
3✔
4995

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

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

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

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

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

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

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

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

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

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

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

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

5069
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
5070
        if !ok {
×
5071
                return nil
×
5072
        }
×
5073

5074
        return pingBytes
×
5075
}
5076

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

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

5098
        p.channelEventClient = sub
3✔
5099

3✔
5100
        return nil
3✔
5101
}
5102

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

3✔
5109
        // Read the current channel.
3✔
5110
        currentChan, loaded := p.activeChannels.Load(chanID)
3✔
5111

3✔
5112
        // currentChan should exist, but we perform a check anyway to avoid nil
3✔
5113
        // pointer dereference.
3✔
5114
        if !loaded {
3✔
UNCOV
5115
                return fmt.Errorf("missing active channel with chanID=%v",
×
UNCOV
5116
                        chanID)
×
UNCOV
5117
        }
×
5118

5119
        // currentChan should not be nil, but we perform a check anyway to
5120
        // avoid nil pointer dereference.
5121
        if currentChan == nil {
3✔
UNCOV
5122
                return fmt.Errorf("found nil active channel with chanID=%v",
×
UNCOV
5123
                        chanID)
×
UNCOV
5124
        }
×
5125

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

5133
        p.log.Infof("Processing retransmitted ChannelReady for "+
3✔
5134
                "ChannelPoint(%v)", chanPoint)
3✔
5135

3✔
5136
        nextRevoke := c.RemoteNextRevocation
3✔
5137

3✔
5138
        err := currentChan.InitNextRevocation(nextRevoke)
3✔
5139
        if err != nil {
3✔
5140
                return fmt.Errorf("unable to init next revocation: %w", err)
×
5141
        }
×
5142

5143
        return nil
3✔
5144
}
5145

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

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

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

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

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

5188
        // Store the channel in the activeChannels map.
5189
        p.activeChannels.Store(chanID, lnChan)
3✔
5190

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

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

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

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

5219
        isTaprootChan := c.ChanType.IsTaproot()
3✔
5220

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

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

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

5241
        return nil
3✔
5242
}
5243

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

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

3✔
5259
                // Handle it and close the err chan on the request.
3✔
5260
                close(req.err)
3✔
5261

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

5268
                return
3✔
5269
        }
5270

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

×
5277
                return
×
5278
        }
×
5279

5280
        // Close the err chan if everything went fine.
5281
        close(req.err)
3✔
5282
}
5283

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

3✔
5291
        chanID := req.channelID
3✔
5292

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

×
UNCOV
5301
                return
×
UNCOV
5302
        }
×
5303

5304
        // The channel has already been added, we will do nothing and return.
5305
        if p.isPendingChannel(chanID) {
3✔
UNCOV
5306
                p.log.Infof("Channel(%v) is already added, ignoring "+
×
UNCOV
5307
                        "pending channel request", chanID)
×
UNCOV
5308

×
UNCOV
5309
                return
×
UNCOV
5310
        }
×
5311

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

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

3✔
5325
        chanID := req.channelID
3✔
5326

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

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

5342
        // Remove the record of this pending channel.
5343
        p.activeChannels.Delete(chanID)
3✔
5344
        p.addedChannels.Delete(chanID)
3✔
5345
}
5346

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

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

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

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

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

UNCOV
5381
        return timeout
×
5382
}
5383

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

5389
        ErrChan chan error
5390
}
5391

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

5401
        return chanCloser.IsRight()
3✔
5402
}
5403

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

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

5418
        closeUpdates := &CoopCloseUpdates{
3✔
5419
                UpdateChan: make(chan interface{}, 1),
3✔
5420
                ErrChan:    make(chan error, 1),
3✔
5421
        }
3✔
5422

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

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

5440
        return closeUpdates, nil
3✔
5441
}
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