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

lightningnetwork / lnd / 17373151115

01 Sep 2025 09:13AM UTC coverage: 66.657% (-0.02%) from 66.678%
17373151115

Pull #10182

github

web-flow
Merge 48f9e78c3 into cd6971ea1
Pull Request #10182: Aux feature bits

45 of 108 new or added lines in 4 files covered. (41.67%)

83 existing lines in 16 files now uncovered.

136034 of 204080 relevant lines covered (66.66%)

21495.48 hits per line

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

78.23
/peer/brontide.go
1
package peer
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

126
        err chan error
127
}
128

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

441
        // QuiescenceTimeout is the max duration that the channel can be
442
        // quiesced. Any dependent protocols (dynamic commitments, splicing,
443
        // etc.) must finish their operations under this timeout value,
444
        // otherwise the node will disconnect.
445
        QuiescenceTimeout time.Duration
446

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

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

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

460
        // AuxChannelNegotiator is an optional interface that allows aux
461
        // channel implementations to inject and process feature bits during
462
        // init and channel_reestablish messages.
463
        AuxChannelNegotiator fn.Option[lnwallet.AuxChannelNegotiator]
464

465
        // ShouldFwdExpEndorsement is a closure that indicates whether
466
        // experimental endorsement signals should be set.
467
        ShouldFwdExpEndorsement func() bool
468

469
        // NoDisconnectOnPongFailure indicates whether the peer should *not* be
470
        // disconnected if a pong is not received in time or is mismatched.
471
        NoDisconnectOnPongFailure bool
472

473
        // Quit is the server's quit channel. If this is closed, we halt operation.
474
        Quit chan struct{}
475
}
476

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

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

491
// makeRbfCloser creates a new RBF closer from a chancloser.RbfChanCloser.
492
func makeRbfCloser(rbfCloser *chancloser.RbfChanCloser) chanCloserFsm {
3✔
493
        return fn.NewRight[*chancloser.ChanCloser](
3✔
494
                rbfCloser,
3✔
495
        )
3✔
496
}
3✔
497

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

508
        // MUST be used atomically.
509
        bytesReceived uint64
510
        bytesSent     uint64
511

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

529
        pingManager *PingManager
530

531
        // lastPingPayload stores an unsafe pointer wrapped as an atomic
532
        // variable which points to the last payload the remote party sent us
533
        // as their ping.
534
        //
535
        // MUST be used atomically.
536
        lastPingPayload atomic.Value
537

538
        cfg Config
539

540
        // activeSignal when closed signals that the peer is now active and
541
        // ready to process messages.
542
        activeSignal chan struct{}
543

544
        // startTime is the time this peer connection was successfully established.
545
        // It will be zero for peers that did not successfully call Start().
546
        startTime time.Time
547

548
        // sendQueue is the channel which is used to queue outgoing messages to be
549
        // written onto the wire. Note that this channel is unbuffered.
550
        sendQueue chan outgoingMsg
551

552
        // outgoingQueue is a buffered channel which allows second/third party
553
        // objects to queue messages to be sent out on the wire.
554
        outgoingQueue chan outgoingMsg
555

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

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

575
        // newActiveChannel is used by the fundingManager to send fully opened
576
        // channels to the source peer which handled the funding workflow.
577
        newActiveChannel chan *newChannelMsg
578

579
        // newPendingChannel is used by the fundingManager to send pending open
580
        // channels to the source peer which handled the funding workflow.
581
        newPendingChannel chan *newChannelMsg
582

583
        // removePendingChannel is used by the fundingManager to cancel pending
584
        // open channels to the source peer when the funding flow is failed.
585
        removePendingChannel chan *newChannelMsg
586

587
        // activeMsgStreams is a map from channel id to the channel streams that
588
        // proxy messages to individual, active links.
589
        activeMsgStreams map[lnwire.ChannelID]*msgStream
590

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

597
        // localCloseChanReqs is a channel in which any local requests to close
598
        // a particular channel are sent over.
599
        localCloseChanReqs chan *htlcswitch.ChanClose
600

601
        // linkFailures receives all reported channel failures from the switch,
602
        // and instructs the channelManager to clean remaining channel state.
603
        linkFailures chan linkFailureReport
604

605
        // chanCloseMsgs is a channel that any message related to channel
606
        // closures are sent over. This includes lnwire.Shutdown message as
607
        // well as lnwire.ClosingSigned messages.
608
        chanCloseMsgs chan *closeMsg
609

610
        // remoteFeatures is the feature vector received from the peer during
611
        // the connection handshake.
612
        remoteFeatures *lnwire.FeatureVector
613

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

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

629
        // msgRouter is an instance of the msgmux.Router which is used to send
630
        // off new wire messages for handing.
631
        msgRouter fn.Option[msgmux.Router]
632

633
        // globalMsgRouter is a flag that indicates whether we have a global
634
        // msg router. If so, then we don't worry about stopping the msg router
635
        // when a peer disconnects.
636
        globalMsgRouter bool
637

638
        startReady chan struct{}
639

640
        // cg is a helper that encapsulates a wait group and quit channel and
641
        // allows contexts that either block or cancel on those depending on
642
        // the use case.
643
        cg *fn.ContextGuard
644

645
        // log is a peer-specific logging instance.
646
        log btclog.Logger
647
}
648

649
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer
650
// interface.
651
var _ lnpeer.Peer = (*Brontide)(nil)
652

653
// NewBrontide creates a new Brontide from a peer.Config struct.
654
func NewBrontide(cfg Config) *Brontide {
28✔
655
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
28✔
656

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

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

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

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

28✔
696
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
31✔
697
                remoteAddr := cfg.Conn.RemoteAddr().String()
3✔
698
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
3✔
699
                        strings.Contains(remoteAddr, "127.0.0.1")
3✔
700
        }
3✔
701

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

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

729
                return lastSerializedBlockHeader[:]
×
730
        }
731

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

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

×
757
                        logMsg := fmt.Sprintf("pong response "+
×
758
                                "failure for %s: %v. Time waited for this "+
×
759
                                "pong: %v. Last successful RTT: %v.",
×
760
                                p, reason, timeWaitedForPong, lastKnownRTT)
×
761

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

771
                        p.log.Warnf("%s -- disconnecting", logMsg)
×
772

×
773
                        go p.Disconnect(fmt.Errorf("pong failure: %w", reason))
×
774
                },
775
        })
776

777
        return p
28✔
778
}
779

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

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

6✔
792
        p.log.Tracef("starting with conn[%v->%v]",
6✔
793
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
6✔
794

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

806
        if len(activeChans) == 0 {
10✔
807
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
4✔
808
        }
4✔
809

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

818
                haveLegacyChan = true
3✔
819
                break
3✔
820
        }
821

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

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

6✔
837
                msg, err := p.readNextMessage()
6✔
838
                if err != nil {
9✔
839
                        readErr <- err
3✔
840
                        msgChan <- nil
3✔
841
                        return
3✔
842
                }
3✔
843
                readErr <- nil
6✔
844
                msgChan <- msg
6✔
845
        }()
846

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

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

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

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

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

895
        msgs, err := p.loadActiveChannels(activeChans)
6✔
896
        if err != nil {
6✔
897
                return fmt.Errorf("unable to load channels: %w", err)
×
898
        }
×
899

900
        p.startTime = time.Now()
6✔
901

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

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

919
        err = p.pingManager.Start()
6✔
920
        if err != nil {
6✔
921
                return fmt.Errorf("could not start ping manager %w", err)
×
922
        }
×
923

924
        p.cg.WgAdd(4)
6✔
925
        go p.queueHandler()
6✔
926
        go p.writeHandler()
6✔
927
        go p.channelManager()
6✔
928
        go p.readHandler()
6✔
929

6✔
930
        // Signal to any external processes that the peer is now active.
6✔
931
        close(p.activeSignal)
6✔
932

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

6✔
948
        return nil
6✔
949
}
950

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

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

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

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

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

994
        return bothHaveBit(lnwire.RbfCoopCloseOptional) ||
10✔
995
                bothHaveBit(lnwire.RbfCoopCloseOptionalStaging)
10✔
996
}
997

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

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

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

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

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

6✔
1042
        // Return a slice of messages to send to the peers in case the channel
6✔
1043
        // cannot be loaded normally.
6✔
1044
        var msgs []lnwire.Message
6✔
1045

6✔
1046
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
6✔
1047

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

1068
                                err = p.cfg.AddLocalAlias(
3✔
1069
                                        aliasScid, dbChan.ShortChanID(), false,
3✔
1070
                                        false,
3✔
1071
                                )
3✔
1072
                                if err != nil {
3✔
1073
                                        return nil, err
×
1074
                                }
×
1075

1076
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
1077
                                        dbChan.FundingOutpoint,
3✔
1078
                                )
3✔
1079

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

1087
                                channelReadyMsg := lnwire.NewChannelReady(
3✔
1088
                                        chanID, second,
3✔
1089
                                )
3✔
1090
                                channelReadyMsg.AliasScid = &aliasScid
3✔
1091

3✔
1092
                                msgs = append(msgs, channelReadyMsg)
3✔
1093
                        }
1094

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

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

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

1129
                chanPoint := dbChan.FundingOutpoint
5✔
1130

5✔
1131
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
5✔
1132

5✔
1133
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
5✔
1134
                        chanPoint, lnChan.IsPending())
5✔
1135

5✔
1136
                // Skip adding any permanently irreconcilable channels to the
5✔
1137
                // htlcswitch.
5✔
1138
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
5✔
1139
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
10✔
1140

5✔
1141
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
5✔
1142
                                "start.", chanPoint, dbChan.ChanStatus())
5✔
1143

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

1158
                        msgs = append(msgs, chanSync)
5✔
1159

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

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

1175
                                if shutdownMsg == nil {
6✔
1176
                                        continue
3✔
1177
                                }
1178

1179
                                // Append the message to the set of messages to
1180
                                // send.
1181
                                msgs = append(msgs, shutdownMsg)
×
1182
                        }
1183

1184
                        continue
5✔
1185
                }
1186

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

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

3✔
1209
                        selfPolicy = p1
3✔
1210
                } else {
6✔
1211
                        selfPolicy = p2
3✔
1212
                }
3✔
1213

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

1237
                p.log.Tracef("Using link policy of: %v",
3✔
1238
                        spew.Sdump(forwardingPolicy))
3✔
1239

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

3✔
1249
                        continue
3✔
1250
                }
1251

1252
                shutdownInfo, err := lnChan.State().ShutdownInfo()
3✔
1253
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
3✔
1254
                        return nil, err
×
1255
                }
×
1256

1257
                isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
1258

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

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

×
1279
                                return
×
1280
                        }
×
1281

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

×
1298
                                return
×
1299
                        }
×
1300

1301
                        chanID := lnwire.NewChanIDFromOutPoint(
3✔
1302
                                lnChan.State().FundingOutpoint,
3✔
1303
                        )
3✔
1304

3✔
1305
                        p.activeChanCloses.Store(chanID, makeNegotiateCloser(
3✔
1306
                                negotiateChanCloser,
3✔
1307
                        ))
3✔
1308

3✔
1309
                        // Create the Shutdown message.
3✔
1310
                        shutdown, err := negotiateChanCloser.ShutdownChan()
3✔
1311
                        if err != nil {
3✔
1312
                                p.activeChanCloses.Delete(chanID)
×
1313
                                shutdownInfoErr = err
×
1314

×
1315
                                return
×
1316
                        }
×
1317

1318
                        shutdownMsg = fn.Some(*shutdown)
3✔
1319
                })
1320
                if shutdownInfoErr != nil {
3✔
1321
                        return nil, shutdownInfoErr
×
1322
                }
×
1323

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

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

1341
                p.activeChannels.Store(chanID, lnChan)
3✔
1342

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

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

×
1360
                        return nil, fmt.Errorf("unable to init RBF chan "+
×
1361
                                "closer during peer connect: %w", err)
×
1362
                }
×
1363

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

1380
        return msgs, nil
6✔
1381
}
1382

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

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

3✔
1396
                failure := linkFailureReport{
3✔
1397
                        chanPoint:   *chanPoint,
3✔
1398
                        chanID:      chanID,
3✔
1399
                        shortChanID: shortChanID,
3✔
1400
                        linkErr:     linkErr,
3✔
1401
                }
3✔
1402

3✔
1403
                select {
3✔
1404
                case p.linkFailures <- failure:
3✔
1405
                case <-p.cg.Done():
×
1406
                case <-p.cfg.Quit:
×
1407
                }
1408
        }
1409

1410
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
6✔
1411
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
3✔
1412
        }
3✔
1413

1414
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
6✔
1415
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
3✔
1416
        }
3✔
1417

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

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

3✔
1475
        // With the channel link created, we'll now notify the htlc switch so
3✔
1476
        // this channel can be used to dispatch local payments and also
3✔
1477
        // passively forward payments.
3✔
1478
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
3✔
1479
}
1480

1481
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1482
// one confirmed public channel exists with them.
1483
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
6✔
1484
        defer p.cg.WgDone()
6✔
1485

6✔
1486
        hasConfirmedPublicChan := false
6✔
1487
        for _, channel := range channels {
11✔
1488
                if channel.IsPending {
8✔
1489
                        continue
3✔
1490
                }
1491
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
10✔
1492
                        continue
5✔
1493
                }
1494

1495
                hasConfirmedPublicChan = true
3✔
1496
                break
3✔
1497
        }
1498
        if !hasConfirmedPublicChan {
12✔
1499
                return
6✔
1500
        }
6✔
1501

1502
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
3✔
1503
        if err != nil {
3✔
1504
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1505
                return
×
1506
        }
×
1507

1508
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
3✔
1509
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1510
        }
×
1511
}
1512

1513
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1514
// have any active channels with them.
1515
func (p *Brontide) maybeSendChannelUpdates() {
6✔
1516
        defer p.cg.WgDone()
6✔
1517

6✔
1518
        // If we don't have any active channels, then we can exit early.
6✔
1519
        if p.activeChannels.Len() == 0 {
10✔
1520
                return
4✔
1521
        }
4✔
1522

1523
        maybeSendUpd := func(cid lnwire.ChannelID,
5✔
1524
                lnChan *lnwallet.LightningChannel) error {
10✔
1525

5✔
1526
                // Nil channels are pending, so we'll skip them.
5✔
1527
                if lnChan == nil {
8✔
1528
                        return nil
3✔
1529
                }
3✔
1530

1531
                dbChan := lnChan.State()
5✔
1532
                scid := func() lnwire.ShortChannelID {
10✔
1533
                        switch {
5✔
1534
                        // Otherwise if it's a zero conf channel and confirmed,
1535
                        // then we need to use the "real" scid.
1536
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
3✔
1537
                                return dbChan.ZeroConfRealScid()
3✔
1538

1539
                        // Otherwise, we can use the normal scid.
1540
                        default:
5✔
1541
                                return dbChan.ShortChanID()
5✔
1542
                        }
1543
                }()
1544

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

3✔
1555
                        return nil
3✔
1556
                }
3✔
1557

1558
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
5✔
1559
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
5✔
1560

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

×
1570
                        return err
×
1571
                }
×
1572

1573
                return nil
5✔
1574
        }
1575

1576
        p.activeChannels.ForEach(maybeSendUpd)
5✔
1577
}
1578

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

1596
        select {
3✔
1597
        case <-ready:
3✔
1598
        case <-p.cg.Done():
3✔
1599
        }
1600

1601
        p.cg.WgWait()
3✔
1602
}
1603

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

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

3✔
1626
                select {
3✔
1627
                case <-p.startReady:
3✔
1628
                case <-p.cg.Done():
×
1629
                        return
×
1630
                }
1631
        }
1632

1633
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
3✔
1634
        p.storeError(err)
3✔
1635

3✔
1636
        p.log.Infof(err.Error())
3✔
1637

3✔
1638
        // Stop PingManager before closing TCP connection.
3✔
1639
        p.pingManager.Stop()
3✔
1640

3✔
1641
        // Ensure that the TCP connection is properly closed before continuing.
3✔
1642
        p.cfg.Conn.Close()
3✔
1643

3✔
1644
        p.cg.Quit()
3✔
1645

3✔
1646
        // If our msg router isn't global (local to this instance), then we'll
3✔
1647
        // stop it. Otherwise, we'll leave it running.
3✔
1648
        if !p.globalMsgRouter {
6✔
1649
                p.msgRouter.WhenSome(func(router msgmux.Router) {
6✔
1650
                        router.Stop()
3✔
1651
                })
3✔
1652
        }
1653
}
1654

