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

lightningnetwork / lnd / 17917482292

22 Sep 2025 01:50PM UTC coverage: 56.562% (-10.1%) from 66.668%
17917482292

Pull #10182

github

web-flow
Merge 9efe3bd8c into 055fb436e
Pull Request #10182: Aux feature bits

32 of 68 new or added lines in 5 files covered. (47.06%)

29734 existing lines in 467 files now uncovered.

98449 of 174056 relevant lines covered (56.56%)

1.18 hits per line

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

76.64
/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/lightningnetwork/lnd/buffer"
23
        "github.com/lightningnetwork/lnd/chainntnfs"
24
        "github.com/lightningnetwork/lnd/channeldb"
25
        "github.com/lightningnetwork/lnd/channelnotifier"
26
        "github.com/lightningnetwork/lnd/contractcourt"
27
        "github.com/lightningnetwork/lnd/discovery"
28
        "github.com/lightningnetwork/lnd/feature"
29
        "github.com/lightningnetwork/lnd/fn/v2"
30
        "github.com/lightningnetwork/lnd/funding"
31
        graphdb "github.com/lightningnetwork/lnd/graph/db"
32
        "github.com/lightningnetwork/lnd/graph/db/models"
33
        "github.com/lightningnetwork/lnd/htlcswitch"
34
        "github.com/lightningnetwork/lnd/htlcswitch/hodl"
35
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
36
        "github.com/lightningnetwork/lnd/input"
37
        "github.com/lightningnetwork/lnd/invoices"
38
        "github.com/lightningnetwork/lnd/keychain"
39
        "github.com/lightningnetwork/lnd/lnpeer"
40
        "github.com/lightningnetwork/lnd/lntypes"
41
        "github.com/lightningnetwork/lnd/lnutils"
42
        "github.com/lightningnetwork/lnd/lnwallet"
43
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
44
        "github.com/lightningnetwork/lnd/lnwallet/chancloser"
45
        "github.com/lightningnetwork/lnd/lnwire"
46
        "github.com/lightningnetwork/lnd/msgmux"
47
        "github.com/lightningnetwork/lnd/netann"
48
        "github.com/lightningnetwork/lnd/pool"
49
        "github.com/lightningnetwork/lnd/protofsm"
50
        "github.com/lightningnetwork/lnd/queue"
51
        "github.com/lightningnetwork/lnd/subscribe"
52
        "github.com/lightningnetwork/lnd/ticker"
53
        "github.com/lightningnetwork/lnd/tlv"
54
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
55
)
56

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

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

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

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

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

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

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

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

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

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

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

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

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

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

125
        err chan error
126
}
127

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

459
        // AuxChannelNegotiator is an optional interface that allows aux channel
460
        // implementations to inject and process custom records over channel
461
        // related wire messages.
462
        AuxChannelNegotiator fn.Option[lnwallet.AuxChannelNegotiator]
463

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

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

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

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

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

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

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

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

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

528
        pingManager *PingManager
529

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

537
        cfg Config
538

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

637
        startReady chan struct{}
638

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

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

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

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

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

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

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

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

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

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

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

728
                return lastSerializedBlockHeader[:]
×
729
        }
730

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

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

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

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

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

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

776
        return p
2✔
777
}
778

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

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

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

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

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

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

817
                haveLegacyChan = true
2✔
818
                break
2✔
819
        }
820

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

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

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

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

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

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

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

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

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

899
        p.startTime = time.Now()
2✔
900

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

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

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

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

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

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

2✔
947
        return nil
2✔
948
}
949

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

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

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

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

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

993
        return bothHaveBit(lnwire.RbfCoopCloseOptional) ||
2✔
994
                bothHaveBit(lnwire.RbfCoopCloseOptionalStaging)
2✔
995
}
996

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

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

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

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

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

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

2✔
1045
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
2✔
1046

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

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

1075
                                chanID := lnwire.NewChanIDFromOutPoint(
2✔
1076
                                        dbChan.FundingOutpoint,
2✔
1077
                                )
2✔
1078

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

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

2✔
1091
                                msgs = append(msgs, channelReadyMsg)
2✔
1092
                        }
1093

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

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

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

1128
                chanPoint := dbChan.FundingOutpoint
2✔
1129

2✔
1130
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
1131

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

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

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

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

1157
                        msgs = append(msgs, chanSync)
2✔
1158

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

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

1174
                                if shutdownMsg == nil {
4✔
1175
                                        continue
2✔
1176
                                }
1177

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

1183
                        continue
2✔
1184
                }
1185

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

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

2✔
1208
                        selfPolicy = p1
2✔
1209
                } else {
4✔
1210
                        selfPolicy = p2
2✔
1211
                }
2✔
1212

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

1236
                p.log.Tracef("Using link policy of: %v",
2✔
1237
                        lnutils.SpewLogClosure(forwardingPolicy))
2✔
1238

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

2✔
1248
                        continue
2✔
1249
                }
1250

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

1256
                isTaprootChan := lnChan.ChanType().IsTaproot()
2✔
1257

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

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

×
1278
                                return
×
1279
                        }
×
1280

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

×
1297
                                return
×
1298
                        }
×
1299

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

2✔
1304
                        p.activeChanCloses.Store(chanID, makeNegotiateCloser(
2✔
1305
                                negotiateChanCloser,
2✔
1306
                        ))
2✔
1307

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

×
1314
                                return
×
1315
                        }
×
1316

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

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

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

1340
                p.activeChannels.Store(chanID, lnChan)
2✔
1341

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

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

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

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

1379
        return msgs, nil
2✔
1380
}
1381

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

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

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

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

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

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

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

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

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

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

2✔
1485
        hasConfirmedPublicChan := false
2✔
1486
        for _, channel := range channels {
4✔
1487
                if channel.IsPending {
4✔
1488
                        continue
2✔
1489
                }
1490
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
4✔
1491
                        continue
2✔
1492
                }
1493

1494
                hasConfirmedPublicChan = true
2✔
1495
                break
2✔
1496
        }
1497
        if !hasConfirmedPublicChan {
4✔
1498
                return
2✔
1499
        }
