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

lightningnetwork / lnd / 14919919715

09 May 2025 02:10AM UTC coverage: 58.581% (-0.009%) from 58.59%
14919919715

Pull #9797

github

web-flow
Merge 49fa69b5e into ee25c228e
Pull Request #9797: peer: introduce super priority send queue for pings+pongs

33 of 119 new or added lines in 1 file covered. (27.73%)

35 existing lines in 11 files now uncovered.

97442 of 166336 relevant lines covered (58.58%)

1.82 hits per line

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

75.98
/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 = 5
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
        // Quit is the server's quit channel. If this is closed, we halt operation.
459
        Quit chan struct{}
460
}
461

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

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

476
// makeRbfCloser creates a new RBF closer from a chancloser.RbfChanCloser.
477
func makeRbfCloser(rbfCloser *chancloser.RbfChanCloser) chanCloserFsm {
3✔
478
        return fn.NewRight[*chancloser.ChanCloser](
3✔
479
                rbfCloser,
3✔
480
        )
3✔
481
}
3✔
482

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

493
        // MUST be used atomically.
494
        bytesReceived uint64
495
        bytesSent     uint64
496

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

514
        pingManager *PingManager
515

516
        // lastPingPayload stores an unsafe pointer wrapped as an atomic
517
        // variable which points to the last payload the remote party sent us
518
        // as their ping.
519
        //
520
        // MUST be used atomically.
521
        lastPingPayload atomic.Value
522

523
        cfg Config
524

525
        // activeSignal when closed signals that the peer is now active and
526
        // ready to process messages.
527
        activeSignal chan struct{}
528

529
        // startTime is the time this peer connection was successfully established.
530
        // It will be zero for peers that did not successfully call Start().
531
        startTime time.Time
532

533
        // sendQueue is the channel which is used to queue outgoing messages to be
534
        // written onto the wire. Note that this channel is unbuffered.
535
        sendQueue chan outgoingMsg
536

537
        // outgoingQueue is a buffered channel which allows second/third party
538
        // objects to queue messages to be sent out on the wire.
539
        outgoingQueue chan outgoingMsg
540

541
        // superPrioSendQueue is a channel for messages that must bypass the
542
        // regular sendQueue, such as pings.
543
        superPrioSendQueue 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
                superPrioSendQueue: make(chan outgoingMsg, 2),
3✔
663
                addedChannels: &lnutils.SyncMap[
3✔
664
                        lnwire.ChannelID, struct{},
3✔
665
                ]{},
3✔
666
                activeChannels: &lnutils.SyncMap[
3✔
667
                        lnwire.ChannelID, *lnwallet.LightningChannel,
3✔
668
                ]{},
3✔
669
                newActiveChannel:     make(chan *newChannelMsg, 1),
3✔
670
                newPendingChannel:    make(chan *newChannelMsg, 1),
3✔
671
                removePendingChannel: make(chan *newChannelMsg),
3✔
672

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

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

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

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

721
                return lastSerializedBlockHeader[:]
×
722
        }
723

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

737
        p.pingManager = NewPingManager(&PingManagerConfig{
3✔
738
                NewPingPayload:   newPingPayload,
3✔
739
                NewPongSize:      randPongSize,
3✔
740
                IntervalDuration: p.scaleTimeout(pingInterval),
3✔
741
                TimeoutDuration:  p.scaleTimeout(pingTimeout),
3✔
742
                SendPing: func(ping *lnwire.Ping) {
3✔
NEW
743
                        // Pings are fire-and-forget, so sync=false,
×
NEW
744
                        // errChan=nil. These messages are sent via the super
×
NEW
745
                        // priority queue to avoid delays from other messages.
×
NEW
746
                        err := p.SendSuperPriorityMessage(false, ping)
×
NEW
747
                        if err != nil &&
×
NEW
748
                                !errors.Is(err, lnpeer.ErrPeerExiting) {
×
NEW
749

×
NEW
750
                                p.log.Warnf("Failed to send ping "+
×
NEW
751
                                        "via super priority queue: %v", err)
×
NEW
752
                        }
×
753
                },
754
                OnPongFailure: func(err error) {
×
755
                        eStr := "pong response failure for %s: %v " +
×
756
                                "-- disconnecting"
×
757
                        p.log.Warnf(eStr, p, err)
×
758
                        go p.Disconnect(fmt.Errorf(eStr, p, err))
×
759
                },
×
760
        })
761

762
        return p
3✔
763
}
764

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

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

3✔
777
        p.log.Tracef("starting with conn[%v->%v]",
3✔
778
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
3✔
779

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

791
        if len(activeChans) == 0 {
6✔
792
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
3✔
793
        }
3✔
794

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

803
                haveLegacyChan = true
3✔
804
                break
3✔
805
        }
806

807
        // Exchange local and global features, the init message should be very
808
        // first between two nodes.
809
        if err := p.sendInitMsg(haveLegacyChan); err != nil {
5✔
810
                return fmt.Errorf("unable to send init msg: %w", err)
2✔
811
        }
2✔
812

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

3✔
822
                msg, err := p.readNextMessage()
3✔
823
                if err != nil {
4✔
824
                        readErr <- err
1✔
825
                        msgChan <- nil
1✔
826
                        return
1✔
827
                }
1✔
828
                readErr <- nil
3✔
829
                msgChan <- msg
3✔
830
        }()
831

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

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

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

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

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

880
        msgs, err := p.loadActiveChannels(activeChans)
3✔
881
        if err != nil {
3✔
882
                return fmt.Errorf("unable to load channels: %w", err)
×
883
        }
×
884

885
        p.startTime = time.Now()
3✔
886

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

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

904
        err = p.pingManager.Start()
3✔
905
        if err != nil {
3✔
906
                return fmt.Errorf("could not start ping manager %w", err)
×
907
        }
×
908

909
        p.cg.WgAdd(4)
3✔
910
        go p.queueHandler()
3✔
911
        go p.writeHandler()
3✔
912
        go p.channelManager()
3✔
913
        go p.readHandler()
3✔
914

3✔
915
        // Signal to any external processes that the peer is now active.
3✔
916
        close(p.activeSignal)
3✔
917

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

3✔
933
        return nil
3✔
934
}
935

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

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

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

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

971
// rbfCoopCloseAllowed returns true if both parties have negotiated the new RBF
972
// coop close feature.
973
func (p *Brontide) rbfCoopCloseAllowed() bool {
3✔
974
        return p.RemoteFeatures().HasFeature(
3✔
975
                lnwire.RbfCoopCloseOptionalStaging,
3✔
976
        ) && p.LocalFeatures().HasFeature(
3✔
977
                lnwire.RbfCoopCloseOptionalStaging,
3✔
978
        )
3✔
979
}
3✔
980

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

991
// addrWithInternalKey takes a delivery script, then attempts to supplement it
992
// with information related to the internal key for the addr, but only if it's
993
// a taproot addr.
994
func (p *Brontide) addrWithInternalKey(
995
        deliveryScript []byte) (*chancloser.DeliveryAddrWithKey, error) {
3✔
996

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

1008
        return &chancloser.DeliveryAddrWithKey{
3✔
1009
                DeliveryAddress: deliveryScript,
3✔
1010
                InternalKey: fn.MapOption(
3✔
1011
                        func(desc keychain.KeyDescriptor) btcec.PublicKey {
6✔
1012
                                return *desc.PubKey
3✔
1013
                        },
3✔
1014
                )(internalKeyDesc),
1015
        }, nil
1016
}
1017

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

3✔
1025
        // Return a slice of messages to send to the peers in case the channel
3✔
1026
        // cannot be loaded normally.
3✔
1027
        var msgs []lnwire.Message
3✔
1028

3✔
1029
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
3✔
1030

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

1051
                                err = p.cfg.AddLocalAlias(
3✔
1052
                                        aliasScid, dbChan.ShortChanID(), false,
3✔
1053
                                        false,
3✔
1054
                                )
3✔
1055
                                if err != nil {
3✔
1056
                                        return nil, err
×
1057
                                }
×
1058

1059
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
1060
                                        dbChan.FundingOutpoint,
3✔
1061
                                )
3✔
1062

3✔
1063
                                // Fetch the second commitment point to send in
3✔
1064
                                // the channel_ready message.
3✔
1065
                                second, err := dbChan.SecondCommitmentPoint()
3✔
1066
                                if err != nil {
3✔
1067
                                        return nil, err
×
1068
                                }
×
1069

1070
                                channelReadyMsg := lnwire.NewChannelReady(
3✔
1071
                                        chanID, second,
3✔
1072
                                )
3✔
1073
                                channelReadyMsg.AliasScid = &aliasScid
3✔
1074

3✔
1075
                                msgs = append(msgs, channelReadyMsg)
3✔
1076
                        }
1077

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

1089
                var chanOpts []lnwallet.ChannelOpt
3✔
1090
                p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
3✔
1091
                        chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
1092
                })
×
1093
                p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
3✔
1094
                        chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
1095
                })
×
1096
                p.cfg.AuxResolver.WhenSome(
3✔
1097
                        func(s lnwallet.AuxContractResolver) {
3✔
1098
                                chanOpts = append(
×
1099
                                        chanOpts, lnwallet.WithAuxResolver(s),
×
1100
                                )
×
1101
                        },
×
1102
                )
1103

1104
                lnChan, err := lnwallet.NewLightningChannel(
3✔
1105
                        p.cfg.Signer, dbChan, p.cfg.SigPool, chanOpts...,
3✔
1106
                )
3✔
1107
                if err != nil {
3✔
1108
                        return nil, fmt.Errorf("unable to create channel "+
×
1109
                                "state machine: %w", err)
×
1110
                }
×
1111

1112
                chanPoint := dbChan.FundingOutpoint
3✔
1113

3✔
1114
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1115

3✔
1116
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
3✔
1117
                        chanPoint, lnChan.IsPending())
3✔
1118

3✔
1119
                // Skip adding any permanently irreconcilable channels to the
3✔
1120
                // htlcswitch.
3✔
1121
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
3✔
1122
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
6✔
1123

3✔
1124
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
3✔
1125
                                "start.", chanPoint, dbChan.ChanStatus())
3✔
1126

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

1141
                        msgs = append(msgs, chanSync)
3✔
1142

3✔
1143
                        // Check if this channel needs to have the cooperative
3✔
1144
                        // close process restarted. If so, we'll need to send
3✔
1145
                        // the Shutdown message that is returned.
3✔
1146
                        if dbChan.HasChanStatus(
3✔
1147
                                channeldb.ChanStatusCoopBroadcasted,
3✔
1148
                        ) {
6✔
1149

3✔
1150
                                shutdownMsg, err := p.restartCoopClose(lnChan)
3✔
1151
                                if err != nil {
3✔
1152
                                        p.log.Errorf("Unable to restart "+
×
1153
                                                "coop close for channel: %v",
×
1154
                                                err)
×
1155
                                        continue
×
1156
                                }
1157

1158
                                if shutdownMsg == nil {
6✔
1159
                                        continue
3✔
1160
                                }
1161

1162
                                // Append the message to the set of messages to
1163
                                // send.
1164
                                msgs = append(msgs, shutdownMsg)
×
1165
                        }
1166

1167
                        continue
3✔
1168
                }
1169

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

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

3✔
1192
                        selfPolicy = p1
3✔
1193
                } else {
6✔
1194
                        selfPolicy = p2
3✔
1195
                }
3✔
1196

1197
                // If we don't yet have an advertised routing policy, then
1198
                // we'll use the current default, otherwise we'll translate the