1655
// String returns the string representation of this peer.
1656
func (p *Brontide) String() string {
3✔
1657
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
3✔
1658
}
3✔
1659

1660
// readNextMessage reads, and returns the next message on the wire along with
1661
// any additional raw payload.
1662
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
10✔
1663
        noiseConn := p.cfg.Conn
10✔
1664
        err := noiseConn.SetReadDeadline(time.Time{})
10✔
1665
        if err != nil {
10✔
1666
                return nil, err
×
1667
        }
×
1668

1669
        pktLen, err := noiseConn.ReadNextHeader()
10✔
1670
        if err != nil {
13✔
1671
                return nil, fmt.Errorf("read next header: %w", err)
3✔
1672
        }
3✔
1673

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

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

7✔
1706
                // Next, create a new io.Reader implementation from the raw
7✔
1707
                // message, and use this to decode the message directly from.
7✔
1708
                msgReader := bytes.NewReader(rawMsg)
7✔
1709
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
7✔
1710
                if err != nil {
10✔
1711
                        return err
3✔
1712
                }
3✔
1713

1714
                // At this point, rawMsg and buf will be returned back to the
1715
                // buffer pool for re-use.
1716
                return nil
7✔
1717
        })
1718
        atomic.AddUint64(&p.bytesReceived, msgLen)
7✔
1719
        if err != nil {
10✔
1720
                return nil, err
3✔
1721
        }
3✔
1722

1723
        p.logWireMessage(nextMsg, true)
7✔
1724

7✔
1725
        return nextMsg, nil
7✔
1726
}
1727

1728
// msgStream implements a goroutine-safe, in-order stream of messages to be
1729
// delivered via closure to a receiver. These messages MUST be in order due to
1730
// the nature of the lightning channel commitment and gossiper state machines.
1731
// TODO(conner): use stream handler interface to abstract out stream
1732
// state/logging.
1733
type msgStream struct {
1734
        streamShutdown int32 // To be used atomically.
1735

1736
        peer *Brontide
1737

1738
        apply func(lnwire.Message)
1739

1740
        startMsg string
1741
        stopMsg  string
1742

1743
        msgCond *sync.Cond
1744
        msgs    []lnwire.Message
1745

1746
        mtx sync.Mutex
1747

1748
        producerSema chan struct{}
1749

1750
        wg   sync.WaitGroup
1751
        quit chan struct{}
1752
}
1753

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

6✔
1762
        stream := &msgStream{
6✔
1763
                peer:         p,
6✔
1764
                apply:        apply,
6✔
1765
                startMsg:     startMsg,
6✔
1766
                stopMsg:      stopMsg,
6✔
1767
                producerSema: make(chan struct{}, bufSize),
6✔
1768
                quit:         make(chan struct{}),
6✔
1769
        }
6✔
1770
        stream.msgCond = sync.NewCond(&stream.mtx)
6✔
1771

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

1780
        return stream
6✔
1781
}
1782

1783
// Start starts the chanMsgStream.
1784
func (ms *msgStream) Start() {
6✔
1785
        ms.wg.Add(1)
6✔
1786
        go ms.msgConsumer()
6✔
1787
}
6✔
1788

1789
// Stop stops the chanMsgStream.
1790
func (ms *msgStream) Stop() {
3✔
1791
        // TODO(roasbeef): signal too?
3✔
1792

3✔
1793
        close(ms.quit)
3✔
1794

3✔
1795
        // Now that we've closed the channel, we'll repeatedly signal the msg
3✔
1796
        // consumer until we've detected that it has exited.
3✔
1797
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
6✔
1798
                ms.msgCond.Signal()
3✔
1799
                time.Sleep(time.Millisecond * 100)
3✔
1800
        }
3✔
1801

1802
        ms.wg.Wait()
3✔
1803
}
1804

1805
// msgConsumer is the main goroutine that streams messages from the peer's
1806
// readHandler directly to the target channel.
1807
func (ms *msgStream) msgConsumer() {
6✔
1808
        defer ms.wg.Done()
6✔
1809
        defer peerLog.Tracef(ms.stopMsg)
6✔
1810
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
6✔
1811

6✔
1812
        peerLog.Tracef(ms.startMsg)
6✔
1813

6✔
1814
        for {
12✔
1815
                // First, we'll check our condition. If the queue of messages
6✔
1816
                // is empty, then we'll wait until a new item is added.
6✔
1817
                ms.msgCond.L.Lock()
6✔
1818
                for len(ms.msgs) == 0 {
12✔
1819
                        ms.msgCond.Wait()
6✔
1820

6✔
1821
                        // If we woke up in order to exit, then we'll do so.
6✔
1822
                        // Otherwise, we'll check the message queue for any new
6✔
1823
                        // items.
6✔
1824
                        select {
6✔
1825
                        case <-ms.peer.cg.Done():
3✔
1826
                                ms.msgCond.L.Unlock()
3✔
1827
                                return
3✔
1828
                        case <-ms.quit:
3✔
1829
                                ms.msgCond.L.Unlock()
3✔
1830
                                return
3✔
1831
                        default:
3✔
1832
                        }
1833
                }
1834

1835
                // Grab the message off the front of the queue, shifting the
1836
                // slice's reference down one in order to remove the message
1837
                // from the queue.
1838
                msg := ms.msgs[0]
3✔
1839
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
3✔
1840
                ms.msgs = ms.msgs[1:]
3✔
1841

3✔
1842
                ms.msgCond.L.Unlock()
3✔
1843

3✔
1844
                ms.apply(msg)
3✔
1845

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

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

1876
        // Next, we'll lock the condition, and add the message to the end of
1877
        // the message queue.
1878
        ms.msgCond.L.Lock()
3✔
1879
        ms.msgs = append(ms.msgs, msg)
3✔
1880
        ms.msgCond.L.Unlock()
3✔
1881

3✔
1882
        // With the message added, we signal to the msgConsumer that there are
3✔
1883
        // additional messages to consume.
3✔
1884
        ms.msgCond.Signal()
3✔
1885
}
1886

1887
// waitUntilLinkActive waits until the target link is active and returns a
1888
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1889
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1890
func waitUntilLinkActive(p *Brontide,
1891
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
3✔
1892

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

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

3✔
1913
        // The link may already be active by this point, and we may have missed the
3✔
1914
        // ActiveLinkEvent. Check if the link exists.
3✔
1915
        link := p.fetchLinkFromKeyAndCid(cid)
3✔
1916
        if link != nil {
6✔
1917
                return link
3✔
1918
        }
3✔
1919

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

1934
                        chanPoint := event.ChannelPoint
3✔
1935

3✔
1936
                        // Check whether the retrieved chanPoint matches the target
3✔
1937
                        // channel id.
3✔
1938
                        if !cid.IsChanPoint(chanPoint) {
3✔
1939
                                continue
×
1940
                        }
1941

1942
                        // The link shouldn't be nil as we received an
1943
                        // ActiveLinkEvent. If it is nil, we return nil and the
1944
                        // calling function should catch it.
1945
                        return p.fetchLinkFromKeyAndCid(cid)
3✔
1946

1947
                case <-p.cg.Done():
3✔
1948
                        return nil
3✔
1949
                }
1950
        }
1951
}
1952

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

3✔
1962
        apply := func(msg lnwire.Message) {
6✔
1963
                // This check is fine because if the link no longer exists, it will
3✔
1964
                // be removed from the activeChannels map and subsequent messages
3✔
1965
                // shouldn't reach the chan msg stream.
3✔
1966
                if chanLink == nil {
6✔
1967
                        chanLink = waitUntilLinkActive(p, cid)
3✔
1968

3✔
1969
                        // If the link is still not active and the calling function
3✔
1970
                        // errored out, just return.
3✔
1971
                        if chanLink == nil {
6✔
1972
                                p.log.Warnf("Link=%v is not active", cid)
3✔
1973
                                return
3✔
1974
                        }
3✔
1975
                }
1976

1977
                // In order to avoid unnecessarily delivering message
1978
                // as the peer is exiting, we'll check quickly to see
1979
                // if we need to exit.
1980
                select {
3✔
1981
                case <-p.cg.Done():
×
1982
                        return
×
1983
                default:
3✔
1984
                }
1985

1986
                chanLink.HandleChannelUpdate(msg)
3✔
1987
        }
1988

1989
        return newMsgStream(p,
3✔
1990
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
3✔
1991
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
3✔
1992
                msgStreamSize,
3✔
1993
                apply,
3✔
1994
        )
3✔
1995
}
1996

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

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

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

2024
        return newMsgStream(
6✔
2025
                p,
6✔
2026
                "Update stream for gossiper created",
6✔
2027
                "Update stream for gossiper exited",
6✔
2028
                msgStreamSize,
6✔
2029
                apply,
6✔
2030
        )
6✔
2031
}
2032

2033
// readHandler is responsible for reading messages off the wire in series, then
2034
// properly dispatching the handling of the message to the proper subsystem.
2035
//
2036
// NOTE: This method MUST be run as a goroutine.
2037
func (p *Brontide) readHandler() {
6✔
2038
        defer p.cg.WgDone()
6✔
2039

6✔
2040
        // We'll stop the timer after a new messages is received, and also
6✔
2041
        // reset it after we process the next message.
6✔
2042
        idleTimer := time.AfterFunc(idleTimeout, func() {
6✔
2043
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
2044
                        p, idleTimeout)
×
2045
                p.Disconnect(err)
×
2046
        })
×
2047

2048
        // Initialize our negotiated gossip sync method before reading messages
2049
        // off the wire. When using gossip queries, this ensures a gossip
2050
        // syncer is active by the time query messages arrive.
2051
        //
2052
        // TODO(conner): have peer store gossip syncer directly and bypass
2053
        // gossiper?
2054
        p.initGossipSync()
6✔
2055

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

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

2085
                        // If they sent us an address type that we don't yet
2086
                        // know of, then this isn't a wire error, so we'll
2087
                        // simply continue parsing the remainder of their
2088
                        // messages.
2089
                        case *lnwire.ErrUnknownAddrType:
×
2090
                                p.storeError(e)
×
2091
                                idleTimer.Reset(idleTimeout)
×
2092
                                continue
×
2093

2094
                        // If the NodeAnnouncement has an invalid alias, then
2095
                        // we'll log that error above and continue so we can
2096
                        // continue to read messages from the peer. We do not
2097
                        // store this error because it is of little debugging
2098
                        // value.
2099
                        case *lnwire.ErrInvalidNodeAlias:
×
2100
                                idleTimer.Reset(idleTimeout)
×
2101
                                continue
×
2102

2103
                        // If the error we encountered wasn't just a message we
2104
                        // didn't recognize, then we'll stop all processing as
2105
                        // this is a fatal error.
2106
                        default:
3✔
2107
                                break out
3✔
2108
                        }
2109
                }
2110

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

2121
                // No error occurred, and the message was handled by the
2122
                // router.
2123
                if err == nil {
7✔
2124
                        continue
3✔
2125
                }
2126

2127
                var (
4✔
2128
                        targetChan   lnwire.ChannelID
4✔
2129
                        isLinkUpdate bool
4✔
2130
                )
4✔
2131

4✔
2132
                switch msg := nextMsg.(type) {
4✔
2133
                case *lnwire.Pong:
×
2134
                        // When we receive a Pong message in response to our
×
2135
                        // last ping message, we send it to the pingManager
×
2136
                        p.pingManager.ReceivedPong(msg)
×
2137

2138
                case *lnwire.Ping:
×
2139
                        // First, we'll store their latest ping payload within
×
2140
                        // the relevant atomic variable.
×
2141
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
2142

×
2143
                        // Next, we'll send over the amount of specified pong
×
2144
                        // bytes.
×
2145
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
×
2146
                        p.queueMsg(pong, nil)
×
2147

2148
                case *lnwire.OpenChannel,
2149
                        *lnwire.AcceptChannel,
2150
                        *lnwire.FundingCreated,
2151
                        *lnwire.FundingSigned,
2152
                        *lnwire.ChannelReady:
3✔
2153

3✔
2154
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2155

2156
                case *lnwire.Shutdown:
3✔
2157
                        select {
3✔
2158
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
2159
                        case <-p.cg.Done():
×
2160
                                break out
×
2161
                        }
2162
                case *lnwire.ClosingSigned:
3✔
2163
                        select {
3✔
2164
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
2165
                        case <-p.cg.Done():
×
2166
                                break out
×
2167
                        }
2168

2169
                case *lnwire.Warning:
×
2170
                        targetChan = msg.ChanID
×
2171
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2172

2173
                case *lnwire.Error:
3✔
2174
                        targetChan = msg.ChanID
3✔
2175
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
3✔
2176

2177
                case *lnwire.ChannelReestablish:
3✔
2178
                        targetChan = msg.ChanID
3✔
2179
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2180

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

2196
                // For messages that implement the LinkUpdater interface, we
2197
                // will consider them as link updates and send them to
2198
                // chanStream. These messages will be queued inside chanStream
2199
                // if the channel is not active yet.
2200
                case lnwire.LinkUpdater:
3✔
2201
                        targetChan = msg.TargetChanID()
3✔
2202
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2203

3✔
2204
                        // Log an error if we don't have this channel. This
3✔
2205
                        // means the peer has sent us a message with unknown
3✔
2206
                        // channel ID.
3✔
2207
                        if !isLinkUpdate {
6✔
2208
                                p.log.Errorf("Unknown channel ID: %v found "+
3✔
2209
                                        "in received msg=%s", targetChan,
3✔
2210
                                        nextMsg.MsgType())
3✔
2211
                        }
3✔
2212

2213
                case *lnwire.ChannelUpdate1,
2214
                        *lnwire.ChannelAnnouncement1,
2215
                        *lnwire.NodeAnnouncement,
2216
                        *lnwire.AnnounceSignatures1,
2217
                        *lnwire.GossipTimestampRange,
2218
                        *lnwire.QueryShortChanIDs,
2219
                        *lnwire.QueryChannelRange,
2220
                        *lnwire.ReplyChannelRange,
2221
                        *lnwire.ReplyShortChanIDsEnd:
3✔
2222

3✔
2223
                        discStream.AddMsg(msg)
3✔
2224

2225
                case *lnwire.Custom:
4✔
2226
                        err := p.handleCustomMessage(msg)
4✔
2227
                        if err != nil {
4✔
2228
                                p.storeError(err)
×
2229
                                p.log.Errorf("%v", err)
×
2230
                        }
×
2231

2232
                default:
×
2233
                        // If the message we received is unknown to us, store
×
2234
                        // the type to track the failure.
×
2235
                        err := fmt.Errorf("unknown message type %v received",
×
2236
                                uint16(msg.MsgType()))
×
2237
                        p.storeError(err)
×
2238

×
2239
                        p.log.Errorf("%v", err)
×
2240
                }
2241

2242
                if isLinkUpdate {
7✔
2243
                        // If this is a channel update, then we need to feed it
3✔
2244
                        // into the channel's in-order message stream.
3✔
2245
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
3✔
2246
                }
3✔
2247

2248
                idleTimer.Reset(idleTimeout)
4✔
2249
        }
2250

2251
        p.Disconnect(errors.New("read handler closed"))
3✔
2252

3✔
2253
        p.log.Trace("readHandler for peer done")
3✔
2254
}
2255

2256
// handleCustomMessage handles the given custom message if a handler is
2257
// registered.
2258
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
4✔
2259
        if p.cfg.HandleCustomMessage == nil {
4✔
2260
                return fmt.Errorf("no custom message handler for "+
×
2261
                        "message type %v", uint16(msg.MsgType()))
×
2262
        }
×
2263

2264
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
4✔
2265
}
2266

2267
// isLoadedFromDisk returns true if the provided channel ID is loaded from
2268
// disk.
2269
//
2270
// NOTE: only returns true for pending channels.
2271
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
3✔
2272
        // If this is a newly added channel, no need to reestablish.
3✔
2273
        _, added := p.addedChannels.Load(chanID)
3✔
2274
        if added {
6✔
2275
                return false
3✔
2276
        }
3✔
2277

2278
        // Return false if the channel is unknown.
2279
        channel, ok := p.activeChannels.Load(chanID)
3✔
2280
        if !ok {
3✔
2281
                return false
×
2282
        }
×
2283

2284
        // During startup, we will use a nil value to mark a pending channel
2285
        // that's loaded from disk.
2286
        return channel == nil
3✔
2287
}
2288

2289
// isActiveChannel returns true if the provided channel id is active, otherwise
2290
// returns false.
2291
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
11✔
2292
        // The channel would be nil if,