2✔
1500

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

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

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

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

1522
        maybeSendUpd := func(cid lnwire.ChannelID,
2✔
1523
                lnChan *lnwallet.LightningChannel) error {
4✔
1524

2✔
1525
                // Nil channels are pending, so we'll skip them.
2✔
1526
                if lnChan == nil {
4✔
1527
                        return nil
2✔
1528
                }
2✔
1529

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

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

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

2✔
1554
                        return nil
2✔
1555
                }
2✔
1556

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

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

×
1569
                        return err
×
1570
                }
×
1571

1572
                return nil
2✔
1573
        }
1574

1575
        p.activeChannels.ForEach(maybeSendUpd)
2✔
1576
}
1577

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

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

1600
        p.cg.WgWait()
2✔
1601
}
1602

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

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

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

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

2✔
1635
        p.log.Infof(err.Error())
2✔
1636

2✔
1637
        // Stop PingManager before closing TCP connection.
2✔
1638
        p.pingManager.Stop()
2✔
1639

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

2✔
1643
        p.cg.Quit()
2✔
1644

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

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

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

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

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

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

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

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

1722
        p.logWireMessage(nextMsg, true)
2✔
1723

2✔
1724
        return nextMsg, nil
2✔
1725
}
1726

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

1735
        peer *Brontide
1736

1737
        apply func(lnwire.Message)
1738

1739
        startMsg string
1740
        stopMsg  string
1741

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

1745
        mtx sync.Mutex
1746

1747
        producerSema chan struct{}
1748

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

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

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

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

1779
        return stream
2✔
1780
}
1781

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

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

2✔
1792
        close(ms.quit)
2✔
1793

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

1801
        ms.wg.Wait()
2✔
1802
}
1803

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

2✔
1811
        peerLog.Tracef(ms.startMsg)
2✔
1812

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

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

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

2✔
1841
                ms.msgCond.L.Unlock()
2✔
1842

2✔
1843
                ms.apply(msg)
2✔
1844

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

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

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

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

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

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

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

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

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

1933
                        chanPoint := event.ChannelPoint
2✔
1934

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

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

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

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

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

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

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

1985
                chanLink.HandleChannelUpdate(msg)
2✔
1986
        }
1987

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2126
                var (
2✔
2127
                        targetChan   lnwire.ChannelID
2✔
2128
                        isLinkUpdate bool
2✔
2129
                )
2✔
2130

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

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

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

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

2✔
2153
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
2✔
2154

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

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

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

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

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

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

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

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

2✔
2222
                        discStream.AddMsg(msg)
2✔
2223

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

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

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

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

2247
                idleTimer.Reset(idleTimeout)
2✔
2248
        }
2249

2250
        p.Disconnect(errors.New("read handler closed"))
2✔
2251

2✔
2252
        p.log.Trace("readHandler for peer done")
2✔
2253
}
2254

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

2263
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
2✔
2264
}
2265

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

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

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

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

2✔
2297
        return channel != nil
2✔
2298
}
2✔
2299

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

2309
        return channel == nil
2✔
2310
}
2311

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

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

2✔
2326
        p.activeChannels.Range(func(_ lnwire.ChannelID,
2✔
2327
                channel *lnwallet.LightningChannel) bool {
4✔
2328

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

2335
                haveChannels = true
2✔
2336

2✔
2337
                // Return false to break the iteration.
2✔
2338
                return false
2✔
2339
        })
2340

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

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

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

2✔
2362
        if errMsg, ok := msg.(*lnwire.Error); ok {
4✔
2363
                p.storeError(errMsg)
2✔
2364
        }
2✔
2365

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

2374
                return false
×
2375

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

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

2386
        default:
2✔
2387
                return false
2✔
2388
        }
2389
}
2390

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

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

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

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

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

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

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

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

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

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

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

2✔
2444
                                blindingPoint = b.Val.SerializeCompressed()
2✔
2445
                        },
2✔
2446
                )
2447

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2568
                preposition := "to"
2✔
2569
                if read {
4✔
2570
                        preposition = "from"
2✔
2571
                }
2✔
2572

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

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

2584
        prefix := "readMessage from peer"
2✔
2585
        if !read {
4✔
2586
                prefix = "writeMessage to peer"
2✔
2587
        }
2✔
2588

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

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

2609
        noiseConn := p.cfg.Conn
2✔
2610

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

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

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

2632
                return err
2✔
2633
        }
2634

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

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

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

2662
        return flushMsg()
2✔
2663
}
2664

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

2680
        var exitErr error
2✔
2681

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

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

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

×
2711
                                goto retry
×
2712
                        }
2713

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

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

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

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

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

2✔
2746
        p.Disconnect(exitErr)
2✔
2747

2✔
2748
        p.log.Trace("writeHandler for peer done")
2✔
2749
}
2750

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

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

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

2✔
2768
        for {
4✔
2769
                // Examine the front of the priority queue, if it is empty check
2✔
2770
                // the low priority queue.
2✔
2771
                elem := priorityMsgs.Front()
2✔
2772
                if elem == nil {
4✔
2773
                        elem = lazyMsgs.Front()
2✔
2774
                }
2✔
2775

2776
                if elem != nil {
4✔
2777
                        front := elem.Value.(outgoingMsg)
2✔
2778

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

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

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

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

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

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

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

2✔
2861
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
2✔
2862
                activeChan *lnwallet.LightningChannel) error {
4✔
2863

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

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

2876
                snapshot := activeChan.StateSnapshot()
2✔
2877
                snapshots = append(snapshots, snapshot)
2✔
2878

2✔
2879
                return nil
2✔
2880
        })
2881

2882
        return snapshots
2✔
2883
}
2884

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

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

2✔
2904
        return txscript.PayToAddrScript(deliveryAddr)
2✔
2905
}
2906

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

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

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

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

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

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

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

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

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

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

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

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

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

3001
                                lc.ResetState()
2✔
3002

2✔
3003
                                return nil
2✔
3004
                        })
3005

3006
                        break out
2✔
3007
                }
3008
        }
3009
}
3010

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

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

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

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

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

2✔
3040
                        continue