1199
                // routing policy into a forwarding policy.
1200
                var forwardingPolicy *models.ForwardingPolicy
3✔
1201
                if selfPolicy != nil {
6✔
1202
                        var inboundWireFee lnwire.Fee
3✔
1203
                        _, err := selfPolicy.ExtraOpaqueData.ExtractRecords(
3✔
1204
                                &inboundWireFee,
3✔
1205
                        )
3✔
1206
                        if err != nil {
3✔
1207
                                return nil, err
×
1208
                        }
×
1209

1210
                        inboundFee := models.NewInboundFeeFromWire(
3✔
1211
                                inboundWireFee,
3✔
1212
                        )
3✔
1213

3✔
1214
                        forwardingPolicy = &models.ForwardingPolicy{
3✔
1215
                                MinHTLCOut:    selfPolicy.MinHTLC,
3✔
1216
                                MaxHTLC:       selfPolicy.MaxHTLC,
3✔
1217
                                BaseFee:       selfPolicy.FeeBaseMSat,
3✔
1218
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
3✔
1219
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
3✔
1220

3✔
1221
                                InboundFee: inboundFee,
3✔
1222
                        }
3✔
1223
                } else {
3✔
1224
                        p.log.Warnf("Unable to find our forwarding policy "+
3✔
1225
                                "for channel %v, using default values",
3✔
1226
                                chanPoint)
3✔
1227
                        forwardingPolicy = &p.cfg.RoutingPolicy
3✔
1228
                }
3✔
1229

1230
                p.log.Tracef("Using link policy of: %v",
3✔
1231
                        spew.Sdump(forwardingPolicy))
3✔
1232

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

3✔
1242
                        continue
3✔
1243
                }
1244

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

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

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

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

×
1272
                                return
×
1273
                        }
×
1274

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

×
1291
                                return
×
1292
                        }
×
1293

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

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

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

×
1308
                                return
×
1309
                        }
×
1310

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

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

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

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

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

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

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

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

1373
        return msgs, nil
3✔
1374
}
1375

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

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

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

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

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

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

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

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

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

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

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

1486
                hasConfirmedPublicChan = true
3✔
1487
                break
3✔
1488
        }
1489
        if !hasConfirmedPublicChan {
6✔
1490
                return
3✔
1491
        }
3✔
1492

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

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

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

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

1514
        maybeSendUpd := func(cid lnwire.ChannelID,
3✔
1515
                lnChan *lnwallet.LightningChannel) error {
6✔
1516

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

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

1530
                        // Otherwise, we can use the normal scid.
1531
                        default:
3✔
1532
                                return dbChan.ShortChanID()
3✔
1533
                        }
1534
                }()
1535

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

3✔
1546
                        return nil
3✔
1547
                }
3✔
1548

1549
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
3✔
1550
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
3✔
1551

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

×
1561
                        return err
×
1562
                }
×
1563

1564
                return nil
3✔
1565
        }
1566

1567
        p.activeChannels.ForEach(maybeSendUpd)
3✔
1568
}
1569

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

1587
        select {
3✔
1588
        case <-ready:
3✔
1589
        case <-p.cg.Done():
2✔
1590
        }
1591

1592
        p.cg.WgWait()
3✔
1593
}
1594

1595
// Disconnect terminates the connection with the remote peer. Additionally, a
1596
// signal is sent to the server and htlcSwitch indicating the resources
1597
// allocated to the peer can now be cleaned up.
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("Started, waiting on startReady signal")
3✔
1611

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1722
        peer *Brontide
1723

1724
        apply func(lnwire.Message)
1725

1726
        startMsg string
1727
        stopMsg  string
1728

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

1732
        mtx sync.Mutex
1733

1734
        producerSema chan struct{}
1735

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

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

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

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

1766
        return stream
3✔
1767
}
1768

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1920
                        chanPoint := event.ChannelPoint
3✔
1921

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

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

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

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

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

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

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

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

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

1983
// newDiscMsgStream is used to setup a msgStream between the peer and the
1984
// authenticated gossiper. This stream should be used to forward all remote
1985
// channel announcements.
1986
func newDiscMsgStream(p *Brontide) *msgStream {
3✔
1987
        apply := func(msg lnwire.Message) {
6✔
1988
                // TODO(yy): `ProcessRemoteAnnouncement` returns an error chan
3✔
1989
                // and we need to process it.
3✔
1990
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(msg, p)
3✔
1991
        }
3✔
1992

1993
        return newMsgStream(
3✔
1994
                p,
3✔
1995
                "Update stream for gossiper created",
3✔
1996
                "Update stream for gossiper exited",
3✔
1997
                msgStreamSize,
3✔
1998
                apply,
3✔
1999
        )
3✔
2000
}
2001

2002
// readHandler is responsible for reading messages off the wire in series, then
2003
// properly dispatching the handling of the message to the proper subsystem.
2004
//
2005
// NOTE: This method MUST be run as a goroutine.
2006
func (p *Brontide) readHandler() {
3✔
2007
        defer p.cg.WgDone()
3✔
2008

3✔
2009
        // We'll stop the timer after a new messages is received, and also
3✔
2010
        // reset it after we process the next message.
3✔
2011
        idleTimer := time.AfterFunc(idleTimeout, func() {
3✔
2012
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
2013
                        p, idleTimeout)
×
2014
                p.Disconnect(err)
×
2015
        })
×
2016

2017
        // Initialize our negotiated gossip sync method before reading messages
2018
        // off the wire. When using gossip queries, this ensures a gossip
2019
        // syncer is active by the time query messages arrive.
2020
        //
2021
        // TODO(conner): have peer store gossip syncer directly and bypass
2022
        // gossiper?
2023
        p.initGossipSync()
3✔
2024

3✔
2025
        discStream := newDiscMsgStream(p)
3✔
2026
        discStream.Start()
3✔
2027
        defer discStream.Stop()
3✔
2028
out:
3✔
2029
        for atomic.LoadInt32(&p.disconnect) == 0 {
6✔
2030
                nextMsg, err := p.readNextMessage()
3✔
2031
                if !idleTimer.Stop() {
6✔
2032
                        select {
3✔
2033
                        case <-idleTimer.C:
×
2034
                        default:
3✔
2035
                        }
2036
                }
2037
                if err != nil {
6✔
2038
                        p.log.Infof("unable to read message from peer: %v", err)
3✔
2039

3✔
2040
                        // If we could not read our peer's message due to an
3✔
2041
                        // unknown type or invalid alias, we continue processing
3✔
2042
                        // as normal. We store unknown message and address
3✔
2043
                        // types, as they may provide debugging insight.
3✔
2044
                        switch e := err.(type) {
3✔
2045
                        // If this is just a message we don't yet recognize,
2046
                        // we'll continue processing as normal as this allows
2047
                        // us to introduce new messages in a forwards
2048
                        // compatible manner.
2049
                        case *lnwire.UnknownMessage:
3✔
2050
                                p.storeError(e)
3✔
2051
                                idleTimer.Reset(idleTimeout)
3✔
2052
                                continue
3✔
2053

2054
                        // If they sent us an address type that we don't yet
2055
                        // know of, then this isn't a wire error, so we'll
2056
                        // simply continue parsing the remainder of their
2057
                        // messages.
2058
                        case *lnwire.ErrUnknownAddrType:
×
2059
                                p.storeError(e)
×
2060
                                idleTimer.Reset(idleTimeout)
×
2061
                                continue
×
2062

2063
                        // If the NodeAnnouncement has an invalid alias, then
2064
                        // we'll log that error above and continue so we can
2065
                        // continue to read messages from the peer. We do not
2066
                        // store this error because it is of little debugging
2067
                        // value.
2068
                        case *lnwire.ErrInvalidNodeAlias:
×
2069
                                idleTimer.Reset(idleTimeout)
×
2070
                                continue
×
2071

2072
                        // If the error we encountered wasn't just a message we
2073
                        // didn't recognize, then we'll stop all processing as
2074
                        // this is a fatal error.
2075
                        default:
3✔
2076
                                break out
3✔
2077
                        }
2078
                }
2079

2080
                // If a message router is active, then we'll try to have it
2081
                // handle this message. If it can, then we're able to skip the
2082
                // rest of the message handling logic.
2083
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
6✔
2084
                        return r.RouteMsg(msgmux.PeerMsg{
3✔
2085
                                PeerPub: *p.IdentityKey(),
3✔
2086
                                Message: nextMsg,
3✔
2087
                        })
3✔
2088
                })
3✔
2089

2090
                // No error occurred, and the message was handled by the
2091
                // router.
2092
                if err == nil {
6✔
2093
                        continue
3✔
2094
                }
2095

2096
                var (
3✔
2097
                        targetChan   lnwire.ChannelID
3✔
2098
                        isLinkUpdate bool
3✔
2099
                )
3✔
2100

3✔
2101
                switch msg := nextMsg.(type) {
3✔
2102
                case *lnwire.Pong:
×
2103
                        // When we receive a Pong message in response to our
×
2104
                        // last ping message, we send it to the pingManager
×
2105
                        p.pingManager.ReceivedPong(msg)
×
2106

2107
                case *lnwire.Ping:
×
2108
                        // First, we'll store their latest ping payload within
×
2109
                        // the relevant atomic variable.
×
2110
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
2111

×
2112
                        // Next, we'll send over the amount of specified pong
×
NEW
2113
                        // bytes. Pong responses are sent via the super priority
×
NEW
2114
                        // queue to ensure timely response to pings. These are
×
NEW
2115
                        // fire-and-forget.
×
NEW
2116
                        pong := lnwire.NewPong(
×
NEW
2117
                                p.cfg.PongBuf[0:msg.NumPongBytes],
×
NEW
2118
                        )
×
NEW
2119
                        _ = p.SendSuperPriorityMessage(false, pong)
×
2120

2121
                case *lnwire.OpenChannel,
2122
                        *lnwire.AcceptChannel,
2123
                        *lnwire.FundingCreated,
2124
                        *lnwire.FundingSigned,
2125
                        *lnwire.ChannelReady:
3✔
2126

3✔
2127
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2128

2129
                case *lnwire.Shutdown:
3✔
2130
                        select {
3✔
2131
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
2132
                        case <-p.cg.Done():
×
2133
                                break out
×
2134
                        }
2135
                case *lnwire.ClosingSigned:
3✔
2136
                        select {
3✔
2137
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
2138
                        case <-p.cg.Done():
×
2139
                                break out
×
2140
                        }
2141

2142
                case *lnwire.Warning:
×
2143
                        targetChan = msg.ChanID
×
2144
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2145

2146
                case *lnwire.Error:
3✔
2147
                        targetChan = msg.ChanID
3✔
2148
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
3✔
2149

2150
                case *lnwire.ChannelReestablish:
3✔
2151
                        targetChan = msg.ChanID
3✔
2152
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2153

3✔
2154
                        // If we failed to find the link in question, and the
3✔
2155
                        // message received was a channel sync message, then
3✔
2156
                        // this might be a peer trying to resync closed channel.
3✔
2157
                        // In this case we'll try to resend our last channel
3✔
2158
                        // sync message, such that the peer can recover funds
3✔
2159
                        // from the closed channel.
3✔
2160
                        if !isLinkUpdate {
6✔
2161
                                err := p.resendChanSyncMsg(targetChan)
3✔
2162
                                if err != nil {
6✔
2163
                                        // TODO(halseth): send error to peer?
3✔
2164
                                        p.log.Errorf("resend failed: %v",
3✔
2165
                                                err)
3✔
2166
                                }
3✔
2167
                        }
2168

2169
                // For messages that implement the LinkUpdater interface, we
2170
                // will consider them as link updates and send them to
2171
                // chanStream. These messages will be queued inside chanStream
2172
                // if the channel is not active yet.
2173
                case lnwire.LinkUpdater:
3✔
2174
                        targetChan = msg.TargetChanID()
3✔
2175
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2176

3✔
2177
                        // Log an error if we don't have this channel. This
3✔
2178
                        // means the peer has sent us a message with unknown
3✔
2179
                        // channel ID.
3✔
2180
                        if !isLinkUpdate {
6✔
2181
                                p.log.Errorf("Unknown channel ID: %v found "+
3✔
2182
                                        "in received msg=%s", targetChan,
3✔
2183
                                        nextMsg.MsgType())
3✔
2184
                        }
3✔
2185

2186
                case *lnwire.ChannelUpdate1,
2187
                        *lnwire.ChannelAnnouncement1,
2188
                        *lnwire.NodeAnnouncement,
2189
                        *lnwire.AnnounceSignatures1,
2190
                        *lnwire.GossipTimestampRange,
2191
                        *lnwire.QueryShortChanIDs,
2192
                        *lnwire.QueryChannelRange,
2193
                        *lnwire.ReplyChannelRange,
2194
                        *lnwire.ReplyShortChanIDsEnd:
3✔
2195

3✔
2196
                        discStream.AddMsg(msg)
3✔
2197

2198
                case *lnwire.Custom:
3✔
2199
                        err := p.handleCustomMessage(msg)
3✔
2200
                        if err != nil {
3✔
2201
                                p.storeError(err)
×
2202
                                p.log.Errorf("%v", err)
×
2203
                        }
×
2204

2205
                default:
×
2206
                        // If the message we received is unknown to us, store
×
2207
                        // the type to track the failure.
×
2208
                        err := fmt.Errorf("unknown message type %v received",
×
2209
                                uint16(msg.MsgType()))
×
2210
                        p.storeError(err)
×
2211

×
2212
                        p.log.Errorf("%v", err)
×
2213
                }