11✔
2293
        // - the channel doesn't exist, or,
11✔
2294
        // - the channel exists, but is pending. In this case, we don't
11✔
2295
        //   consider this channel active.
11✔
2296
        channel, _ := p.activeChannels.Load(chanID)
11✔
2297

11✔
2298
        return channel != nil
11✔
2299
}
11✔
2300

2301
// isPendingChannel returns true if the provided channel ID is pending, and
2302
// returns false if the channel is active or unknown.
2303
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
9✔
2304
        // Return false if the channel is unknown.
9✔
2305
        channel, ok := p.activeChannels.Load(chanID)
9✔
2306
        if !ok {
15✔
2307
                return false
6✔
2308
        }
6✔
2309

2310
        return channel == nil
6✔
2311
}
2312

2313
// hasChannel returns true if the peer has a pending/active channel specified
2314
// by the channel ID.
2315
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
3✔
2316
        _, ok := p.activeChannels.Load(chanID)
3✔
2317
        return ok
3✔
2318
}
3✔
2319

2320
// storeError stores an error in our peer's buffer of recent errors with the
2321
// current timestamp. Errors are only stored if we have at least one active
2322
// channel with the peer to mitigate a dos vector where a peer costlessly
2323
// connects to us and spams us with errors.
2324
func (p *Brontide) storeError(err error) {
3✔
2325
        var haveChannels bool
3✔
2326

3✔
2327
        p.activeChannels.Range(func(_ lnwire.ChannelID,
3✔
2328
                channel *lnwallet.LightningChannel) bool {
6✔
2329

3✔
2330
                // Pending channels will be nil in the activeChannels map.
3✔
2331
                if channel == nil {
6✔
2332
                        // Return true to continue the iteration.
3✔
2333
                        return true
3✔
2334
                }
3✔
2335

2336
                haveChannels = true
3✔
2337

3✔
2338
                // Return false to break the iteration.
3✔
2339
                return false
3✔
2340
        })
2341

2342
        // If we do not have any active channels with the peer, we do not store
2343
        // errors as a dos mitigation.
2344
        if !haveChannels {
6✔
2345
                p.log.Trace("no channels with peer, not storing err")
3✔
2346
                return
3✔
2347
        }
3✔
2348

2349
        p.cfg.ErrorBuffer.Add(
3✔
2350
                &TimestampedError{Timestamp: time.Now(), Error: err},
3✔
2351
        )
3✔
2352
}
2353

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

3✔
2363
        if errMsg, ok := msg.(*lnwire.Error); ok {
6✔
2364
                p.storeError(errMsg)
3✔
2365
        }
3✔
2366

2367
        switch {
3✔
2368
        // Connection wide messages should be forwarded to all channel links
2369
        // with this peer.
2370
        case chanID == lnwire.ConnectionWideID:
×
2371
                for _, chanStream := range p.activeMsgStreams {
×
2372
                        chanStream.AddMsg(msg)
×
2373
                }
×
2374

2375
                return false
×
2376

2377
        // If the channel ID for the message corresponds to a pending channel,
2378
        // then the funding manager will handle it.
2379
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
3✔
2380
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2381
                return false
3✔
2382

2383
        // If not we hand the message to the channel link for this channel.
2384
        case p.isActiveChannel(chanID):
3✔
2385
                return true
3✔
2386

2387
        default:
3✔
2388
                return false
3✔
2389
        }
2390
}
2391

2392
// messageSummary returns a human-readable string that summarizes a
2393
// incoming/outgoing message. Not all messages will have a summary, only those
2394
// which have additional data that can be informative at a glance.
2395
func messageSummary(msg lnwire.Message) string {
3✔
2396
        switch msg := msg.(type) {
3✔
2397
        case *lnwire.Init:
3✔
2398
                // No summary.
3✔
2399
                return ""
3✔
2400

2401
        case *lnwire.OpenChannel:
3✔
2402
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
3✔
2403
                        "push_amt=%v, reserve=%v, flags=%v",
3✔
2404
                        msg.PendingChannelID[:], msg.ChainHash,
3✔
2405
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
3✔
2406
                        msg.ChannelReserve, msg.ChannelFlags)
3✔
2407

2408
        case *lnwire.AcceptChannel:
3✔
2409
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
3✔
2410
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
3✔
2411
                        msg.MinAcceptDepth)
3✔
2412

2413
        case *lnwire.FundingCreated:
3✔
2414
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
3✔
2415
                        msg.PendingChannelID[:], msg.FundingPoint)
3✔
2416

2417
        case *lnwire.FundingSigned:
3✔
2418
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
3✔
2419

2420
        case *lnwire.ChannelReady:
3✔
2421
                return fmt.Sprintf("chan_id=%v, next_point=%x",
3✔
2422
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
3✔
2423

2424
        case *lnwire.Shutdown:
3✔
2425
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
3✔
2426
                        msg.Address[:])
3✔
2427

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

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

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

2439
        case *lnwire.UpdateAddHTLC:
3✔
2440
                var blindingPoint []byte
3✔
2441
                msg.BlindingPoint.WhenSome(
3✔
2442
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
3✔
2443
                                *btcec.PublicKey]) {
6✔
2444

3✔
2445
                                blindingPoint = b.Val.SerializeCompressed()
3✔
2446
                        },
3✔
2447
                )
2448

2449
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
3✔
2450
                        "hash=%x, blinding_point=%x, custom_records=%v",
3✔
2451
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
3✔
2452
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
3✔
2453

2454
        case *lnwire.UpdateFailHTLC:
3✔
2455
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
3✔
2456
                        msg.ID, msg.Reason)
3✔
2457

2458
        case *lnwire.UpdateFulfillHTLC:
3✔
2459
                return fmt.Sprintf("chan_id=%v, id=%v, preimage=%x, "+
3✔
2460
                        "custom_records=%v", msg.ChanID, msg.ID,
3✔
2461
                        msg.PaymentPreimage[:], msg.CustomRecords)
3✔
2462

2463
        case *lnwire.CommitSig:
3✔
2464
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
3✔
2465
                        len(msg.HtlcSigs))
3✔
2466

2467
        case *lnwire.RevokeAndAck:
3✔
2468
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
3✔
2469
                        msg.ChanID, msg.Revocation[:],
3✔
2470
                        msg.NextRevocationKey.SerializeCompressed())
3✔
2471

2472
        case *lnwire.UpdateFailMalformedHTLC:
3✔
2473
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
3✔
2474
                        msg.ChanID, msg.ID, msg.FailureCode)
3✔
2475

2476
        case *lnwire.Warning:
×
2477
                return fmt.Sprintf("%v", msg.Warning())
×
2478

2479
        case *lnwire.Error:
3✔
2480
                return fmt.Sprintf("%v", msg.Error())
3✔
2481

2482
        case *lnwire.AnnounceSignatures1:
3✔
2483
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
3✔
2484
                        msg.ShortChannelID.ToUint64())
3✔
2485

2486
        case *lnwire.ChannelAnnouncement1:
3✔
2487
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
3✔
2488
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
3✔
2489

2490
        case *lnwire.ChannelUpdate1:
3✔
2491
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
3✔
2492
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
3✔
2493
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
3✔
2494
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
3✔
2495

2496
        case *lnwire.NodeAnnouncement:
3✔
2497
                return fmt.Sprintf("node=%x, update_time=%v",
3✔
2498
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
3✔
2499

2500
        case *lnwire.Ping:
×
2501
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
2502

2503
        case *lnwire.Pong:
×
2504
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
×
2505

2506
        case *lnwire.UpdateFee:
×
2507
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2508
                        msg.ChanID, int64(msg.FeePerKw))
×
2509

2510
        case *lnwire.ChannelReestablish:
3✔
2511
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
3✔
2512
                        "remote_tail_height=%v", msg.ChanID,
3✔
2513
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
3✔
2514

2515
        case *lnwire.ReplyShortChanIDsEnd:
3✔
2516
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
3✔
2517
                        msg.Complete)
3✔
2518

2519
        case *lnwire.ReplyChannelRange:
3✔
2520
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
3✔
2521
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
3✔
2522
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
3✔
2523
                        msg.EncodingType)
3✔
2524

2525
        case *lnwire.QueryShortChanIDs:
3✔
2526
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
3✔
2527
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
3✔
2528

2529
        case *lnwire.QueryChannelRange:
3✔
2530
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
3✔
2531
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
3✔
2532
                        msg.LastBlockHeight())
3✔
2533

2534
        case *lnwire.GossipTimestampRange:
3✔
2535
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
3✔
2536
                        "stamp_range=%v", msg.ChainHash,
3✔
2537
                        time.Unix(int64(msg.FirstTimestamp), 0),
3✔
2538
                        msg.TimestampRange)
3✔
2539

2540
        case *lnwire.Stfu:
3✔
2541
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
3✔
2542
                        msg.Initiator)
3✔
2543

2544
        case *lnwire.Custom:
3✔
2545
                return fmt.Sprintf("type=%d", msg.Type)
3✔
2546
        }
2547

2548
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2549
}
2550

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

2562
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
23✔
2563
                // Debug summary of message.
3✔
2564
                summary := messageSummary(msg)
3✔
2565
                if len(summary) > 0 {
6✔
2566
                        summary = "(" + summary + ")"
3✔
2567
                }
3✔
2568

2569
                preposition := "to"
3✔
2570
                if read {
6✔
2571
                        preposition = "from"
3✔
2572
                }
3✔
2573

2574
                var msgType string
3✔
2575
                if msg.MsgType() < lnwire.CustomTypeStart {
6✔
2576
                        msgType = msg.MsgType().String()
3✔
2577
                } else {
6✔
2578
                        msgType = "custom"
3✔
2579
                }
3✔
2580

2581
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
3✔
2582
                        msgType, summary, preposition, p)
3✔
2583
        }))
2584

2585
        prefix := "readMessage from peer"
20✔
2586
        if !read {
36✔
2587
                prefix = "writeMessage to peer"
16✔
2588
        }
16✔
2589

2590
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
20✔
2591
}
2592

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

2610
        noiseConn := p.cfg.Conn
16✔
2611

16✔
2612
        flushMsg := func() error {
32✔
2613
                // Ensure the write deadline is set before we attempt to send
16✔
2614
                // the message.
16✔
2615
                writeDeadline := time.Now().Add(
16✔
2616
                        p.scaleTimeout(writeMessageTimeout),
16✔
2617
                )
16✔
2618
                err := noiseConn.SetWriteDeadline(writeDeadline)
16✔
2619
                if err != nil {
16✔
2620
                        return err
×
2621
                }
×
2622

2623
                // Flush the pending message to the wire. If an error is
2624
                // encountered, e.g. write timeout, the number of bytes written
2625
                // so far will be returned.
2626
                n, err := noiseConn.Flush()
16✔
2627

16✔
2628
                // Record the number of bytes written on the wire, if any.
16✔
2629
                if n > 0 {
19✔
2630
                        atomic.AddUint64(&p.bytesSent, uint64(n))
3✔
2631
                }
3✔
2632

2633
                return err
16✔
2634
        }
2635

2636
        // If the current message has already been serialized, encrypted, and
2637
        // buffered on the underlying connection we will skip straight to
2638
        // flushing it to the wire.
2639
        if msg == nil {
16✔
2640
                return flushMsg()
×
2641
        }
×
2642

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

2653
                // Finally, write the message itself in a single swoop. This
2654
                // will buffer the ciphertext on the underlying connection. We
2655
                // will defer flushing the message until the write pool has been
2656
                // released.
2657
                return noiseConn.WriteMessage(buf.Bytes())
16✔
2658
        })
2659
        if err != nil {
16✔
2660
                return err
×
2661
        }
×
2662

2663
        return flushMsg()
16✔
2664
}
2665

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

2681
        var exitErr error
6✔
2682

6✔
2683
out:
6✔
2684
        for {
16✔
2685
                select {
10✔
2686
                case outMsg := <-p.sendQueue:
7✔
2687
                        // Record the time at which we first attempt to send the
7✔
2688
                        // message.
7✔
2689
                        startTime := time.Now()
7✔
2690

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

×
2703
                                // If we received a timeout error, this implies
×
2704
                                // that the message was buffered on the
×
2705
                                // connection successfully and that a flush was
×
2706
                                // attempted. We'll set the message to nil so
×
2707
                                // that on a subsequent pass we only try to
×
2708
                                // flush the buffered message, and forgo
×
2709
                                // reserializing or reencrypting it.
×
2710
                                outMsg.msg = nil
×
2711

×
2712
                                goto retry
×
2713
                        }
2714

2715
                        // The write succeeded, reset the idle timer to prevent
2716
                        // us from disconnecting the peer.
2717
                        if !idleTimer.Stop() {
7✔
2718
                                select {
×
2719
                                case <-idleTimer.C:
×
2720
                                default:
×
2721
                                }
2722
                        }
2723
                        idleTimer.Reset(idleTimeout)
7✔
2724

7✔
2725
                        // If the peer requested a synchronous write, respond
7✔
2726
                        // with the error.
7✔
2727
                        if outMsg.errChan != nil {
11✔
2728
                                outMsg.errChan <- err
4✔
2729
                        }
4✔
2730

2731
                        if err != nil {
7✔
2732
                                exitErr = fmt.Errorf("unable to write "+
×
2733
                                        "message: %v", err)
×
2734
                                break out
×
2735
                        }
2736

2737
                case <-p.cg.Done():
3✔
2738
                        exitErr = lnpeer.ErrPeerExiting
3✔
2739
                        break out
3✔
2740
                }
2741
        }
2742

2743
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2744
        // disconnect.
2745
        p.cg.WgDone()
3✔
2746

3✔
2747
        p.Disconnect(exitErr)
3✔
2748

3✔
2749
        p.log.Trace("writeHandler for peer done")
3✔
2750
}
2751

2752
// queueHandler is responsible for accepting messages from outside subsystems
2753
// to be eventually sent out on the wire by the writeHandler.
2754
//
2755
// NOTE: This method MUST be run as a goroutine.
2756
func (p *Brontide) queueHandler() {
6✔
2757
        defer p.cg.WgDone()
6✔
2758

6✔
2759
        // priorityMsgs holds an in order list of messages deemed high-priority
6✔
2760
        // to be added to the sendQueue. This predominately includes messages
6✔
2761
        // from the funding manager and htlcswitch.
6✔
2762
        priorityMsgs := list.New()
6✔
2763

6✔
2764
        // lazyMsgs holds an in order list of messages deemed low-priority to be
6✔
2765
        // added to the sendQueue only after all high-priority messages have
6✔
2766
        // been queued. This predominately includes messages from the gossiper.
6✔
2767
        lazyMsgs := list.New()
6✔
2768

6✔
2769
        for {
20✔
2770
                // Examine the front of the priority queue, if it is empty check
14✔
2771
                // the low priority queue.
14✔
2772
                elem := priorityMsgs.Front()
14✔
2773
                if elem == nil {
25✔
2774
                        elem = lazyMsgs.Front()
11✔
2775
                }
11✔
2776

2777
                if elem != nil {
21✔
2778
                        front := elem.Value.(outgoingMsg)
7✔
2779

7✔
2780
                        // There's an element on the queue, try adding
7✔
2781
                        // it to the sendQueue. We also watch for
7✔
2782
                        // messages on the outgoingQueue, in case the
7✔
2783
                        // writeHandler cannot accept messages on the
7✔
2784
                        // sendQueue.
7✔
2785
                        select {
7✔
2786
                        case p.sendQueue <- front:
7✔
2787
                                if front.priority {
13✔
2788
                                        priorityMsgs.Remove(elem)
6✔
2789
                                } else {
10✔
2790
                                        lazyMsgs.Remove(elem)
4✔
2791
                                }
4✔
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():
×
2799
                                return
×
2800
                        }
2801
                } else {
10✔
2802
                        // If there weren't any messages to send to the
10✔
2803
                        // writeHandler, then we'll accept a new message
10✔
2804
                        // into the queue from outside sub-systems.
10✔
2805
                        select {
10✔
2806
                        case msg := <-p.outgoingQueue:
7✔
2807
                                if msg.priority {
13✔
2808
                                        priorityMsgs.PushBack(msg)
6✔
2809
                                } else {
10✔
2810
                                        lazyMsgs.PushBack(msg)
4✔
2811
                                }
4✔
2812
                        case <-p.cg.Done():
3✔
2813
                                return
3✔
2814
                        }
2815
                }
2816
        }
2817
}
2818