2✔
3041

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

×
3059
                                continue
×
3060
                        }
3061

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

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

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

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

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

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

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

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

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

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

3143
        chanCloser = makeNegotiateCloser(negotiateChanCloser)
2✔
3144

2✔
3145
        p.activeChanCloses.Store(chanID, chanCloser)
2✔
3146

2✔
3147
        return &chanCloser, nil
2✔
3148
}
3149

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

2✔
3156
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
2✔
3157
                lnChan *lnwallet.LightningChannel) bool {
4✔
3158

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

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

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

3179
                activePublicChans = append(
2✔
3180
                        activePublicChans, dbChan.FundingOutpoint,
2✔
3181
                )
2✔
3182

2✔
3183
                return true
2✔
3184
        })
3185

3186
        return activePublicChans
2✔
3187
}
3188

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

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

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

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

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

3224
                return nil
×
3225
        }
3226

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

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

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

3252
                                continue
×
3253
                        }
3254

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

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

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

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

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

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

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

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

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

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

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

2✔
3322
        isTaprootChan := lnChan.ChanType().IsTaproot()
2✔
3323

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

3343
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
2✔
3344

2✔
3345
        var deliveryScript []byte
2✔
3346

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

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

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

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

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

3384
                shutdownDesc := fn.MapOption(
2✔
3385
                        newRestartShutdownInit,
2✔
3386
                )(shutdownInfo)
2✔
3387

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

2✔
3392
                return nil, err
2✔
3393
        }
3394

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

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

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

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

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

3433
        return shutdownMsg, nil
×
3434
}
3435

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

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

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

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

3480
        return chanCloser, nil
2✔
3481
}
3482

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

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

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

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

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

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

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

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

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

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

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

3556
        link.OnCommitOnce(htlcswitch.Outgoing, func() {
4✔
3557
                p.queueMsg(shutdownMsg, nil)
2✔
3558
        })
2✔
3559

3560
        return nil
2✔
3561
}
3562

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

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

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

2✔
3580
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
2✔
3581
        defer chanCloser.RemoveStateSub(coopCloseStates)
2✔
3582

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

2✔
3588
        maybeNotifyTxBroadcast := func(state chancloser.AsymmetricPeerState,
2✔
3589
                party lntypes.ChannelParty) {
4✔
3590

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

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

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

3609
                        return
2✔
3610
                }
3611

3612
                closePending, ok := state.(*chancloser.ClosePending)
2✔
3613

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

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

2✔
3629
                        return
2✔
3630
                }
2✔
3631

3632
                feeRate := closePending.FeeRate
2✔
3633
                lastFeeRates.SetForParty(party, feeRate)
2✔
3634

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

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

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

3659
                lastTxids.SetForParty(party, closingTxid)
2✔
3660
        }
3661

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

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

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

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

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

2✔
3707
                                return
2✔
3708
                        }
3709

3710
                case <-closeReq.Ctx.Done():
2✔
3711
                        return
2✔
3712

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

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

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

2✔
3731
        return &chanErrorReporter{
2✔
3732
                chanID: chanID,
2✔
3733
                peer:   peer,
2✔
3734
        }
2✔
3735
}
2✔
3736

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

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

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

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

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

×
3775
                return
×
3776
        }
×
3777

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

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

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

2✔
3795
        defer p.cg.WgDone()
2✔
3796

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

3803
        coopCloseStates := chanCloser.RegisterStateEvents()
2✔
3804
        defer chanCloser.RemoveStateSub(coopCloseStates)
2✔
3805

2✔
3806
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
2✔
3807

2✔
3808
        sendChanFlushed := func() {
4✔
3809
                chanState := channel.StateSnapshot()
2✔
3810

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

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

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

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

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

2✔
3847
                                return
2✔
3848
                        }
2✔
3849

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

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

2✔
3862
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
2✔
3863

2✔
3864
        link := p.fetchLinkFromKeyAndCid(chanID)
2✔
3865

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

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

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

3883
        peerPub := *p.IdentityKey()
2✔
3884

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

2✔
3889
        initialState := chancloser.ChannelActive{}
2✔
3890

2✔
3891
        scid := channel.ZeroConfRealScid().UnwrapOr(
2✔
3892
                channel.ShortChanID(),
2✔
3893
        )
2✔
3894

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

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

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

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

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

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

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

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

3964
        p.activeChanCloses.Store(chanID, makeRbfCloser(&chanCloser))
2✔
3965

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

2✔
3972
        return &chanCloser, nil
2✔
3973
}
3974

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

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

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

3994
                return feeRate
2✔
3995
        })(s)
3996

3997
        return fn.FlattenOption(feeRateOpt)
2✔
3998
}
3999

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

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

4017
                return addr
2✔
4018
        })(s)
4019

4020
        return fn.FlattenOption(addrOpt)
2✔
4021
}
4022

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

2✔
4029
                init.WhenLeft(f)
2✔
4030
        })
2✔
4031
}
4032

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

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

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

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

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

4064
                localState := state.PeerState.GetForParty(lntypes.Local)
2✔
4065

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

2✔
4070
                return ok
2✔
4071
        }
4072

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

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

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

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

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

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

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

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

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

×
4136
                        return
×
4137
                }
×
4138

4139
                coopCloseStates := rbfCloser.RegisterStateEvents()
2✔
4140

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

2✔
4148
                        p.cg.WgAdd(1)
2✔
4149
                        go func() {
4✔
4150
                                defer p.cg.WgDone()
2✔
4151

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

4158
                if !rpcShutdown {
4✔
4159
                        defer rbfCloser.RemoveStateSub(coopCloseStates)
2✔
4160
                }
2✔
4161

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

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

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

×
4195
                                return
×
4196
                        }
×
4197

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

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

4211
        return nil
2✔
4212
}
4213

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

2✔
4219
        channel, ok := p.activeChannels.Load(chanID)
2✔
4220

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

4231
        isTaprootChan := channel.ChanType().IsTaproot()
2✔
4232

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

4255
                if err != nil {
2✔
UNCOV
4256
                        p.log.Errorf(err.Error())
×
UNCOV
4257
                        req.Err <- err
×
UNCOV
4258
                }