2214

2215
                if isLinkUpdate {
6✔
2216
                        // If this is a channel update, then we need to feed it
3✔
2217
                        // into the channel's in-order message stream.
3✔
2218
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
3✔
2219
                }
3✔
2220

2221
                idleTimer.Reset(idleTimeout)
3✔
2222
        }
2223

2224
        p.Disconnect(errors.New("read handler closed"))
3✔
2225

3✔
2226
        p.log.Trace("readHandler for peer done")
3✔
2227
}
2228

2229
// handleCustomMessage handles the given custom message if a handler is
2230
// registered.
2231
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
3✔
2232
        if p.cfg.HandleCustomMessage == nil {
3✔
2233
                return fmt.Errorf("no custom message handler for "+
×
2234
                        "message type %v", uint16(msg.MsgType()))
×
2235
        }
×
2236

2237
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
3✔
2238
}
2239

2240
// isLoadedFromDisk returns true if the provided channel ID is loaded from
2241
// disk.
2242
//
2243
// NOTE: only returns true for pending channels.
2244
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
3✔
2245
        // If this is a newly added channel, no need to reestablish.
3✔
2246
        _, added := p.addedChannels.Load(chanID)
3✔
2247
        if added {
6✔
2248
                return false
3✔
2249
        }
3✔
2250

2251
        // Return false if the channel is unknown.
2252
        channel, ok := p.activeChannels.Load(chanID)
3✔
2253
        if !ok {
3✔
2254
                return false
×
2255
        }
×
2256

2257
        // During startup, we will use a nil value to mark a pending channel
2258
        // that's loaded from disk.
2259
        return channel == nil
3✔
2260
}
2261

2262
// isActiveChannel returns true if the provided channel id is active, otherwise
2263
// returns false.
2264
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
3✔
2265
        // The channel would be nil if,
3✔
2266
        // - the channel doesn't exist, or,
3✔
2267
        // - the channel exists, but is pending. In this case, we don't
3✔
2268
        //   consider this channel active.
3✔
2269
        channel, _ := p.activeChannels.Load(chanID)
3✔
2270

3✔
2271
        return channel != nil
3✔
2272
}
3✔
2273

2274
// isPendingChannel returns true if the provided channel ID is pending, and
2275
// returns false if the channel is active or unknown.
2276
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
3✔
2277
        // Return false if the channel is unknown.
3✔
2278
        channel, ok := p.activeChannels.Load(chanID)
3✔
2279
        if !ok {
6✔
2280
                return false
3✔
2281
        }
3✔
2282

2283
        return channel == nil
3✔
2284
}
2285

2286
// hasChannel returns true if the peer has a pending/active channel specified
2287
// by the channel ID.
2288
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
3✔
2289
        _, ok := p.activeChannels.Load(chanID)
3✔
2290
        return ok
3✔
2291
}
3✔
2292

2293
// storeError stores an error in our peer's buffer of recent errors with the
2294
// current timestamp. Errors are only stored if we have at least one active
2295
// channel with the peer to mitigate a dos vector where a peer costlessly
2296
// connects to us and spams us with errors.
2297
func (p *Brontide) storeError(err error) {
3✔
2298
        var haveChannels bool
3✔
2299

3✔
2300
        p.activeChannels.Range(func(_ lnwire.ChannelID,
3✔
2301
                channel *lnwallet.LightningChannel) bool {
6✔
2302

3✔
2303
                // Pending channels will be nil in the activeChannels map.
3✔
2304
                if channel == nil {
6✔
2305
                        // Return true to continue the iteration.
3✔
2306
                        return true
3✔
2307
                }
3✔
2308

2309
                haveChannels = true
3✔
2310

3✔
2311
                // Return false to break the iteration.
3✔
2312
                return false
3✔
2313
        })
2314

2315
        // If we do not have any active channels with the peer, we do not store
2316
        // errors as a dos mitigation.
2317
        if !haveChannels {
6✔
2318
                p.log.Trace("no channels with peer, not storing err")
3✔
2319
                return
3✔
2320
        }
3✔
2321

2322
        p.cfg.ErrorBuffer.Add(
3✔
2323
                &TimestampedError{Timestamp: time.Now(), Error: err},
3✔
2324
        )
3✔
2325
}
2326

2327
// handleWarningOrError processes a warning or error msg and returns true if
2328
// msg should be forwarded to the associated channel link. False is returned if
2329
// any necessary forwarding of msg was already handled by this method. If msg is
2330
// an error from a peer with an active channel, we'll store it in memory.
2331
//
2332
// NOTE: This method should only be called from within the readHandler.
2333
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
2334
        msg lnwire.Message) bool {
3✔
2335

3✔
2336
        if errMsg, ok := msg.(*lnwire.Error); ok {
6✔
2337
                p.storeError(errMsg)
3✔
2338
        }
3✔
2339

2340
        switch {
3✔
2341
        // Connection wide messages should be forwarded to all channel links
2342
        // with this peer.
2343
        case chanID == lnwire.ConnectionWideID:
×
2344
                for _, chanStream := range p.activeMsgStreams {
×
2345
                        chanStream.AddMsg(msg)
×
2346
                }
×
2347

2348
                return false
×
2349

2350
        // If the channel ID for the message corresponds to a pending channel,
2351
        // then the funding manager will handle it.
2352
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
3✔
2353
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2354
                return false
3✔
2355

2356
        // If not we hand the message to the channel link for this channel.
2357
        case p.isActiveChannel(chanID):
3✔
2358
                return true
3✔
2359

2360
        default:
3✔
2361
                return false
3✔
2362
        }
2363
}
2364

2365
// messageSummary returns a human-readable string that summarizes a
2366
// incoming/outgoing message. Not all messages will have a summary, only those
2367
// which have additional data that can be informative at a glance.
2368
func messageSummary(msg lnwire.Message) string {
3✔
2369
        switch msg := msg.(type) {
3✔
2370
        case *lnwire.Init:
3✔
2371
                // No summary.
3✔
2372
                return ""
3✔
2373

2374
        case *lnwire.OpenChannel:
3✔
2375
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
3✔
2376
                        "push_amt=%v, reserve=%v, flags=%v",
3✔
2377
                        msg.PendingChannelID[:], msg.ChainHash,
3✔
2378
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
3✔
2379
                        msg.ChannelReserve, msg.ChannelFlags)
3✔
2380

2381
        case *lnwire.AcceptChannel:
3✔
2382
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
3✔
2383
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
3✔
2384
                        msg.MinAcceptDepth)
3✔
2385

2386
        case *lnwire.FundingCreated:
3✔
2387
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
3✔
2388
                        msg.PendingChannelID[:], msg.FundingPoint)
3✔
2389

2390
        case *lnwire.FundingSigned:
3✔
2391
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
3✔
2392

2393
        case *lnwire.ChannelReady:
3✔
2394
                return fmt.Sprintf("chan_id=%v, next_point=%x",
3✔
2395
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
3✔
2396

2397
        case *lnwire.Shutdown:
3✔
2398
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
3✔
2399
                        msg.Address[:])
3✔
2400

2401
        case *lnwire.ClosingComplete:
3✔
2402
                return fmt.Sprintf("chan_id=%v, fee_sat=%v, locktime=%v",
3✔
2403
                        msg.ChannelID, msg.FeeSatoshis, msg.LockTime)
3✔
2404

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

2408
        case *lnwire.ClosingSigned:
3✔
2409
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
3✔
2410
                        msg.FeeSatoshis)
3✔
2411

2412
        case *lnwire.UpdateAddHTLC:
3✔
2413
                var blindingPoint []byte
3✔
2414
                msg.BlindingPoint.WhenSome(
3✔
2415
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
3✔
2416
                                *btcec.PublicKey]) {
6✔
2417

3✔
2418
                                blindingPoint = b.Val.SerializeCompressed()
3✔
2419
                        },
3✔
2420
                )
2421

2422
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
3✔
2423
                        "hash=%x, blinding_point=%x, custom_records=%v",
3✔
2424
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
3✔
2425
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
3✔
2426

2427
        case *lnwire.UpdateFailHTLC:
3✔
2428
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
3✔
2429
                        msg.ID, msg.Reason)
3✔
2430

2431
        case *lnwire.UpdateFulfillHTLC:
3✔
2432
                return fmt.Sprintf("chan_id=%v, id=%v, preimage=%x, "+
3✔
2433
                        "custom_records=%v", msg.ChanID, msg.ID,
3✔
2434
                        msg.PaymentPreimage[:], msg.CustomRecords)
3✔
2435

2436
        case *lnwire.CommitSig:
3✔
2437
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
3✔
2438
                        len(msg.HtlcSigs))
3✔
2439

2440
        case *lnwire.RevokeAndAck:
3✔
2441
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
3✔
2442
                        msg.ChanID, msg.Revocation[:],
3✔
2443
                        msg.NextRevocationKey.SerializeCompressed())
3✔
2444

2445
        case *lnwire.UpdateFailMalformedHTLC:
3✔
2446
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
3✔
2447
                        msg.ChanID, msg.ID, msg.FailureCode)
3✔
2448

2449
        case *lnwire.Warning:
×
2450
                return fmt.Sprintf("%v", msg.Warning())
×
2451

2452
        case *lnwire.Error:
3✔
2453
                return fmt.Sprintf("%v", msg.Error())
3✔
2454

2455
        case *lnwire.AnnounceSignatures1:
3✔
2456
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
3✔
2457
                        msg.ShortChannelID.ToUint64())