2819
// PingTime returns the estimated ping time to the peer in microseconds.
2820
func (p *Brontide) PingTime() int64 {
3✔
2821
        return p.pingManager.GetPingTimeMicroSeconds()
3✔
2822
}
3✔
2823

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

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

2838
// queue sends a given message to the queueHandler using the passed priority. If
2839
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2840
// failed to write, and nil otherwise.
2841
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2842
        errChan chan error) {
29✔
2843

29✔
2844
        select {
29✔
2845
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
28✔
2846
        case <-p.cg.Done():
×
2847
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
×
2848
                        spew.Sdump(msg))
×
2849
                if errChan != nil {
×
2850
                        errChan <- lnpeer.ErrPeerExiting
×
2851
                }
×
2852
        }
2853
}
2854

2855
// ChannelSnapshots returns a slice of channel snapshots detailing all
2856
// currently active channels maintained with the remote peer.
2857
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
3✔
2858
        snapshots := make(
3✔
2859
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
3✔
2860
        )
3✔
2861

3✔
2862
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2863
                activeChan *lnwallet.LightningChannel) error {
6✔
2864

3✔
2865
                // If the activeChan is nil, then we skip it as the channel is
3✔
2866
                // pending.
3✔
2867
                if activeChan == nil {
6✔
2868
                        return nil
3✔
2869
                }
3✔
2870

2871
                // We'll only return a snapshot for channels that are
2872
                // *immediately* available for routing payments over.
2873
                if activeChan.RemoteNextRevocation() == nil {
6✔
2874
                        return nil
3✔
2875
                }
3✔
2876

2877
                snapshot := activeChan.StateSnapshot()
3✔
2878
                snapshots = append(snapshots, snapshot)
3✔
2879

3✔
2880
                return nil
3✔
2881
        })
2882

2883
        return snapshots
3✔
2884
}
2885

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

2896
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
9✔
2897
                addrType, false, lnwallet.DefaultAccountName,
9✔
2898
        )
9✔
2899
        if err != nil {
9✔
2900
                return nil, err
×
2901
        }
×
2902
        p.log.Infof("Delivery addr for channel close: %v",
9✔
2903
                deliveryAddr)
9✔
2904

9✔
2905
        return txscript.PayToAddrScript(deliveryAddr)
9✔
2906
}
2907

2908
// channelManager is goroutine dedicated to handling all requests/signals
2909
// pertaining to the opening, cooperative closing, and force closing of all
2910
// channels maintained with the remote peer.
2911
//
2912
// NOTE: This method MUST be run as a goroutine.
2913
func (p *Brontide) channelManager() {
20✔
2914
        defer p.cg.WgDone()
20✔
2915

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

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

2932
                // A new channel has arrived which means we've just completed a
2933
                // funding workflow. We'll initialize the necessary local
2934
                // state, and notify the htlc switch of a new link.
2935
                case req := <-p.newActiveChannel:
3✔
2936
                        p.handleNewActiveChannel(req)
3✔
2937

2938
                // The funding flow for a pending channel is failed, we will
2939
                // remove it from Brontide.
2940
                case req := <-p.removePendingChannel:
4✔
2941
                        p.handleRemovePendingChannel(req)
4✔
2942

2943
                // We've just received a local request to close an active
2944
                // channel. It will either kick of a cooperative channel
2945
                // closure negotiation, or be a notification of a breached
2946
                // contract that should be abandoned.
2947
                case req := <-p.localCloseChanReqs:
10✔
2948
                        p.handleLocalCloseReq(req)
10✔
2949

2950
                // We've received a link failure from a link that was added to
2951
                // the switch. This will initiate the teardown of the link, and
2952
                // initiate any on-chain closures if necessary.
2953
                case failure := <-p.linkFailures:
3✔
2954
                        p.handleLinkFailure(failure)
3✔
2955

2956
                // We've received a new cooperative channel closure related
2957
                // message from the remote peer, we'll use this message to
2958
                // advance the chan closer state machine.
2959
                case closeMsg := <-p.chanCloseMsgs:
16✔
2960
                        p.handleCloseMsg(closeMsg)
16✔
2961

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

3✔
2972
                        // Since this channel will never fire again during the
3✔
2973
                        // lifecycle of the peer, we nil the channel to mark it
3✔
2974
                        // eligible for garbage collection, and make this
3✔
2975
                        // explicitly ineligible to receive in future calls to
3✔
2976
                        // select. This also shaves a few CPU cycles since the
3✔
2977
                        // select will ignore this case entirely.
3✔
2978
                        reenableTimeout = nil
3✔
2979

3✔
2980
                        // Once the reenabling is attempted, we also cancel the
3✔
2981
                        // channel event subscription to free up the overflow
3✔
2982
                        // queue used in channel notifier.
3✔
2983
                        //
3✔
2984
                        // NOTE: channelEventClient will be nil if the
3✔
2985
                        // reenableTimeout is greater than 1 minute.
3✔
2986
                        if p.channelEventClient != nil {
6✔
2987
                                p.channelEventClient.Cancel()
3✔
2988
                        }
3✔
2989

2990
                case <-p.cg.Done():
3✔
2991
                        // As, we've been signalled to exit, we'll reset all
3✔
2992
                        // our active channel back to their default state.
3✔
2993
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2994
                                lc *lnwallet.LightningChannel) error {
6✔
2995

3✔
2996
                                // Exit if the channel is nil as it's a pending
3✔
2997
                                // channel.
3✔
2998
                                if lc == nil {
6✔
2999
                                        return nil
3✔
3000
                                }
3✔
3001

3002
                                lc.ResetState()
3✔
3003

3✔
3004
                                return nil
3✔
3005
                        })
3006

3007
                        break out
3✔
3008
                }
3009
        }
3010
}
3011

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

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

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

3✔
3030
                switch {
3✔
3031
                // No error occurred, continue to request the next channel.
3032
                case err == nil:
3✔
3033
                        continue
3✔
3034

3035
                // Cannot auto enable a manually disabled channel so we do
3036
                // nothing but proceed to the next channel.
3037
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
3✔
3038
                        p.log.Debugf("Channel(%v) was manually disabled, "+
3✔
3039
                                "ignoring automatic enable request", chanPoint)
3✔
3040

3✔
3041
                        continue
3✔
3042

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

×
3060
                                continue
×
3061
                        }
3062

3063
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
3064
                                "ChanStatusManager reported inactive, retrying")
×
3065

×
3066
                        // Add the channel to the retry map.
×
3067
                        retryChans[chanPoint] = struct{}{}
×
3068
                }
3069
        }
3070

3071
        // Retry the channels if we have any.
3072
        if len(retryChans) != 0 {
3✔
3073
                p.retryRequestEnable(retryChans)
×
3074
        }
×
3075
}
3076

3077
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
3078
// for the target channel ID. If the channel isn't active an error is returned.
3079
// Otherwise, either an existing state machine will be returned, or a new one
3080
// will be created.
3081
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
3082
        *chanCloserFsm, error) {
16✔
3083

16✔
3084
        chanCloser, found := p.activeChanCloses.Load(chanID)
16✔
3085
        if found {
29✔
3086
                // An entry will only be found if the closer has already been
13✔
3087
                // created for a non-pending channel or for a channel that had
13✔
3088
                // previously started the shutdown process but the connection
13✔
3089
                // was restarted.
13✔
3090
                return &chanCloser, nil
13✔
3091
        }
13✔
3092

3093
        // First, we'll ensure that we actually know of the target channel. If
3094
        // not, we'll ignore this message.
3095
        channel, ok := p.activeChannels.Load(chanID)
6✔
3096

6✔
3097
        // If the channel isn't in the map or the channel is nil, return
6✔
3098
        // ErrChannelNotFound as the channel is pending.
6✔
3099
        if !ok || channel == nil {
9✔
3100
                return nil, ErrChannelNotFound
3✔
3101
        }
3✔
3102

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

3122
        // In order to begin fee negotiations, we'll first compute our target
3123
        // ideal fee-per-kw.
3124
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
6✔
3125
                p.cfg.CoopCloseTargetConfs,
6✔
3126
        )
6✔
3127
        if err != nil {
6✔
3128
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3129
                return nil, fmt.Errorf("unable to estimate fee")
×
3130
        }
×
3131

3132
        addr, err := p.addrWithInternalKey(deliveryScript)
6✔
3133
        if err != nil {
6✔
3134
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3135
        }
×
3136
        negotiateChanCloser, err := p.createChanCloser(
6✔
3137
                channel, addr, feePerKw, nil, lntypes.Remote,
6✔
3138
        )
6✔
3139
        if err != nil {
6✔
3140
                p.log.Errorf("unable to create chan closer: %v", err)
×
3141
                return nil, fmt.Errorf("unable to create chan closer")
×
3142
        }
×
3143

3144
        chanCloser = makeNegotiateCloser(negotiateChanCloser)
6✔
3145

6✔
3146
        p.activeChanCloses.Store(chanID, chanCloser)
6✔
3147

6✔
3148
        return &chanCloser, nil
6✔
3149
}
3150

3151
// filterChannelsToEnable filters a list of channels to be enabled upon start.
3152
// The filtered channels are active channels that's neither private nor
3153
// pending.
3154
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
3✔
3155
        var activePublicChans []wire.OutPoint
3✔
3156

3✔
3157
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
3✔
3158
                lnChan *lnwallet.LightningChannel) bool {
6✔
3159

3✔
3160
                // If the lnChan is nil, continue as this is a pending channel.
3✔
3161
                if lnChan == nil {
6✔
3162
                        return true
3✔
3163
                }
3✔
3164

3165
                dbChan := lnChan.State()
3✔
3166
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
3167
                if !isPublic || dbChan.IsPending {
3✔
3168
                        return true
×
3169
                }
×
3170

3171
                // We'll also skip any channels added during this peer's
3172
                // lifecycle since they haven't waited out the timeout. Their
3173
                // first announcement will be enabled, and the chan status
3174
                // manager will begin monitoring them passively since they exist
3175
                // in the database.
3176
                if _, ok := p.addedChannels.Load(chanID); ok {
3✔
3177
                        return true
×
3178
                }
×
3179

3180
                activePublicChans = append(
3✔
3181
                        activePublicChans, dbChan.FundingOutpoint,
3✔
3182
                )
3✔
3183

3✔
3184
                return true
3✔
3185
        })
3186

3187
        return activePublicChans
3✔
3188
}
3189

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

×
3197
        // retryEnable is a helper closure that sends an enable request and
×
3198
        // removes the channel from the map if it's matched.
×
3199
        retryEnable := func(chanPoint wire.OutPoint) error {
×
3200
                // If this is an active channel event, check whether it's in
×
3201
                // our targeted channels map.
×
3202
                _, found := activeChans[chanPoint]
×
3203

×
3204
                // If this channel is irrelevant, return nil so the loop can
×
3205
                // jump to next iteration.
×
3206
                if !found {
×
3207
                        return nil
×
3208
                }
×
3209

3210
                // Otherwise we've just received an active signal for a channel
3211
                // that's previously failed to be enabled, we send the request
3212
                // again.
3213
                //
3214
                // We only give the channel one more shot, so we delete it from
3215
                // our map first to keep it from being attempted again.
3216
                delete(activeChans, chanPoint)
×
3217

×
3218
                // Send the request.
×
3219
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3220
                if err != nil {
×
3221
                        return fmt.Errorf("request enabling channel %v "+
×
3222
                                "failed: %w", chanPoint, err)
×
3223
                }
×
3224

3225
                return nil
×
3226
        }
3227

3228
        for {
×
3229
                // If activeChans is empty, we've done processing all the
×
3230
                // channels.
×
3231
                if len(activeChans) == 0 {
×
3232
                        p.log.Debug("Finished retry enabling channels")
×
3233
                        return
×
3234
                }
×
3235

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

×
3246
                                // If we received an error for this particular
×
3247
                                // channel, we log an error and won't quit as
×
3248
                                // we still want to retry other channels.
×
3249
                                if err := retryEnable(chanPoint); err != nil {
×
3250
                                        p.log.Errorf("Retry failed: %v", err)
×
3251
                                }
×
3252

3253
                                continue
×
3254
                        }
3255

3256
                        // Otherwise check for inactive link event, and jump to
3257
                        // next iteration if it's not.
3258
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3259
                        if !ok {
×
3260
                                continue
×
3261
                        }
3262

3263
                        // Found an inactive link event, if this is our
3264
                        // targeted channel, remove it from our map.
3265
                        chanPoint := *inactive.ChannelPoint
×
3266
                        _, found := activeChans[chanPoint]
×
3267
                        if !found {
×
3268
                                continue
×
3269
                        }
3270

3271
                        delete(activeChans, chanPoint)
×
3272
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3273
                                "inactive link event", chanPoint)
×
3274

3275
                case <-p.cg.Done():
×
3276
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3277
                        return
×
3278
                }
3279
        }
3280
}
3281

3282
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3283
// a suitable script to close out to. This may be nil if neither script is
3284
// set. If both scripts are set, this function will error if they do not match.
3285
func chooseDeliveryScript(upfront, requested lnwire.DeliveryAddress,
3286
        genDeliveryScript func() ([]byte, error),
3287
) (lnwire.DeliveryAddress, error) {
15✔
3288

15✔
3289
        switch {
15✔
3290
        // If no script was provided, then we'll generate a new delivery script.
3291
        case len(upfront) == 0 && len(requested) == 0:
7✔
3292
                return genDeliveryScript()
7✔
3293

3294
        // If no upfront shutdown script was provided, return the user
3295
        // requested address (which may be nil).
3296
        case len(upfront) == 0:
5✔
3297
                return requested, nil
5✔
3298

3299
        // If an upfront shutdown script was provided, and the user did not
3300
        // request a custom shutdown script, return the upfront address.
3301
        case len(requested) == 0:
5✔
3302
                return upfront, nil
5✔
3303

3304
        // If both an upfront shutdown script and a custom close script were
3305
        // provided, error if the user provided shutdown script does not match
3306
        // the upfront shutdown script (because closing out to a different
3307
        // script would violate upfront shutdown).
3308
        case !bytes.Equal(upfront, requested):
2✔
3309
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
3310

3311
        // The user requested script matches the upfront shutdown script, so we
3312
        // can return it without error.
3313
        default:
2✔
3314
                return upfront, nil
2✔
3315
        }
3316
}
3317

3318
// restartCoopClose checks whether we need to restart the cooperative close
3319
// process for a given channel.
3320
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3321
        *lnwire.Shutdown, error) {
3✔
3322

3✔
3323
        isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
3324

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

3344
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
3✔
3345

3✔
3346
        var deliveryScript []byte
3✔
3347

3✔
3348
        shutdownInfo, err := c.ShutdownInfo()
3✔
3349
        switch {
3✔
3350
        // We have previously stored the delivery script that we need to use
3351
        // in the shutdown message. Re-use this script.
3352
        case err == nil:
3✔
3353
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
6✔
3354
                        deliveryScript = info.DeliveryScript.Val
3✔
3355
                })
3✔
3356

3357
        // An error other than ErrNoShutdownInfo was returned
3358
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3359
                return nil, err
×
3360

3361
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3362
                deliveryScript = c.LocalShutdownScript
×
3363
                if len(deliveryScript) == 0 {
×
3364
                        var err error
×
3365
                        deliveryScript, err = p.genDeliveryScript()
×
3366
                        if err != nil {
×
3367
                                p.log.Errorf("unable to gen delivery script: "+
×
3368
                                        "%v", err)
×
3369

×
3370
                                return nil, fmt.Errorf("close addr unavailable")
×
3371
                        }
×
3372
                }
3373
        }
3374

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

3385
                shutdownDesc := fn.MapOption(
3✔
3386
                        newRestartShutdownInit,
3✔
3387
                )(shutdownInfo)
3✔
3388

3✔
3389
                err = p.startRbfChanCloser(
3✔
3390
                        fn.FlattenOption(shutdownDesc), lnChan.ChannelPoint(),
3✔
3391
                )
3✔
3392

3✔
3393
                return nil, err
3✔
3394
        }
3395

3396
        // Compute an ideal fee.
3397
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
3398
                p.cfg.CoopCloseTargetConfs,
×
3399
        )
×
3400
        if err != nil {
×
3401
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3402
                return nil, fmt.Errorf("unable to estimate fee")
×
3403
        }
×
3404

3405
        // Determine whether we or the peer are the initiator of the coop
3406
        // close attempt by looking at the channel's status.
3407
        closingParty := lntypes.Remote
×
3408
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3409
                closingParty = lntypes.Local
×
3410
        }
×
3411

3412
        addr, err := p.addrWithInternalKey(deliveryScript)