×
4259

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

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

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

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

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

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

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

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

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

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

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

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

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

2✔
4373
        var chanLink htlcswitch.ChannelUpdateHandler
2✔
4374

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

4385
        return chanLink
2✔
4386
}
4387

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

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

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

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

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

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

4425
        closingTxid := closingTx.TxHash()
2✔
4426

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

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

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

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

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

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

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

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

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

2✔
4501
        p.activeChannels.Delete(chanID)
2✔
4502

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

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

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

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

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

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

4546
        // If we have an AuxChannelNegotiator and the peer sent aux features,
4547
        // process them.
4548
        p.cfg.AuxChannelNegotiator.WhenSome(
2✔
4549
                func(acn lnwallet.AuxChannelNegotiator) {
2✔
NEW
4550
                        err = acn.ProcessInitRecords(
×
NEW
4551
                                p.cfg.PubKeyBytes, msg.CustomRecords.Copy(),
×
NEW
4552
                        )
×
NEW
4553
                },
×
4554
        )
4555
        if err != nil {
2✔
NEW
4556
                return fmt.Errorf("could not process init records: %w", err)
×
NEW
4557
        }
×
4558

4559
        return nil
2✔
4560
}
4561

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

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

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

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

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

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

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

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

2✔
4619
        // If we have an AuxChannelNegotiator, get custom feature bits to
2✔
4620
        // include in the init message.
2✔
4621
        p.cfg.AuxChannelNegotiator.WhenSome(
2✔
4622
                func(negotiator lnwallet.AuxChannelNegotiator) {
2✔
NEW
4623
                        auxRecords, err := negotiator.GetInitRecords(
×
NEW
4624
                                p.cfg.PubKeyBytes,
×
NEW
4625
                        )
×
NEW
4626
                        if err != nil {
×
NEW
4627
                                p.log.Warnf("Failed to get aux init features: "+
×
NEW
4628
                                        "%v", err)
×
NEW
4629
                                return
×
NEW
4630
                        }
×
4631

NEW
4632
                        mergedRecs := msg.CustomRecords.MergedCopy(auxRecords)
×
NEW
4633
                        msg.CustomRecords = mergedRecs
×
4634
                },
4635
        )
4636

4637
        return p.writeMessage(msg)
2✔
4638
}
4639

4640
// resendChanSyncMsg will attempt to find a channel sync message for the closed
4641
// channel and resend it to our peer.
4642
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
2✔
4643
        // If we already re-sent the mssage for this channel, we won't do it
2✔
4644
        // again.
2✔
4645
        if _, ok := p.resentChanSyncMsg[cid]; ok {
2✔
UNCOV
4646
                return nil
×
UNCOV
4647
        }
×
4648

4649
        // Check if we have any channel sync messages stored for this channel.
4650
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
2✔
4651
        if err != nil {
4✔
4652
                return fmt.Errorf("unable to fetch channel sync messages for "+
2✔
4653
                        "peer %v: %v", p, err)
2✔
4654
        }
2✔
4655

4656
        if c.LastChanSyncMsg == nil {
2✔
4657
                return fmt.Errorf("no chan sync message stored for channel %v",
×
4658
                        cid)
×
4659
        }
×
4660

4661
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
2✔
4662
                return fmt.Errorf("ignoring channel reestablish from "+
×
4663
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
4664
        }
×
4665

4666
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
2✔
4667
                "peer", cid)
2✔
4668

2✔
4669
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
2✔
4670
                return fmt.Errorf("failed resending channel sync "+
×
4671
                        "message to peer %v: %v", p, err)
×
4672
        }
×
4673

4674
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
2✔
4675
                cid)
2✔
4676

2✔
4677
        // Note down that we sent the message, so we won't resend it again for
2✔
4678
        // this connection.
2✔
4679
        p.resentChanSyncMsg[cid] = struct{}{}
2✔
4680

2✔
4681
        return nil
2✔
4682
}
4683

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

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

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

4725
                if priority {
4✔
4726
                        p.queueMsg(msg, errChan)
2✔
4727
                } else {
4✔
4728
                        p.queueMsgLazy(msg, errChan)
2✔
4729
                }
2✔
4730
        }
4731

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

4745
        return nil
2✔
4746
}
4747

4748
// PubKey returns the pubkey of the peer in compressed serialized format.
4749
//
4750
// NOTE: Part of the lnpeer.Peer interface.
4751
func (p *Brontide) PubKey() [33]byte {
2✔
4752
        return p.cfg.PubKeyBytes
2✔
4753
}
2✔
4754

4755
// IdentityKey returns the public key of the remote peer.
4756
//
4757
// NOTE: Part of the lnpeer.Peer interface.
4758
func (p *Brontide) IdentityKey() *btcec.PublicKey {
2✔
4759
        return p.cfg.Addr.IdentityKey
2✔
4760
}
2✔
4761

4762
// Address returns the network address of the remote peer.
4763
//
4764
// NOTE: Part of the lnpeer.Peer interface.
4765
func (p *Brontide) Address() net.Addr {
2✔
4766
        return p.cfg.Addr.Address
2✔
4767
}
2✔
4768

4769
// AddNewChannel adds a new channel to the peer. The channel should fail to be
4770
// added if the cancel channel is closed.
4771
//
4772
// NOTE: Part of the lnpeer.Peer interface.
4773
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
4774
        cancel <-chan struct{}) error {
2✔
4775

2✔
4776
        errChan := make(chan error, 1)
2✔
4777
        newChanMsg := &newChannelMsg{
2✔
4778
                channel: newChan,
2✔
4779
                err:     errChan,
2✔
4780
        }
2✔
4781

2✔
4782
        select {
2✔
4783
        case p.newActiveChannel <- newChanMsg:
2✔
4784
        case <-cancel:
×
4785
                return errors.New("canceled adding new channel")
×
4786
        case <-p.cg.Done():
×
4787
                return lnpeer.ErrPeerExiting
×
4788
        }
4789

4790
        // We pause here to wait for the peer to recognize the new channel
4791
        // before we close the channel barrier corresponding to the channel.
4792
        select {
2✔
4793
        case err := <-errChan:
2✔
4794
                return err
2✔
4795
        case <-p.cg.Done():
×
4796
                return lnpeer.ErrPeerExiting
×
4797
        }
4798
}
4799