3✔
2458

2459
        case *lnwire.ChannelAnnouncement1:
3✔
2460
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
3✔
2461
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
3✔
2462

2463
        case *lnwire.ChannelUpdate1:
3✔
2464
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
3✔
2465
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
3✔
2466
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
3✔
2467
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
3✔
2468

2469
        case *lnwire.NodeAnnouncement:
3✔
2470
                return fmt.Sprintf("node=%x, update_time=%v",
3✔
2471
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
3✔
2472

2473
        case *lnwire.Ping:
×
2474
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
2475

2476
        case *lnwire.Pong:
×
2477
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
×
2478

2479
        case *lnwire.UpdateFee:
×
2480
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2481
                        msg.ChanID, int64(msg.FeePerKw))
×
2482

2483
        case *lnwire.ChannelReestablish:
3✔
2484
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
3✔
2485
                        "remote_tail_height=%v", msg.ChanID,
3✔
2486
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
3✔
2487

2488
        case *lnwire.ReplyShortChanIDsEnd:
3✔
2489
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
3✔
2490
                        msg.Complete)
3✔
2491

2492
        case *lnwire.ReplyChannelRange:
3✔
2493
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
3✔
2494
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
3✔
2495
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
3✔
2496
                        msg.EncodingType)
3✔
2497

2498
        case *lnwire.QueryShortChanIDs:
3✔
2499
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
3✔
2500
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
3✔
2501

2502
        case *lnwire.QueryChannelRange:
3✔
2503
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
3✔
2504
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
3✔
2505
                        msg.LastBlockHeight())
3✔
2506

2507
        case *lnwire.GossipTimestampRange:
3✔
2508
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
3✔
2509
                        "stamp_range=%v", msg.ChainHash,
3✔
2510
                        time.Unix(int64(msg.FirstTimestamp), 0),
3✔
2511
                        msg.TimestampRange)
3✔
2512

2513
        case *lnwire.Stfu:
3✔
2514
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
3✔
2515
                        msg.Initiator)
3✔
2516

2517
        case *lnwire.Custom:
3✔
2518
                return fmt.Sprintf("type=%d", msg.Type)
3✔
2519
        }
2520

2521
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2522
}
2523

2524
// logWireMessage logs the receipt or sending of particular wire message. This
2525
// function is used rather than just logging the message in order to produce
2526
// less spammy log messages in trace mode by setting the 'Curve" parameter to
2527
// nil. Doing this avoids printing out each of the field elements in the curve
2528
// parameters for secp256k1.
2529
func (p *Brontide) logWireMessage(msg lnwire.Message, read bool) {
3✔
2530
        summaryPrefix := "Received"
3✔
2531
        if !read {
6✔
2532
                summaryPrefix = "Sending"
3✔
2533
        }
3✔
2534

2535
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
6✔
2536
                // Debug summary of message.
3✔
2537
                summary := messageSummary(msg)
3✔
2538
                if len(summary) > 0 {
6✔
2539
                        summary = "(" + summary + ")"
3✔
2540
                }
3✔
2541

2542
                preposition := "to"
3✔
2543
                if read {
6✔
2544
                        preposition = "from"
3✔
2545
                }
3✔
2546

2547
                var msgType string
3✔
2548
                if msg.MsgType() < lnwire.CustomTypeStart {
6✔
2549
                        msgType = msg.MsgType().String()
3✔
2550
                } else {
6✔
2551
                        msgType = "custom"
3✔
2552
                }
3✔
2553

2554
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
3✔
2555
                        msgType, summary, preposition, p)
3✔
2556
        }))
2557

2558
        prefix := "readMessage from peer"
3✔
2559
        if !read {
6✔
2560
                prefix = "writeMessage to peer"
3✔
2561
        }
3✔
2562

2563
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
3✔
2564
}
2565

2566
// writeMessage writes and flushes the target lnwire.Message to the remote peer.
2567
// If the passed message is nil, this method will only try to flush an existing
2568
// message buffered on the connection. It is safe to call this method again
2569
// with a nil message iff a timeout error is returned. This will continue to
2570
// flush the pending message to the wire.
2571
//
2572
// NOTE:
2573
// Besides its usage in Start, this function should not be used elsewhere
2574
// except in writeHandler. If multiple goroutines call writeMessage at the same
2575
// time, panics can occur because WriteMessage and Flush don't use any locking
2576
// internally.
2577
func (p *Brontide) writeMessage(msg lnwire.Message) error {
3✔
2578
        // Only log the message on the first attempt.
3✔
2579
        if msg != nil {
6✔
2580
                p.logWireMessage(msg, false)
3✔
2581
        }
3✔
2582

2583
        noiseConn := p.cfg.Conn
3✔
2584

3✔
2585
        flushMsg := func() error {
6✔
2586
                // Ensure the write deadline is set before we attempt to send
3✔
2587
                // the message.
3✔
2588
                writeDeadline := time.Now().Add(
3✔
2589
                        p.scaleTimeout(writeMessageTimeout),
3✔
2590
                )
3✔
2591
                err := noiseConn.SetWriteDeadline(writeDeadline)
3✔
2592
                if err != nil {
3✔
2593
                        return err
×
2594
                }
×
2595

2596
                // Flush the pending message to the wire. If an error is
2597
                // encountered, e.g. write timeout, the number of bytes written
2598
                // so far will be returned.
2599
                n, err := noiseConn.Flush()
3✔
2600

3✔
2601
                // Record the number of bytes written on the wire, if any.
3✔
2602
                if n > 0 {
6✔
2603
                        atomic.AddUint64(&p.bytesSent, uint64(n))
3✔
2604
                }
3✔
2605

2606
                return err
3✔
2607
        }
2608

2609
        // If the current message has already been serialized, encrypted, and
2610
        // buffered on the underlying connection we will skip straight to
2611
        // flushing it to the wire.
2612
        if msg == nil {
3✔
2613
                return flushMsg()
×
2614
        }
×
2615

2616
        // Otherwise, this is a new message. We'll acquire a write buffer to
2617
        // serialize the message and buffer the ciphertext on the connection.
2618
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
6✔
2619
                // Using a buffer allocated by the write pool, encode the
3✔
2620
                // message directly into the buffer.
3✔
2621
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
3✔
2622
                if writeErr != nil {
3✔
2623
                        return writeErr
×
2624
                }
×
2625

2626
                // Finally, write the message itself in a single swoop. This
2627
                // will buffer the ciphertext on the underlying connection. We
2628
                // will defer flushing the message until the write pool has been
2629
                // released.
2630
                return noiseConn.WriteMessage(buf.Bytes())
3✔
2631
        })
2632
        if err != nil {
3✔
2633
                return err
×
2634
        }
×
2635

2636
        return flushMsg()
3✔
2637
}
2638

2639
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2640
// queue, and writing them out to the wire. This goroutine coordinates with the
2641
// queueHandler in order to ensure the incoming message queue is quickly
2642
// drained.
2643
//
2644
// NOTE: This method MUST be run as a goroutine.
2645
func (p *Brontide) writeHandler() {
3✔
2646
        // We'll stop the timer after a new messages is sent, and also reset it
3✔
2647
        // after we process the next message.
3✔
2648
        idleTimer := time.AfterFunc(idleTimeout, func() {
3✔
2649
                err := fmt.Errorf("peer %s no write for %s -- disconnecting",
×
2650
                        p, idleTimeout)
×
2651
                p.Disconnect(err)
×
2652
        })
×
2653

2654
        var exitErr error
3✔
2655

3✔
2656
out:
3✔
2657
        for {
6✔
2658
                var msgToWrite outgoingMsg
3✔
2659

3✔
2660
                // Prioritize superPrioSendQueue, only falling into the default
3✔
2661
                // to check the normal queue if we don't have anything to send.
3✔
2662
                select {
3✔
NEW
2663
                case msgToWrite = <-p.superPrioSendQueue:
×
2664
                default:
3✔
2665
                        // No superPrio msg, check normal sendQueue or quit.
3✔
2666
                        select {
3✔
NEW
2667
                        case msgToWrite = <-p.superPrioSendQueue:
×
2668

2669
                        case msgToWrite = <-p.sendQueue:
3✔
2670

2671
                        case <-p.cg.Done():
3✔
2672
                                exitErr = lnpeer.ErrPeerExiting
3✔
2673
                                break out
3✔
2674
                        }
2675
                }
2676

2677
                // Record the time at which we first attempt to send the
2678
                // message.
2679
                startTime := time.Now()
3✔
2680

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

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

×
NEW
2702
                        goto retryWrite
×
2703
                }
2704

2705
                // The write succeeded or failed with a non-timeout error. Reset
2706
                // the idle timer.
2707
                if !idleTimer.Stop() {
3✔
NEW
2708
                        select {
×
NEW
2709
                        case <-idleTimer.C:
×
NEW
2710
                        default:
×
2711
                        }
2712
                }
2713
                idleTimer.Reset(idleTimeout)
3✔
2714

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

2721
                if err != nil {
3✔
NEW
2722
                        errMsgPrefix := "unable to write message"
×
NEW
2723
                        exitErr = fmt.Errorf("%s: %w", errMsgPrefix, err)
×
UNCOV
2724
                        break out
×
2725
                }
2726

2727
        }
2728

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

3✔
2733
        p.Disconnect(exitErr)
3✔
2734

3✔
2735
        p.log.Trace("writeHandler for peer done")
3✔
2736
}
2737

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

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

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

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

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

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

2805
// queueSuperPriorityMsg adds the lnwire.Message to the super priority send
2806
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2807
// queue or failed to write, and nil otherwise.
2808
func (p *Brontide) queueSuperPriorityMsg(msg lnwire.Message,
NEW
2809
        errChan chan error) {
×
NEW
2810

×
NEW
2811
        outMsg := outgoingMsg{
×
NEW
2812
                priority: true,
×
NEW
2813
                msg:      msg,
×
NEW
2814
                errChan:  errChan,
×
NEW
2815
        }
×
NEW
2816

×
NEW
2817
        select {
×
NEW
2818
        case p.superPrioSendQueue <- outMsg:
×
2819

NEW
2820
        case <-p.cg.Done():
×
NEW
2821
                p.log.Tracef("Peer shutting down, could not enqueue "+
×
NEW
2822
                        "super priority msg: %v.", spew.Sdump(msg))
×
NEW
2823

×
NEW
2824
                if errChan != nil {
×
NEW
2825
                        errChan <- lnpeer.ErrPeerExiting
×
NEW
2826
                }
×
2827

NEW
2828
        case <-p.cfg.Quit:
×
NEW
2829
                p.log.Tracef("Server shutting down, could not enqueue "+
×
NEW
2830
                        "super priority msg: %v.", spew.Sdump(msg))
×
NEW
2831

×
NEW
2832
                if errChan != nil {
×
NEW
2833
                        errChan <- lnpeer.ErrPeerExiting
×
NEW
2834
                }
×
2835
        }
2836
}
2837

2838
// PingTime returns the estimated ping time to the peer in microseconds.
2839
func (p *Brontide) PingTime() int64 {
3✔
2840
        return p.pingManager.GetPingTimeMicroSeconds()
3✔
2841
}
3✔
2842

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

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

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

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

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

3✔
2881
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2882
                activeChan *lnwallet.LightningChannel) error {
6✔
2883

3✔
2884
                // If the activeChan is nil, then we skip it as the channel is
3✔
2885
                // pending.
3✔
2886
                if activeChan == nil {
6✔
2887
                        return nil
3✔
2888
                }
3✔
2889

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

2896
                snapshot := activeChan.StateSnapshot()
3✔
2897
                snapshots = append(snapshots, snapshot)
3✔
2898

3✔
2899
                return nil
3✔
2900
        })