×
3413
        if err != nil {
×
3414
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3415
        }
×
3416
        chanCloser, err := p.createChanCloser(
×
3417
                lnChan, addr, feePerKw, nil, closingParty,
×
3418
        )
×
3419
        if err != nil {
×
3420
                p.log.Errorf("unable to create chan closer: %v", err)
×
3421
                return nil, fmt.Errorf("unable to create chan closer")
×
3422
        }
×
3423

3424
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
×
3425

×
3426
        // Create the Shutdown message.
×
3427
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3428
        if err != nil {
×
3429
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3430
                p.activeChanCloses.Delete(chanID)
×
3431
                return nil, err
×
3432
        }
×
3433

3434
        return shutdownMsg, nil
×
3435
}
3436

3437
// createChanCloser constructs a ChanCloser from the passed parameters and is
3438
// used to de-duplicate code.
3439
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3440
        deliveryScript *chancloser.DeliveryAddrWithKey,
3441
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3442
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
12✔
3443

12✔
3444
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
12✔
3445
        if err != nil {
12✔
3446
                p.log.Errorf("unable to obtain best block: %v", err)
×
3447
                return nil, fmt.Errorf("cannot obtain best block")
×
3448
        }
×
3449

3450
        // The req will only be set if we initiated the co-op closing flow.
3451
        var maxFee chainfee.SatPerKWeight
12✔
3452
        if req != nil {
21✔
3453
                maxFee = req.MaxFee
9✔
3454
        }
9✔
3455

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

3481
        return chanCloser, nil
12✔
3482
}
3483

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

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

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

3510
        addr, err := p.addrWithInternalKey(deliveryScript)
9✔
3511
        if err != nil {
9✔
3512
                return fmt.Errorf("unable to parse addr for channel "+
×
3513
                        "%v: %w", req.ChanPoint, err)
×
3514
        }
×
3515

3516
        chanCloser, err := p.createChanCloser(
9✔
3517
                channel, addr, req.TargetFeePerKw, req, lntypes.Local,
9✔
3518
        )
9✔
3519
        if err != nil {
9✔
3520
                return fmt.Errorf("unable to make chan closer: %w", err)
×
3521
        }
×
3522

3523
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
9✔
3524
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
9✔
3525

9✔
3526
        // Finally, we'll initiate the channel shutdown within the
9✔
3527
        // chanCloser, and send the shutdown message to the remote
9✔
3528
        // party to kick things off.
9✔
3529
        shutdownMsg, err := chanCloser.ShutdownChan()
9✔
3530
        if err != nil {
9✔
3531
                // As we were unable to shutdown the channel, we'll return it
×
3532
                // back to its normal state.
×
3533
                defer channel.ResetState()
×
3534

×
3535
                p.activeChanCloses.Delete(chanID)
×
3536

×
3537
                return fmt.Errorf("unable to shutdown channel: %w", err)
×
3538
        }
×
3539

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

3552
        if !link.DisableAdds(htlcswitch.Outgoing) {
9✔
3553
                p.log.Warnf("Outgoing link adds already "+
×
3554
                        "disabled: %v", link.ChanID())
×
3555
        }
×
3556

3557
        link.OnCommitOnce(htlcswitch.Outgoing, func() {
18✔
3558
                p.queueMsg(shutdownMsg, nil)
9✔
3559
        })
9✔
3560

3561
        return nil
9✔
3562
}
3563

3564
// chooseAddr returns the provided address if it is non-zero length, otherwise
3565
// None.
3566
func chooseAddr(addr lnwire.DeliveryAddress) fn.Option[lnwire.DeliveryAddress] {
3✔
3567
        if len(addr) == 0 {
6✔
3568
                return fn.None[lnwire.DeliveryAddress]()
3✔
3569
        }
3✔
3570

3571
        return fn.Some(addr)
×
3572
}
3573

3574
// observeRbfCloseUpdates observes the channel for any updates that may
3575
// indicate that a new txid has been broadcasted, or the channel fully closed
3576
// on chain.
3577
func (p *Brontide) observeRbfCloseUpdates(chanCloser *chancloser.RbfChanCloser,
3578
        closeReq *htlcswitch.ChanClose,
3579
        coopCloseStates chancloser.RbfStateSub) {
3✔
3580

3✔
3581
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3582
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3583

3✔
3584
        var (
3✔
3585
                lastTxids    lntypes.Dual[chainhash.Hash]
3✔
3586
                lastFeeRates lntypes.Dual[chainfee.SatPerVByte]
3✔
3587
        )
3✔
3588

3✔
3589
        maybeNotifyTxBroadcast := func(state chancloser.AsymmetricPeerState,
3✔
3590
                party lntypes.ChannelParty) {
6✔
3591

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

3✔
3601
                        peerLog.Warnf("ChannelPoint(%v): encountered close "+
3✔
3602
                                "err: %v", closeReq.ChanPoint, err)
3✔
3603

3✔
3604
                        select {
3✔
3605
                        case closeReq.Err <- err:
3✔
3606
                        case <-closeReq.Ctx.Done():
×
3607
                        case <-p.cg.Done():
×
3608
                        }
3609

3610
                        return
3✔
3611
                }
3612

3613
                closePending, ok := state.(*chancloser.ClosePending)
3✔
3614

3✔
3615
                // If this isn't the close pending state, we aren't at the
3✔
3616
                // terminal state yet.
3✔
3617
                if !ok {
6✔
3618
                        return
3✔
3619
                }
3✔
3620

3621
                // Only notify if the fee rate is greater.
3622
                newFeeRate := closePending.FeeRate
3✔
3623
                lastFeeRate := lastFeeRates.GetForParty(party)
3✔
3624
                if newFeeRate <= lastFeeRate {
6✔
3625
                        peerLog.Debugf("ChannelPoint(%v): remote party made "+
3✔
3626
                                "update for fee rate %v, but we already have "+
3✔
3627
                                "a higher fee rate of %v", closeReq.ChanPoint,
3✔
3628
                                newFeeRate, lastFeeRate)
3✔
3629

3✔
3630
                        return
3✔
3631
                }
3✔
3632

3633
                feeRate := closePending.FeeRate
3✔
3634
                lastFeeRates.SetForParty(party, feeRate)
3✔
3635

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

3652
                        case <-closeReq.Ctx.Done():
×
3653
                                return
×
3654

3655
                        case <-p.cg.Done():
×
3656
                                return
×
3657
                        }
3658
                }
3659

3660
                lastTxids.SetForParty(party, closingTxid)
3✔
3661
        }
3662

3663
        peerLog.Infof("Observing RBF close updates for channel %v",
3✔
3664
                closeReq.ChanPoint)
3✔
3665

3✔
3666
        // We'll consume each new incoming state to send out the appropriate
3✔
3667
        // RPC update.
3✔
3668
        for {
6✔
3669
                select {
3✔
3670
                case newState := <-newStateChan:
3✔
3671

3✔
3672
                        switch closeState := newState.(type) {
3✔
3673
                        // Once we've reached the state of pending close, we
3674
                        // have a txid that we broadcasted.
3675
                        case *chancloser.ClosingNegotiation:
3✔
3676
                                peerState := closeState.PeerState
3✔
3677

3✔
3678
                                // Each side may have gained a new co-op close
3✔
3679
                                // tx, so we'll examine both to see if they've
3✔
3680
                                // changed.
3✔
3681
                                maybeNotifyTxBroadcast(
3✔
3682
                                        peerState.GetForParty(lntypes.Local),
3✔
3683
                                        lntypes.Local,
3✔
3684
                                )
3✔
3685
                                maybeNotifyTxBroadcast(
3✔
3686
                                        peerState.GetForParty(lntypes.Remote),
3✔
3687
                                        lntypes.Remote,
3✔
3688
                                )
3✔
3689

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

3✔
3708
                                return
3✔
3709
                        }
3710

3711
                case <-closeReq.Ctx.Done():
3✔
3712
                        return
3✔
3713

3714
                case <-p.cg.Done():
3✔
3715
                        return
3✔
3716
                }
3717
        }
3718
}
3719

3720
// chanErrorReporter is a simple implementation of the
3721
// chancloser.ErrorReporter. This is bound to a single channel by the channel
3722
// ID.
3723
type chanErrorReporter struct {
3724
        chanID lnwire.ChannelID
3725
        peer   *Brontide
3726
}
3727

3728
// newChanErrorReporter creates a new instance of the chanErrorReporter.
3729
func newChanErrorReporter(chanID lnwire.ChannelID,
3730
        peer *Brontide) *chanErrorReporter {
3✔
3731

3✔
3732
        return &chanErrorReporter{
3✔
3733
                chanID: chanID,
3✔
3734
                peer:   peer,
3✔
3735
        }
3✔
3736
}
3✔
3737

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

×
3747
        var errMsg []byte
×
3748
        if errors.Is(chanErr, chancloser.ErrInvalidStateTransition) {
×
3749
                errMsg = []byte("unexpected protocol message")
×
3750
        } else {
×
3751
                errMsg = []byte(chanErr.Error())
×
3752
        }
×
3753

3754
        err := c.peer.SendMessageLazy(false, &lnwire.Error{
×
3755
                ChanID: c.chanID,
×
3756
                Data:   errMsg,
×
3757
        })
×
3758
        if err != nil {
×
3759
                c.peer.log.Warnf("unable to send error message to peer: %v",
×
3760
                        err)
×
3761
        }
×
3762

3763
        // After we send the error message to the peer, we'll re-initialize the
3764
        // coop close state machine as they may send a shutdown message to
3765
        // retry the coop close.
3766
        lnChan, ok := c.peer.activeChannels.Load(c.chanID)
×
3767
        if !ok {
×
3768
                return
×
3769
        }
×
3770

3771
        if lnChan == nil {
×
3772
                c.peer.log.Debugf("channel %v is pending, not "+
×
3773
                        "re-initializing coop close state machine",
×
3774
                        c.chanID)
×
3775

×
3776
                return
×
3777
        }
×
3778

3779
        if _, err := c.peer.initRbfChanCloser(lnChan); err != nil {
×
3780
                c.peer.activeChanCloses.Delete(c.chanID)
×
3781

×
3782
                c.peer.log.Errorf("unable to init RBF chan closer after "+
×
3783
                        "error case: %v", err)
×
3784
        }
×
3785
}
3786

3787
// chanFlushEventSentinel is used to send the RBF coop close state machine the
3788
// channel flushed event. We'll wait until the state machine enters the
3789
// ChannelFlushing state, then request the link to send the event once flushed.
3790
//
3791
// NOTE: This MUST be run as a goroutine.
3792
func (p *Brontide) chanFlushEventSentinel(chanCloser *chancloser.RbfChanCloser,
3793
        link htlcswitch.ChannelUpdateHandler,
3794
        channel *lnwallet.LightningChannel) {
3✔
3795

3✔
3796
        defer p.cg.WgDone()
3✔
3797

3✔
3798
        // If there's no link, then the channel has already been flushed, so we
3✔
3799
        // don't need to continue.
3✔
3800
        if link == nil {
6✔
3801
                return
3✔
3802
        }
3✔
3803

3804
        coopCloseStates := chanCloser.RegisterStateEvents()
3✔
3805
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3806

3✔
3807
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3808

3✔
3809
        sendChanFlushed := func() {
6✔
3810
                chanState := channel.StateSnapshot()
3✔
3811

3✔
3812
                peerLog.Infof("ChannelPoint(%v) has been flushed for co-op "+
3✔
3813
                        "close, sending event to chan closer",
3✔
3814
                        channel.ChannelPoint())
3✔
3815

3✔
3816
                chanBalances := chancloser.ShutdownBalances{
3✔
3817
                        LocalBalance:  chanState.LocalBalance,
3✔
3818
                        RemoteBalance: chanState.RemoteBalance,
3✔
3819
                }
3✔
3820
                ctx := context.Background()
3✔
3821
                chanCloser.SendEvent(ctx, &chancloser.ChannelFlushed{
3✔
3822
                        ShutdownBalances: chanBalances,
3✔
3823
                        FreshFlush:       true,
3✔
3824
                })
3✔
3825
        }
3✔
3826

3827
        // We'll wait until the channel enters the ChannelFlushing state. We
3828
        // exit after a success loop. As after the first RBF iteration, the
3829
        // channel will always be flushed.
3830
        for {
6✔
3831
                select {
3✔
3832
                case newState, ok := <-newStateChan:
3✔
3833
                        if !ok {
3✔
3834
                                return
×
3835
                        }
×
3836

3837
                        if _, ok := newState.(*chancloser.ChannelFlushing); ok {
6✔
3838
                                peerLog.Infof("ChannelPoint(%v): rbf coop "+
3✔
3839
                                        "close is awaiting a flushed state, "+
3✔
3840
                                        "registering with link..., ",
3✔
3841
                                        channel.ChannelPoint())
3✔
3842

3✔
3843
                                // Request the link to send the event once the
3✔
3844
                                // channel is flushed. We only need this event
3✔
3845
                                // sent once, so we can exit now.
3✔
3846
                                link.OnFlushedOnce(sendChanFlushed)
3✔
3847

3✔
3848
                                return
3✔
3849
                        }
3✔
3850

3851
                case <-p.cg.Done():
3✔
3852
                        return
3✔
3853
                }
3854
        }
3855
}
3856

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

3✔
3863
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
3✔
3864

3✔
3865
        link := p.fetchLinkFromKeyAndCid(chanID)
3✔
3866

3✔
3867
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
3✔
3868
        if err != nil {
3✔
3869
                return nil, fmt.Errorf("cannot obtain best block: %w", err)
×
3870
        }
×
3871

3872
        defaultFeePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
3873
                p.cfg.CoopCloseTargetConfs,
3✔
3874
        )
3✔
3875
        if err != nil {
3✔
3876
                return nil, fmt.Errorf("unable to estimate fee: %w", err)
×
3877
        }
×
3878

3879
        thawHeight, err := channel.AbsoluteThawHeight()
3✔
3880
        if err != nil {
3✔
3881
                return nil, fmt.Errorf("unable to get thaw height: %w", err)
×
3882
        }
×
3883

3884
        peerPub := *p.IdentityKey()
3✔
3885

3✔
3886
        msgMapper := chancloser.NewRbfMsgMapper(
3✔
3887
                uint32(startingHeight), chanID, peerPub,
3✔
3888
        )
3✔
3889

3✔
3890
        initialState := chancloser.ChannelActive{}
3✔
3891

3✔
3892
        scid := channel.ZeroConfRealScid().UnwrapOr(
3✔
3893
                channel.ShortChanID(),
3✔
3894
        )
3✔
3895

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

3921
        spendEvent := protofsm.RegisterSpend[chancloser.ProtocolEvent]{
3✔
3922
                OutPoint:   channel.ChannelPoint(),
3✔
3923
                PkScript:   channel.FundingTxOut().PkScript,
3✔
3924
                HeightHint: channel.DeriveHeightHint(),
3✔
3925
                PostSpendEvent: fn.Some[chancloser.RbfSpendMapper](
3✔
3926
                        chancloser.SpendMapper,
3✔
3927
                ),
3✔
3928
        }
3✔
3929

3✔
3930
        daemonAdapters := NewLndDaemonAdapters(LndAdapterCfg{
3✔
3931
                MsgSender:     newPeerMsgSender(peerPub, p),
3✔
3932
                TxBroadcaster: p.cfg.Wallet,
3✔
3933
                ChainNotifier: p.cfg.ChainNotifier,
3✔
3934
        })
3✔
3935

3✔
3936
        protoCfg := chancloser.RbfChanCloserCfg{
3✔
3937
                Daemon:        daemonAdapters,
3✔
3938
                InitialState:  &initialState,
3✔
3939
                Env:           &env,
3✔
3940
                InitEvent:     fn.Some[protofsm.DaemonEvent](&spendEvent),
3✔
3941
                ErrorReporter: newChanErrorReporter(chanID, p),
3✔
3942
                MsgMapper: fn.Some[protofsm.MsgMapper[chancloser.ProtocolEvent]]( //nolint:ll
3✔
3943
                        msgMapper,
3✔
3944
                ),
3✔
3945
        }
3✔
3946

3✔
3947
        ctx := context.Background()
3✔
3948
        chanCloser := protofsm.NewStateMachine(protoCfg)
3✔
3949
        chanCloser.Start(ctx)
3✔
3950

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

3✔
3956
                return r.RegisterEndpoint(&chanCloser)
3✔
3957
        })
3✔
3958
        if err != nil {
3✔
3959
                chanCloser.Stop()
×
3960

×
3961
                return nil, fmt.Errorf("unable to register endpoint for co-op "+
×
3962
                        "close: %w", err)
×
3963
        }