4800
// AddPendingChannel adds a pending open channel to the peer. The channel
4801
// should fail to be added if the cancel channel is closed.
4802
//
4803
// NOTE: Part of the lnpeer.Peer interface.
4804
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
4805
        cancel <-chan struct{}) error {
2✔
4806

2✔
4807
        errChan := make(chan error, 1)
2✔
4808
        newChanMsg := &newChannelMsg{
2✔
4809
                channelID: cid,
2✔
4810
                err:       errChan,
2✔
4811
        }
2✔
4812

2✔
4813
        select {
2✔
4814
        case p.newPendingChannel <- newChanMsg:
2✔
4815

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

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

4823
        // We pause here to wait for the peer to recognize the new pending
4824
        // channel before we close the channel barrier corresponding to the
4825
        // channel.
4826
        select {
2✔
4827
        case err := <-errChan:
2✔
4828
                return err
2✔
4829

4830
        case <-cancel:
×
4831
                return errors.New("canceled adding pending channel")
×
4832

4833
        case <-p.cg.Done():
×
4834
                return lnpeer.ErrPeerExiting
×
4835
        }
4836
}
4837

4838
// RemovePendingChannel removes a pending open channel from the peer.
4839
//
4840
// NOTE: Part of the lnpeer.Peer interface.
4841
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
2✔
4842
        errChan := make(chan error, 1)
2✔
4843
        newChanMsg := &newChannelMsg{
2✔
4844
                channelID: cid,
2✔
4845
                err:       errChan,
2✔
4846
        }
2✔
4847

2✔
4848
        select {
2✔
4849
        case p.removePendingChannel <- newChanMsg:
2✔
4850
        case <-p.cg.Done():
×
4851
                return lnpeer.ErrPeerExiting
×
4852
        }
4853

4854
        // We pause here to wait for the peer to respond to the cancellation of
4855
        // the pending channel before we close the channel barrier
4856
        // corresponding to the channel.
4857
        select {
2✔
4858
        case err := <-errChan:
2✔
4859
                return err
2✔
4860

4861
        case <-p.cg.Done():
×
4862
                return lnpeer.ErrPeerExiting
×
4863
        }
4864
}
4865

4866
// StartTime returns the time at which the connection was established if the
4867
// peer started successfully, and zero otherwise.
4868
func (p *Brontide) StartTime() time.Time {
2✔
4869
        return p.startTime
2✔
4870
}
2✔
4871

4872
// handleCloseMsg is called when a new cooperative channel closure related
4873
// message is received from the remote peer. We'll use this message to advance
4874
// the chan closer state machine.
4875
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
2✔
4876
        link := p.fetchLinkFromKeyAndCid(msg.cid)
2✔
4877

2✔
4878
        // We'll now fetch the matching closing state machine in order to
2✔
4879
        // continue, or finalize the channel closure process.
2✔
4880
        chanCloserE, err := p.fetchActiveChanCloser(msg.cid)
2✔
4881
        if err != nil {
4✔
4882
                // If the channel is not known to us, we'll simply ignore this
2✔
4883
                // message.
2✔
4884
                if err == ErrChannelNotFound {
4✔
4885
                        return
2✔
4886
                }
2✔
4887

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

×
4890
                errMsg := &lnwire.Error{
×
4891
                        ChanID: msg.cid,
×
4892
                        Data:   lnwire.ErrorData(err.Error()),
×
4893
                }
×
4894
                p.queueMsg(errMsg, nil)
×
4895
                return
×
4896
        }
4897

4898
        if chanCloserE.IsRight() {
2✔
4899
                // TODO(roasbeef): assert?
×
4900
                return
×
4901
        }
×
4902

4903
        // At this point, we'll only enter this call path if a negotiate chan
4904
        // closer was used. So we'll extract that from the either now.
4905
        //
4906
        // TODO(roabeef): need extra helper func for either to make cleaner
4907
        var chanCloser *chancloser.ChanCloser
2✔
4908
        chanCloserE.WhenLeft(func(c *chancloser.ChanCloser) {
4✔
4909
                chanCloser = c
2✔
4910
        })
2✔
4911

4912
        handleErr := func(err error) {
3✔
4913
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
4914
                p.log.Error(err)
1✔
4915

1✔
4916
                // As the negotiations failed, we'll reset the channel state
1✔
4917
                // machine to ensure we act to on-chain events as normal.
1✔
4918
                chanCloser.Channel().ResetState()
1✔
4919
                if chanCloser.CloseRequest() != nil {
1✔
4920
                        chanCloser.CloseRequest().Err <- err
×
4921
                }
×
4922

4923
                p.activeChanCloses.Delete(msg.cid)
1✔
4924

1✔
4925
                p.Disconnect(err)
1✔
4926
        }
4927

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

4938
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
2✔
4939
                if err != nil {
2✔
4940
                        handleErr(err)
×
4941
                        return
×
4942
                }
×
4943

4944
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
4✔
4945
                        // If the link is nil it means we can immediately queue
2✔
4946
                        // the Shutdown message since we don't have to wait for
2✔
4947
                        // commitment transaction synchronization.
2✔
4948
                        if link == nil {
2✔
UNCOV
4949
                                p.queueMsg(&msg, nil)
×
UNCOV
4950
                                return
×
UNCOV
4951
                        }
×
4952

4953
                        // Immediately disallow any new HTLC's from being added
4954
                        // in the outgoing direction.
4955
                        if !link.DisableAdds(htlcswitch.Outgoing) {
2✔
4956
                                p.log.Warnf("Outgoing link adds already "+
×
4957
                                        "disabled: %v", link.ChanID())
×
4958
                        }
×
4959

4960
                        // When we have a Shutdown to send, we defer it till the
4961
                        // next time we send a CommitSig to remain spec
4962
                        // compliant.
4963
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
4✔
4964
                                p.queueMsg(&msg, nil)