2901

2902
        return snapshots
3✔
2903
}
2904

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

2915
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
3✔
2916
                addrType, false, lnwallet.DefaultAccountName,
3✔
2917
        )
3✔
2918
        if err != nil {
3✔
2919
                return nil, err
×
2920
        }
×
2921
        p.log.Infof("Delivery addr for channel close: %v",
3✔
2922
                deliveryAddr)
3✔
2923

3✔
2924
        return txscript.PayToAddrScript(deliveryAddr)
3✔
2925
}
2926

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

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

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

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

2957
                // The funding flow for a pending channel is failed, we will
2958
                // remove it from Brontide.
2959
                case req := <-p.removePendingChannel:
3✔
2960
                        p.handleRemovePendingChannel(req)
3✔
2961

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

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

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

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

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

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

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

3✔
3015
                                // Exit if the channel is nil as it's a pending
3✔
3016
                                // channel.
3✔
3017
                                if lc == nil {
6✔
3018
                                        return nil
3✔
3019
                                }
3✔
3020

3021
                                lc.ResetState()
3✔
3022

3✔
3023
                                return nil
3✔
3024
                        })
3025

3026
                        break out
3✔
3027
                }
3028
        }
3029
}
3030

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

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

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

3✔
3049
                switch {
3✔
3050
                // No error occurred, continue to request the next channel.
3051
                case err == nil:
3✔
3052
                        continue
3✔
3053

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

3✔
3060
                        continue
3✔
3061

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

×
3079
                                continue
×
3080
                        }
3081

3082
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
3083
                                "ChanStatusManager reported inactive, retrying")
×
3084

×
3085
                        // Add the channel to the retry map.
×
3086
                        retryChans[chanPoint] = struct{}{}
×
3087
                }
3088
        }
3089

3090
        // Retry the channels if we have any.
3091
        if len(retryChans) != 0 {
3✔
3092
                p.retryRequestEnable(retryChans)
×
3093
        }
×
3094
}
3095

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

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

3112
        // First, we'll ensure that we actually know of the target channel. If
3113
        // not, we'll ignore this message.
3114
        channel, ok := p.activeChannels.Load(chanID)
3✔
3115

3✔
3116
        // If the channel isn't in the map or the channel is nil, return
3✔
3117
        // ErrChannelNotFound as the channel is pending.
3✔
3118
        if !ok || channel == nil {
6✔
3119
                return nil, ErrChannelNotFound
3✔
3120
        }
3✔
3121

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

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

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

3163
        chanCloser = makeNegotiateCloser(negotiateChanCloser)
3✔
3164

3✔
3165
        p.activeChanCloses.Store(chanID, chanCloser)
3✔
3166

3✔
3167
        return &chanCloser, nil
3✔
3168
}
3169

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

3✔
3176
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
3✔
3177
                lnChan *lnwallet.LightningChannel) bool {
6✔
3178

3✔
3179
                // If the lnChan is nil, continue as this is a pending channel.
3✔
3180
                if lnChan == nil {
4✔
3181
                        return true
1✔
3182
                }
1✔
3183

3184
                dbChan := lnChan.State()
3✔
3185
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
3186
                if !isPublic || dbChan.IsPending {
3✔
3187
                        return true
×
3188
                }
×
3189

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

3199
                activePublicChans = append(
3✔
3200
                        activePublicChans, dbChan.FundingOutpoint,
3✔
3201
                )
3✔
3202

3✔
3203
                return true
3✔
3204
        })
3205

3206
        return activePublicChans
3✔
3207
}
3208

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

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

×
3223
                // If this channel is irrelevant, return nil so the loop can
×
3224
                // jump to next iteration.
×
3225
                if !found {
×
3226
                        return nil
×
3227
                }
×
3228

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

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

3244
                return nil
×
3245
        }
3246

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

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

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

3272
                                continue
×
3273
                        }
3274

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

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

3290
                        delete(activeChans, chanPoint)
×
3291
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3292
                                "inactive link event", chanPoint)
×
3293

3294
                case <-p.cg.Done():
×
3295
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3296
                        return
×
3297
                }
3298
        }
3299
}
3300

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

3✔
3308
        switch {
3✔
3309
        // If no script was provided, then we'll generate a new delivery script.
3310
        case len(upfront) == 0 && len(requested) == 0:
3✔
3311
                return genDeliveryScript()
3✔
3312

3313
        // If no upfront shutdown script was provided, return the user
3314
        // requested address (which may be nil).
3315
        case len(upfront) == 0:
3✔
3316
                return requested, nil
3✔
3317

3318
        // If an upfront shutdown script was provided, and the user did not
3319
        // request a custom shutdown script, return the upfront address.
3320
        case len(requested) == 0:
3✔
3321
                return upfront, nil
3✔
3322

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

3330
        // The user requested script matches the upfront shutdown script, so we
3331
        // can return it without error.
3332
        default:
×
3333
                return upfront, nil
×
3334
        }
3335
}
3336

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

3✔
3342
        isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
3343

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

3363
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
3✔
3364

3✔
3365
        var deliveryScript []byte
3✔
3366

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

3376
        // An error other than ErrNoShutdownInfo was returned
3377
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3378
                return nil, err
×
3379

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

×
3389
                                return nil, fmt.Errorf("close addr unavailable")
×
3390
                        }
×
3391
                }
3392
        }
3393

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

3404
                shutdownDesc := fn.MapOption(
3✔
3405
                        newRestartShutdownInit,
3✔
3406
                )(shutdownInfo)
3✔
3407

3✔
3408
                err = p.startRbfChanCloser(
3✔
3409
                        fn.FlattenOption(shutdownDesc), lnChan.ChannelPoint(),
3✔
3410
                )
3✔
3411

3✔
3412
                return nil, err
3✔
3413
        }
3414

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

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

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

3443
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
×
3444

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

3453
        return shutdownMsg, nil
×
3454
}
3455

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

3✔
3463
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
3✔
3464
        if err != nil {
3✔
3465
                p.log.Errorf("unable to obtain best block: %v", err)
×
3466
                return nil, fmt.Errorf("cannot obtain best block")
×
3467
        }
×
3468

3469
        // The req will only be set if we initiated the co-op closing flow.
3470
        var maxFee chainfee.SatPerKWeight
3✔
3471
        if req != nil {
6✔
3472
                maxFee = req.MaxFee
3✔
3473
        }
3✔
3474

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

3500
        return chanCloser, nil
3✔
3501
}
3502

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

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

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

3529
        addr, err := p.addrWithInternalKey(deliveryScript)
3✔
3530
        if err != nil {
3✔
3531
                return fmt.Errorf("unable to parse addr for channel "+
×
3532
                        "%v: %w", req.ChanPoint, err)
×
3533
        }
×
3534

3535
        chanCloser, err := p.createChanCloser(
3✔
3536
                channel, addr, req.TargetFeePerKw, req, lntypes.Local,
3✔
3537
        )
3✔
3538
        if err != nil {
3✔
3539
                return fmt.Errorf("unable to make chan closer: %w", err)
×
3540
        }
×
3541

3542
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
3✔
3543
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
3✔
3544

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

×
3554
                p.activeChanCloses.Delete(chanID)
×
3555

×
3556
                return fmt.Errorf("unable to shutdown channel: %w", err)
×
3557
        }
×
3558

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

3571
        if !link.DisableAdds(htlcswitch.Outgoing) {
3✔
3572
                p.log.Warnf("Outgoing link adds already "+
×
3573
                        "disabled: %v", link.ChanID())
×
3574
        }
×
3575

3576
        link.OnCommitOnce(htlcswitch.Outgoing, func() {
6✔
3577
                p.queueMsg(shutdownMsg, nil)
3✔
3578
        })
3✔
3579

3580
        return nil
3✔
3581
}
3582

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

3590
        return fn.Some(addr)
×
3591
}
3592

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

3✔
3600
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3601
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3602

3✔
3603
        var (
3✔
3604
                lastTxids    lntypes.Dual[chainhash.Hash]
3✔
3605
                lastFeeRates lntypes.Dual[chainfee.SatPerVByte]
3✔
3606
        )
3✔
3607

3✔
3608
        maybeNotifyTxBroadcast := func(state chancloser.AsymmetricPeerState,
3✔
3609
                party lntypes.ChannelParty) {
6✔
3610

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

3✔
3620
                        peerLog.Warnf("ChannelPoint(%v): encountered close "+
3✔
3621
                                "err: %v", closeReq.ChanPoint, err)
3✔
3622

3✔
3623
                        select {
3✔
3624
                        case closeReq.Err <- err:
3✔
3625
                        case <-closeReq.Ctx.Done():
×
3626
                        case <-p.cg.Done():
×
3627
                        }
3628

3629
                        return
3✔
3630
                }
3631

3632
                closePending, ok := state.(*chancloser.ClosePending)
3✔
3633

3✔
3634
                // If this isn't the close pending state, we aren't at the
3✔
3635
                // terminal state yet.
3✔
3636
                if !ok {
6✔
3637
                        return
3✔
3638
                }
3✔
3639

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

3✔
3649
                        return
3✔
3650
                }
3✔
3651

3652
                feeRate := closePending.FeeRate
3✔
3653
                lastFeeRates.SetForParty(party, feeRate)
3✔
3654

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

3671
                        case <-closeReq.Ctx.Done():
×
3672
                                return
×
3673

3674
                        case <-p.cg.Done():
×
3675
                                return
×
3676
                        }
3677
                }
3678

3679
                lastTxids.SetForParty(party, closingTxid)
3✔
3680
        }
3681

3682
        peerLog.Infof("Observing RBF close updates for channel %v",
3✔
3683
                closeReq.ChanPoint)
3✔
3684

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

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

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

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

3✔
3727
                                return
3✔
3728
                        }
3729

3730
                case <-closeReq.Ctx.Done():
3✔
3731
                        return
3✔
3732

3733
                case <-p.cg.Done():
3✔
3734
                        return
3✔
3735
                }
3736
        }
3737
}
3738

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

3747
// newChanErrorReporter creates a new instance of the chanErrorReporter.
3748
func newChanErrorReporter(chanID lnwire.ChannelID,
3749
        peer *Brontide) *chanErrorReporter {
3✔
3750

3✔
3751
        return &chanErrorReporter{
3✔
3752
                chanID: chanID,
3✔
3753
                peer:   peer,
3✔
3754
        }
3✔
3755
}
3✔
3756

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

×
3766
        var errMsg []byte
×
3767
        if errors.Is(chanErr, chancloser.ErrInvalidStateTransition) {
×
3768
                errMsg = []byte("unexpected protocol message")
×
3769
        } else {
×
3770
                errMsg = []byte(chanErr.Error())
×
3771
        }
×
3772

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

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

3790
        if lnChan == nil {
×
3791
                c.peer.log.Debugf("channel %v is pending, not "+
×
3792
                        "re-initializing coop close state machine",
×
3793
                        c.chanID)
×
3794

×
3795
                return
×
3796
        }
×
3797

3798
        if _, err := c.peer.initRbfChanCloser(lnChan); err != nil {
×
3799
                c.peer.activeChanCloses.Delete(c.chanID)
×
3800

×
3801
                c.peer.log.Errorf("unable to init RBF chan closer after "+
×
3802
                        "error case: %v", err)
×
3803
        }
×
3804
}
3805

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