×
3964

3965
        p.activeChanCloses.Store(chanID, makeRbfCloser(&chanCloser))
3✔
3966

3✔
3967
        // Now that we've created the rbf closer state machine, we'll launch a
3✔
3968
        // new goroutine to eventually send in the ChannelFlushed event once
3✔
3969
        // needed.
3✔
3970
        p.cg.WgAdd(1)
3✔
3971
        go p.chanFlushEventSentinel(&chanCloser, link, channel)
3✔
3972

3✔
3973
        return &chanCloser, nil
3✔
3974
}
3975

3976
// shutdownInit describes the two ways we can initiate a new shutdown. Either we
3977
// got an RPC request to do so (left), or we sent a shutdown message to the
3978
// party (for w/e reason), but crashed before the close was complete.
3979
//
3980
//nolint:ll
3981
type shutdownInit = fn.Option[fn.Either[*htlcswitch.ChanClose, channeldb.ShutdownInfo]]
3982

3983
// shutdownStartFeeRate returns the fee rate that should be used for the
3984
// shutdown.  This returns a doubly wrapped option as the shutdown info might
3985
// be none, and the fee rate is only defined for the user initiated shutdown.
3986
func shutdownStartFeeRate(s shutdownInit) fn.Option[chainfee.SatPerKWeight] {
3✔
3987
        feeRateOpt := fn.MapOption(func(init fn.Either[*htlcswitch.ChanClose,
3✔
3988
                channeldb.ShutdownInfo]) fn.Option[chainfee.SatPerKWeight] {
6✔
3989

3✔
3990
                var feeRate fn.Option[chainfee.SatPerKWeight]
3✔
3991
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
6✔
3992
                        feeRate = fn.Some(req.TargetFeePerKw)
3✔
3993
                })
3✔
3994

3995
                return feeRate
3✔
3996
        })(s)
3997

3998
        return fn.FlattenOption(feeRateOpt)
3✔
3999
}
4000

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

3✔
4008
                var addr fn.Option[lnwire.DeliveryAddress]
3✔
4009
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
6✔
4010
                        if len(req.DeliveryScript) != 0 {
6✔
4011
                                addr = fn.Some(req.DeliveryScript)
3✔
4012
                        }
3✔
4013
                })
4014
                init.WhenRight(func(info channeldb.ShutdownInfo) {
6✔
4015
                        addr = fn.Some(info.DeliveryScript.Val)
3✔
4016
                })
3✔
4017

4018
                return addr
3✔
4019
        })(s)
4020

4021
        return fn.FlattenOption(addrOpt)
3✔
4022
}
4023

4024
// whenRPCShutdown registers a callback to be executed when the shutdown init
4025
// type is and RPC request.
4026
func whenRPCShutdown(s shutdownInit, f func(r *htlcswitch.ChanClose)) {
3✔
4027
        s.WhenSome(func(init fn.Either[*htlcswitch.ChanClose,
3✔
4028
                channeldb.ShutdownInfo]) {
6✔
4029

3✔
4030
                init.WhenLeft(f)
3✔
4031
        })
3✔
4032
}
4033

4034
// newRestartShutdownInit creates a new shutdownInit for the case where we need
4035
// to restart the shutdown flow after a restart.
4036
func newRestartShutdownInit(info channeldb.ShutdownInfo) shutdownInit {
3✔
4037
        return fn.Some(fn.NewRight[*htlcswitch.ChanClose](info))
3✔
4038
}
3✔
4039

4040
// newRPCShutdownInit creates a new shutdownInit for the case where we
4041
// initiated the shutdown via an RPC client.
4042
func newRPCShutdownInit(req *htlcswitch.ChanClose) shutdownInit {
3✔
4043
        return fn.Some(
3✔
4044
                fn.NewLeft[*htlcswitch.ChanClose, channeldb.ShutdownInfo](req),
3✔
4045
        )
3✔
4046
}
3✔
4047

4048
// waitUntilRbfCoastClear waits until the RBF co-op close state machine has
4049
// advanced to a terminal state before attempting another fee bump.
4050
func waitUntilRbfCoastClear(ctx context.Context,
4051
        rbfCloser *chancloser.RbfChanCloser) error {
3✔
4052

3✔
4053
        coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4054
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
4055
        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4056

3✔
4057
        isTerminalState := func(newState chancloser.RbfState) bool {
6✔
4058
                // If we're not in the negotiation sub-state, then we aren't at
3✔
4059
                // the terminal state yet.
3✔
4060
                state, ok := newState.(*chancloser.ClosingNegotiation)
3✔
4061
                if !ok {
3✔
4062
                        return false
×
4063
                }
×
4064

4065
                localState := state.PeerState.GetForParty(lntypes.Local)
3✔
4066

3✔
4067
                // If this isn't the close pending state, we aren't at the
3✔
4068
                // terminal state yet.
3✔
4069
                _, ok = localState.(*chancloser.ClosePending)
3✔
4070

3✔
4071
                return ok
3✔
4072
        }
4073

4074
        // Before we enter the subscription loop below, check to see if we're
4075
        // already in the terminal state.
4076
        rbfState, err := rbfCloser.CurrentState()
3✔
4077
        if err != nil {
3✔
4078
                return err
×
4079
        }
×
4080
        if isTerminalState(rbfState) {
6✔
4081
                return nil
3✔
4082
        }
3✔
4083

4084
        peerLog.Debugf("Waiting for RBF iteration to complete...")
×
4085

×
4086
        for {
×
4087
                select {
×
4088
                case newState := <-newStateChan:
×
4089
                        if isTerminalState(newState) {
×
4090
                                return nil
×
4091
                        }
×
4092

4093
                case <-ctx.Done():
×
4094
                        return fmt.Errorf("context canceled")
×
4095
                }
4096
        }
4097
}
4098

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

3✔
4107
        // Unlike the old negotiate chan closer, we'll always create the RBF
3✔
4108
        // chan closer on startup, so we can skip init here.
3✔
4109
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4110
        chanCloser, found := p.activeChanCloses.Load(chanID)
3✔
4111
        if !found {
3✔
4112
                return fmt.Errorf("rbf chan closer not found for channel %v",
×
4113
                        chanPoint)
×
4114
        }
×
4115

4116
        defaultFeePerKw, err := shutdownStartFeeRate(
3✔
4117
                shutdown,
3✔
4118
        ).UnwrapOrFuncErr(func() (chainfee.SatPerKWeight, error) {
6✔
4119
                return p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
4120
                        p.cfg.CoopCloseTargetConfs,
3✔
4121
                )
3✔
4122
        })
3✔
4123
        if err != nil {
3✔
4124
                return fmt.Errorf("unable to estimate fee: %w", err)
×
4125
        }
×
4126

4127
        chanCloser.WhenRight(func(rbfCloser *chancloser.RbfChanCloser) {
6✔
4128
                peerLog.Infof("ChannelPoint(%v): rbf-coop close requested, "+
3✔
4129
                        "sending shutdown", chanPoint)
3✔
4130

3✔
4131
                rbfState, err := rbfCloser.CurrentState()
3✔
4132
                if err != nil {
3✔
4133
                        peerLog.Warnf("ChannelPoint(%v): unable to get "+
×
4134
                                "current state for rbf-coop close: %v",
×
4135
                                chanPoint, err)
×
4136

×
4137
                        return
×
4138
                }
×
4139

4140
                coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4141

3✔
4142
                // Before we send our event below, we'll launch a goroutine to
3✔
4143
                // watch for the final terminal state to send updates to the RPC
3✔
4144
                // client. We only need to do this if there's an RPC caller.
3✔
4145
                var rpcShutdown bool
3✔
4146
                whenRPCShutdown(shutdown, func(req *htlcswitch.ChanClose) {
6✔
4147
                        rpcShutdown = true
3✔
4148

3✔
4149
                        p.cg.WgAdd(1)
3✔
4150
                        go func() {
6✔
4151
                                defer p.cg.WgDone()
3✔
4152

3✔
4153
                                p.observeRbfCloseUpdates(
3✔
4154
                                        rbfCloser, req, coopCloseStates,
3✔
4155
                                )
3✔
4156
                        }()
3✔
4157
                })
4158

4159
                if !rpcShutdown {
6✔
4160
                        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4161
                }
3✔
4162

4163
                ctx, _ := p.cg.Create(context.Background())
3✔
4164
                feeRate := defaultFeePerKw.FeePerVByte()
3✔
4165

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

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

×
4196
                                return
×
4197
                        }
×
4198

4199
                        event := chancloser.ProtocolEvent(
3✔
4200
                                &chancloser.SendOfferEvent{
3✔
4201
                                        TargetFeeRate: feeRate,
3✔
4202
                                },
3✔
4203
                        )
3✔
4204
                        rbfCloser.SendEvent(ctx, event)
3✔
4205

4206
                default:
×
4207
                        peerLog.Warnf("ChannelPoint(%v): unexpected state "+
×
4208
                                "for rbf-coop close: %T", chanPoint, rbfState)
×
4209
                }
4210
        })
4211

4212
        return nil
3✔
4213
}
4214

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

10✔
4220
        channel, ok := p.activeChannels.Load(chanID)
10✔
4221

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

4232
        isTaprootChan := channel.ChanType().IsTaproot()
10✔
4233

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

4256
                if err != nil {
11✔
4257
                        p.log.Errorf(err.Error())
1✔
4258
                        req.Err <- err
1✔
4259
                }
1✔
4260

4261
        // A type of CloseBreach indicates that the counterparty has breached
4262
        // the channel therefore we need to clean up our local state.
4263
        case contractcourt.CloseBreach:
×
4264
                // TODO(roasbeef): no longer need with newer beach logic?
×
4265
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
×
4266
                        "channel", req.ChanPoint)
×
4267
                p.WipeChannel(req.ChanPoint)
×
4268
        }
4269
}
4270

4271
// linkFailureReport is sent to the channelManager whenever a link reports a
4272
// link failure, and is forced to exit. The report houses the necessary
4273
// information to clean up the channel state, send back the error message, and
4274
// force close if necessary.
4275
type linkFailureReport struct {
4276
        chanPoint   wire.OutPoint
4277
        chanID      lnwire.ChannelID
4278
        shortChanID lnwire.ShortChannelID
4279
        linkErr     htlcswitch.LinkFailureError
4280
}
4281

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

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

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

3✔
4306
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
3✔
4307
                        failure.chanPoint,
3✔
4308
                )
3✔
4309
                if err != nil {
6✔
4310
                        p.log.Errorf("unable to force close "+
3✔
4311
                                "link(%v): %v", failure.shortChanID, err)
3✔
4312
                } else {
6✔
4313
                        p.log.Infof("channel(%v) force "+
3✔
4314
                                "closed with txid %v",
3✔
4315
                                failure.shortChanID, closeTx.TxHash())
3✔
4316
                }
3✔
4317
        }
4318

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

×
4324
                if err := lnChan.State().MarkBorked(); err != nil {
×
4325
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
4326
                                failure.shortChanID, err)
×
4327
                }
×
4328
        }
4329

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

4341
                var networkMsg lnwire.Message
3✔
4342
                if failure.linkErr.Warning {
3✔
4343
                        networkMsg = &lnwire.Warning{
×
4344
                                ChanID: failure.chanID,
×
4345
                                Data:   data,
×
4346
                        }
×
4347
                } else {
3✔
4348
                        networkMsg = &lnwire.Error{
3✔
4349
                                ChanID: failure.chanID,
3✔
4350
                                Data:   data,
3✔
4351
                        }
3✔
4352
                }
3✔
4353

4354
                err := p.SendMessage(true, networkMsg)
3✔
4355
                if err != nil {
3✔
4356
                        p.log.Errorf("unable to send msg to "+
×
4357
                                "remote peer: %v", err)
×
4358
                }
×
4359
        }
4360

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

4369
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
4370
// public key and the channel id.
4371
func (p *Brontide) fetchLinkFromKeyAndCid(
4372
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
22✔
4373

22✔
4374
        var chanLink htlcswitch.ChannelUpdateHandler
22✔
4375

22✔
4376
        // We don't need to check the error here, and can instead just loop
22✔
4377
        // over the slice and return nil.
22✔
4378
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
22✔
4379
        for _, link := range links {
43✔
4380
                if link.ChanID() == cid {
42✔
4381
                        chanLink = link
21✔
4382
                        break
21✔
4383
                }
4384
        }
4385

4386
        return chanLink
22✔
4387
}
4388

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

7✔
4397
        // First, we'll clear all indexes related to the channel in question.
7✔
4398
        chanPoint := chanCloser.Channel().ChannelPoint()
7✔
4399
        p.WipeChannel(&chanPoint)
7✔
4400

7✔
4401
        // Also clear the activeChanCloses map of this channel.
7✔
4402
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
7✔
4403
        p.activeChanCloses.Delete(cid) // TODO(roasbeef): existing race
7✔
4404

7✔
4405
        // Next, we'll launch a goroutine which will request to be notified by
7✔
4406
        // the ChainNotifier once the closure transaction obtains a single
7✔
4407
        // confirmation.
7✔
4408
        notifier := p.cfg.ChainNotifier
7✔
4409

7✔
4410
        // If any error happens during waitForChanToClose, forward it to
7✔
4411
        // closeReq. If this channel closure is not locally initiated, closeReq
7✔
4412
        // will be nil, so just ignore the error.
7✔
4413
        errChan := make(chan error, 1)
7✔
4414
        if closeReq != nil {
12✔
4415
                errChan = closeReq.Err
5✔
4416
        }
5✔
4417

4418
        closingTx, err := chanCloser.ClosingTx()
7✔
4419
        if err != nil {
7✔
4420
                if closeReq != nil {
×
4421
                        p.log.Error(err)
×
4422
                        closeReq.Err <- err
×
4423
                }
×
4424
        }
4425

4426
        closingTxid := closingTx.TxHash()
7✔
4427

7✔
4428
        // If this is a locally requested shutdown, update the caller with a
7✔
4429
        // new event detailing the current pending state of this request.
7✔
4430
        if closeReq != nil {
12✔
4431
                closeReq.Updates <- &PendingUpdate{
5✔
4432
                        Txid: closingTxid[:],
5✔
4433
                }
5✔
4434
        }
5✔
4435

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

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

7✔
4466
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
7✔
4467
                "with txid: %v", chanPoint, closingTxID)
7✔
4468

7✔
4469
        // TODO(roasbeef): add param for num needed confs
7✔
4470
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
7✔
4471
                closingTxID, closeScript, 1, bestHeight,
7✔
4472
        )
7✔
4473
        if err != nil {
7✔
4474
                if errChan != nil {
×
4475
                        errChan <- err
×
4476
                }
×
4477
                return
×
4478
        }
4479

4480
        // In the case that the ChainNotifier is shutting down, all subscriber
4481
        // notification channels will be closed, generating a nil receive.
4482
        height, ok := <-confNtfn.Confirmed
7✔
4483
        if !ok {
10✔
4484
                return
3✔
4485
        }
3✔
4486

4487
        // The channel has been closed, remove it from any active indexes, and
4488
        // the database state.
4489
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
7✔
4490
                "height %v", chanPoint, height.BlockHeight)
7✔
4491

7✔
4492
        // Finally, execute the closure call back to mark the confirmation of
7✔
4493
        // the transaction closing the contract.
7✔
4494
        cb()
7✔
4495
}
4496

4497
// WipeChannel removes the passed channel point from all indexes associated with
4498
// the peer and the switch.
4499
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
7✔
4500
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
7✔
4501

7✔
4502
        p.activeChannels.Delete(chanID)
7✔
4503

7✔
4504
        // Instruct the HtlcSwitch to close this link as the channel is no
7✔
4505
        // longer active.
7✔
4506
        p.cfg.Switch.RemoveLink(chanID)
7✔
4507
}
7✔
4508

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

4520
        // Then, finalize the remote feature vector providing the flattened
4521
        // feature bit namespace.
4522
        p.remoteFeatures = lnwire.NewFeatureVector(
6✔
4523
                msg.Features, lnwire.Features,
6✔
4524
        )
6✔
4525

6✔
4526
        // Now that we have their features loaded, we'll ensure that they
6✔
4527
        // didn't set any required bits that we don't know of.
6✔
4528
        err = feature.ValidateRequired(p.remoteFeatures)
6✔
4529
        if err != nil {
6✔
4530
                return fmt.Errorf("invalid remote features: %w", err)
×
4531
        }
×
4532