2✔
4965
                        })
2✔
4966
                })
4967

4968
                beginNegotiation := func() {
4✔
4969
                        oClosingSigned, err := chanCloser.BeginNegotiation()
2✔
4970
                        if err != nil {
2✔
4971
                                handleErr(err)
×
4972
                                return
×
4973
                        }
×
4974

4975
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
4✔
4976
                                p.queueMsg(&msg, nil)
2✔
4977
                        })
2✔
4978
                }
4979

4980
                if link == nil {
2✔
UNCOV
4981
                        beginNegotiation()
×
4982
                } else {
2✔
4983
                        // Now we register a flush hook to advance the
2✔
4984
                        // ChanCloser and possibly send out a ClosingSigned
2✔
4985
                        // when the link finishes draining.
2✔
4986
                        link.OnFlushedOnce(func() {
4✔
4987
                                // Remove link in goroutine to prevent deadlock.
2✔
4988
                                go p.cfg.Switch.RemoveLink(msg.cid)
2✔
4989
                                beginNegotiation()
2✔
4990
                        })
2✔
4991
                }
4992

4993
        case *lnwire.ClosingSigned:
2✔
4994
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
2✔
4995
                if err != nil {
3✔
4996
                        handleErr(err)
1✔
4997
                        return
1✔
4998
                }
1✔
4999

5000
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
4✔
5001
                        p.queueMsg(&msg, nil)
2✔
5002
                })
2✔
5003

5004
        default:
×
5005
                panic("impossible closeMsg type")
×
5006
        }
5007

5008
        // If we haven't finished close negotiations, then we'll continue as we
5009
        // can't yet finalize the closure.
5010
        if _, err := chanCloser.ClosingTx(); err != nil {
4✔
5011
                return
2✔
5012
        }
2✔
5013

5014
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
5015
        // the channel closure by notifying relevant sub-systems and launching a
5016
        // goroutine to wait for close tx conf.
5017
        p.finalizeChanClosure(chanCloser)
2✔
5018
}
5019

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

5034
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
5035
func (p *Brontide) NetAddress() *lnwire.NetAddress {
2✔
5036
        return p.cfg.Addr
2✔
5037
}
2✔
5038

5039
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
5040
func (p *Brontide) Inbound() bool {
2✔
5041
        return p.cfg.Inbound
2✔
5042
}
2✔
5043

5044
// ConnReq is a getter for the Brontide's connReq in cfg.
5045
func (p *Brontide) ConnReq() *connmgr.ConnReq {
2✔
5046
        return p.cfg.ConnReq
2✔
5047
}
2✔
5048

5049
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
5050
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
2✔
5051
        return p.cfg.ErrorBuffer
2✔
5052
}
2✔
5053

5054
// SetAddress sets the remote peer's address given an address.
5055
func (p *Brontide) SetAddress(address net.Addr) {
×
5056
        p.cfg.Addr.Address = address
×
5057
}
×
5058

5059
// ActiveSignal returns the peer's active signal.
5060
func (p *Brontide) ActiveSignal() chan struct{} {
2✔
5061
        return p.activeSignal
2✔
5062
}
2✔
5063

5064
// Conn returns a pointer to the peer's connection struct.
5065
func (p *Brontide) Conn() net.Conn {
2✔
5066
        return p.cfg.Conn
2✔
5067
}
2✔
5068

5069
// BytesReceived returns the number of bytes received from the peer.
5070
func (p *Brontide) BytesReceived() uint64 {
2✔
5071
        return atomic.LoadUint64(&p.bytesReceived)
2✔
5072
}
2✔
5073

5074
// BytesSent returns the number of bytes sent to the peer.
5075
func (p *Brontide) BytesSent() uint64 {
2✔
5076
        return atomic.LoadUint64(&p.bytesSent)
2✔
5077
}
2✔
5078

5079
// LastRemotePingPayload returns the last payload the remote party sent as part
5080
// of their ping.
5081
func (p *Brontide) LastRemotePingPayload() []byte {
2✔
5082
        pingPayload := p.lastPingPayload.Load()
2✔
5083
        if pingPayload == nil {
4✔
5084
                return []byte{}
2✔
5085
        }
2✔
5086

5087
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
5088
        if !ok {
×
5089
                return nil
×
5090
        }
×
5091

5092
        return pingBytes
×
5093
}
5094

5095
// attachChannelEventSubscription creates a channel event subscription and
5096
// attaches to client to Brontide if the reenableTimeout is no greater than 1
5097
// minute.
5098
func (p *Brontide) attachChannelEventSubscription() error {
2✔
5099
        // If the timeout is greater than 1 minute, it's unlikely that the link
2✔
5100
        // hasn't yet finished its reestablishment. Return a nil without
2✔
5101
        // creating the client to specify that we don't want to retry.
2✔
5102
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
4✔
5103
                return nil
2✔
5104
        }
2✔
5105

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

5116
        p.channelEventClient = sub
2✔
5117

2✔
5118
        return nil
2✔
5119
}
5120

5121
// updateNextRevocation updates the existing channel's next revocation if it's
5122
// nil.
5123
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
2✔
5124
        chanPoint := c.FundingOutpoint
2✔
5125
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
5126

2✔
5127
        // Read the current channel.
2✔
5128
        currentChan, loaded := p.activeChannels.Load(chanID)
2✔
5129

2✔
5130
        // currentChan should exist, but we perform a check anyway to avoid nil
2✔
5131
        // pointer dereference.
2✔
5132
        if !loaded {
2✔
UNCOV
5133
                return fmt.Errorf("missing active channel with chanID=%v",
×
UNCOV
5134
                        chanID)
×
UNCOV
5135
        }
×
5136

5137
        // currentChan should not be nil, but we perform a check anyway to
5138
        // avoid nil pointer dereference.
5139
        if currentChan == nil {
2✔
UNCOV
5140
                return fmt.Errorf("found nil active channel with chanID=%v",
×
UNCOV
5141
                        chanID)
×
UNCOV
5142
        }
×
5143

5144
        // If we're being sent a new channel, and our existing channel doesn't