3✔
3815
        defer p.cg.WgDone()
3✔
3816

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

3823
        coopCloseStates := chanCloser.RegisterStateEvents()
3✔
3824
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3825

3✔
3826
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3827

3✔
3828
        sendChanFlushed := func() {
6✔
3829
                chanState := channel.StateSnapshot()
3✔
3830

3✔
3831
                peerLog.Infof("ChannelPoint(%v) has been flushed for co-op "+
3✔
3832
                        "close, sending event to chan closer",
3✔
3833
                        channel.ChannelPoint())
3✔
3834

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

3846
        // We'll wait until the channel enters the ChannelFlushing state. We
3847
        // exit after a success loop. As after the first RBF iteration, the
3848
        // channel will always be flushed.
3849
        for newState := range newStateChan {
6✔
3850
                if _, ok := newState.(*chancloser.ChannelFlushing); ok {
6✔
3851
                        peerLog.Infof("ChannelPoint(%v): rbf coop "+
3✔
3852
                                "close is awaiting a flushed state, "+
3✔
3853
                                "registering with link..., ",
3✔
3854
                                channel.ChannelPoint())
3✔
3855

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

3✔
3861
                        return
3✔
3862
                }
3✔
3863
        }
3864
}
3865

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

3✔
3872
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
3✔
3873

3✔
3874
        link := p.fetchLinkFromKeyAndCid(chanID)
3✔
3875

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

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

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

3893
        peerPub := *p.IdentityKey()
3✔
3894

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

3✔
3899
        initialState := chancloser.ChannelActive{}
3✔
3900

3✔
3901
        scid := channel.ZeroConfRealScid().UnwrapOr(
3✔
3902
                channel.ShortChanID(),
3✔
3903
        )
3✔
3904

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

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

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

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

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

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

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

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

3974
        p.activeChanCloses.Store(chanID, makeRbfCloser(&chanCloser))
3✔
3975

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

3✔
3982
        return &chanCloser, nil
3✔
3983
}
3984

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

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

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

4004
                return feeRate
3✔
4005
        })(s)
4006

4007
        return fn.FlattenOption(feeRateOpt)
3✔
4008
}
4009

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

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

4027
                return addr
3✔
4028
        })(s)
4029

4030
        return fn.FlattenOption(addrOpt)
3✔
4031
}
4032

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

3✔
4039
                init.WhenLeft(f)
3✔
4040
        })
3✔
4041
}
4042

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

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

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

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

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

4074
                localState := state.PeerState.GetForParty(lntypes.Local)
3✔
4075

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

3✔
4080
                return ok
3✔
4081
        }
4082

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

4093
        peerLog.Debugf("Waiting for RBF iteration to complete...")
×
4094

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

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

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

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

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

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

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

×
4146
                        return
×
4147
                }
×
4148

4149
                coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4150

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

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

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

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

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

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

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

×
4205
                                return
×
4206
                        }
×
4207

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

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

4221
        return nil
3✔
4222
}
4223

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

3✔
4229
        channel, ok := p.activeChannels.Load(chanID)
3✔
4230

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

4241
        isTaprootChan := channel.ChanType().IsTaproot()
3✔
4242

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

4265
                if err != nil {
3✔
4266
                        p.log.Errorf(err.Error())
×
4267
                        req.Err <- err
×
4268
                }
×
4269

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
4383
        var chanLink htlcswitch.ChannelUpdateHandler
3✔
4384

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

4395
        return chanLink
3✔
4396
}
4397

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

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

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

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

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

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

4435
        closingTxid := closingTx.TxHash()
3✔
4436

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

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

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

3✔
4475
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
3✔
4476
                "with txid: %v", chanPoint, closingTxID)
3✔
4477

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

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

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

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

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

3✔
4511
        p.activeChannels.Delete(chanID)
3✔
4512

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

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

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

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

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

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

4556
        return nil
3✔
4557
}
4558

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

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

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

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

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

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

×
4607
                features.Set(lnwire.StaticRemoteKeyOptional)
×
4608
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
×
4609
        }
×
4610

4611
        msg := lnwire.NewInitMessage(
3✔
4612
                legacyFeatures.RawFeatureVector,
3✔
4613
                features.RawFeatureVector,
3✔
4614
        )
3✔
4615

3✔
4616
        return p.writeMessage(msg)
3✔
4617
}
4618

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

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

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

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

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

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

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

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

3✔
4660
        return nil
3✔
4661
}
4662

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

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

4683
// SendSuperPriorityMessage sends a variadic number of super-priority messages
4684
// to the remote peer. If sync is true, this method will block until the
4685
// messages have been sent to the remote peer or an error is returned, otherwise
4686
// it returns immediately after queueing. These messages bypass the regular and
4687
// lazy send queues handled by the queueHandler.
4688
func (p *Brontide) SendSuperPriorityMessage(sync bool,
NEW
4689
        msgs ...lnwire.Message) error {
×
NEW
4690

×
NEW
4691
        var errChans []chan error
×
NEW
4692
        if sync {
×
NEW
4693
                errChans = make([]chan error, 0, len(msgs))
×
NEW
4694
        }
×
4695

NEW
4696
        for _, msg := range msgs {
×
NEW
4697
                var errChan chan error
×
NEW
4698
                if sync {
×
NEW
4699
                        errChan = make(chan error, 1)
×
NEW
4700
                        errChans = append(errChans, errChan)
×
NEW
4701
                }
×
4702

NEW
4703
                p.queueSuperPriorityMsg(msg, errChan)
×
4704
        }
4705

4706
        // Wait for all replies from the writeHandler if a sync send was
4707
        // requested.
NEW
4708
        for _, errChan := range errChans {
×
NEW
4709
                select {
×
NEW
4710
                case err := <-errChan:
×
NEW
4711
                        if err != nil {
×
NEW
4712
                                return err
×
NEW
4713
                        }
×
4714

NEW
4715
                case <-p.cg.Done():
×
NEW
4716
                        return lnpeer.ErrPeerExiting
×
4717

NEW
4718
                case <-p.cfg.Quit:
×
NEW
4719
                        return lnpeer.ErrPeerExiting
×
4720
                }
4721
        }
4722

NEW
4723
        return nil
×
4724
}
4725

4726
// sendMessage queues a variadic number of messages using the passed priority
4727
// to the remote peer. If sync is true, this method will block until the
4728
// messages have been sent to the remote peer or an error is returned, otherwise
4729
// it returns immediately after queueing.
4730
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
3✔
4731
        // Add all incoming messages to the outgoing queue. A list of error
3✔
4732
        // chans is populated for each message if the caller requested a sync
3✔
4733
        // send.
3✔
4734
        var errChans []chan error
3✔
4735
        if sync {
6✔
4736
                errChans = make([]chan error, 0, len(msgs))
3✔
4737
        }
3✔
4738
        for _, msg := range msgs {
6✔
4739
                // If a sync send was requested, create an error chan to listen
3✔
4740
                // for an ack from the writeHandler.
3✔
4741
                var errChan chan error
3✔
4742
                if sync {
6✔
4743
                        errChan = make(chan error, 1)
3✔
4744
                        errChans = append(errChans, errChan)
3✔
4745
                }
3✔
4746

4747
                if priority {
6✔
4748
                        p.queueMsg(msg, errChan)
3✔
4749
                } else {
6✔
4750
                        p.queueMsgLazy(msg, errChan)
3✔
4751
                }
3✔
4752
        }
4753

4754
        // Wait for all replies from the writeHandler. For async sends, this
4755
        // will be a NOP as the list of error chans is nil.
4756
        for _, errChan := range errChans {
6✔
4757
                select {
3✔
4758
                case err := <-errChan:
3✔
4759
                        return err
3✔
4760
                case <-p.cg.Done():
×
4761
                        return lnpeer.ErrPeerExiting
×
4762
                case <-p.cfg.Quit:
×
4763
                        return lnpeer.ErrPeerExiting
×
4764
                }
4765
        }
4766

4767
        return nil
3✔
4768
}
4769

4770
// PubKey returns the pubkey of the peer in compressed serialized format.
4771
//
4772
// NOTE: Part of the lnpeer.Peer interface.
4773
func (p *Brontide) PubKey() [33]byte {
3✔
4774
        return p.cfg.PubKeyBytes
3✔
4775
}
3✔
4776

4777
// IdentityKey returns the public key of the remote peer.
4778
//
4779
// NOTE: Part of the lnpeer.Peer interface.
4780
func (p *Brontide) IdentityKey() *btcec.PublicKey {
3✔
4781
        return p.cfg.Addr.IdentityKey
3✔
4782
}
3✔
4783

4784
// Address returns the network address of the remote peer.
4785
//
4786
// NOTE: Part of the lnpeer.Peer interface.
4787
func (p *Brontide) Address() net.Addr {
3✔
4788
        return p.cfg.Addr.Address
3✔
4789
}
3✔
4790

4791
// AddNewChannel adds a new channel to the peer. The channel should fail to be
4792
// added if the cancel channel is closed.
4793
//
4794
// NOTE: Part of the lnpeer.Peer interface.
4795
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
4796
        cancel <-chan struct{}) error {
3✔
4797

3✔
4798
        errChan := make(chan error, 1)
3✔
4799
        newChanMsg := &newChannelMsg{
3✔
4800
                channel: newChan,
3✔
4801
                err:     errChan,
3✔
4802
        }
3✔
4803

3✔
4804
        select {
3✔
4805
        case p.newActiveChannel <- newChanMsg:
3✔
4806
        case <-cancel:
×
4807
                return errors.New("canceled adding new channel")
×
4808
        case <-p.cg.Done():
×
4809
                return lnpeer.ErrPeerExiting
×
4810
        }
4811

4812
        // We pause here to wait for the peer to recognize the new channel
4813
        // before we close the channel barrier corresponding to the channel.
4814
        select {
3✔
4815
        case err := <-errChan:
3✔
4816
                return err
3✔
4817
        case <-p.cg.Done():
×
4818
                return lnpeer.ErrPeerExiting
×
4819
        }
4820
}
4821

4822
// AddPendingChannel adds a pending open channel to the peer. The channel
4823
// should fail to be added if the cancel channel is closed.
4824
//
4825
// NOTE: Part of the lnpeer.Peer interface.
4826
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
4827
        cancel <-chan struct{}) error {
3✔
4828

3✔
4829
        errChan := make(chan error, 1)
3✔
4830
        newChanMsg := &newChannelMsg{
3✔
4831
                channelID: cid,
3✔
4832
                err:       errChan,
3✔
4833
        }
3✔
4834

3✔
4835
        select {
3✔
4836
        case p.newPendingChannel <- newChanMsg:
3✔
4837

4838
        case <-cancel:
×
4839
                return errors.New("canceled adding pending channel")
×
4840

4841
        case <-p.cg.Done():
×
4842
                return lnpeer.ErrPeerExiting
×
4843
        }
4844

4845
        // We pause here to wait for the peer to recognize the new pending
4846
        // channel before we close the channel barrier corresponding to the
4847
        // channel.
4848
        select {
3✔
4849
        case err := <-errChan:
3✔
4850
                return err
3✔
4851

4852
        case <-cancel:
×
4853
                return errors.New("canceled adding pending channel")
×
4854

4855
        case <-p.cg.Done():
×
4856
                return lnpeer.ErrPeerExiting
×
4857
        }
4858
}
4859

4860
// RemovePendingChannel removes a pending open channel from the peer.
4861
//
4862
// NOTE: Part of the lnpeer.Peer interface.
4863
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
3✔
4864
        errChan := make(chan error, 1)