4533
        // Ensure the remote party's feature vector contains all transitive
4534
        // dependencies. We know ours are correct since they are validated
4535
        // during the feature manager's instantiation.
4536
        err = feature.ValidateDeps(p.remoteFeatures)
6✔
4537
        if err != nil {
6✔
4538
                return fmt.Errorf("invalid remote features: %w", err)
×
4539
        }
×
4540

4541
        // Now that we know we understand their requirements, we'll check to
4542
        // see if they don't support anything that we deem to be mandatory.
4543
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
6✔
4544
                return fmt.Errorf("data loss protection required")
×
4545
        }
×
4546

4547
        negotiatorClosure := func(negotiator lnwallet.AuxChannelNegotiator) {
6✔
NEW
4548
                msg.AuxFeatures.WhenSome(
×
NEW
4549
                        func(features lnwire.AuxFeatureBits) {
×
NEW
4550
                                err = negotiator.ProcessInitFeatures(
×
NEW
4551
                                        p.cfg.PubKeyBytes, features,
×
NEW
4552
                                )
×
NEW
4553
                        },
×
4554
                )
4555
        }
4556

4557
        // If we have an AuxChannelNegotiator and the peer sent aux features,
4558
        // process them.
4559
        if msg.AuxFeatures.IsSome() {
6✔
NEW
4560
                p.cfg.AuxChannelNegotiator.WhenSome(negotiatorClosure)
×
NEW
4561
        }
×
4562
        if err != nil {
6✔
NEW
4563
                return fmt.Errorf("got error from aux init features: %w", err)
×
NEW
4564
        }
×
4565

4566
        return nil
6✔
4567
}
4568

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

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

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

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

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

1✔
4611
                // Unset and set in both the local and global features to
1✔
4612
                // ensure both sets are consistent and merge able by old and
1✔
4613
                // new nodes.
1✔
4614
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4615
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4616

1✔
4617
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
4618
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
4619
        }
1✔
4620

4621
        msg := lnwire.NewInitMessage(
10✔
4622
                legacyFeatures.RawFeatureVector,
10✔
4623
                features.RawFeatureVector,
10✔
4624
        )
10✔
4625

10✔
4626
        // If we have an AuxChannelNegotiator, get custom feature bits to
10✔
4627
        // include in the init message.
10✔
4628
        p.cfg.AuxChannelNegotiator.WhenSome(
10✔
4629
                func(negotiator lnwallet.AuxChannelNegotiator) {
10✔
NEW
4630
                        auxFeatures, err := negotiator.GetInitFeatures(
×
NEW
4631
                                p.cfg.PubKeyBytes,
×
NEW
4632
                        )
×
NEW
4633
                        if err != nil {
×
NEW
4634
                                p.log.Warnf("Failed to get aux init features: "+
×
NEW
4635
                                        "%v", err)
×
NEW
4636
                                return
×
NEW
4637
                        }
×
4638

NEW
4639
                        msg.AuxFeatures = fn.Some(auxFeatures)
×
4640
                },
4641
        )
4642

4643
        return p.writeMessage(msg)
10✔
4644
}
4645

4646
// resendChanSyncMsg will attempt to find a channel sync message for the closed
4647
// channel and resend it to our peer.
4648
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
3✔
4649
        // If we already re-sent the mssage for this channel, we won't do it
3✔
4650
        // again.
3✔
4651
        if _, ok := p.resentChanSyncMsg[cid]; ok {
4✔
4652
                return nil
1✔
4653
        }
1✔
4654

4655
        // Check if we have any channel sync messages stored for this channel.
4656
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
3✔
4657
        if err != nil {
6✔
4658
                return fmt.Errorf("unable to fetch channel sync messages for "+
3✔
4659
                        "peer %v: %v", p, err)
3✔
4660
        }
3✔
4661

4662
        if c.LastChanSyncMsg == nil {
3✔
4663
                return fmt.Errorf("no chan sync message stored for channel %v",
×
4664
                        cid)
×
4665
        }
×
4666

4667
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
3✔
4668
                return fmt.Errorf("ignoring channel reestablish from "+
×
4669
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
4670
        }
×
4671

4672
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
3✔
4673
                "peer", cid)
3✔
4674

3✔
4675
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
3✔
4676
                return fmt.Errorf("failed resending channel sync "+
×
4677
                        "message to peer %v: %v", p, err)
×
4678
        }
×
4679

4680
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
3✔
4681
                cid)
3✔
4682

3✔
4683
        // Note down that we sent the message, so we won't resend it again for
3✔
4684
        // this connection.
3✔
4685
        p.resentChanSyncMsg[cid] = struct{}{}
3✔
4686

3✔
4687
        return nil
3✔
4688
}
4689

4690
// SendMessage sends a variadic number of high-priority messages to the remote
4691
// peer. The first argument denotes if the method should block until the
4692
// messages have been sent to the remote peer or an error is returned,
4693
// otherwise it returns immediately after queuing.
4694
//
4695
// NOTE: Part of the lnpeer.Peer interface.
4696
func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error {
6✔
4697
        return p.sendMessage(sync, true, msgs...)
6✔
4698
}
6✔
4699

4700
// SendMessageLazy sends a variadic number of low-priority messages to the
4701
// remote peer. The first argument denotes if the method should block until
4702
// the messages have been sent to the remote peer or an error is returned,
4703
// otherwise it returns immediately after queueing.
4704
//
4705
// NOTE: Part of the lnpeer.Peer interface.
4706
func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
4✔
4707
        return p.sendMessage(sync, false, msgs...)
4✔
4708
}
4✔
4709

4710
// sendMessage queues a variadic number of messages using the passed priority
4711
// to the remote peer. If sync is true, this method will block until the
4712
// messages have been sent to the remote peer or an error is returned, otherwise
4713
// it returns immediately after queueing.
4714
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
7✔
4715
        // Add all incoming messages to the outgoing queue. A list of error
7✔
4716
        // chans is populated for each message if the caller requested a sync
7✔
4717
        // send.
7✔
4718
        var errChans []chan error
7✔
4719
        if sync {
11✔
4720
                errChans = make([]chan error, 0, len(msgs))
4✔
4721
        }
4✔
4722
        for _, msg := range msgs {
14✔
4723
                // If a sync send was requested, create an error chan to listen
7✔
4724
                // for an ack from the writeHandler.
7✔
4725
                var errChan chan error
7✔
4726
                if sync {
11✔
4727
                        errChan = make(chan error, 1)
4✔
4728
                        errChans = append(errChans, errChan)
4✔
4729
                }
4✔
4730

4731
                if priority {
13✔
4732
                        p.queueMsg(msg, errChan)
6✔
4733
                } else {
10✔
4734
                        p.queueMsgLazy(msg, errChan)
4✔
4735
                }
4✔
4736
        }
4737

4738
        // Wait for all replies from the writeHandler. For async sends, this
4739
        // will be a NOP as the list of error chans is nil.
4740
        for _, errChan := range errChans {
11✔
4741
                select {
4✔
4742
                case err := <-errChan:
4✔
4743
                        return err
4✔
4744
                case <-p.cg.Done():
×
4745
                        return lnpeer.ErrPeerExiting
×
4746
                case <-p.cfg.Quit:
×
4747
                        return lnpeer.ErrPeerExiting
×
4748
                }
4749
        }
4750

4751
        return nil
6✔
4752
}
4753

4754
// PubKey returns the pubkey of the peer in compressed serialized format.
4755
//
4756
// NOTE: Part of the lnpeer.Peer interface.
4757
func (p *Brontide) PubKey() [33]byte {
5✔
4758
        return p.cfg.PubKeyBytes
5✔
4759
}
5✔
4760

4761
// IdentityKey returns the public key of the remote peer.
4762
//
4763
// NOTE: Part of the lnpeer.Peer interface.
4764
func (p *Brontide) IdentityKey() *btcec.PublicKey {
18✔
4765
        return p.cfg.Addr.IdentityKey
18✔
4766
}
18✔
4767

4768
// Address returns the network address of the remote peer.
4769
//
4770
// NOTE: Part of the lnpeer.Peer interface.
4771
func (p *Brontide) Address() net.Addr {
3✔
4772
        return p.cfg.Addr.Address
3✔
4773
}
3✔
4774

4775
// AddNewChannel adds a new channel to the peer. The channel should fail to be
4776
// added if the cancel channel is closed.
4777
//
4778
// NOTE: Part of the lnpeer.Peer interface.
4779
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
4780
        cancel <-chan struct{}) error {
3✔
4781

3✔
4782
        errChan := make(chan error, 1)
3✔
4783
        newChanMsg := &newChannelMsg{
3✔
4784
                channel: newChan,
3✔
4785
                err:     errChan,
3✔
4786
        }
3✔
4787

3✔
4788
        select {
3✔
4789
        case p.newActiveChannel <- newChanMsg:
3✔
4790
        case <-cancel:
×
4791
                return errors.New("canceled adding new channel")
×
4792
        case <-p.cg.Done():
×
4793
                return lnpeer.ErrPeerExiting
×
4794
        }
4795

4796
        // We pause here to wait for the peer to recognize the new channel
4797
        // before we close the channel barrier corresponding to the channel.
4798
        select {
3✔
4799
        case err := <-errChan:
3✔
4800
                return err
3✔
4801
        case <-p.cg.Done():
×
4802
                return lnpeer.ErrPeerExiting
×
4803
        }
4804
}
4805

4806
// AddPendingChannel adds a pending open channel to the peer. The channel
4807
// should fail to be added if the cancel channel is closed.
4808
//
4809
// NOTE: Part of the lnpeer.Peer interface.
4810
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
4811
        cancel <-chan struct{}) error {
3✔
4812

3✔
4813
        errChan := make(chan error, 1)
3✔
4814
        newChanMsg := &newChannelMsg{
3✔
4815
                channelID: cid,
3✔
4816
                err:       errChan,
3✔
4817
        }
3✔
4818

3✔
4819
        select {
3✔
4820
        case p.newPendingChannel <- newChanMsg:
3✔
4821

4822
        case <-cancel:
×
4823
                return errors.New("canceled adding pending channel")
×
4824

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

4829
        // We pause here to wait for the peer to recognize the new pending
4830
        // channel before we close the channel barrier corresponding to the
4831
        // channel.
4832
        select {
3✔
4833
        case err := <-errChan:
3✔
4834
                return err
3✔
4835

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

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

4844
// RemovePendingChannel removes a pending open channel from the peer.
4845
//
4846
// NOTE: Part of the lnpeer.Peer interface.
4847
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
3✔
4848
        errChan := make(chan error, 1)
3✔
4849
        newChanMsg := &newChannelMsg{
3✔
4850
                channelID: cid,
3✔
4851
                err:       errChan,
3✔
4852
        }
3✔
4853

3✔
4854
        select {
3✔
4855
        case p.removePendingChannel <- newChanMsg:
3✔
4856
        case <-p.cg.Done():
×
4857
                return lnpeer.ErrPeerExiting
×
4858
        }
4859

4860
        // We pause here to wait for the peer to respond to the cancellation of
4861
        // the pending channel before we close the channel barrier
4862
        // corresponding to the channel.
4863
        select {
3✔
4864
        case err := <-errChan:
3✔
4865
                return err
3✔
4866

4867
        case <-p.cg.Done():
×
4868
                return lnpeer.ErrPeerExiting
×
4869
        }
4870
}
4871

4872
// StartTime returns the time at which the connection was established if the
4873
// peer started successfully, and zero otherwise.
4874
func (p *Brontide) StartTime() time.Time {
3✔
4875
        return p.startTime
3✔
4876
}
3✔
4877

4878
// handleCloseMsg is called when a new cooperative channel closure related
4879
// message is received from the remote peer. We'll use this message to advance
4880
// the chan closer state machine.
4881
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
16✔
4882
        link := p.fetchLinkFromKeyAndCid(msg.cid)
16✔
4883

16✔
4884
        // We'll now fetch the matching closing state machine in order to
16✔
4885
        // continue, or finalize the channel closure process.
16✔
4886
        chanCloserE, err := p.fetchActiveChanCloser(msg.cid)
16✔
4887
        if err != nil {
19✔
4888
                // If the channel is not known to us, we'll simply ignore this
3✔
4889
                // message.
3✔
4890
                if err == ErrChannelNotFound {
6✔
4891
                        return
3✔
4892
                }
3✔
4893

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

×
4896
                errMsg := &lnwire.Error{
×
4897
                        ChanID: msg.cid,
×
4898
                        Data:   lnwire.ErrorData(err.Error()),
×
4899
                }
×
4900
                p.queueMsg(errMsg, nil)
×
4901
                return
×
4902
        }
4903

4904
        if chanCloserE.IsRight() {
16✔
4905
                // TODO(roasbeef): assert?
×
4906
                return
×
4907
        }
×
4908

4909
        // At this point, we'll only enter this call path if a negotiate chan
4910
        // closer was used. So we'll extract that from the either now.
4911
        //
4912
        // TODO(roabeef): need extra helper func for either to make cleaner
4913
        var chanCloser *chancloser.ChanCloser
16✔
4914
        chanCloserE.WhenLeft(func(c *chancloser.ChanCloser) {
32✔
4915
                chanCloser = c
16✔
4916
        })
16✔
4917

4918
        handleErr := func(err error) {
17✔
4919
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
4920
                p.log.Error(err)
1✔
4921

1✔
4922
                // As the negotiations failed, we'll reset the channel state
1✔
4923
                // machine to ensure we act to on-chain events as normal.
1✔
4924
                chanCloser.Channel().ResetState()
1✔
4925
                if chanCloser.CloseRequest() != nil {
1✔
4926
                        chanCloser.CloseRequest().Err <- err
×
4927
                }
×
4928

4929
                p.activeChanCloses.Delete(msg.cid)
1✔
4930

1✔
4931
                p.Disconnect(err)
1✔
4932
        }
4933

4934
        // Next, we'll process the next message using the target state machine.
4935
        // We'll either continue negotiation, or halt.
4936
        switch typed := msg.msg.(type) {
16✔
4937
        case *lnwire.Shutdown:
8✔
4938
                // Disable incoming adds immediately.
8✔
4939
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
8✔
4940
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
4941
                                link.ChanID())
×
4942
                }
×
4943

4944
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
8✔
4945
                if err != nil {
8✔
4946
                        handleErr(err)
×
4947
                        return
×
4948
                }
×
4949

4950
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
14✔
4951
                        // If the link is nil it means we can immediately queue
6✔
4952
                        // the Shutdown message since we don't have to wait for
6✔
4953
                        // commitment transaction synchronization.
6✔
4954
                        if link == nil {
7✔
4955
                                p.queueMsg(&msg, nil)
1✔
4956
                                return
1✔
4957
                        }
1✔
4958

4959
                        // Immediately disallow any new HTLC's from being added
4960
                        // in the outgoing direction.
4961
                        if !link.DisableAdds(htlcswitch.Outgoing) {
5✔
4962
                                p.log.Warnf("Outgoing link adds already "+
×
4963
                                        "disabled: %v", link.ChanID())
×
4964
                        }
×
4965

4966
                        // When we have a Shutdown to send, we defer it till the
4967
                        // next time we send a CommitSig to remain spec
4968
                        // compliant.
4969
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
10✔
4970
                                p.queueMsg(&msg, nil)
5✔
4971
                        })
5✔
4972
                })
4973

4974
                beginNegotiation := func() {
16✔
4975
                        oClosingSigned, err := chanCloser.BeginNegotiation()
8✔
4976
                        if err != nil {
8✔
4977
                                handleErr(err)
×
4978
                                return
×
4979
                        }
×
4980

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

4986
                if link == nil {
9✔
4987
                        beginNegotiation()
1✔
4988
                } else {
8✔
4989
                        // Now we register a flush hook to advance the
7✔
4990
                        // ChanCloser and possibly send out a ClosingSigned
7✔
4991
                        // when the link finishes draining.
7✔
4992
                        link.OnFlushedOnce(func() {
14✔
4993
                                // Remove link in goroutine to prevent deadlock.
7✔
4994
                                go p.cfg.Switch.RemoveLink(msg.cid)
7✔
4995
                                beginNegotiation()
7✔
4996
                        })
7✔
4997
                }
4998

4999
        case *lnwire.ClosingSigned:
11✔
5000
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
11✔
5001
                if err != nil {
12✔
5002
                        handleErr(err)
1✔
5003
                        return
1✔
5004
                }
1✔
5005

5006
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
22✔
5007
                        p.queueMsg(&msg, nil)
11✔
5008
                })
11✔
5009

5010
        default:
×
5011
                panic("impossible closeMsg type")
×
5012
        }
5013

5014
        // If we haven't finished close negotiations, then we'll continue as we
5015
        // can't yet finalize the closure.
5016
        if _, err := chanCloser.ClosingTx(); err != nil {
26✔
5017
                return
11✔
5018
        }
11✔
5019

5020
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
5021
        // the channel closure by notifying relevant sub-systems and launching a
5022
        // goroutine to wait for close tx conf.
5023
        p.finalizeChanClosure(chanCloser)
7✔
5024
}
5025

5026
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
5027
// the channelManager goroutine, which will shut down the link and possibly
5028
// close the channel.
5029
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
3✔
5030
        select {
3✔
5031
        case p.localCloseChanReqs <- req:
3✔
5032
                p.log.Info("Local close channel request is going to be " +
3✔
5033
                        "delivered to the peer")
3✔
5034
        case <-p.cg.Done():
×
5035
                p.log.Info("Unable to deliver local close channel request " +
×
5036
                        "to peer")
×
5037
        }
5038
}
5039

5040
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
5041
func (p *Brontide) NetAddress() *lnwire.NetAddress {
3✔
5042
        return p.cfg.Addr
3✔
5043
}
3✔
5044

5045
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
5046
func (p *Brontide) Inbound() bool {
3✔
5047
        return p.cfg.Inbound
3✔
5048
}
3✔
5049

5050
// ConnReq is a getter for the Brontide's connReq in cfg.
5051
func (p *Brontide) ConnReq() *connmgr.ConnReq {
3✔
5052
        return p.cfg.ConnReq
3✔
5053
}
3✔
5054

5055
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
5056
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
3✔
5057
        return p.cfg.ErrorBuffer
3✔
5058
}
3✔
5059

5060
// SetAddress sets the remote peer's address given an address.
5061
func (p *Brontide) SetAddress(address net.Addr) {
×
5062
        p.cfg.Addr.Address = address
×
5063
}
×
5064

5065
// ActiveSignal returns the peer's active signal.
5066
func (p *Brontide) ActiveSignal() chan struct{} {
3✔
5067
        return p.activeSignal
3✔
5068
}
3✔
5069

5070
// Conn returns a pointer to the peer's connection struct.
5071
func (p *Brontide) Conn() net.Conn {
3✔
5072
        return p.cfg.Conn
3✔
5073
}
3✔
5074

5075
// BytesReceived returns the number of bytes received from the peer.
5076
func (p *Brontide) BytesReceived() uint64 {
3✔
5077
        return atomic.LoadUint64(&p.bytesReceived)
3✔
5078
}
3✔
5079

5080
// BytesSent returns the number of bytes sent to the peer.
5081
func (p *Brontide) BytesSent() uint64 {
3✔
5082
        return atomic.LoadUint64(&p.bytesSent)
3✔
5083
}
3✔
5084

5085
// LastRemotePingPayload returns the last payload the remote party sent as part
5086
// of their ping.
5087
func (p *Brontide) LastRemotePingPayload() []byte {
3✔
5088
        pingPayload := p.lastPingPayload.Load()
3✔
5089
        if pingPayload == nil {
6✔
5090
                return []byte{}
3✔
5091
        }
3✔
5092

5093
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
5094
        if !ok {
×
5095
                return nil
×
5096
        }
×
5097

5098
        return pingBytes
×
5099
}
5100

5101
// attachChannelEventSubscription creates a channel event subscription and
5102
// attaches to client to Brontide if the reenableTimeout is no greater than 1
5103
// minute.
5104
func (p *Brontide) attachChannelEventSubscription() error {
6✔
5105
        // If the timeout is greater than 1 minute, it's unlikely that the link
6✔
5106
        // hasn't yet finished its reestablishment. Return a nil without
6✔
5107
        // creating the client to specify that we don't want to retry.
6✔
5108
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
9✔
5109
                return nil
3✔
5110
        }
3✔
5111

5112
        // When the reenable timeout is less than 1 minute, it's likely the
5113
        // channel link hasn't finished its reestablishment yet. In that case,
5114
        // we'll give it a second chance by subscribing to the channel update
5115
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
5116
        // enabling the channel again.
5117
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
6✔
5118
        if err != nil {
6✔
5119
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
5120
        }
×
5121

5122
        p.channelEventClient = sub
6✔
5123

6✔
5124
        return nil
6✔
5125
}
5126

5127
// updateNextRevocation updates the existing channel's next revocation if it's
5128
// nil.
5129
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
6✔
5130
        chanPoint := c.FundingOutpoint
6✔
5131
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
6✔
5132

6✔
5133
        // Read the current channel.
6✔
5134
        currentChan, loaded := p.activeChannels.Load(chanID)
6✔
5135

6✔
5136
        // currentChan should exist, but we perform a check anyway to avoid nil
6✔
5137
        // pointer dereference.
6✔
5138
        if !loaded {
7✔
5139
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
5140
                        chanID)
1✔
5141
        }
1✔
5142

5143
        // currentChan should not be nil, but we perform a check anyway to
5144
        // avoid nil pointer dereference.
5145
        if currentChan == nil {
6✔
5146
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
5147
                        chanID)
1✔
5148
        }
1✔
5149

5150
        // If we're being sent a new channel, and our existing channel doesn't
5151
        // have the next revocation, then we need to update the current
5152
        // existing channel.
5153
        if currentChan.RemoteNextRevocation() != nil {
4✔
5154
                return nil
×
5155
        }
×
5156

5157
        p.log.Infof("Processing retransmitted ChannelReady for "+
4✔
5158
                "ChannelPoint(%v)", chanPoint)
4✔
5159

4✔
5160
        nextRevoke := c.RemoteNextRevocation
4✔
5161

4✔
5162
        err := currentChan.InitNextRevocation(nextRevoke)
4✔
5163
        if err != nil {
4✔
5164
                return fmt.Errorf("unable to init next revocation: %w", err)
×
5165
        }
×
5166

5167
        return nil
4✔
5168
}
5169

5170
// addActiveChannel adds a new active channel to the `activeChannels` map. It
5171
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
5172
// it and assembles it with a channel link.
5173
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
3✔
5174
        chanPoint := c.FundingOutpoint
3✔
5175
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5176

3✔
5177
        // If we've reached this point, there are two possible scenarios.  If
3✔
5178
        // the channel was in the active channels map as nil, then it was
3✔
5179
        // loaded from disk and we need to send reestablish. Else, it was not
3✔
5180
        // loaded from disk and we don't need to send reestablish as this is a
3✔
5181
        // fresh channel.
3✔
5182
        shouldReestablish := p.isLoadedFromDisk(chanID)
3✔
5183

3✔
5184
        chanOpts := c.ChanOpts
3✔
5185
        if shouldReestablish {
6✔
5186
                // If we have to do the reestablish dance for this channel,
3✔
5187
                // ensure that we don't try to call InitRemoteMusigNonces twice
3✔
5188
                // by calling SkipNonceInit.
3✔
5189
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
3✔
5190
        }
3✔
5191

5192
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
3✔
5193
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
5194
        })
×
5195
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
3✔
5196
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
5197
        })
×
5198
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
3✔
5199
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
5200
        })
×
5201

5202
        // If not already active, we'll add this channel to the set of active
5203
        // channels, so we can look it up later easily according to its channel
5204
        // ID.
5205
        lnChan, err := lnwallet.NewLightningChannel(
3✔
5206
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
3✔
5207
        )
3✔
5208
        if err != nil {
3✔
5209
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
5210
        }
×
5211

5212
        // Store the channel in the activeChannels map.
5213
        p.activeChannels.Store(chanID, lnChan)
3✔
5214

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

3✔
5217
        // Next, we'll assemble a ChannelLink along with the necessary items it
3✔
5218
        // needs to function.
3✔
5219
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
3✔
5220
        if err != nil {
3✔
5221
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
5222
                        err)
×
5223
        }
×
5224

5225
        // We'll query the channel DB for the new channel's initial forwarding
5226
        // policies to determine the policy we start out with.
5227
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
3✔
5228
        if err != nil {
3✔
5229
                return fmt.Errorf("unable to query for initial forwarding "+
×
5230
                        "policy: %v", err)
×
5231
        }
×
5232

5233
        // Create the link and add it to the switch.
5234
        err = p.addLink(
3✔
5235
                &chanPoint, lnChan, initialPolicy, chainEvents,
3✔
5236
                shouldReestablish, fn.None[lnwire.Shutdown](),
3✔
5237
        )
3✔
5238
        if err != nil {
3✔
5239
                return fmt.Errorf("can't register new channel link(%v) with "+
×
5240
                        "peer", chanPoint)
×
5241
        }
×
5242

5243
        isTaprootChan := c.ChanType.IsTaproot()
3✔
5244

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

5252
        // Now that the link has been added above, we'll also init an RBF chan
5253
        // closer for this channel, but only if the new close feature is
5254
        // negotiated.
5255
        //
5256
        // Creating this here ensures that any shutdown messages sent will be
5257
        // automatically routed by the msg router.
5258
        if _, err := p.initRbfChanCloser(lnChan); err != nil {
3✔
5259
                p.activeChanCloses.Delete(chanID)
×
5260

×
5261
                return fmt.Errorf("unable to init RBF chan closer for new "+
×
5262
                        "chan: %w", err)
×
5263
        }
×
5264

5265
        return nil
3✔
5266
}
5267

5268
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
5269
// know this channel ID or not, we'll either add it to the `activeChannels` map
5270
// or init the next revocation for it.
5271
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
3✔
5272
        newChan := req.channel
3✔
5273
        chanPoint := newChan.FundingOutpoint
3✔
5274
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5275

3✔
5276
        // Only update RemoteNextRevocation if the channel is in the
3✔
5277
        // activeChannels map and if we added the link to the switch. Only
3✔
5278
        // active channels will be added to the switch.
3✔
5279
        if p.isActiveChannel(chanID) {
6✔
5280
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
3✔
5281
                        chanPoint)
3✔
5282

3✔
5283
                // Handle it and close the err chan on the request.
3✔
5284
                close(req.err)
3✔
5285

3✔
5286
                // Update the next revocation point.
3✔
5287
                err := p.updateNextRevocation(newChan.OpenChannel)
3✔
5288
                if err != nil {
3✔
5289
                        p.log.Errorf(err.Error())
×
5290
                }
×
5291

5292
                return
3✔
5293
        }
5294

5295
        // This is a new channel, we now add it to the map.
5296
        if err := p.addActiveChannel(req.channel); err != nil {
3✔
5297
                // Log and send back the error to the request.
×
5298
                p.log.Errorf(err.Error())
×
5299
                req.err <- err
×
5300

×
5301
                return
×
5302
        }
×
5303

5304
        // Close the err chan if everything went fine.
5305
        close(req.err)
3✔
5306
}
5307

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

7✔
5315
        chanID := req.channelID
7✔
5316

7✔
5317
        // If we already have this channel, something is wrong with the funding
7✔
5318
        // flow as it will only be marked as active after `ChannelReady` is
7✔
5319
        // handled. In this case, we will do nothing but log an error, just in
7✔
5320
        // case this is a legit channel.
7✔
5321
        if p.isActiveChannel(chanID) {
8✔
5322
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
5323
                        "pending channel request", chanID)
1✔
5324

1✔
5325
                return
1✔
5326
        }
1✔
5327

5328
        // The channel has already been added, we will do nothing and return.
5329
        if p.isPendingChannel(chanID) {
7✔
5330
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
5331
                        "pending channel request", chanID)
1✔
5332

1✔
5333
                return
1✔
5334
        }
1✔
5335

5336
        // This is a new channel, we now add it to the map `activeChannels`
5337
        // with nil value and mark it as a newly added channel in
5338
        // `addedChannels`.
5339
        p.activeChannels.Store(chanID, nil)
5✔
5340
        p.addedChannels.Store(chanID, struct{}{})
5✔
5341
}
5342

5343
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
5344
// from `activeChannels` map. The request will be ignored if the channel is
5345
// considered active by Brontide. Noop if the channel ID cannot be found.
5346
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
7✔
5347
        defer close(req.err)
7✔
5348

7✔
5349
        chanID := req.channelID
7✔
5350

7✔
5351
        // If we already have this channel, something is wrong with the funding
7✔
5352
        // flow as it will only be marked as active after `ChannelReady` is
7✔
5353
        // handled. In this case, we will log an error and exit.
7✔
5354
        if p.isActiveChannel(chanID) {
8✔
5355
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
5356
                        chanID)
1✔
5357
                return
1✔
5358
        }
1✔
5359

5360
        // The channel has not been added yet, we will log a warning as there
5361
        // is an unexpected call from funding manager.
5362
        if !p.isPendingChannel(chanID) {
10✔
5363
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
4✔
5364
        }
4✔
5365

5366
        // Remove the record of this pending channel.
5367
        p.activeChannels.Delete(chanID)
6✔
5368
        p.addedChannels.Delete(chanID)
6✔
5369
}
5370

5371
// sendLinkUpdateMsg sends a message that updates the channel to the
5372
// channel's message stream.
5373
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
3✔
5374
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
3✔
5375

3✔
5376
        chanStream, ok := p.activeMsgStreams[cid]
3✔
5377
        if !ok {
6✔
5378
                // If a stream hasn't yet been created, then we'll do so, add
3✔
5379
                // it to the map, and finally start it.
3✔
5380
                chanStream = newChanMsgStream(p, cid)
3✔
5381
                p.activeMsgStreams[cid] = chanStream
3✔
5382
                chanStream.Start()
3✔
5383

3✔
5384
                // Stop the stream when quit.
3✔
5385
                go func() {
6✔
5386
                        <-p.cg.Done()
3✔
5387
                        chanStream.Stop()
3✔
5388
                }()
3✔
5389
        }
5390

5391
        // With the stream obtained, add the message to the stream so we can
5392
        // continue processing message.
5393
        chanStream.AddMsg(msg)
3✔
5394
}
5395

5396
// scaleTimeout multiplies the argument duration by a constant factor depending
5397
// on variious heuristics. Currently this is only used to check whether our peer
5398
// appears to be connected over Tor and relaxes the timout deadline. However,
5399
// this is subject to change and should be treated as opaque.
5400
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
70✔
5401
        if p.isTorConnection {
73✔
5402
                return timeout * time.Duration(torTimeoutMultiplier)
3✔
5403
        }
3✔
5404

5405
        return timeout
67✔
5406
}
5407

5408
// CoopCloseUpdates is a struct used to communicate updates for an active close
5409
// to the caller.
5410
type CoopCloseUpdates struct {
5411
        UpdateChan chan interface{}
5412

5413
        ErrChan chan error
5414
}
5415

5416
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5417
// point has an active RBF chan closer.
5418
func (p *Brontide) ChanHasRbfCoopCloser(chanPoint wire.OutPoint) bool {
3✔
5419
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5420
        chanCloser, found := p.activeChanCloses.Load(chanID)
3✔
5421
        if !found {
6✔
5422
                return false
3✔
5423
        }
3✔
5424

5425
        return chanCloser.IsRight()
3✔
5426
}
5427

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

3✔
5436
        // If RBF coop close isn't permitted, then we'll an error.
3✔
5437
        if !p.rbfCoopCloseAllowed() {
3✔
5438
                return nil, fmt.Errorf("rbf coop close not enabled for " +
×
5439
                        "channel")
×
5440
        }
×
5441

5442
        closeUpdates := &CoopCloseUpdates{
3✔
5443
                UpdateChan: make(chan interface{}, 1),
3✔
5444
                ErrChan:    make(chan error, 1),
3✔
5445
        }
3✔
5446

3✔
5447
        // We'll re-use the existing switch struct here, even though we're
3✔
5448
        // bypassing the switch entirely.
3✔
5449
        closeReq := htlcswitch.ChanClose{
3✔
5450
                CloseType:      contractcourt.CloseRegular,
3✔
5451
                ChanPoint:      &chanPoint,
3✔
5452
                TargetFeePerKw: feeRate,
3✔
5453
                DeliveryScript: deliveryScript,
3✔
5454
                Updates:        closeUpdates.UpdateChan,
3✔
5455
                Err:            closeUpdates.ErrChan,
3✔
5456
                Ctx:            ctx,
3✔
5457
        }
3✔
5458

3✔
5459
        err := p.startRbfChanCloser(newRPCShutdownInit(&closeReq), chanPoint)
3✔
5460
        if err != nil {
3✔
5461
                return nil, err
×
5462
        }
×
5463

5464
        return closeUpdates, nil
3✔
5465
}
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