5145
        // have the next revocation, then we need to update the current
5146
        // existing channel.
5147
        if currentChan.RemoteNextRevocation() != nil {
2✔
5148
                return nil
×
5149
        }
×
5150

5151
        p.log.Infof("Processing retransmitted ChannelReady for "+
2✔
5152
                "ChannelPoint(%v)", chanPoint)
2✔
5153

2✔
5154
        nextRevoke := c.RemoteNextRevocation
2✔
5155

2✔
5156
        err := currentChan.InitNextRevocation(nextRevoke)
2✔
5157
        if err != nil {
2✔
5158
                return fmt.Errorf("unable to init next revocation: %w", err)
×
5159
        }
×
5160

5161
        return nil
2✔
5162
}
5163

5164
// addActiveChannel adds a new active channel to the `activeChannels` map. It
5165
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
5166
// it and assembles it with a channel link.
5167
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
2✔
5168
        chanPoint := c.FundingOutpoint
2✔
5169
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
5170

2✔
5171
        // If we've reached this point, there are two possible scenarios.  If
2✔
5172
        // the channel was in the active channels map as nil, then it was
2✔
5173
        // loaded from disk and we need to send reestablish. Else, it was not
2✔
5174
        // loaded from disk and we don't need to send reestablish as this is a
2✔
5175
        // fresh channel.
2✔
5176
        shouldReestablish := p.isLoadedFromDisk(chanID)
2✔
5177

2✔
5178
        chanOpts := c.ChanOpts
2✔
5179
        if shouldReestablish {
4✔
5180
                // If we have to do the reestablish dance for this channel,
2✔
5181
                // ensure that we don't try to call InitRemoteMusigNonces twice
2✔
5182
                // by calling SkipNonceInit.
2✔
5183
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
2✔
5184
        }
2✔
5185

5186
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
2✔
5187
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
5188
        })
×
5189
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
2✔
5190
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
5191
        })
×
5192
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
2✔
5193
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
5194
        })
×
5195

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

5206
        // Store the channel in the activeChannels map.
5207
        p.activeChannels.Store(chanID, lnChan)
2✔
5208

2✔
5209
        p.log.Infof("New channel active ChannelPoint(%v) with peer", chanPoint)
2✔
5210

2✔
5211
        // Next, we'll assemble a ChannelLink along with the necessary items it
2✔
5212
        // needs to function.
2✔
5213
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
2✔
5214
        if err != nil {
2✔
5215
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
5216
                        err)
×
5217
        }
×
5218

5219
        // We'll query the channel DB for the new channel's initial forwarding
5220
        // policies to determine the policy we start out with.
5221
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
2✔
5222
        if err != nil {
2✔
5223
                return fmt.Errorf("unable to query for initial forwarding "+
×
5224
                        "policy: %v", err)
×
5225
        }
×
5226

5227
        // Create the link and add it to the switch.
5228
        err = p.addLink(
2✔
5229
                &chanPoint, lnChan, initialPolicy, chainEvents,
2✔
5230
                shouldReestablish, fn.None[lnwire.Shutdown](),
2✔
5231
        )
2✔
5232
        if err != nil {
2✔
5233
                return fmt.Errorf("can't register new channel link(%v) with "+
×
5234
                        "peer", chanPoint)
×
5235
        }
×
5236

5237
        isTaprootChan := c.ChanType.IsTaproot()
2✔
5238

2✔
5239
        // We're using the old co-op close, so we don't need to init the new RBF
2✔
5240
        // chan closer. If this is a taproot channel, then we'll also fall
2✔
5241
        // through, as we don't support this type yet w/ rbf close.
2✔
5242
        if !p.rbfCoopCloseAllowed() || isTaprootChan {
4✔
5243
                return nil
2✔
5244
        }
2✔
5245

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

×
5255
                return fmt.Errorf("unable to init RBF chan closer for new "+
×
5256
                        "chan: %w", err)
×
5257
        }
×
5258

5259
        return nil
2✔
5260
}
5261

5262
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
5263
// know this channel ID or not, we'll either add it to the `activeChannels` map
5264
// or init the next revocation for it.
5265
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
2✔
5266
        newChan := req.channel
2✔
5267
        chanPoint := newChan.FundingOutpoint
2✔
5268
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
5269

2✔
5270
        // Only update RemoteNextRevocation if the channel is in the
2✔
5271
        // activeChannels map and if we added the link to the switch. Only
2✔
5272
        // active channels will be added to the switch.
2✔
5273
        if p.isActiveChannel(chanID) {
4✔
5274
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
2✔
5275
                        chanPoint)
2✔
5276

2✔
5277
                // Handle it and close the err chan on the request.
2✔
5278
                close(req.err)
2✔
5279

2✔
5280
                // Update the next revocation point.
2✔
5281
                err := p.updateNextRevocation(newChan.OpenChannel)
2✔
5282
                if err != nil {
2✔
5283
                        p.log.Errorf(err.Error())
×
5284
                }
×
5285

5286
                return
2✔
5287
        }
5288

5289
        // This is a new channel, we now add it to the map.
5290
        if err := p.addActiveChannel(req.channel); err != nil {
2✔
5291
                // Log and send back the error to the request.
×
5292
                p.log.Errorf(err.Error())
×
5293
                req.err <- err
×
5294

×
5295
                return
×
5296
        }
×
5297

5298
        // Close the err chan if everything went fine.
5299
        close(req.err)
2✔
5300
}
5301

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

2✔
5309
        chanID := req.channelID
2✔
5310

2✔
5311
        // If we already have this channel, something is wrong with the funding
2✔
5312
        // flow as it will only be marked as active after `ChannelReady` is
2✔
5313
        // handled. In this case, we will do nothing but log an error, just in
2✔
5314
        // case this is a legit channel.
2✔
5315
        if p.isActiveChannel(chanID) {
2✔
UNCOV
5316
                p.log.Errorf("Channel(%v) is already active, ignoring "+
×
UNCOV
5317
                        "pending channel request", chanID)
×
UNCOV
5318

×
UNCOV
5319
                return
×
UNCOV
5320
        }
×
5321