3✔
4865
        newChanMsg := &newChannelMsg{
3✔
4866
                channelID: cid,
3✔
4867
                err:       errChan,
3✔
4868
        }
3✔
4869

3✔
4870
        select {
3✔
4871
        case p.removePendingChannel <- newChanMsg:
3✔
4872
        case <-p.cg.Done():
×
4873
                return lnpeer.ErrPeerExiting
×
4874
        }
4875

4876
        // We pause here to wait for the peer to respond to the cancellation of
4877
        // the pending channel before we close the channel barrier
4878
        // corresponding to the channel.
4879
        select {
3✔
4880
        case err := <-errChan:
3✔
4881
                return err
3✔
4882

4883
        case <-p.cg.Done():
×
4884
                return lnpeer.ErrPeerExiting
×
4885
        }
4886
}
4887

4888
// StartTime returns the time at which the connection was established if the
4889
// peer started successfully, and zero otherwise.
4890
func (p *Brontide) StartTime() time.Time {
3✔
4891
        return p.startTime
3✔
4892
}
3✔
4893

4894
// handleCloseMsg is called when a new cooperative channel closure related
4895
// message is received from the remote peer. We'll use this message to advance
4896
// the chan closer state machine.
4897
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
3✔
4898
        link := p.fetchLinkFromKeyAndCid(msg.cid)
3✔
4899

3✔
4900
        // We'll now fetch the matching closing state machine in order to
3✔
4901
        // continue, or finalize the channel closure process.
3✔
4902
        chanCloserE, err := p.fetchActiveChanCloser(msg.cid)
3✔
4903
        if err != nil {
6✔
4904
                // If the channel is not known to us, we'll simply ignore this
3✔
4905
                // message.
3✔
4906
                if err == ErrChannelNotFound {
6✔
4907
                        return
3✔
4908
                }
3✔
4909

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

×
4912
                errMsg := &lnwire.Error{
×
4913
                        ChanID: msg.cid,
×
4914
                        Data:   lnwire.ErrorData(err.Error()),
×
4915
                }
×
4916
                p.queueMsg(errMsg, nil)
×
4917
                return
×
4918
        }
4919

4920
        if chanCloserE.IsRight() {
3✔
4921
                // TODO(roasbeef): assert?
×
4922
                return
×
4923
        }
×
4924

4925
        // At this point, we'll only enter this call path if a negotiate chan
4926
        // closer was used. So we'll extract that from the either now.
4927
        //
4928
        // TODO(roabeef): need extra helper func for either to make cleaner
4929
        var chanCloser *chancloser.ChanCloser
3✔
4930
        chanCloserE.WhenLeft(func(c *chancloser.ChanCloser) {
6✔
4931
                chanCloser = c
3✔
4932
        })
3✔
4933

4934
        handleErr := func(err error) {
4✔
4935
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
4936
                p.log.Error(err)
1✔
4937

1✔
4938
                // As the negotiations failed, we'll reset the channel state
1✔
4939
                // machine to ensure we act to on-chain events as normal.
1✔
4940
                chanCloser.Channel().ResetState()
1✔
4941
                if chanCloser.CloseRequest() != nil {
1✔
4942
                        chanCloser.CloseRequest().Err <- err
×
4943
                }
×
4944

4945
                p.activeChanCloses.Delete(msg.cid)
1✔
4946

1✔
4947
                p.Disconnect(err)
1✔
4948
        }
4949

4950
        // Next, we'll process the next message using the target state machine.
4951
        // We'll either continue negotiation, or halt.
4952
        switch typed := msg.msg.(type) {
3✔
4953
        case *lnwire.Shutdown:
3✔
4954
                // Disable incoming adds immediately.
3✔
4955
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
3✔
4956
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
4957
                                link.ChanID())
×
4958
                }
×
4959

4960
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
3✔
4961
                if err != nil {
3✔
4962
                        handleErr(err)
×
4963
                        return
×
4964
                }
×
4965

4966
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
6✔
4967
                        // If the link is nil it means we can immediately queue
3✔
4968
                        // the Shutdown message since we don't have to wait for
3✔
4969
                        // commitment transaction synchronization.
3✔
4970
                        if link == nil {
3✔
4971
                                p.queueMsg(&msg, nil)
×
4972
                                return
×
4973
                        }
×
4974

4975
                        // Immediately disallow any new HTLC's from being added
4976
                        // in the outgoing direction.
4977
                        if !link.DisableAdds(htlcswitch.Outgoing) {
3✔
4978
                                p.log.Warnf("Outgoing link adds already "+
×
4979
                                        "disabled: %v", link.ChanID())
×
4980
                        }
×
4981

4982
                        // When we have a Shutdown to send, we defer it till the
4983
                        // next time we send a CommitSig to remain spec
4984
                        // compliant.
4985
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
6✔
4986
                                p.queueMsg(&msg, nil)
3✔
4987
                        })
3✔
4988
                })
4989

4990
                beginNegotiation := func() {
6✔
4991
                        oClosingSigned, err := chanCloser.BeginNegotiation()
3✔
4992
                        if err != nil {
3✔
4993
                                handleErr(err)
×
4994
                                return
×
4995
                        }
×
4996

4997
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
6✔
4998
                                p.queueMsg(&msg, nil)
3✔
4999
                        })
3✔
5000
                }
5001

5002
                if link == nil {
3✔
5003
                        beginNegotiation()
×
5004
                } else {
3✔
5005
                        // Now we register a flush hook to advance the
3✔
5006
                        // ChanCloser and possibly send out a ClosingSigned
3✔
5007
                        // when the link finishes draining.
3✔
5008
                        link.OnFlushedOnce(func() {
6✔
5009
                                // Remove link in goroutine to prevent deadlock.
3✔
5010
                                go p.cfg.Switch.RemoveLink(msg.cid)
3✔
5011
                                beginNegotiation()
3✔
5012
                        })
3✔
5013
                }
5014

5015
        case *lnwire.ClosingSigned:
3✔
5016
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
3✔
5017
                if err != nil {
4✔
5018
                        handleErr(err)
1✔
5019
                        return
1✔
5020
                }
1✔
5021

5022
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
6✔
5023
                        p.queueMsg(&msg, nil)
3✔
5024
                })
3✔
5025

5026
        default:
×
5027
                panic("impossible closeMsg type")
×
5028
        }
5029

5030
        // If we haven't finished close negotiations, then we'll continue as we
5031
        // can't yet finalize the closure.
5032
        if _, err := chanCloser.ClosingTx(); err != nil {
6✔
5033
                return
3✔
5034
        }
3✔
5035

5036
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
5037
        // the channel closure by notifying relevant sub-systems and launching a
5038
        // goroutine to wait for close tx conf.
5039
        p.finalizeChanClosure(chanCloser)
3✔
5040
}
5041

5042
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
5043
// the channelManager goroutine, which will shut down the link and possibly
5044
// close the channel.
5045
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
3✔
5046
        select {
3✔
5047
        case p.localCloseChanReqs <- req:
3✔
5048
                p.log.Info("Local close channel request is going to be " +
3✔
5049
                        "delivered to the peer")
3✔
5050
        case <-p.cg.Done():
×
5051
                p.log.Info("Unable to deliver local close channel request " +
×
5052
                        "to peer")
×
5053
        }
5054
}
5055

5056
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
5057
func (p *Brontide) NetAddress() *lnwire.NetAddress {
3✔
5058
        return p.cfg.Addr
3✔
5059
}
3✔
5060

5061
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
5062
func (p *Brontide) Inbound() bool {
3✔
5063
        return p.cfg.Inbound
3✔
5064
}
3✔
5065

5066
// ConnReq is a getter for the Brontide's connReq in cfg.
5067
func (p *Brontide) ConnReq() *connmgr.ConnReq {
3✔
5068
        return p.cfg.ConnReq
3✔
5069
}
3✔
5070

5071
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
5072
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
3✔
5073
        return p.cfg.ErrorBuffer
3✔
5074
}
3✔
5075

5076
// SetAddress sets the remote peer's address given an address.
5077
func (p *Brontide) SetAddress(address net.Addr) {
×
5078
        p.cfg.Addr.Address = address
×
5079
}
×
5080

5081
// ActiveSignal returns the peer's active signal.
5082
func (p *Brontide) ActiveSignal() chan struct{} {
3✔
5083
        return p.activeSignal
3✔
5084
}
3✔
5085

5086
// Conn returns a pointer to the peer's connection struct.
5087
func (p *Brontide) Conn() net.Conn {
3✔
5088
        return p.cfg.Conn
3✔
5089
}
3✔
5090

5091
// BytesReceived returns the number of bytes received from the peer.
5092
func (p *Brontide) BytesReceived() uint64 {
3✔
5093
        return atomic.LoadUint64(&p.bytesReceived)
3✔
5094
}
3✔
5095

5096
// BytesSent returns the number of bytes sent to the peer.
5097
func (p *Brontide) BytesSent() uint64 {
3✔
5098
        return atomic.LoadUint64(&p.bytesSent)
3✔
5099
}
3✔
5100

5101
// LastRemotePingPayload returns the last payload the remote party sent as part
5102
// of their ping.
5103
func (p *Brontide) LastRemotePingPayload() []byte {
3✔
5104
        pingPayload := p.lastPingPayload.Load()
3✔
5105
        if pingPayload == nil {
6✔
5106
                return []byte{}
3✔
5107
        }
3✔
5108

5109
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
5110
        if !ok {
×
5111
                return nil
×
5112
        }
×
5113

5114
        return pingBytes
×
5115
}
5116

5117
// attachChannelEventSubscription creates a channel event subscription and
5118
// attaches to client to Brontide if the reenableTimeout is no greater than 1
5119
// minute.
5120
func (p *Brontide) attachChannelEventSubscription() error {
3✔
5121
        // If the timeout is greater than 1 minute, it's unlikely that the link
3✔
5122
        // hasn't yet finished its reestablishment. Return a nil without
3✔
5123
        // creating the client to specify that we don't want to retry.
3✔
5124
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
6✔
5125
                return nil
3✔
5126
        }
3✔
5127

5128
        // When the reenable timeout is less than 1 minute, it's likely the
5129
        // channel link hasn't finished its reestablishment yet. In that case,
5130
        // we'll give it a second chance by subscribing to the channel update
5131
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
5132
        // enabling the channel again.
5133
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
3✔
5134
        if err != nil {
3✔
5135
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
5136
        }
×
5137

5138
        p.channelEventClient = sub
3✔
5139

3✔
5140
        return nil
3✔
5141
}
5142

5143
// updateNextRevocation updates the existing channel's next revocation if it's
5144
// nil.
5145
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
3✔
5146
        chanPoint := c.FundingOutpoint
3✔
5147
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5148

3✔
5149
        // Read the current channel.
3✔
5150
        currentChan, loaded := p.activeChannels.Load(chanID)
3✔
5151

3✔
5152
        // currentChan should exist, but we perform a check anyway to avoid nil
3✔
5153
        // pointer dereference.
3✔
5154
        if !loaded {
3✔
5155
                return fmt.Errorf("missing active channel with chanID=%v",
×
5156
                        chanID)
×
5157
        }
×
5158

5159
        // currentChan should not be nil, but we perform a check anyway to
5160
        // avoid nil pointer dereference.
5161
        if currentChan == nil {
3✔
5162
                return fmt.Errorf("found nil active channel with chanID=%v",
×
5163
                        chanID)
×
5164
        }
×
5165

5166
        // If we're being sent a new channel, and our existing channel doesn't
5167
        // have the next revocation, then we need to update the current
5168
        // existing channel.
5169
        if currentChan.RemoteNextRevocation() != nil {
3✔
5170
                return nil
×
5171
        }
×
5172

5173
        p.log.Infof("Processing retransmitted ChannelReady for "+
3✔
5174
                "ChannelPoint(%v)", chanPoint)
3✔
5175

3✔
5176
        nextRevoke := c.RemoteNextRevocation
3✔
5177

3✔
5178
        err := currentChan.InitNextRevocation(nextRevoke)
3✔
5179
        if err != nil {
3✔
5180
                return fmt.Errorf("unable to init next revocation: %w", err)
×
5181
        }
×
5182

5183
        return nil
3✔
5184
}
5185

5186
// addActiveChannel adds a new active channel to the `activeChannels` map. It
5187
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
5188
// it and assembles it with a channel link.
5189
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
3✔
5190
        chanPoint := c.FundingOutpoint
3✔
5191
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5192

3✔
5193
        // If we've reached this point, there are two possible scenarios.  If
3✔
5194
        // the channel was in the active channels map as nil, then it was
3✔
5195
        // loaded from disk and we need to send reestablish. Else, it was not
3✔
5196
        // loaded from disk and we don't need to send reestablish as this is a
3✔
5197
        // fresh channel.
3✔
5198
        shouldReestablish := p.isLoadedFromDisk(chanID)
3✔
5199

3✔
5200
        chanOpts := c.ChanOpts
3✔
5201
        if shouldReestablish {
6✔
5202
                // If we have to do the reestablish dance for this channel,
3✔
5203
                // ensure that we don't try to call InitRemoteMusigNonces twice
3✔
5204
                // by calling SkipNonceInit.
3✔
5205
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
3✔
5206
        }
3✔
5207

5208
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
3✔
5209
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
5210
        })
×
5211
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
3✔
5212
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
5213
        })
×
5214
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
3✔
5215
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
5216
        })
×
5217

5218
        // If not already active, we'll add this channel to the set of active
5219
        // channels, so we can look it up later easily according to its channel
5220
        // ID.
5221
        lnChan, err := lnwallet.NewLightningChannel(
3✔
5222
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
3✔
5223
        )
3✔
5224
        if err != nil {
3✔
5225
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
5226
        }
×
5227

5228
        // Store the channel in the activeChannels map.
5229
        p.activeChannels.Store(chanID, lnChan)
3✔
5230

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

3✔
5233
        // Next, we'll assemble a ChannelLink along with the necessary items it
3✔
5234
        // needs to function.
3✔
5235
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
3✔
5236
        if err != nil {
3✔
5237
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
5238
                        err)
×
5239
        }
×
5240

5241
        // We'll query the channel DB for the new channel's initial forwarding
5242
        // policies to determine the policy we start out with.
5243
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
3✔
5244
        if err != nil {
3✔
5245
                return fmt.Errorf("unable to query for initial forwarding "+
×
5246
                        "policy: %v", err)
×
5247
        }
×
5248

5249
        // Create the link and add it to the switch.
5250
        err = p.addLink(
3✔
5251
                &chanPoint, lnChan, initialPolicy, chainEvents,
3✔
5252
                shouldReestablish, fn.None[lnwire.Shutdown](),
3✔
5253
        )
3✔
5254
        if err != nil {
3✔
5255
                return fmt.Errorf("can't register new channel link(%v) with "+
×
5256
                        "peer", chanPoint)
×
5257
        }
×
5258

5259
        isTaprootChan := c.ChanType.IsTaproot()
3✔
5260

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

5268
        // Now that the link has been added above, we'll also init an RBF chan
5269
        // closer for this channel, but only if the new close feature is
5270
        // negotiated.
5271
        //
5272
        // Creating this here ensures that any shutdown messages sent will be
5273
        // automatically routed by the msg router.
5274
        if _, err := p.initRbfChanCloser(lnChan); err != nil {
3✔
5275
                p.activeChanCloses.Delete(chanID)
×
5276

×
5277
                return fmt.Errorf("unable to init RBF chan closer for new "+
×
5278
                        "chan: %w", err)
×
5279
        }
×
5280

5281
        return nil
3✔
5282
}
5283

5284
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
5285
// know this channel ID or not, we'll either add it to the `activeChannels` map
5286
// or init the next revocation for it.
5287
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
3✔
5288
        newChan := req.channel
3✔
5289
        chanPoint := newChan.FundingOutpoint
3✔
5290
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5291

3✔
5292
        // Only update RemoteNextRevocation if the channel is in the
3✔
5293
        // activeChannels map and if we added the link to the switch. Only
3✔
5294
        // active channels will be added to the switch.
3✔
5295
        if p.isActiveChannel(chanID) {
6✔
5296
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
3✔
5297
                        chanPoint)
3✔
5298

3✔
5299
                // Handle it and close the err chan on the request.
3✔
5300
                close(req.err)
3✔
5301

3✔
5302
                // Update the next revocation point.
3✔
5303
                err := p.updateNextRevocation(newChan.OpenChannel)
3✔
5304
                if err != nil {
3✔
5305
                        p.log.Errorf(err.Error())
×
5306
                }
×
5307

5308
                return
3✔
5309
        }
5310

5311
        // This is a new channel, we now add it to the map.
5312
        if err := p.addActiveChannel(req.channel); err != nil {
3✔
5313
                // Log and send back the error to the request.
×
5314
                p.log.Errorf(err.Error())
×
5315
                req.err <- err
×
5316

×
5317
                return
×
5318
        }
×
5319

5320
        // Close the err chan if everything went fine.
5321
        close(req.err)
3✔
5322
}
5323

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

3✔
5331
        chanID := req.channelID
3✔
5332

3✔
5333
        // If we already have this channel, something is wrong with the funding
3✔
5334
        // flow as it will only be marked as active after `ChannelReady` is
3✔
5335
        // handled. In this case, we will do nothing but log an error, just in
3✔
5336
        // case this is a legit channel.
3✔
5337
        if p.isActiveChannel(chanID) {
3✔
5338
                p.log.Errorf("Channel(%v) is already active, ignoring "+
×
5339
                        "pending channel request", chanID)
×
5340

×
5341
                return
×
5342
        }
×
5343

5344
        // The channel has already been added, we will do nothing and return.
5345
        if p.isPendingChannel(chanID) {
3✔
5346
                p.log.Infof("Channel(%v) is already added, ignoring "+
×
5347
                        "pending channel request", chanID)
×
5348

×
5349
                return
×
5350
        }
×
5351

5352
        // This is a new channel, we now add it to the map `activeChannels`
5353
        // with nil value and mark it as a newly added channel in
5354
        // `addedChannels`.
5355
        p.activeChannels.Store(chanID, nil)
3✔
5356
        p.addedChannels.Store(chanID, struct{}{})
3✔
5357
}
5358

5359
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
5360
// from `activeChannels` map. The request will be ignored if the channel is
5361
// considered active by Brontide. Noop if the channel ID cannot be found.
5362
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
3✔
5363
        defer close(req.err)
3✔
5364

3✔
5365
        chanID := req.channelID
3✔
5366

3✔
5367
        // If we already have this channel, something is wrong with the funding
3✔
5368
        // flow as it will only be marked as active after `ChannelReady` is
3✔
5369
        // handled. In this case, we will log an error and exit.
3✔
5370
        if p.isActiveChannel(chanID) {
3✔
5371
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
×
5372
                        chanID)
×
5373
                return
×
5374
        }
×
5375

5376
        // The channel has not been added yet, we will log a warning as there
5377
        // is an unexpected call from funding manager.
5378
        if !p.isPendingChannel(chanID) {
6✔
5379
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
3✔
5380
        }
3✔
5381

5382
        // Remove the record of this pending channel.
5383
        p.activeChannels.Delete(chanID)
3✔
5384
        p.addedChannels.Delete(chanID)
3✔
5385
}
5386

5387
// sendLinkUpdateMsg sends a message that updates the channel to the
5388
// channel's message stream.
5389
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
3✔
5390
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
3✔
5391

3✔
5392
        chanStream, ok := p.activeMsgStreams[cid]
3✔
5393
        if !ok {
6✔
5394
                // If a stream hasn't yet been created, then we'll do so, add
3✔
5395
                // it to the map, and finally start it.
3✔
5396
                chanStream = newChanMsgStream(p, cid)
3✔
5397
                p.activeMsgStreams[cid] = chanStream
3✔
5398
                chanStream.Start()
3✔
5399

3✔
5400
                // Stop the stream when quit.
3✔
5401
                go func() {
6✔
5402
                        <-p.cg.Done()
3✔
5403
                        chanStream.Stop()
3✔
5404
                }()
3✔
5405
        }
5406

5407
        // With the stream obtained, add the message to the stream so we can
5408
        // continue processing message.
5409
        chanStream.AddMsg(msg)
3✔
5410
}
5411

5412
// scaleTimeout multiplies the argument duration by a constant factor depending
5413
// on variious heuristics. Currently this is only used to check whether our peer
5414
// appears to be connected over Tor and relaxes the timout deadline. However,
5415
// this is subject to change and should be treated as opaque.
5416
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
3✔
5417
        if p.isTorConnection {
6✔
5418
                return timeout * time.Duration(torTimeoutMultiplier)
3✔
5419
        }
3✔
5420

5421
        return timeout
×
5422
}
5423

5424
// CoopCloseUpdates is a struct used to communicate updates for an active close
5425
// to the caller.
5426
type CoopCloseUpdates struct {
5427
        UpdateChan chan interface{}
5428

5429
        ErrChan chan error
5430
}
5431

5432
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5433
// point has an active RBF chan closer.
5434
func (p *Brontide) ChanHasRbfCoopCloser(chanPoint wire.OutPoint) bool {
3✔
5435
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5436
        chanCloser, found := p.activeChanCloses.Load(chanID)
3✔
5437
        if !found {
6✔
5438
                return false
3✔
5439
        }
3✔
5440

5441
        return chanCloser.IsRight()
3✔
5442
}
5443

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

3✔
5452
        // If RBF coop close isn't permitted, then we'll an error.
3✔
5453
        if !p.rbfCoopCloseAllowed() {
3✔
5454
                return nil, fmt.Errorf("rbf coop close not enabled for " +
×
5455
                        "channel")
×
5456
        }
×
5457

5458
        closeUpdates := &CoopCloseUpdates{
3✔
5459
                UpdateChan: make(chan interface{}, 1),
3✔
5460
                ErrChan:    make(chan error, 1),
3✔
5461
        }
3✔
5462

3✔
5463
        // We'll re-use the existing switch struct here, even though we're
3✔
5464
        // bypassing the switch entirely.
3✔
5465
        closeReq := htlcswitch.ChanClose{
3✔
5466
                CloseType:      contractcourt.CloseRegular,
3✔
5467
                ChanPoint:      &chanPoint,
3✔
5468
                TargetFeePerKw: feeRate,
3✔
5469
                DeliveryScript: deliveryScript,
3✔
5470
                Updates:        closeUpdates.UpdateChan,
3✔
5471
                Err:            closeUpdates.ErrChan,
3✔
5472
                Ctx:            ctx,
3✔
5473
        }
3✔
5474

3✔
5475
        err := p.startRbfChanCloser(newRPCShutdownInit(&closeReq), chanPoint)
3✔
5476
        if err != nil {
3✔
5477
                return nil, err
×
5478
        }
×
5479

5480
        return closeUpdates, nil
3✔
5481
}
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