5322
        // The channel has already been added, we will do nothing and return.
5323
        if p.isPendingChannel(chanID) {
2✔
UNCOV
5324
                p.log.Infof("Channel(%v) is already added, ignoring "+
×
UNCOV
5325
                        "pending channel request", chanID)
×
UNCOV
5326

×
UNCOV
5327
                return
×
UNCOV
5328
        }
×
5329

5330
        // This is a new channel, we now add it to the map `activeChannels`
5331
        // with nil value and mark it as a newly added channel in
5332
        // `addedChannels`.
5333
        p.activeChannels.Store(chanID, nil)
2✔
5334
        p.addedChannels.Store(chanID, struct{}{})
2✔
5335
}
5336

5337
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
5338
// from `activeChannels` map. The request will be ignored if the channel is
5339
// considered active by Brontide. Noop if the channel ID cannot be found.
5340
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
2✔
5341
        defer close(req.err)
2✔
5342

2✔
5343
        chanID := req.channelID
2✔
5344

2✔
5345
        // If we already have this channel, something is wrong with the funding
2✔
5346
        // flow as it will only be marked as active after `ChannelReady` is
2✔
5347
        // handled. In this case, we will log an error and exit.
2✔
5348
        if p.isActiveChannel(chanID) {
2✔
UNCOV
5349
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
×
UNCOV
5350
                        chanID)
×
UNCOV
5351
                return
×
UNCOV
5352
        }
×
5353

5354
        // The channel has not been added yet, we will log a warning as there
5355
        // is an unexpected call from funding manager.
5356
        if !p.isPendingChannel(chanID) {
4✔
5357
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
2✔
5358
        }
2✔
5359

5360
        // Remove the record of this pending channel.
5361
        p.activeChannels.Delete(chanID)
2✔
5362
        p.addedChannels.Delete(chanID)
2✔
5363
}
5364

5365
// sendLinkUpdateMsg sends a message that updates the channel to the
5366
// channel's message stream.
5367
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
2✔
5368
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
2✔
5369

2✔
5370
        chanStream, ok := p.activeMsgStreams[cid]
2✔
5371
        if !ok {
4✔
5372
                // If a stream hasn't yet been created, then we'll do so, add
2✔
5373
                // it to the map, and finally start it.
2✔
5374
                chanStream = newChanMsgStream(p, cid)
2✔
5375
                p.activeMsgStreams[cid] = chanStream
2✔
5376
                chanStream.Start()
2✔
5377

2✔
5378
                // Stop the stream when quit.
2✔
5379
                go func() {
4✔
5380
                        <-p.cg.Done()
2✔
5381
                        chanStream.Stop()
2✔
5382
                }()
2✔
5383
        }
5384

5385
        // With the stream obtained, add the message to the stream so we can
5386
        // continue processing message.
5387
        chanStream.AddMsg(msg)
2✔
5388
}
5389

5390
// scaleTimeout multiplies the argument duration by a constant factor depending
5391
// on variious heuristics. Currently this is only used to check whether our peer
5392
// appears to be connected over Tor and relaxes the timout deadline. However,
5393
// this is subject to change and should be treated as opaque.
5394
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
2✔
5395
        if p.isTorConnection {
4✔
5396
                return timeout * time.Duration(torTimeoutMultiplier)
2✔
5397
        }
2✔
5398

UNCOV
5399
        return timeout
×
5400
}
5401

5402
// CoopCloseUpdates is a struct used to communicate updates for an active close
5403
// to the caller.
5404
type CoopCloseUpdates struct {
5405
        UpdateChan chan interface{}
5406

5407
        ErrChan chan error
5408
}
5409

5410
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5411
// point has an active RBF chan closer.
5412
func (p *Brontide) ChanHasRbfCoopCloser(chanPoint wire.OutPoint) bool {
2✔
5413
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
5414
        chanCloser, found := p.activeChanCloses.Load(chanID)
2✔
5415
        if !found {
4✔
5416
                return false
2✔
5417
        }
2✔
5418

5419
        return chanCloser.IsRight()
2✔
5420
}
5421

5422
// TriggerCoopCloseRbfBump given a chan ID, and the params needed to trigger a
5423
// new RBF co-op close update, a bump is attempted. A channel used for updates,
5424
// along with one used to o=communicate any errors is returned. If no chan
5425
// closer is found, then false is returned for the second argument.
5426
func (p *Brontide) TriggerCoopCloseRbfBump(ctx context.Context,
5427
        chanPoint wire.OutPoint, feeRate chainfee.SatPerKWeight,
5428
        deliveryScript lnwire.DeliveryAddress) (*CoopCloseUpdates, error) {
2✔
5429

2✔
5430
        // If RBF coop close isn't permitted, then we'll an error.
2✔
5431
        if !p.rbfCoopCloseAllowed() {
2✔
5432
                return nil, fmt.Errorf("rbf coop close not enabled for " +
×
5433
                        "channel")
×
5434
        }
×
5435

5436
        closeUpdates := &CoopCloseUpdates{
2✔
5437
                UpdateChan: make(chan interface{}, 1),
2✔
5438
                ErrChan:    make(chan error, 1),
2✔
5439
        }
2✔
5440

2✔
5441
        // We'll re-use the existing switch struct here, even though we're
2✔
5442
        // bypassing the switch entirely.
2✔
5443
        closeReq := htlcswitch.ChanClose{
2✔
5444
                CloseType:      contractcourt.CloseRegular,
2✔
5445
                ChanPoint:      &chanPoint,
2✔
5446
                TargetFeePerKw: feeRate,
2✔
5447
                DeliveryScript: deliveryScript,
2✔
5448
                Updates:        closeUpdates.UpdateChan,
2✔
5449
                Err:            closeUpdates.ErrChan,
2✔
5450
                Ctx:            ctx,
2✔
5451
        }
2✔
5452

2✔
5453
        err := p.startRbfChanCloser(newRPCShutdownInit(&closeReq), chanPoint)
2✔
5454
        if err != nil {
2✔
5455
                return nil, err
×
5456
        }
×
5457

5458
        return closeUpdates, nil
2✔
5459
}
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