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

lightningnetwork / lnd / 13536249039

26 Feb 2025 03:42AM UTC coverage: 57.462% (-1.4%) from 58.835%
13536249039

Pull #8453

github

Roasbeef
peer: update chooseDeliveryScript to gen script if needed

In this commit, we update `chooseDeliveryScript` to generate a new
script if needed. This allows us to fold in a few other lines that
always followed this function into this expanded function.

The tests have been updated accordingly.
Pull Request #8453: [4/4] - multi: integrate new rbf coop close FSM into the existing peer flow

275 of 1318 new or added lines in 22 files covered. (20.86%)

19521 existing lines in 257 files now uncovered.

103858 of 180741 relevant lines covered (57.46%)

24750.23 hits per line

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

32.09
/peer/brontide.go
1
package peer
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

123
        err chan error
124
}
125

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

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

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

144
        // OutputIndex is the output index of our output in the closing
145
        // transaction.
146
        OutputIndex uint32
147

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

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

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

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

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

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

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

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

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

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

200
        // Addr is the network address of the peer.
201
        Addr *lnwire.NetAddress
202

203
        // Inbound indicates whether or not the peer is an inbound peer.
204
        Inbound bool
205

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

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

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

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

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

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

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

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

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

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

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

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

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

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

269
        // ChainIO is used to retrieve the best block.
270
        ChainIO lnwallet.BlockChainIO
271

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

276
        // Signer is used when creating *lnwallet.LightningChannel instances.
277
        Signer input.Signer
278

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

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

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

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

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

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

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

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

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

315
        // HtlcNotifier is used when creating a ChannelLink.
316
        HtlcNotifier *htlcswitch.HtlcNotifier
317

318
        // TowerClient is used to backup revoked states.
319
        TowerClient wtclient.ClientManager
320

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

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

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

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

339
        // FundingManager is an implementation of the funding.Controller interface.
340
        FundingManager funding.Controller
341

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

438
        // MaxFeeExposure limits the number of outstanding fees in a channel.
439
        // This value will be passed to created links.
440
        MaxFeeExposure lnwire.MilliSatoshi
441

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

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

451
        // ShouldFwdExpEndorsement is a closure that indicates whether
452
        // experimental endorsement signals should be set.
453
        ShouldFwdExpEndorsement func() bool
454

455
        // Quit is the server's quit channel. If this is closed, we halt operation.
456
        Quit chan struct{}
457
}
458

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

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

473
// makeRbfCloser creates a new RBF closer from a chancloser.RbfChanCloser.
NEW
474
func makeRbfCloser(rbfCloser *chancloser.RbfChanCloser) chanCloserFsm {
×
NEW
475
        return fn.NewRight[*chancloser.ChanCloser](
×
NEW
476
                rbfCloser,
×
NEW
477
        )
×
NEW
478
}
×
479

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

490
        // MUST be used atomically.
491
        bytesReceived uint64
492
        bytesSent     uint64
493

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

511
        pingManager *PingManager
512

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

520
        cfg Config
521

522
        // activeSignal when closed signals that the peer is now active and
523
        // ready to process messages.
524
        activeSignal chan struct{}
525

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

530
        // sendQueue is the channel which is used to queue outgoing messages to be
531
        // written onto the wire. Note that this channel is unbuffered.
532
        sendQueue chan outgoingMsg
533

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

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

551
        // addedChannels tracks any new channels opened during this peer's
552
        // lifecycle. We use this to filter out these new channels when the time
553
        // comes to request a reenable for active channels, since they will have
554
        // waited a shorter duration.
555
        addedChannels *lnutils.SyncMap[lnwire.ChannelID, struct{}]
556

557
        // newActiveChannel is used by the fundingManager to send fully opened
558
        // channels to the source peer which handled the funding workflow.
559
        newActiveChannel chan *newChannelMsg
560

561
        // newPendingChannel is used by the fundingManager to send pending open
562
        // channels to the source peer which handled the funding workflow.
563
        newPendingChannel chan *newChannelMsg
564

565
        // removePendingChannel is used by the fundingManager to cancel pending
566
        // open channels to the source peer when the funding flow is failed.
567
        removePendingChannel chan *newChannelMsg
568

569
        // activeMsgStreams is a map from channel id to the channel streams that
570
        // proxy messages to individual, active links.
571
        activeMsgStreams map[lnwire.ChannelID]*msgStream
572

573
        // activeChanCloses is a map that keeps track of all the active
574
        // cooperative channel closures. Any channel closing messages are directed
575
        // to one of these active state machines. Once the channel has been closed,
576
        // the state machine will be deleted from the map.
577
        activeChanCloses *lnutils.SyncMap[lnwire.ChannelID, chanCloserFsm]
578

579
        // localCloseChanReqs is a channel in which any local requests to close
580
        // a particular channel are sent over.
581
        localCloseChanReqs chan *htlcswitch.ChanClose
582

583
        // linkFailures receives all reported channel failures from the switch,
584
        // and instructs the channelManager to clean remaining channel state.
585
        linkFailures chan linkFailureReport
586

587
        // chanCloseMsgs is a channel that any message related to channel
588
        // closures are sent over. This includes lnwire.Shutdown message as
589
        // well as lnwire.ClosingSigned messages.
590
        chanCloseMsgs chan *closeMsg
591

592
        // remoteFeatures is the feature vector received from the peer during
593
        // the connection handshake.
594
        remoteFeatures *lnwire.FeatureVector
595

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

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

611
        // msgRouter is an instance of the msgmux.Router which is used to send
612
        // off new wire messages for handing.
613
        msgRouter fn.Option[msgmux.Router]
614

615
        // globalMsgRouter is a flag that indicates whether we have a global
616
        // msg router. If so, then we don't worry about stopping the msg router
617
        // when a peer disconnects.
618
        globalMsgRouter bool
619

620
        startReady chan struct{}
621

622
        // cg is a helper that encapsulates a wait group and quit channel and
623
        // allows contexts that either block or cancel on those depending on
624
        // the use case.
625
        cg *fn.ContextGuard
626

627
        // log is a peer-specific logging instance.
628
        log btclog.Logger
629
}
630

631
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer
632
// interface.
633
var _ lnpeer.Peer = (*Brontide)(nil)
634

635
// NewBrontide creates a new Brontide from a peer.Config struct.
636
func NewBrontide(cfg Config) *Brontide {
25✔
637
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
25✔
638

25✔
639
        // We have a global message router if one was passed in via the config.
25✔
640
        // In this case, we don't need to attempt to tear it down when the peer
25✔
641
        // is stopped.
25✔
642
        globalMsgRouter := cfg.MsgRouter.IsSome()
25✔
643

25✔
644
        // We'll either use the msg router instance passed in, or create a new
25✔
645
        // blank instance.
25✔
646
        msgRouter := cfg.MsgRouter.Alt(fn.Some[msgmux.Router](
25✔
647
                msgmux.NewMultiMsgRouter(),
25✔
648
        ))
25✔
649

25✔
650
        p := &Brontide{
25✔
651
                cfg:           cfg,
25✔
652
                activeSignal:  make(chan struct{}),
25✔
653
                sendQueue:     make(chan outgoingMsg),
25✔
654
                outgoingQueue: make(chan outgoingMsg),
25✔
655
                addedChannels: &lnutils.SyncMap[lnwire.ChannelID, struct{}]{},
25✔
656
                activeChannels: &lnutils.SyncMap[
25✔
657
                        lnwire.ChannelID, *lnwallet.LightningChannel,
25✔
658
                ]{},
25✔
659
                newActiveChannel:     make(chan *newChannelMsg, 1),
25✔
660
                newPendingChannel:    make(chan *newChannelMsg, 1),
25✔
661
                removePendingChannel: make(chan *newChannelMsg),
25✔
662

25✔
663
                activeMsgStreams: make(map[lnwire.ChannelID]*msgStream),
25✔
664
                activeChanCloses: &lnutils.SyncMap[
25✔
665
                        lnwire.ChannelID, chanCloserFsm,
25✔
666
                ]{},
25✔
667
                localCloseChanReqs: make(chan *htlcswitch.ChanClose),
25✔
668
                linkFailures:       make(chan linkFailureReport),
25✔
669
                chanCloseMsgs:      make(chan *closeMsg),
25✔
670
                resentChanSyncMsg:  make(map[lnwire.ChannelID]struct{}),
25✔
671
                startReady:         make(chan struct{}),
25✔
672
                log:                peerLog.WithPrefix(logPrefix),
25✔
673
                msgRouter:          msgRouter,
25✔
674
                globalMsgRouter:    globalMsgRouter,
25✔
675
                cg:                 fn.NewContextGuard(),
25✔
676
        }
25✔
677

25✔
678
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
25✔
UNCOV
679
                remoteAddr := cfg.Conn.RemoteAddr().String()
×
UNCOV
680
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
×
UNCOV
681
                        strings.Contains(remoteAddr, "127.0.0.1")
×
UNCOV
682
        }
×
683

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

700
                buf := bytes.NewBuffer(lastSerializedBlockHeader[0:0])
×
701
                err = header.Serialize(buf)
×
702
                if err == nil {
×
703
                        lastBlockHeader = header
×
704
                } else {
×
705
                        p.log.Warn("unable to serialize current block" +
×
706
                                "header for ping payload generation." +
×
707
                                "This should be impossible and means" +
×
708
                                "there is an implementation bug.")
×
709
                }
×
710

711
                return lastSerializedBlockHeader[:]
×
712
        }
713

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

727
        p.pingManager = NewPingManager(&PingManagerConfig{
25✔
728
                NewPingPayload:   newPingPayload,
25✔
729
                NewPongSize:      randPongSize,
25✔
730
                IntervalDuration: p.scaleTimeout(pingInterval),
25✔
731
                TimeoutDuration:  p.scaleTimeout(pingTimeout),
25✔
732
                SendPing: func(ping *lnwire.Ping) {
25✔
733
                        p.queueMsg(ping, nil)
×
734
                },
×
735
                OnPongFailure: func(err error) {
×
736
                        eStr := "pong response failure for %s: %v " +
×
737
                                "-- disconnecting"
×
738
                        p.log.Warnf(eStr, p, err)
×
739
                        go p.Disconnect(fmt.Errorf(eStr, p, err))
×
740
                },
×
741
        })
742

743
        return p
25✔
744
}
745

746
// Start starts all helper goroutines the peer needs for normal operations.  In
747
// the case this peer has already been started, then this function is a noop.
748
func (p *Brontide) Start() error {
3✔
749
        if atomic.AddInt32(&p.started, 1) != 1 {
3✔
750
                return nil
×
751
        }
×
752

753
        // Once we've finished starting up the peer, we'll signal to other
754
        // goroutines that the they can move forward to tear down the peer, or
755
        // carry out other relevant changes.
756
        defer close(p.startReady)
3✔
757

3✔
758
        p.log.Tracef("starting with conn[%v->%v]",
3✔
759
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
3✔
760

3✔
761
        // Fetch and then load all the active channels we have with this remote
3✔
762
        // peer from the database.
3✔
763
        activeChans, err := p.cfg.ChannelDB.FetchOpenChannels(
3✔
764
                p.cfg.Addr.IdentityKey,
3✔
765
        )
3✔
766
        if err != nil {
3✔
767
                p.log.Errorf("Unable to fetch active chans "+
×
768
                        "for peer: %v", err)
×
769
                return err
×
770
        }
×
771

772
        if len(activeChans) == 0 {
4✔
773
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
1✔
774
        }
1✔
775

776
        // Quickly check if we have any existing legacy channels with this
777
        // peer.
778
        haveLegacyChan := false
3✔
779
        for _, c := range activeChans {
5✔
780
                if c.ChanType.IsTweakless() {
4✔
781
                        continue
2✔
782
                }
783

UNCOV
784
                haveLegacyChan = true
×
UNCOV
785
                break
×
786
        }
787

788
        // Exchange local and global features, the init message should be very
789
        // first between two nodes.
790
        if err := p.sendInitMsg(haveLegacyChan); err != nil {
3✔
791
                return fmt.Errorf("unable to send init msg: %w", err)
×
792
        }
×
793

794
        // Before we launch any of the helper goroutines off the peer struct,
795
        // we'll first ensure proper adherence to the p2p protocol. The init
796
        // message MUST be sent before any other message.
797
        readErr := make(chan error, 1)
3✔
798
        msgChan := make(chan lnwire.Message, 1)
3✔
799
        p.cg.WgAdd(1)
3✔
800
        go func() {
6✔
801
                defer p.cg.WgDone()
3✔
802

3✔
803
                msg, err := p.readNextMessage()
3✔
804
                if err != nil {
3✔
805
                        readErr <- err
×
806
                        msgChan <- nil
×
807
                        return
×
808
                }
×
809
                readErr <- nil
3✔
810
                msgChan <- msg
3✔
811
        }()
812

813
        select {
3✔
814
        // In order to avoid blocking indefinitely, we'll give the other peer
815
        // an upper timeout to respond before we bail out early.
816
        case <-time.After(handshakeTimeout):
×
817
                return fmt.Errorf("peer did not complete handshake within %v",
×
818
                        handshakeTimeout)
×
819
        case err := <-readErr:
3✔
820
                if err != nil {
3✔
821
                        return fmt.Errorf("unable to read init msg: %w", err)
×
822
                }
×
823
        }
824

825
        // Once the init message arrives, we can parse it so we can figure out
826
        // the negotiation of features for this session.
827
        msg := <-msgChan
3✔
828
        if msg, ok := msg.(*lnwire.Init); ok {
6✔
829
                if err := p.handleInitMsg(msg); err != nil {
3✔
830
                        p.storeError(err)
×
831
                        return err
×
832
                }
×
833
        } else {
×
834
                return errors.New("very first message between nodes " +
×
835
                        "must be init message")
×
836
        }
×
837

838
        // Next, load all the active channels we have with this peer,
839
        // registering them with the switch and launching the necessary
840
        // goroutines required to operate them.
841
        p.log.Debugf("Loaded %v active channels from database",
3✔
842
                len(activeChans))
3✔
843

3✔
844
        // Conditionally subscribe to channel events before loading channels so
3✔
845
        // we won't miss events. This subscription is used to listen to active
3✔
846
        // channel event when reenabling channels. Once the reenabling process
3✔
847
        // is finished, this subscription will be canceled.
3✔
848
        //
3✔
849
        // NOTE: ChannelNotifier must be started before subscribing events
3✔
850
        // otherwise we'd panic here.
3✔
851
        if err := p.attachChannelEventSubscription(); err != nil {
3✔
852
                return err
×
853
        }
×
854

855
        // Register the message router now as we may need to register some
856
        // endpoints while loading the channels below.
857
        p.msgRouter.WhenSome(func(router msgmux.Router) {
6✔
858
                ctx, _ := p.cg.Create(context.Background())
3✔
859
                router.Start(ctx)
3✔
860
        })
3✔
861

862
        msgs, err := p.loadActiveChannels(activeChans)
3✔
863
        if err != nil {
3✔
864
                return fmt.Errorf("unable to load channels: %w", err)
×
865
        }
×
866

867
        p.startTime = time.Now()
3✔
868

3✔
869
        // Before launching the writeHandler goroutine, we send any channel
3✔
870
        // sync messages that must be resent for borked channels. We do this to
3✔
871
        // avoid data races with WriteMessage & Flush calls.
3✔
872
        if len(msgs) > 0 {
5✔
873
                p.log.Infof("Sending %d channel sync messages to peer after "+
2✔
874
                        "loading active channels", len(msgs))
2✔
875

2✔
876
                // Send the messages directly via writeMessage and bypass the
2✔
877
                // writeHandler goroutine.
2✔
878
                for _, msg := range msgs {
4✔
879
                        if err := p.writeMessage(msg); err != nil {
2✔
880
                                return fmt.Errorf("unable to send "+
×
881
                                        "reestablish msg: %v", err)
×
882
                        }
×
883
                }
884
        }
885

886
        err = p.pingManager.Start()
3✔
887
        if err != nil {
3✔
888
                return fmt.Errorf("could not start ping manager %w", err)
×
889
        }
×
890

891
        p.cg.WgAdd(4)
3✔
892
        go p.queueHandler()
3✔
893
        go p.writeHandler()
3✔
894
        go p.channelManager()
3✔
895
        go p.readHandler()
3✔
896

3✔
897
        // Signal to any external processes that the peer is now active.
3✔
898
        close(p.activeSignal)
3✔
899

3✔
900
        // Node announcements don't propagate very well throughout the network
3✔
901
        // as there isn't a way to efficiently query for them through their
3✔
902
        // timestamp, mostly affecting nodes that were offline during the time
3✔
903
        // of broadcast. We'll resend our node announcement to the remote peer
3✔
904
        // as a best-effort delivery such that it can also propagate to their
3✔
905
        // peers. To ensure they can successfully process it in most cases,
3✔
906
        // we'll only resend it as long as we have at least one confirmed
3✔
907
        // advertised channel with the remote peer.
3✔
908
        //
3✔
909
        // TODO(wilmer): Remove this once we're able to query for node
3✔
910
        // announcements through their timestamps.
3✔
911
        p.cg.WgAdd(2)
3✔
912
        go p.maybeSendNodeAnn(activeChans)
3✔
913
        go p.maybeSendChannelUpdates()
3✔
914

3✔
915
        return nil
3✔
916
}
917

918
// initGossipSync initializes either a gossip syncer or an initial routing
919
// dump, depending on the negotiated synchronization method.
920
func (p *Brontide) initGossipSync() {
3✔
921
        // If the remote peer knows of the new gossip queries feature, then
3✔
922
        // we'll create a new gossipSyncer in the AuthenticatedGossiper for it.
3✔
923
        if p.remoteFeatures.HasFeature(lnwire.GossipQueriesOptional) {
6✔
924
                p.log.Info("Negotiated chan series queries")
3✔
925

3✔
926
                if p.cfg.AuthGossiper == nil {
6✔
927
                        // This should only ever be hit in the unit tests.
3✔
928
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
3✔
929
                                "gossip sync.")
3✔
930
                        return
3✔
931
                }
3✔
932

933
                // Register the peer's gossip syncer with the gossiper.
934
                // This blocks synchronously to ensure the gossip syncer is
935
                // registered with the gossiper before attempting to read
936
                // messages from the remote peer.
937
                //
938
                // TODO(wilmer): Only sync updates from non-channel peers. This
939
                // requires an improved version of the current network
940
                // bootstrapper to ensure we can find and connect to non-channel
941
                // peers.
UNCOV
942
                p.cfg.AuthGossiper.InitSyncState(p)
×
943
        }
944
}
945

946
// taprootShutdownAllowed returns true if both parties have negotiated the
947
// shutdown-any-segwit feature.
948
func (p *Brontide) taprootShutdownAllowed() bool {
6✔
949
        return p.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
6✔
950
                p.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
6✔
951
}
6✔
952

953
// rbfCoopCloseAllowed returns true if both parties have negotiated the new RBF
954
// coop close feature.
955
func (p *Brontide) rbfCoopCloseAllowed() bool {
7✔
956
        return p.RemoteFeatures().HasFeature(
7✔
957
                lnwire.RbfCoopCloseOptionalStaging,
7✔
958
        ) && p.LocalFeatures().HasFeature(
7✔
959
                lnwire.RbfCoopCloseOptionalStaging,
7✔
960
        )
7✔
961
}
7✔
962

963
// QuitSignal is a method that should return a channel which will be sent upon
964
// or closed once the backing peer exits. This allows callers using the
965
// interface to cancel any processing in the event the backing implementation
966
// exits.
967
//
968
// NOTE: Part of the lnpeer.Peer interface.
UNCOV
969
func (p *Brontide) QuitSignal() <-chan struct{} {
×
NEW
970
        return p.cg.Done()
×
UNCOV
971
}
×
972

973
// addrWithInternalKey takes a delivery script, then attempts to supplement it
974
// with information related to the internal key for the addr, but only if it's
975
// a taproot addr.
976
func (p *Brontide) addrWithInternalKey(
977
        deliveryScript []byte) (*chancloser.DeliveryAddrWithKey, error) {
9✔
978

9✔
979
        // Currently, custom channels cannot be created with external upfront
9✔
980
        // shutdown addresses, so this shouldn't be an issue. We only require
9✔
981
        // the internal key for taproot addresses to be able to provide a non
9✔
982
        // inclusion proof of any scripts.
9✔
983
        internalKeyDesc, err := lnwallet.InternalKeyForAddr(
9✔
984
                p.cfg.Wallet, &p.cfg.Wallet.Cfg.NetParams, deliveryScript,
9✔
985
        )
9✔
986
        if err != nil {
9✔
987
                return nil, fmt.Errorf("unable to fetch internal key: %w", err)
×
988
        }
×
989

990
        return &chancloser.DeliveryAddrWithKey{
9✔
991
                DeliveryAddress: deliveryScript,
9✔
992
                InternalKey: fn.MapOption(
9✔
993
                        func(desc keychain.KeyDescriptor) btcec.PublicKey {
9✔
UNCOV
994
                                return *desc.PubKey
×
UNCOV
995
                        },
×
996
                )(internalKeyDesc),
997
        }, nil
998
}
999

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

3✔
1007
        // Return a slice of messages to send to the peers in case the channel
3✔
1008
        // cannot be loaded normally.
3✔
1009
        var msgs []lnwire.Message
3✔
1010

3✔
1011
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
3✔
1012

3✔
1013
        for _, dbChan := range chans {
5✔
1014
                hasScidFeature := dbChan.ChanType.HasScidAliasFeature()
2✔
1015
                if scidAliasNegotiated && !hasScidFeature {
2✔
UNCOV
1016
                        // We'll request and store an alias, making sure that a
×
UNCOV
1017
                        // gossiper mapping is not created for the alias to the
×
UNCOV
1018
                        // real SCID. This is done because the peer and funding
×
UNCOV
1019
                        // manager are not aware of each other's states and if
×
UNCOV
1020
                        // we did not do this, we would accept alias channel
×
UNCOV
1021
                        // updates after 6 confirmations, which would be buggy.
×
UNCOV
1022
                        // We'll queue a channel_ready message with the new
×
UNCOV
1023
                        // alias. This should technically be done *after* the
×
UNCOV
1024
                        // reestablish, but this behavior is pre-existing since
×
UNCOV
1025
                        // the funding manager may already queue a
×
UNCOV
1026
                        // channel_ready before the channel_reestablish.
×
UNCOV
1027
                        if !dbChan.IsPending {
×
UNCOV
1028
                                aliasScid, err := p.cfg.RequestAlias()
×
UNCOV
1029
                                if err != nil {
×
1030
                                        return nil, err
×
1031
                                }
×
1032

UNCOV
1033
                                err = p.cfg.AddLocalAlias(
×
UNCOV
1034
                                        aliasScid, dbChan.ShortChanID(), false,
×
UNCOV
1035
                                        false,
×
UNCOV
1036
                                )
×
UNCOV
1037
                                if err != nil {
×
1038
                                        return nil, err
×
1039
                                }
×
1040

UNCOV
1041
                                chanID := lnwire.NewChanIDFromOutPoint(
×
UNCOV
1042
                                        dbChan.FundingOutpoint,
×
UNCOV
1043
                                )
×
UNCOV
1044

×
UNCOV
1045
                                // Fetch the second commitment point to send in
×
UNCOV
1046
                                // the channel_ready message.
×
UNCOV
1047
                                second, err := dbChan.SecondCommitmentPoint()
×
UNCOV
1048
                                if err != nil {
×
1049
                                        return nil, err
×
1050
                                }
×
1051

UNCOV
1052
                                channelReadyMsg := lnwire.NewChannelReady(
×
UNCOV
1053
                                        chanID, second,
×
UNCOV
1054
                                )
×
UNCOV
1055
                                channelReadyMsg.AliasScid = &aliasScid
×
UNCOV
1056

×
UNCOV
1057
                                msgs = append(msgs, channelReadyMsg)
×
1058
                        }
1059

1060
                        // If we've negotiated the option-scid-alias feature
1061
                        // and this channel does not have ScidAliasFeature set
1062
                        // to true due to an upgrade where the feature bit was
1063
                        // turned on, we'll update the channel's database
1064
                        // state.
UNCOV
1065
                        err := dbChan.MarkScidAliasNegotiated()
×
UNCOV
1066
                        if err != nil {
×
1067
                                return nil, err
×
1068
                        }
×
1069
                }
1070

1071
                var chanOpts []lnwallet.ChannelOpt
2✔
1072
                p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
2✔
1073
                        chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
1074
                })
×
1075
                p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
2✔
1076
                        chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
1077
                })
×
1078
                p.cfg.AuxResolver.WhenSome(
2✔
1079
                        func(s lnwallet.AuxContractResolver) {
2✔
1080
                                chanOpts = append(
×
1081
                                        chanOpts, lnwallet.WithAuxResolver(s),
×
1082
                                )
×
1083
                        },
×
1084
                )
1085

1086
                lnChan, err := lnwallet.NewLightningChannel(
2✔
1087
                        p.cfg.Signer, dbChan, p.cfg.SigPool, chanOpts...,
2✔
1088
                )
2✔
1089
                if err != nil {
2✔
1090
                        return nil, fmt.Errorf("unable to create channel "+
×
1091
                                "state machine: %w", err)
×
1092
                }
×
1093

1094
                chanPoint := dbChan.FundingOutpoint
2✔
1095

2✔
1096
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
1097

2✔
1098
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
2✔
1099
                        chanPoint, lnChan.IsPending())
2✔
1100

2✔
1101
                // Skip adding any permanently irreconcilable channels to the
2✔
1102
                // htlcswitch.
2✔
1103
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
2✔
1104
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
4✔
1105

2✔
1106
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
2✔
1107
                                "start.", chanPoint, dbChan.ChanStatus())
2✔
1108

2✔
1109
                        // To help our peer recover from a potential data loss,
2✔
1110
                        // we resend our channel reestablish message if the
2✔
1111
                        // channel is in a borked state. We won't process any
2✔
1112
                        // channel reestablish message sent from the peer, but
2✔
1113
                        // that's okay since the assumption is that we did when
2✔
1114
                        // marking the channel borked.
2✔
1115
                        chanSync, err := dbChan.ChanSyncMsg()
2✔
1116
                        if err != nil {
2✔
1117
                                p.log.Errorf("Unable to create channel "+
×
1118
                                        "reestablish message for channel %v: "+
×
1119
                                        "%v", chanPoint, err)
×
1120
                                continue
×
1121
                        }
1122

1123
                        msgs = append(msgs, chanSync)
2✔
1124

2✔
1125
                        // Check if this channel needs to have the cooperative
2✔
1126
                        // close process restarted. If so, we'll need to send
2✔
1127
                        // the Shutdown message that is returned.
2✔
1128
                        if dbChan.HasChanStatus(
2✔
1129
                                channeldb.ChanStatusCoopBroadcasted,
2✔
1130
                        ) {
2✔
1131

×
1132
                                shutdownMsg, err := p.restartCoopClose(lnChan)
×
1133
                                if err != nil {
×
1134
                                        p.log.Errorf("Unable to restart "+
×
1135
                                                "coop close for channel: %v",
×
1136
                                                err)
×
1137
                                        continue
×
1138
                                }
1139

1140
                                if shutdownMsg == nil {
×
1141
                                        continue
×
1142
                                }
1143

1144
                                // Append the message to the set of messages to
1145
                                // send.
1146
                                msgs = append(msgs, shutdownMsg)
×
1147
                        }
1148

1149
                        continue
2✔
1150
                }
1151

1152
                // Before we register this new link with the HTLC Switch, we'll
1153
                // need to fetch its current link-layer forwarding policy from
1154
                // the database.
UNCOV
1155
                graph := p.cfg.ChannelGraph
×
UNCOV
1156
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
×
UNCOV
1157
                        &chanPoint,
×
UNCOV
1158
                )
×
UNCOV
1159
                if err != nil && !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
1160
                        return nil, err
×
1161
                }
×
1162

1163
                // We'll filter out our policy from the directional channel
1164
                // edges based whom the edge connects to. If it doesn't connect
1165
                // to us, then we know that we were the one that advertised the
1166
                // policy.
1167
                //
1168
                // TODO(roasbeef): can add helper method to get policy for
1169
                // particular channel.
UNCOV
1170
                var selfPolicy *models.ChannelEdgePolicy
×
UNCOV
1171
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
×
UNCOV
1172
                        p.cfg.ServerPubKey[:]) {
×
UNCOV
1173

×
UNCOV
1174
                        selfPolicy = p1
×
UNCOV
1175
                } else {
×
UNCOV
1176
                        selfPolicy = p2
×
UNCOV
1177
                }
×
1178

1179
                // If we don't yet have an advertised routing policy, then
1180
                // we'll use the current default, otherwise we'll translate the
1181
                // routing policy into a forwarding policy.
UNCOV
1182
                var forwardingPolicy *models.ForwardingPolicy
×
UNCOV
1183
                if selfPolicy != nil {
×
UNCOV
1184
                        var inboundWireFee lnwire.Fee
×
UNCOV
1185
                        _, err := selfPolicy.ExtraOpaqueData.ExtractRecords(
×
UNCOV
1186
                                &inboundWireFee,
×
UNCOV
1187
                        )
×
UNCOV
1188
                        if err != nil {
×
1189
                                return nil, err
×
1190
                        }
×
1191

UNCOV
1192
                        inboundFee := models.NewInboundFeeFromWire(
×
UNCOV
1193
                                inboundWireFee,
×
UNCOV
1194
                        )
×
UNCOV
1195

×
UNCOV
1196
                        forwardingPolicy = &models.ForwardingPolicy{
×
UNCOV
1197
                                MinHTLCOut:    selfPolicy.MinHTLC,
×
UNCOV
1198
                                MaxHTLC:       selfPolicy.MaxHTLC,
×
UNCOV
1199
                                BaseFee:       selfPolicy.FeeBaseMSat,
×
UNCOV
1200
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
×
UNCOV
1201
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
×
UNCOV
1202

×
UNCOV
1203
                                InboundFee: inboundFee,
×
UNCOV
1204
                        }
×
UNCOV
1205
                } else {
×
UNCOV
1206
                        p.log.Warnf("Unable to find our forwarding policy "+
×
UNCOV
1207
                                "for channel %v, using default values",
×
UNCOV
1208
                                chanPoint)
×
UNCOV
1209
                        forwardingPolicy = &p.cfg.RoutingPolicy
×
UNCOV
1210
                }
×
1211

UNCOV
1212
                p.log.Tracef("Using link policy of: %v",
×
UNCOV
1213
                        spew.Sdump(forwardingPolicy))
×
UNCOV
1214

×
UNCOV
1215
                // If the channel is pending, set the value to nil in the
×
UNCOV
1216
                // activeChannels map. This is done to signify that the channel
×
UNCOV
1217
                // is pending. We don't add the link to the switch here - it's
×
UNCOV
1218
                // the funding manager's responsibility to spin up pending
×
UNCOV
1219
                // channels. Adding them here would just be extra work as we'll
×
UNCOV
1220
                // tear them down when creating + adding the final link.
×
UNCOV
1221
                if lnChan.IsPending() {
×
UNCOV
1222
                        p.activeChannels.Store(chanID, nil)
×
UNCOV
1223

×
UNCOV
1224
                        continue
×
1225
                }
1226

UNCOV
1227
                shutdownInfo, err := lnChan.State().ShutdownInfo()
×
UNCOV
1228
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
×
1229
                        return nil, err
×
1230
                }
×
1231

UNCOV
1232
                var (
×
UNCOV
1233
                        shutdownMsg     fn.Option[lnwire.Shutdown]
×
UNCOV
1234
                        shutdownInfoErr error
×
UNCOV
1235
                )
×
UNCOV
1236
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
×
NEW
1237
                        // If we can use the new RBF close feature, we don't
×
NEW
1238
                        // need to create the legacy closer.
×
NEW
1239
                        if p.rbfCoopCloseAllowed() {
×
NEW
1240
                                return
×
NEW
1241
                        }
×
1242

1243
                        // Compute an ideal fee.
UNCOV
1244
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
UNCOV
1245
                                p.cfg.CoopCloseTargetConfs,
×
UNCOV
1246
                        )
×
UNCOV
1247
                        if err != nil {
×
1248
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1249
                                        "estimate fee: %w", err)
×
1250

×
1251
                                return
×
1252
                        }
×
1253

UNCOV
1254
                        addr, err := p.addrWithInternalKey(
×
UNCOV
1255
                                info.DeliveryScript.Val,
×
UNCOV
1256
                        )
×
UNCOV
1257
                        if err != nil {
×
1258
                                shutdownInfoErr = fmt.Errorf("unable to make "+
×
1259
                                        "delivery addr: %w", err)
×
1260
                                return
×
1261
                        }
×
NEW
1262
                        negotiateChanCloser, err := p.createChanCloser(
×
NEW
1263
                                lnChan, addr, feePerKw, nil,
×
NEW
1264
                                info.Closer(),
×
UNCOV
1265
                        )
×
UNCOV
1266
                        if err != nil {
×
1267
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1268
                                        "create chan closer: %w", err)
×
1269

×
1270
                                return
×
1271
                        }
×
1272

UNCOV
1273
                        chanID := lnwire.NewChanIDFromOutPoint(
×
UNCOV
1274
                                lnChan.State().FundingOutpoint,
×
UNCOV
1275
                        )
×
UNCOV
1276

×
NEW
1277
                        p.activeChanCloses.Store(chanID, makeNegotiateCloser(
×
NEW
1278
                                negotiateChanCloser,
×
NEW
1279
                        ))
×
UNCOV
1280

×
UNCOV
1281
                        // Create the Shutdown message.
×
NEW
1282
                        shutdown, err := negotiateChanCloser.ShutdownChan()
×
UNCOV
1283
                        if err != nil {
×
NEW
1284
                                p.activeChanCloses.Delete(chanID)
×
1285
                                shutdownInfoErr = err
×
1286

×
1287
                                return
×
1288
                        }
×
1289

UNCOV
1290
                        shutdownMsg = fn.Some(*shutdown)
×
1291
                })
UNCOV
1292
                if shutdownInfoErr != nil {
×
1293
                        return nil, shutdownInfoErr
×
1294
                }
×
1295

1296
                // Subscribe to the set of on-chain events for this channel.
UNCOV
1297
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
×
UNCOV
1298
                        chanPoint,
×
UNCOV
1299
                )
×
UNCOV
1300
                if err != nil {
×
1301
                        return nil, err
×
1302
                }
×
1303

UNCOV
1304
                err = p.addLink(
×
UNCOV
1305
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
×
UNCOV
1306
                        true, shutdownMsg,
×
UNCOV
1307
                )
×
UNCOV
1308
                if err != nil {
×
1309
                        return nil, fmt.Errorf("unable to add link %v to "+
×
1310
                                "switch: %v", chanPoint, err)
×
1311
                }
×
1312

UNCOV
1313
                p.activeChannels.Store(chanID, lnChan)
×
NEW
1314

×
NEW
1315
                // We're using the old co-op close, so we don't need to init
×
NEW
1316
                // the new RBF chan closer.
×
NEW
1317
                if !p.rbfCoopCloseAllowed() {
×
NEW
1318
                        continue
×
1319
                }
1320

1321
                // Now that the link has been added above, we'll also init an
1322
                // RBF chan closer for this channel, but only if the new close
1323
                // feature is negotiated.
1324
                //
1325
                // Creating this here ensures that any shutdown messages sent
1326
                // will be automatically routed by the msg router.
NEW
1327
                if _, err := p.initRbfChanCloser(lnChan); err != nil {
×
NEW
1328
                        p.activeChanCloses.Delete(chanID)
×
NEW
1329

×
NEW
1330
                        return nil, fmt.Errorf("unable to init RBF chan "+
×
NEW
1331
                                "closer during peer connect: %w", err)
×
NEW
1332
                }
×
1333

1334
                // If the shutdown info isn't blank, then we should kick things
1335
                // off by sending a shutdown message to the remote party to
1336
                // continue the old shutdown flow.
NEW
1337
                restartShutdown := func(s channeldb.ShutdownInfo) error {
×
NEW
1338
                        return p.startRbfChanCloser(
×
NEW
1339
                                newRestartShutdownInit(s),
×
NEW
1340
                                lnChan.ChannelPoint(),
×
NEW
1341
                        )
×
NEW
1342
                }
×
NEW
1343
                err = fn.MapOptionZ(shutdownInfo, restartShutdown)
×
NEW
1344
                if err != nil {
×
NEW
1345
                        return nil, fmt.Errorf("unable to start RBF "+
×
NEW
1346
                                "chan closer: %w", err)
×
NEW
1347
                }
×
1348
        }
1349

1350
        return msgs, nil
3✔
1351
}
1352

1353
// addLink creates and adds a new ChannelLink from the specified channel.
1354
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1355
        lnChan *lnwallet.LightningChannel,
1356
        forwardingPolicy *models.ForwardingPolicy,
1357
        chainEvents *contractcourt.ChainEventSubscription,
UNCOV
1358
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
×
UNCOV
1359

×
UNCOV
1360
        // onChannelFailure will be called by the link in case the channel
×
UNCOV
1361
        // fails for some reason.
×
UNCOV
1362
        onChannelFailure := func(chanID lnwire.ChannelID,
×
UNCOV
1363
                shortChanID lnwire.ShortChannelID,
×
UNCOV
1364
                linkErr htlcswitch.LinkFailureError) {
×
UNCOV
1365

×
UNCOV
1366
                failure := linkFailureReport{
×
UNCOV
1367
                        chanPoint:   *chanPoint,
×
UNCOV
1368
                        chanID:      chanID,
×
UNCOV
1369
                        shortChanID: shortChanID,
×
UNCOV
1370
                        linkErr:     linkErr,
×
UNCOV
1371
                }
×
UNCOV
1372

×
UNCOV
1373
                select {
×
UNCOV
1374
                case p.linkFailures <- failure:
×
NEW
1375
                case <-p.cg.Done():
×
1376
                case <-p.cfg.Quit:
×
1377
                }
1378
        }
1379

UNCOV
1380
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
×
UNCOV
1381
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
×
UNCOV
1382
        }
×
1383

UNCOV
1384
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
×
UNCOV
1385
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
×
UNCOV
1386
        }
×
1387

1388
        //nolint:ll
UNCOV
1389
        linkCfg := htlcswitch.ChannelLinkConfig{
×
UNCOV
1390
                Peer:                   p,
×
UNCOV
1391
                DecodeHopIterators:     p.cfg.Sphinx.DecodeHopIterators,
×
UNCOV
1392
                ExtractErrorEncrypter:  p.cfg.Sphinx.ExtractErrorEncrypter,
×
UNCOV
1393
                FetchLastChannelUpdate: p.cfg.FetchLastChanUpdate,
×
UNCOV
1394
                HodlMask:               p.cfg.Hodl.Mask(),
×
UNCOV
1395
                Registry:               p.cfg.Invoices,
×
UNCOV
1396
                BestHeight:             p.cfg.Switch.BestHeight,
×
UNCOV
1397
                Circuits:               p.cfg.Switch.CircuitModifier(),
×
UNCOV
1398
                ForwardPackets:         p.cfg.InterceptSwitch.ForwardPackets,
×
UNCOV
1399
                FwrdingPolicy:          *forwardingPolicy,
×
UNCOV
1400
                FeeEstimator:           p.cfg.FeeEstimator,
×
UNCOV
1401
                PreimageCache:          p.cfg.WitnessBeacon,
×
UNCOV
1402
                ChainEvents:            chainEvents,
×
UNCOV
1403
                UpdateContractSignals:  updateContractSignals,
×
UNCOV
1404
                NotifyContractUpdate:   notifyContractUpdate,
×
UNCOV
1405
                OnChannelFailure:       onChannelFailure,
×
UNCOV
1406
                SyncStates:             syncStates,
×
UNCOV
1407
                BatchTicker:            ticker.New(p.cfg.ChannelCommitInterval),
×
UNCOV
1408
                FwdPkgGCTicker:         ticker.New(time.Hour),
×
UNCOV
1409
                PendingCommitTicker: ticker.New(
×
UNCOV
1410
                        p.cfg.PendingCommitInterval,
×
UNCOV
1411
                ),
×
UNCOV
1412
                BatchSize:               p.cfg.ChannelCommitBatchSize,
×
UNCOV
1413
                UnsafeReplay:            p.cfg.UnsafeReplay,
×
UNCOV
1414
                MinUpdateTimeout:        htlcswitch.DefaultMinLinkFeeUpdateTimeout,
×
UNCOV
1415
                MaxUpdateTimeout:        htlcswitch.DefaultMaxLinkFeeUpdateTimeout,
×
UNCOV
1416
                OutgoingCltvRejectDelta: p.cfg.OutgoingCltvRejectDelta,
×
UNCOV
1417
                TowerClient:             p.cfg.TowerClient,
×
UNCOV
1418
                MaxOutgoingCltvExpiry:   p.cfg.MaxOutgoingCltvExpiry,
×
UNCOV
1419
                MaxFeeAllocation:        p.cfg.MaxChannelFeeAllocation,
×
UNCOV
1420
                MaxAnchorsCommitFeeRate: p.cfg.MaxAnchorsCommitFeeRate,
×
UNCOV
1421
                NotifyActiveLink:        p.cfg.ChannelNotifier.NotifyActiveLinkEvent,
×
UNCOV
1422
                NotifyActiveChannel:     p.cfg.ChannelNotifier.NotifyActiveChannelEvent,
×
UNCOV
1423
                NotifyInactiveChannel:   p.cfg.ChannelNotifier.NotifyInactiveChannelEvent,
×
UNCOV
1424
                NotifyInactiveLinkEvent: p.cfg.ChannelNotifier.NotifyInactiveLinkEvent,
×
UNCOV
1425
                HtlcNotifier:            p.cfg.HtlcNotifier,
×
UNCOV
1426
                GetAliases:              p.cfg.GetAliases,
×
UNCOV
1427
                PreviouslySentShutdown:  shutdownMsg,
×
UNCOV
1428
                DisallowRouteBlinding:   p.cfg.DisallowRouteBlinding,
×
UNCOV
1429
                MaxFeeExposure:          p.cfg.MaxFeeExposure,
×
UNCOV
1430
                ShouldFwdExpEndorsement: p.cfg.ShouldFwdExpEndorsement,
×
UNCOV
1431
                DisallowQuiescence: p.cfg.DisallowQuiescence ||
×
UNCOV
1432
                        !p.remoteFeatures.HasFeature(lnwire.QuiescenceOptional),
×
UNCOV
1433
                AuxTrafficShaper: p.cfg.AuxTrafficShaper,
×
UNCOV
1434
        }
×
UNCOV
1435

×
UNCOV
1436
        // Before adding our new link, purge the switch of any pending or live
×
UNCOV
1437
        // links going by the same channel id. If one is found, we'll shut it
×
UNCOV
1438
        // down to ensure that the mailboxes are only ever under the control of
×
UNCOV
1439
        // one link.
×
UNCOV
1440
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
×
UNCOV
1441
        p.cfg.Switch.RemoveLink(chanID)
×
UNCOV
1442

×
UNCOV
1443
        // With the channel link created, we'll now notify the htlc switch so
×
UNCOV
1444
        // this channel can be used to dispatch local payments and also
×
UNCOV
1445
        // passively forward payments.
×
UNCOV
1446
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
×
1447
}
1448

1449
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1450
// one confirmed public channel exists with them.
1451
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
3✔
1452
        defer p.cg.WgDone()
3✔
1453

3✔
1454
        hasConfirmedPublicChan := false
3✔
1455
        for _, channel := range channels {
5✔
1456
                if channel.IsPending {
2✔
UNCOV
1457
                        continue
×
1458
                }
1459
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
4✔
1460
                        continue
2✔
1461
                }
1462

UNCOV
1463
                hasConfirmedPublicChan = true
×
UNCOV
1464
                break
×
1465
        }
1466
        if !hasConfirmedPublicChan {
6✔
1467
                return
3✔
1468
        }
3✔
1469

UNCOV
1470
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
×
UNCOV
1471
        if err != nil {
×
1472
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1473
                return
×
1474
        }
×
1475

UNCOV
1476
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
×
1477
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1478
        }
×
1479
}
1480

1481
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1482
// have any active channels with them.
1483
func (p *Brontide) maybeSendChannelUpdates() {
3✔
1484
        defer p.cg.WgDone()
3✔
1485

3✔
1486
        // If we don't have any active channels, then we can exit early.
3✔
1487
        if p.activeChannels.Len() == 0 {
4✔
1488
                return
1✔
1489
        }
1✔
1490

1491
        maybeSendUpd := func(cid lnwire.ChannelID,
2✔
1492
                lnChan *lnwallet.LightningChannel) error {
4✔
1493

2✔
1494
                // Nil channels are pending, so we'll skip them.
2✔
1495
                if lnChan == nil {
2✔
UNCOV
1496
                        return nil
×
UNCOV
1497
                }
×
1498

1499
                dbChan := lnChan.State()
2✔
1500
                scid := func() lnwire.ShortChannelID {
4✔
1501
                        switch {
2✔
1502
                        // Otherwise if it's a zero conf channel and confirmed,
1503
                        // then we need to use the "real" scid.
UNCOV
1504
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
×
UNCOV
1505
                                return dbChan.ZeroConfRealScid()
×
1506

1507
                        // Otherwise, we can use the normal scid.
1508
                        default:
2✔
1509
                                return dbChan.ShortChanID()
2✔
1510
                        }
1511
                }()
1512

1513
                // Now that we know the channel is in a good state, we'll try
1514
                // to fetch the update to send to the remote peer. If the
1515
                // channel is pending, and not a zero conf channel, we'll get
1516
                // an error here which we'll ignore.
1517
                chanUpd, err := p.cfg.FetchLastChanUpdate(scid)
2✔
1518
                if err != nil {
2✔
UNCOV
1519
                        p.log.Debugf("Unable to fetch channel update for "+
×
UNCOV
1520
                                "ChannelPoint(%v), scid=%v: %v",
×
UNCOV
1521
                                dbChan.FundingOutpoint, dbChan.ShortChanID, err)
×
UNCOV
1522

×
UNCOV
1523
                        return nil
×
UNCOV
1524
                }
×
1525

1526
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
2✔
1527
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
2✔
1528

2✔
1529
                // We'll send it as a normal message instead of using the lazy
2✔
1530
                // queue to prioritize transmission of the fresh update.
2✔
1531
                if err := p.SendMessage(false, chanUpd); err != nil {
2✔
1532
                        err := fmt.Errorf("unable to send channel update for "+
×
1533
                                "ChannelPoint(%v), scid=%v: %w",
×
1534
                                dbChan.FundingOutpoint, dbChan.ShortChanID(),
×
1535
                                err)
×
1536
                        p.log.Errorf(err.Error())
×
1537

×
1538
                        return err
×
1539
                }
×
1540

1541
                return nil
2✔
1542
        }
1543

1544
        p.activeChannels.ForEach(maybeSendUpd)
2✔
1545
}
1546

1547
// WaitForDisconnect waits until the peer has disconnected. A peer may be
1548
// disconnected if the local or remote side terminates the connection, or an
1549
// irrecoverable protocol error has been encountered. This method will only
1550
// begin watching the peer's waitgroup after the ready channel or the peer's
1551
// quit channel are signaled. The ready channel should only be signaled if a
1552
// call to Start returns no error. Otherwise, if the peer fails to start,
1553
// calling Disconnect will signal the quit channel and the method will not
1554
// block, since no goroutines were spawned.
UNCOV
1555
func (p *Brontide) WaitForDisconnect(ready chan struct{}) {
×
UNCOV
1556
        // Before we try to call the `Wait` goroutine, we'll make sure the main
×
UNCOV
1557
        // set of goroutines are already active.
×
UNCOV
1558
        select {
×
UNCOV
1559
        case <-p.startReady:
×
NEW
1560
        case <-p.cg.Done():
×
1561
                return
×
1562
        }
1563

UNCOV
1564
        select {
×
UNCOV
1565
        case <-ready:
×
NEW
1566
        case <-p.cg.Done():
×
1567
        }
1568

NEW
1569
        p.cg.WgWait()
×
1570
}
1571

1572
// Disconnect terminates the connection with the remote peer. Additionally, a
1573
// signal is sent to the server and htlcSwitch indicating the resources
1574
// allocated to the peer can now be cleaned up.
UNCOV
1575
func (p *Brontide) Disconnect(reason error) {
×
UNCOV
1576
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
×
UNCOV
1577
                return
×
UNCOV
1578
        }
×
1579

1580
        // Make sure initialization has completed before we try to tear things
1581
        // down.
1582
        //
1583
        // NOTE: We only read the `startReady` chan if the peer has been
1584
        // started, otherwise we will skip reading it as this chan won't be
1585
        // closed, hence blocks forever.
UNCOV
1586
        if atomic.LoadInt32(&p.started) == 1 {
×
UNCOV
1587
                p.log.Debugf("Started, waiting on startReady signal")
×
UNCOV
1588

×
UNCOV
1589
                select {
×
UNCOV
1590
                case <-p.startReady:
×
NEW
1591
                case <-p.cg.Done():
×
1592
                        return
×
1593
                }
1594
        }
1595

UNCOV
1596
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
×
UNCOV
1597
        p.storeError(err)
×
UNCOV
1598

×
UNCOV
1599
        p.log.Infof(err.Error())
×
UNCOV
1600

×
UNCOV
1601
        // Stop PingManager before closing TCP connection.
×
UNCOV
1602
        p.pingManager.Stop()
×
UNCOV
1603

×
UNCOV
1604
        // Ensure that the TCP connection is properly closed before continuing.
×
UNCOV
1605
        p.cfg.Conn.Close()
×
UNCOV
1606

×
NEW
1607
        p.cg.Quit()
×
UNCOV
1608

×
UNCOV
1609
        // If our msg router isn't global (local to this instance), then we'll
×
UNCOV
1610
        // stop it. Otherwise, we'll leave it running.
×
UNCOV
1611
        if !p.globalMsgRouter {
×
UNCOV
1612
                p.msgRouter.WhenSome(func(router msgmux.Router) {
×
UNCOV
1613
                        router.Stop()
×
UNCOV
1614
                })
×
1615
        }
1616
}
1617

1618
// String returns the string representation of this peer.
UNCOV
1619
func (p *Brontide) String() string {
×
UNCOV
1620
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
×
UNCOV
1621
}
×
1622

1623
// readNextMessage reads, and returns the next message on the wire along with
1624
// any additional raw payload.
1625
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
7✔
1626
        noiseConn := p.cfg.Conn
7✔
1627
        err := noiseConn.SetReadDeadline(time.Time{})
7✔
1628
        if err != nil {
7✔
1629
                return nil, err
×
1630
        }
×
1631

1632
        pktLen, err := noiseConn.ReadNextHeader()
7✔
1633
        if err != nil {
7✔
UNCOV
1634
                return nil, fmt.Errorf("read next header: %w", err)
×
UNCOV
1635
        }
×
1636

1637
        // First we'll read the next _full_ message. We do this rather than
1638
        // reading incrementally from the stream as the Lightning wire protocol
1639
        // is message oriented and allows nodes to pad on additional data to
1640
        // the message stream.
1641
        var (
4✔
1642
                nextMsg lnwire.Message
4✔
1643
                msgLen  uint64
4✔
1644
        )
4✔
1645
        err = p.cfg.ReadPool.Submit(func(buf *buffer.Read) error {
8✔
1646
                // Before reading the body of the message, set the read timeout
4✔
1647
                // accordingly to ensure we don't block other readers using the
4✔
1648
                // pool. We do so only after the task has been scheduled to
4✔
1649
                // ensure the deadline doesn't expire while the message is in
4✔
1650
                // the process of being scheduled.
4✔
1651
                readDeadline := time.Now().Add(
4✔
1652
                        p.scaleTimeout(readMessageTimeout),
4✔
1653
                )
4✔
1654
                readErr := noiseConn.SetReadDeadline(readDeadline)
4✔
1655
                if readErr != nil {
4✔
1656
                        return readErr
×
1657
                }
×
1658

1659
                // The ReadNextBody method will actually end up re-using the
1660
                // buffer, so within this closure, we can continue to use
1661
                // rawMsg as it's just a slice into the buf from the buffer
1662
                // pool.
1663
                rawMsg, readErr := noiseConn.ReadNextBody(buf[:pktLen])
4✔
1664
                if readErr != nil {
4✔
1665
                        return fmt.Errorf("read next body: %w", readErr)
×
1666
                }
×
1667
                msgLen = uint64(len(rawMsg))
4✔
1668

4✔
1669
                // Next, create a new io.Reader implementation from the raw
4✔
1670
                // message, and use this to decode the message directly from.
4✔
1671
                msgReader := bytes.NewReader(rawMsg)
4✔
1672
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
4✔
1673
                if err != nil {
4✔
UNCOV
1674
                        return err
×
UNCOV
1675
                }
×
1676

1677
                // At this point, rawMsg and buf will be returned back to the
1678
                // buffer pool for re-use.
1679
                return nil
4✔
1680
        })
1681
        atomic.AddUint64(&p.bytesReceived, msgLen)
4✔
1682
        if err != nil {
4✔
UNCOV
1683
                return nil, err
×
UNCOV
1684
        }
×
1685

1686
        p.logWireMessage(nextMsg, true)
4✔
1687

4✔
1688
        return nextMsg, nil
4✔
1689
}
1690

1691
// msgStream implements a goroutine-safe, in-order stream of messages to be
1692
// delivered via closure to a receiver. These messages MUST be in order due to
1693
// the nature of the lightning channel commitment and gossiper state machines.
1694
// TODO(conner): use stream handler interface to abstract out stream
1695
// state/logging.
1696
type msgStream struct {
1697
        streamShutdown int32 // To be used atomically.
1698

1699
        peer *Brontide
1700

1701
        apply func(lnwire.Message)
1702

1703
        startMsg string
1704
        stopMsg  string
1705

1706
        msgCond *sync.Cond
1707
        msgs    []lnwire.Message
1708

1709
        mtx sync.Mutex
1710

1711
        producerSema chan struct{}
1712

1713
        wg   sync.WaitGroup
1714
        quit chan struct{}
1715
}
1716

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

3✔
1725
        stream := &msgStream{
3✔
1726
                peer:         p,
3✔
1727
                apply:        apply,
3✔
1728
                startMsg:     startMsg,
3✔
1729
                stopMsg:      stopMsg,
3✔
1730
                producerSema: make(chan struct{}, bufSize),
3✔
1731
                quit:         make(chan struct{}),
3✔
1732
        }
3✔
1733
        stream.msgCond = sync.NewCond(&stream.mtx)
3✔
1734

3✔
1735
        // Before we return the active stream, we'll populate the producer's
3✔
1736
        // semaphore channel. We'll use this to ensure that the producer won't
3✔
1737
        // attempt to allocate memory in the queue for an item until it has
3✔
1738
        // sufficient extra space.
3✔
1739
        for i := uint32(0); i < bufSize; i++ {
3,003✔
1740
                stream.producerSema <- struct{}{}
3,000✔
1741
        }
3,000✔
1742

1743
        return stream
3✔
1744
}
1745

1746
// Start starts the chanMsgStream.
1747
func (ms *msgStream) Start() {
3✔
1748
        ms.wg.Add(1)
3✔
1749
        go ms.msgConsumer()
3✔
1750
}
3✔
1751

1752
// Stop stops the chanMsgStream.
UNCOV
1753
func (ms *msgStream) Stop() {
×
UNCOV
1754
        // TODO(roasbeef): signal too?
×
UNCOV
1755

×
UNCOV
1756
        close(ms.quit)
×
UNCOV
1757

×
UNCOV
1758
        // Now that we've closed the channel, we'll repeatedly signal the msg
×
UNCOV
1759
        // consumer until we've detected that it has exited.
×
UNCOV
1760
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
×
UNCOV
1761
                ms.msgCond.Signal()
×
UNCOV
1762
                time.Sleep(time.Millisecond * 100)
×
UNCOV
1763
        }
×
1764

UNCOV
1765
        ms.wg.Wait()
×
1766
}
1767

1768
// msgConsumer is the main goroutine that streams messages from the peer's
1769
// readHandler directly to the target channel.
1770
func (ms *msgStream) msgConsumer() {
3✔
1771
        defer ms.wg.Done()
3✔
1772
        defer peerLog.Tracef(ms.stopMsg)
3✔
1773
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
3✔
1774

3✔
1775
        peerLog.Tracef(ms.startMsg)
3✔
1776

3✔
1777
        for {
6✔
1778
                // First, we'll check our condition. If the queue of messages
3✔
1779
                // is empty, then we'll wait until a new item is added.
3✔
1780
                ms.msgCond.L.Lock()
3✔
1781
                for len(ms.msgs) == 0 {
6✔
1782
                        ms.msgCond.Wait()
3✔
1783

3✔
1784
                        // If we woke up in order to exit, then we'll do so.
3✔
1785
                        // Otherwise, we'll check the message queue for any new
3✔
1786
                        // items.
3✔
1787
                        select {
3✔
NEW
1788
                        case <-ms.peer.cg.Done():
×
UNCOV
1789
                                ms.msgCond.L.Unlock()
×
UNCOV
1790
                                return
×
UNCOV
1791
                        case <-ms.quit:
×
UNCOV
1792
                                ms.msgCond.L.Unlock()
×
UNCOV
1793
                                return
×
UNCOV
1794
                        default:
×
1795
                        }
1796
                }
1797

1798
                // Grab the message off the front of the queue, shifting the
1799
                // slice's reference down one in order to remove the message
1800
                // from the queue.
UNCOV
1801
                msg := ms.msgs[0]
×
UNCOV
1802
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
×
UNCOV
1803
                ms.msgs = ms.msgs[1:]
×
UNCOV
1804

×
UNCOV
1805
                ms.msgCond.L.Unlock()
×
UNCOV
1806

×
UNCOV
1807
                ms.apply(msg)
×
UNCOV
1808

×
UNCOV
1809
                // We've just successfully processed an item, so we'll signal
×
UNCOV
1810
                // to the producer that a new slot in the buffer. We'll use
×
UNCOV
1811
                // this to bound the size of the buffer to avoid allowing it to
×
UNCOV
1812
                // grow indefinitely.
×
UNCOV
1813
                select {
×
UNCOV
1814
                case ms.producerSema <- struct{}{}:
×
NEW
1815
                case <-ms.peer.cg.Done():
×
UNCOV
1816
                        return
×
UNCOV
1817
                case <-ms.quit:
×
UNCOV
1818
                        return
×
1819
                }
1820
        }
1821
}
1822

1823
// AddMsg adds a new message to the msgStream. This function is safe for
1824
// concurrent access.
UNCOV
1825
func (ms *msgStream) AddMsg(msg lnwire.Message) {
×
UNCOV
1826
        // First, we'll attempt to receive from the producerSema struct. This
×
UNCOV
1827
        // acts as a semaphore to prevent us from indefinitely buffering
×
UNCOV
1828
        // incoming items from the wire. Either the msg queue isn't full, and
×
UNCOV
1829
        // we'll not block, or the queue is full, and we'll block until either
×
UNCOV
1830
        // we're signalled to quit, or a slot is freed up.
×
UNCOV
1831
        select {
×
UNCOV
1832
        case <-ms.producerSema:
×
NEW
1833
        case <-ms.peer.cg.Done():
×
1834
                return
×
1835
        case <-ms.quit:
×
1836
                return
×
1837
        }
1838

1839
        // Next, we'll lock the condition, and add the message to the end of
1840
        // the message queue.
UNCOV
1841
        ms.msgCond.L.Lock()
×
UNCOV
1842
        ms.msgs = append(ms.msgs, msg)
×
UNCOV
1843
        ms.msgCond.L.Unlock()
×
UNCOV
1844

×
UNCOV
1845
        // With the message added, we signal to the msgConsumer that there are
×
UNCOV
1846
        // additional messages to consume.
×
UNCOV
1847
        ms.msgCond.Signal()
×
1848
}
1849

1850
// waitUntilLinkActive waits until the target link is active and returns a
1851
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1852
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1853
func waitUntilLinkActive(p *Brontide,
UNCOV
1854
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
×
UNCOV
1855

×
UNCOV
1856
        p.log.Tracef("Waiting for link=%v to be active", cid)
×
UNCOV
1857

×
UNCOV
1858
        // Subscribe to receive channel events.
×
UNCOV
1859
        //
×
UNCOV
1860
        // NOTE: If the link is already active by SubscribeChannelEvents, then
×
UNCOV
1861
        // GetLink will retrieve the link and we can send messages. If the link
×
UNCOV
1862
        // becomes active between SubscribeChannelEvents and GetLink, then GetLink
×
UNCOV
1863
        // will retrieve the link. If the link becomes active after GetLink, then
×
UNCOV
1864
        // we will get an ActiveLinkEvent notification and retrieve the link. If
×
UNCOV
1865
        // the call to GetLink is before SubscribeChannelEvents, however, there
×
UNCOV
1866
        // will be a race condition.
×
UNCOV
1867
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
×
UNCOV
1868
        if err != nil {
×
UNCOV
1869
                // If we have a non-nil error, then the server is shutting down and we
×
UNCOV
1870
                // can exit here and return nil. This means no message will be delivered
×
UNCOV
1871
                // to the link.
×
UNCOV
1872
                return nil
×
UNCOV
1873
        }
×
UNCOV
1874
        defer sub.Cancel()
×
UNCOV
1875

×
UNCOV
1876
        // The link may already be active by this point, and we may have missed the
×
UNCOV
1877
        // ActiveLinkEvent. Check if the link exists.
×
UNCOV
1878
        link := p.fetchLinkFromKeyAndCid(cid)
×
UNCOV
1879
        if link != nil {
×
UNCOV
1880
                return link
×
UNCOV
1881
        }
×
1882

1883
        // If the link is nil, we must wait for it to be active.
UNCOV
1884
        for {
×
UNCOV
1885
                select {
×
1886
                // A new event has been sent by the ChannelNotifier. We first check
1887
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1888
                // that the event is for this channel. Otherwise, we discard the
1889
                // message.
UNCOV
1890
                case e := <-sub.Updates():
×
UNCOV
1891
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
×
UNCOV
1892
                        if !ok {
×
UNCOV
1893
                                // Ignore this notification.
×
UNCOV
1894
                                continue
×
1895
                        }
1896

UNCOV
1897
                        chanPoint := event.ChannelPoint
×
UNCOV
1898

×
UNCOV
1899
                        // Check whether the retrieved chanPoint matches the target
×
UNCOV
1900
                        // channel id.
×
UNCOV
1901
                        if !cid.IsChanPoint(chanPoint) {
×
1902
                                continue
×
1903
                        }
1904

1905
                        // The link shouldn't be nil as we received an
1906
                        // ActiveLinkEvent. If it is nil, we return nil and the
1907
                        // calling function should catch it.
UNCOV
1908
                        return p.fetchLinkFromKeyAndCid(cid)
×
1909

NEW
1910
                case <-p.cg.Done():
×
UNCOV
1911
                        return nil
×
1912
                }
1913
        }
1914
}
1915

1916
// newChanMsgStream is used to create a msgStream between the peer and
1917
// particular channel link in the htlcswitch. We utilize additional
1918
// synchronization with the fundingManager to ensure we don't attempt to
1919
// dispatch a message to a channel before it is fully active. A reference to the
1920
// channel this stream forwards to is held in scope to prevent unnecessary
1921
// lookups.
UNCOV
1922
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
×
UNCOV
1923
        var chanLink htlcswitch.ChannelUpdateHandler
×
UNCOV
1924

×
UNCOV
1925
        apply := func(msg lnwire.Message) {
×
UNCOV
1926
                // This check is fine because if the link no longer exists, it will
×
UNCOV
1927
                // be removed from the activeChannels map and subsequent messages
×
UNCOV
1928
                // shouldn't reach the chan msg stream.
×
UNCOV
1929
                if chanLink == nil {
×
UNCOV
1930
                        chanLink = waitUntilLinkActive(p, cid)
×
UNCOV
1931

×
UNCOV
1932
                        // If the link is still not active and the calling function
×
UNCOV
1933
                        // errored out, just return.
×
UNCOV
1934
                        if chanLink == nil {
×
UNCOV
1935
                                p.log.Warnf("Link=%v is not active", cid)
×
UNCOV
1936
                                return
×
UNCOV
1937
                        }
×
1938
                }
1939

1940
                // In order to avoid unnecessarily delivering message
1941
                // as the peer is exiting, we'll check quickly to see
1942
                // if we need to exit.
UNCOV
1943
                select {
×
NEW
1944
                case <-p.cg.Done():
×
1945
                        return
×
UNCOV
1946
                default:
×
1947
                }
1948

UNCOV
1949
                chanLink.HandleChannelUpdate(msg)
×
1950
        }
1951

UNCOV
1952
        return newMsgStream(p,
×
UNCOV
1953
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
×
UNCOV
1954
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
×
UNCOV
1955
                1000,
×
UNCOV
1956
                apply,
×
UNCOV
1957
        )
×
1958
}
1959

1960
// newDiscMsgStream is used to setup a msgStream between the peer and the
1961
// authenticated gossiper. This stream should be used to forward all remote
1962
// channel announcements.
1963
func newDiscMsgStream(p *Brontide) *msgStream {
3✔
1964
        apply := func(msg lnwire.Message) {
3✔
UNCOV
1965
                // TODO(yy): `ProcessRemoteAnnouncement` returns an error chan
×
UNCOV
1966
                // and we need to process it.
×
UNCOV
1967
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(msg, p)
×
UNCOV
1968
        }
×
1969

1970
        return newMsgStream(
3✔
1971
                p,
3✔
1972
                "Update stream for gossiper created",
3✔
1973
                "Update stream for gossiper exited",
3✔
1974
                1000,
3✔
1975
                apply,
3✔
1976
        )
3✔
1977
}
1978

1979
// readHandler is responsible for reading messages off the wire in series, then
1980
// properly dispatching the handling of the message to the proper subsystem.
1981
//
1982
// NOTE: This method MUST be run as a goroutine.
1983
func (p *Brontide) readHandler() {
3✔
1984
        defer p.cg.WgDone()
3✔
1985

3✔
1986
        // We'll stop the timer after a new messages is received, and also
3✔
1987
        // reset it after we process the next message.
3✔
1988
        idleTimer := time.AfterFunc(idleTimeout, func() {
3✔
1989
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
1990
                        p, idleTimeout)
×
1991
                p.Disconnect(err)
×
1992
        })
×
1993

1994
        // Initialize our negotiated gossip sync method before reading messages
1995
        // off the wire. When using gossip queries, this ensures a gossip
1996
        // syncer is active by the time query messages arrive.
1997
        //
1998
        // TODO(conner): have peer store gossip syncer directly and bypass
1999
        // gossiper?
2000
        p.initGossipSync()
3✔
2001

3✔
2002
        discStream := newDiscMsgStream(p)
3✔
2003
        discStream.Start()
3✔
2004
        defer discStream.Stop()
3✔
2005
out:
3✔
2006
        for atomic.LoadInt32(&p.disconnect) == 0 {
7✔
2007
                nextMsg, err := p.readNextMessage()
4✔
2008
                if !idleTimer.Stop() {
4✔
2009
                        select {
×
2010
                        case <-idleTimer.C:
×
2011
                        default:
×
2012
                        }
2013
                }
2014
                if err != nil {
1✔
UNCOV
2015
                        p.log.Infof("unable to read message from peer: %v", err)
×
UNCOV
2016

×
UNCOV
2017
                        // If we could not read our peer's message due to an
×
UNCOV
2018
                        // unknown type or invalid alias, we continue processing
×
UNCOV
2019
                        // as normal. We store unknown message and address
×
UNCOV
2020
                        // types, as they may provide debugging insight.
×
UNCOV
2021
                        switch e := err.(type) {
×
2022
                        // If this is just a message we don't yet recognize,
2023
                        // we'll continue processing as normal as this allows
2024
                        // us to introduce new messages in a forwards
2025
                        // compatible manner.
UNCOV
2026
                        case *lnwire.UnknownMessage:
×
UNCOV
2027
                                p.storeError(e)
×
UNCOV
2028
                                idleTimer.Reset(idleTimeout)
×
UNCOV
2029
                                continue
×
2030

2031
                        // If they sent us an address type that we don't yet
2032
                        // know of, then this isn't a wire error, so we'll
2033
                        // simply continue parsing the remainder of their
2034
                        // messages.
2035
                        case *lnwire.ErrUnknownAddrType:
×
2036
                                p.storeError(e)
×
2037
                                idleTimer.Reset(idleTimeout)
×
2038
                                continue
×
2039

2040
                        // If the NodeAnnouncement has an invalid alias, then
2041
                        // we'll log that error above and continue so we can
2042
                        // continue to read messages from the peer. We do not
2043
                        // store this error because it is of little debugging
2044
                        // value.
2045
                        case *lnwire.ErrInvalidNodeAlias:
×
2046
                                idleTimer.Reset(idleTimeout)
×
2047
                                continue
×
2048

2049
                        // If the error we encountered wasn't just a message we
2050
                        // didn't recognize, then we'll stop all processing as
2051
                        // this is a fatal error.
UNCOV
2052
                        default:
×
UNCOV
2053
                                break out
×
2054
                        }
2055
                }
2056

2057
                // If a message router is active, then we'll try to have it
2058
                // handle this message. If it can, then we're able to skip the
2059
                // rest of the message handling logic.
2060
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
2✔
2061
                        return r.RouteMsg(msgmux.PeerMsg{
1✔
2062
                                PeerPub: *p.IdentityKey(),
1✔
2063
                                Message: nextMsg,
1✔
2064
                        })
1✔
2065
                })
1✔
2066

2067
                // No error occurred, and the message was handled by the
2068
                // router.
2069
                if err == nil {
1✔
2070
                        continue
×
2071
                }
2072

2073
                var (
1✔
2074
                        targetChan   lnwire.ChannelID
1✔
2075
                        isLinkUpdate bool
1✔
2076
                )
1✔
2077

1✔
2078
                switch msg := nextMsg.(type) {
1✔
2079
                case *lnwire.Pong:
×
2080
                        // When we receive a Pong message in response to our
×
2081
                        // last ping message, we send it to the pingManager
×
2082
                        p.pingManager.ReceivedPong(msg)
×
2083

2084
                case *lnwire.Ping:
×
2085
                        // First, we'll store their latest ping payload within
×
2086
                        // the relevant atomic variable.
×
2087
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
2088

×
2089
                        // Next, we'll send over the amount of specified pong
×
2090
                        // bytes.
×
2091
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
×
2092
                        p.queueMsg(pong, nil)
×
2093

2094
                case *lnwire.OpenChannel,
2095
                        *lnwire.AcceptChannel,
2096
                        *lnwire.FundingCreated,
2097
                        *lnwire.FundingSigned,
UNCOV
2098
                        *lnwire.ChannelReady:
×
UNCOV
2099

×
UNCOV
2100
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
×
2101

UNCOV
2102
                case *lnwire.Shutdown:
×
UNCOV
2103
                        select {
×
UNCOV
2104
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
×
NEW
2105
                        case <-p.cg.Done():
×
2106
                                break out
×
2107
                        }
UNCOV
2108
                case *lnwire.ClosingSigned:
×
UNCOV
2109
                        select {
×
UNCOV
2110
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
×
NEW
2111
                        case <-p.cg.Done():
×
2112
                                break out
×
2113
                        }
2114

2115
                case *lnwire.Warning:
×
2116
                        targetChan = msg.ChanID
×
2117
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2118

UNCOV
2119
                case *lnwire.Error:
×
UNCOV
2120
                        targetChan = msg.ChanID
×
UNCOV
2121
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2122

UNCOV
2123
                case *lnwire.ChannelReestablish:
×
UNCOV
2124
                        targetChan = msg.ChanID
×
UNCOV
2125
                        isLinkUpdate = p.hasChannel(targetChan)
×
UNCOV
2126

×
UNCOV
2127
                        // If we failed to find the link in question, and the
×
UNCOV
2128
                        // message received was a channel sync message, then
×
UNCOV
2129
                        // this might be a peer trying to resync closed channel.
×
UNCOV
2130
                        // In this case we'll try to resend our last channel
×
UNCOV
2131
                        // sync message, such that the peer can recover funds
×
UNCOV
2132
                        // from the closed channel.
×
UNCOV
2133
                        if !isLinkUpdate {
×
UNCOV
2134
                                err := p.resendChanSyncMsg(targetChan)
×
UNCOV
2135
                                if err != nil {
×
UNCOV
2136
                                        // TODO(halseth): send error to peer?
×
UNCOV
2137
                                        p.log.Errorf("resend failed: %v",
×
UNCOV
2138
                                                err)
×
UNCOV
2139
                                }
×
2140
                        }
2141

2142
                // For messages that implement the LinkUpdater interface, we
2143
                // will consider them as link updates and send them to
2144
                // chanStream. These messages will be queued inside chanStream
2145
                // if the channel is not active yet.
UNCOV
2146
                case lnwire.LinkUpdater:
×
UNCOV
2147
                        targetChan = msg.TargetChanID()
×
UNCOV
2148
                        isLinkUpdate = p.hasChannel(targetChan)
×
UNCOV
2149

×
UNCOV
2150
                        // Log an error if we don't have this channel. This
×
UNCOV
2151
                        // means the peer has sent us a message with unknown
×
UNCOV
2152
                        // channel ID.
×
UNCOV
2153
                        if !isLinkUpdate {
×
UNCOV
2154
                                p.log.Errorf("Unknown channel ID: %v found "+
×
UNCOV
2155
                                        "in received msg=%s", targetChan,
×
UNCOV
2156
                                        nextMsg.MsgType())
×
UNCOV
2157
                        }
×
2158

2159
                case *lnwire.ChannelUpdate1,
2160
                        *lnwire.ChannelAnnouncement1,
2161
                        *lnwire.NodeAnnouncement,
2162
                        *lnwire.AnnounceSignatures1,
2163
                        *lnwire.GossipTimestampRange,
2164
                        *lnwire.QueryShortChanIDs,
2165
                        *lnwire.QueryChannelRange,
2166
                        *lnwire.ReplyChannelRange,
UNCOV
2167
                        *lnwire.ReplyShortChanIDsEnd:
×
UNCOV
2168

×
UNCOV
2169
                        discStream.AddMsg(msg)
×
2170

2171
                case *lnwire.Custom:
1✔
2172
                        err := p.handleCustomMessage(msg)
1✔
2173
                        if err != nil {
1✔
2174
                                p.storeError(err)
×
2175
                                p.log.Errorf("%v", err)
×
2176
                        }
×
2177

2178
                default:
×
2179
                        // If the message we received is unknown to us, store
×
2180
                        // the type to track the failure.
×
2181
                        err := fmt.Errorf("unknown message type %v received",
×
2182
                                uint16(msg.MsgType()))
×
2183
                        p.storeError(err)
×
2184

×
2185
                        p.log.Errorf("%v", err)
×
2186
                }
2187

2188
                if isLinkUpdate {
1✔
UNCOV
2189
                        // If this is a channel update, then we need to feed it
×
UNCOV
2190
                        // into the channel's in-order message stream.
×
UNCOV
2191
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
×
UNCOV
2192
                }
×
2193

2194
                idleTimer.Reset(idleTimeout)
1✔
2195
        }
2196

UNCOV
2197
        p.Disconnect(errors.New("read handler closed"))
×
UNCOV
2198

×
UNCOV
2199
        p.log.Trace("readHandler for peer done")
×
2200
}
2201

2202
// handleCustomMessage handles the given custom message if a handler is
2203
// registered.
2204
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
1✔
2205
        if p.cfg.HandleCustomMessage == nil {
1✔
2206
                return fmt.Errorf("no custom message handler for "+
×
2207
                        "message type %v", uint16(msg.MsgType()))
×
2208
        }
×
2209

2210
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
1✔
2211
}
2212

2213
// isLoadedFromDisk returns true if the provided channel ID is loaded from
2214
// disk.
2215
//
2216
// NOTE: only returns true for pending channels.
UNCOV
2217
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
×
UNCOV
2218
        // If this is a newly added channel, no need to reestablish.
×
UNCOV
2219
        _, added := p.addedChannels.Load(chanID)
×
UNCOV
2220
        if added {
×
UNCOV
2221
                return false
×
UNCOV
2222
        }
×
2223

2224
        // Return false if the channel is unknown.
UNCOV
2225
        channel, ok := p.activeChannels.Load(chanID)
×
UNCOV
2226
        if !ok {
×
2227
                return false
×
2228
        }
×
2229

2230
        // During startup, we will use a nil value to mark a pending channel
2231
        // that's loaded from disk.
UNCOV
2232
        return channel == nil
×
2233
}
2234

2235
// isActiveChannel returns true if the provided channel id is active, otherwise
2236
// returns false.
2237
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
8✔
2238
        // The channel would be nil if,
8✔
2239
        // - the channel doesn't exist, or,
8✔
2240
        // - the channel exists, but is pending. In this case, we don't
8✔
2241
        //   consider this channel active.
8✔
2242
        channel, _ := p.activeChannels.Load(chanID)
8✔
2243

8✔
2244
        return channel != nil
8✔
2245
}
8✔
2246

2247
// isPendingChannel returns true if the provided channel ID is pending, and
2248
// returns false if the channel is active or unknown.
2249
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
6✔
2250
        // Return false if the channel is unknown.
6✔
2251
        channel, ok := p.activeChannels.Load(chanID)
6✔
2252
        if !ok {
9✔
2253
                return false
3✔
2254
        }
3✔
2255

2256
        return channel == nil
3✔
2257
}
2258

2259
// hasChannel returns true if the peer has a pending/active channel specified
2260
// by the channel ID.
UNCOV
2261
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
×
UNCOV
2262
        _, ok := p.activeChannels.Load(chanID)
×
UNCOV
2263
        return ok
×
UNCOV
2264
}
×
2265

2266
// storeError stores an error in our peer's buffer of recent errors with the
2267
// current timestamp. Errors are only stored if we have at least one active
2268
// channel with the peer to mitigate a dos vector where a peer costlessly
2269
// connects to us and spams us with errors.
UNCOV
2270
func (p *Brontide) storeError(err error) {
×
UNCOV
2271
        var haveChannels bool
×
UNCOV
2272

×
UNCOV
2273
        p.activeChannels.Range(func(_ lnwire.ChannelID,
×
UNCOV
2274
                channel *lnwallet.LightningChannel) bool {
×
UNCOV
2275

×
UNCOV
2276
                // Pending channels will be nil in the activeChannels map.
×
UNCOV
2277
                if channel == nil {
×
UNCOV
2278
                        // Return true to continue the iteration.
×
UNCOV
2279
                        return true
×
UNCOV
2280
                }
×
2281

UNCOV
2282
                haveChannels = true
×
UNCOV
2283

×
UNCOV
2284
                // Return false to break the iteration.
×
UNCOV
2285
                return false
×
2286
        })
2287

2288
        // If we do not have any active channels with the peer, we do not store
2289
        // errors as a dos mitigation.
UNCOV
2290
        if !haveChannels {
×
UNCOV
2291
                p.log.Trace("no channels with peer, not storing err")
×
UNCOV
2292
                return
×
UNCOV
2293
        }
×
2294

UNCOV
2295
        p.cfg.ErrorBuffer.Add(
×
UNCOV
2296
                &TimestampedError{Timestamp: time.Now(), Error: err},
×
UNCOV
2297
        )
×
2298
}
2299

2300
// handleWarningOrError processes a warning or error msg and returns true if
2301
// msg should be forwarded to the associated channel link. False is returned if
2302
// any necessary forwarding of msg was already handled by this method. If msg is
2303
// an error from a peer with an active channel, we'll store it in memory.
2304
//
2305
// NOTE: This method should only be called from within the readHandler.
2306
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
UNCOV
2307
        msg lnwire.Message) bool {
×
UNCOV
2308

×
UNCOV
2309
        if errMsg, ok := msg.(*lnwire.Error); ok {
×
UNCOV
2310
                p.storeError(errMsg)
×
UNCOV
2311
        }
×
2312

UNCOV
2313
        switch {
×
2314
        // Connection wide messages should be forwarded to all channel links
2315
        // with this peer.
2316
        case chanID == lnwire.ConnectionWideID:
×
2317
                for _, chanStream := range p.activeMsgStreams {
×
2318
                        chanStream.AddMsg(msg)
×
2319
                }
×
2320

2321
                return false
×
2322

2323
        // If the channel ID for the message corresponds to a pending channel,
2324
        // then the funding manager will handle it.
UNCOV
2325
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
×
UNCOV
2326
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
×
UNCOV
2327
                return false
×
2328

2329
        // If not we hand the message to the channel link for this channel.
UNCOV
2330
        case p.isActiveChannel(chanID):
×
UNCOV
2331
                return true
×
2332

UNCOV
2333
        default:
×
UNCOV
2334
                return false
×
2335
        }
2336
}
2337

2338
// messageSummary returns a human-readable string that summarizes a
2339
// incoming/outgoing message. Not all messages will have a summary, only those
2340
// which have additional data that can be informative at a glance.
UNCOV
2341
func messageSummary(msg lnwire.Message) string {
×
UNCOV
2342
        switch msg := msg.(type) {
×
UNCOV
2343
        case *lnwire.Init:
×
UNCOV
2344
                // No summary.
×
UNCOV
2345
                return ""
×
2346

UNCOV
2347
        case *lnwire.OpenChannel:
×
UNCOV
2348
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
×
UNCOV
2349
                        "push_amt=%v, reserve=%v, flags=%v",
×
UNCOV
2350
                        msg.PendingChannelID[:], msg.ChainHash,
×
UNCOV
2351
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
×
UNCOV
2352
                        msg.ChannelReserve, msg.ChannelFlags)
×
2353

UNCOV
2354
        case *lnwire.AcceptChannel:
×
UNCOV
2355
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
×
UNCOV
2356
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
×
UNCOV
2357
                        msg.MinAcceptDepth)
×
2358

UNCOV
2359
        case *lnwire.FundingCreated:
×
UNCOV
2360
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
×
UNCOV
2361
                        msg.PendingChannelID[:], msg.FundingPoint)
×
2362

UNCOV
2363
        case *lnwire.FundingSigned:
×
UNCOV
2364
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
×
2365

UNCOV
2366
        case *lnwire.ChannelReady:
×
UNCOV
2367
                return fmt.Sprintf("chan_id=%v, next_point=%x",
×
UNCOV
2368
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
×
2369

UNCOV
2370
        case *lnwire.Shutdown:
×
UNCOV
2371
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
×
UNCOV
2372
                        msg.Address[:])
×
2373

2374
        case *lnwire.ClosingComplete:
×
2375
                return fmt.Sprintf("chan_id=%v, fee_sat=%v, locktime=%v",
×
2376
                        msg.ChannelID, msg.FeeSatoshis, msg.LockTime)
×
2377

2378
        case *lnwire.ClosingSig:
×
2379
                return fmt.Sprintf("chan_id=%v", msg.ChannelID)
×
2380

UNCOV
2381
        case *lnwire.ClosingSigned:
×
UNCOV
2382
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
×
UNCOV
2383
                        msg.FeeSatoshis)
×
2384

UNCOV
2385
        case *lnwire.UpdateAddHTLC:
×
UNCOV
2386
                var blindingPoint []byte
×
UNCOV
2387
                msg.BlindingPoint.WhenSome(
×
UNCOV
2388
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
×
UNCOV
2389
                                *btcec.PublicKey]) {
×
UNCOV
2390

×
UNCOV
2391
                                blindingPoint = b.Val.SerializeCompressed()
×
UNCOV
2392
                        },
×
2393
                )
2394

UNCOV
2395
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
×
UNCOV
2396
                        "hash=%x, blinding_point=%x, custom_records=%v",
×
UNCOV
2397
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
×
UNCOV
2398
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
×
2399

UNCOV
2400
        case *lnwire.UpdateFailHTLC:
×
UNCOV
2401
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
×
UNCOV
2402
                        msg.ID, msg.Reason)
×
2403

UNCOV
2404
        case *lnwire.UpdateFulfillHTLC:
×
UNCOV
2405
                return fmt.Sprintf("chan_id=%v, id=%v, pre_image=%x, "+
×
UNCOV
2406
                        "custom_records=%v", msg.ChanID, msg.ID,
×
UNCOV
2407
                        msg.PaymentPreimage[:], msg.CustomRecords)
×
2408

UNCOV
2409
        case *lnwire.CommitSig:
×
UNCOV
2410
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
×
UNCOV
2411
                        len(msg.HtlcSigs))
×
2412

UNCOV
2413
        case *lnwire.RevokeAndAck:
×
UNCOV
2414
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
×
UNCOV
2415
                        msg.ChanID, msg.Revocation[:],
×
UNCOV
2416
                        msg.NextRevocationKey.SerializeCompressed())
×
2417

UNCOV
2418
        case *lnwire.UpdateFailMalformedHTLC:
×
UNCOV
2419
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
×
UNCOV
2420
                        msg.ChanID, msg.ID, msg.FailureCode)
×
2421

2422
        case *lnwire.Warning:
×
2423
                return fmt.Sprintf("%v", msg.Warning())
×
2424

UNCOV
2425
        case *lnwire.Error:
×
UNCOV
2426
                return fmt.Sprintf("%v", msg.Error())
×
2427

UNCOV
2428
        case *lnwire.AnnounceSignatures1:
×
UNCOV
2429
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
×
UNCOV
2430
                        msg.ShortChannelID.ToUint64())
×
2431

UNCOV
2432
        case *lnwire.ChannelAnnouncement1:
×
UNCOV
2433
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
×
UNCOV
2434
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
×
2435

UNCOV
2436
        case *lnwire.ChannelUpdate1:
×
UNCOV
2437
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
×
UNCOV
2438
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
×
UNCOV
2439
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
×
UNCOV
2440
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
×
2441

UNCOV
2442
        case *lnwire.NodeAnnouncement:
×
UNCOV
2443
                return fmt.Sprintf("node=%x, update_time=%v",
×
UNCOV
2444
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
×
2445

2446
        case *lnwire.Ping:
×
2447
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
2448

2449
        case *lnwire.Pong:
×
2450
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
×
2451

2452
        case *lnwire.UpdateFee:
×
2453
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2454
                        msg.ChanID, int64(msg.FeePerKw))
×
2455

UNCOV
2456
        case *lnwire.ChannelReestablish:
×
UNCOV
2457
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
×
UNCOV
2458
                        "remote_tail_height=%v", msg.ChanID,
×
UNCOV
2459
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
×
2460

UNCOV
2461
        case *lnwire.ReplyShortChanIDsEnd:
×
UNCOV
2462
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
×
UNCOV
2463
                        msg.Complete)
×
2464

UNCOV
2465
        case *lnwire.ReplyChannelRange:
×
UNCOV
2466
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
×
UNCOV
2467
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
×
UNCOV
2468
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
×
UNCOV
2469
                        msg.EncodingType)
×
2470

UNCOV
2471
        case *lnwire.QueryShortChanIDs:
×
UNCOV
2472
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
×
UNCOV
2473
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
×
2474

UNCOV
2475
        case *lnwire.QueryChannelRange:
×
UNCOV
2476
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
×
UNCOV
2477
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
×
UNCOV
2478
                        msg.LastBlockHeight())
×
2479

UNCOV
2480
        case *lnwire.GossipTimestampRange:
×
UNCOV
2481
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
×
UNCOV
2482
                        "stamp_range=%v", msg.ChainHash,
×
UNCOV
2483
                        time.Unix(int64(msg.FirstTimestamp), 0),
×
UNCOV
2484
                        msg.TimestampRange)
×
2485

UNCOV
2486
        case *lnwire.Stfu:
×
UNCOV
2487
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
×
UNCOV
2488
                        msg.Initiator)
×
2489

UNCOV
2490
        case *lnwire.Custom:
×
UNCOV
2491
                return fmt.Sprintf("type=%d", msg.Type)
×
2492
        }
2493

2494
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2495
}
2496

2497
// logWireMessage logs the receipt or sending of particular wire message. This
2498
// function is used rather than just logging the message in order to produce
2499
// less spammy log messages in trace mode by setting the 'Curve" parameter to
2500
// nil. Doing this avoids printing out each of the field elements in the curve
2501
// parameters for secp256k1.
2502
func (p *Brontide) logWireMessage(msg lnwire.Message, read bool) {
17✔
2503
        summaryPrefix := "Received"
17✔
2504
        if !read {
30✔
2505
                summaryPrefix = "Sending"
13✔
2506
        }
13✔
2507

2508
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
17✔
UNCOV
2509
                // Debug summary of message.
×
UNCOV
2510
                summary := messageSummary(msg)
×
UNCOV
2511
                if len(summary) > 0 {
×
UNCOV
2512
                        summary = "(" + summary + ")"
×
UNCOV
2513
                }
×
2514

UNCOV
2515
                preposition := "to"
×
UNCOV
2516
                if read {
×
UNCOV
2517
                        preposition = "from"
×
UNCOV
2518
                }
×
2519

UNCOV
2520
                var msgType string
×
UNCOV
2521
                if msg.MsgType() < lnwire.CustomTypeStart {
×
UNCOV
2522
                        msgType = msg.MsgType().String()
×
UNCOV
2523
                } else {
×
UNCOV
2524
                        msgType = "custom"
×
UNCOV
2525
                }
×
2526

UNCOV
2527
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
×
UNCOV
2528
                        msgType, summary, preposition, p)
×
2529
        }))
2530

2531
        prefix := "readMessage from peer"
17✔
2532
        if !read {
30✔
2533
                prefix = "writeMessage to peer"
13✔
2534
        }
13✔
2535

2536
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
17✔
2537
}
2538

2539
// writeMessage writes and flushes the target lnwire.Message to the remote peer.
2540
// If the passed message is nil, this method will only try to flush an existing
2541
// message buffered on the connection. It is safe to call this method again
2542
// with a nil message iff a timeout error is returned. This will continue to
2543
// flush the pending message to the wire.
2544
//
2545
// NOTE:
2546
// Besides its usage in Start, this function should not be used elsewhere
2547
// except in writeHandler. If multiple goroutines call writeMessage at the same
2548
// time, panics can occur because WriteMessage and Flush don't use any locking
2549
// internally.
2550
func (p *Brontide) writeMessage(msg lnwire.Message) error {
13✔
2551
        // Only log the message on the first attempt.
13✔
2552
        if msg != nil {
26✔
2553
                p.logWireMessage(msg, false)
13✔
2554
        }
13✔
2555

2556
        noiseConn := p.cfg.Conn
13✔
2557

13✔
2558
        flushMsg := func() error {
26✔
2559
                // Ensure the write deadline is set before we attempt to send
13✔
2560
                // the message.
13✔
2561
                writeDeadline := time.Now().Add(
13✔
2562
                        p.scaleTimeout(writeMessageTimeout),
13✔
2563
                )
13✔
2564
                err := noiseConn.SetWriteDeadline(writeDeadline)
13✔
2565
                if err != nil {
13✔
2566
                        return err
×
2567
                }
×
2568

2569
                // Flush the pending message to the wire. If an error is
2570
                // encountered, e.g. write timeout, the number of bytes written
2571
                // so far will be returned.
2572
                n, err := noiseConn.Flush()
13✔
2573

13✔
2574
                // Record the number of bytes written on the wire, if any.
13✔
2575
                if n > 0 {
13✔
UNCOV
2576
                        atomic.AddUint64(&p.bytesSent, uint64(n))
×
UNCOV
2577
                }
×
2578

2579
                return err
13✔
2580
        }
2581

2582
        // If the current message has already been serialized, encrypted, and
2583
        // buffered on the underlying connection we will skip straight to
2584
        // flushing it to the wire.
2585
        if msg == nil {
13✔
2586
                return flushMsg()
×
2587
        }
×
2588

2589
        // Otherwise, this is a new message. We'll acquire a write buffer to
2590
        // serialize the message and buffer the ciphertext on the connection.
2591
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
26✔
2592
                // Using a buffer allocated by the write pool, encode the
13✔
2593
                // message directly into the buffer.
13✔
2594
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
13✔
2595
                if writeErr != nil {
13✔
2596
                        return writeErr
×
2597
                }
×
2598

2599
                // Finally, write the message itself in a single swoop. This
2600
                // will buffer the ciphertext on the underlying connection. We
2601
                // will defer flushing the message until the write pool has been
2602
                // released.
2603
                return noiseConn.WriteMessage(buf.Bytes())
13✔
2604
        })
2605
        if err != nil {
13✔
2606
                return err
×
2607
        }
×
2608

2609
        return flushMsg()
13✔
2610
}
2611

2612
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2613
// queue, and writing them out to the wire. This goroutine coordinates with the
2614
// queueHandler in order to ensure the incoming message queue is quickly
2615
// drained.
2616
//
2617
// NOTE: This method MUST be run as a goroutine.
2618
func (p *Brontide) writeHandler() {
3✔
2619
        // We'll stop the timer after a new messages is sent, and also reset it
3✔
2620
        // after we process the next message.
3✔
2621
        idleTimer := time.AfterFunc(idleTimeout, func() {
3✔
2622
                err := fmt.Errorf("peer %s no write for %s -- disconnecting",
×
2623
                        p, idleTimeout)
×
2624
                p.Disconnect(err)
×
2625
        })
×
2626

2627
        var exitErr error
3✔
2628

3✔
2629
out:
3✔
2630
        for {
10✔
2631
                select {
7✔
2632
                case outMsg := <-p.sendQueue:
4✔
2633
                        // Record the time at which we first attempt to send the
4✔
2634
                        // message.
4✔
2635
                        startTime := time.Now()
4✔
2636

4✔
2637
                retry:
4✔
2638
                        // Write out the message to the socket. If a timeout
2639
                        // error is encountered, we will catch this and retry
2640
                        // after backing off in case the remote peer is just
2641
                        // slow to process messages from the wire.
2642
                        err := p.writeMessage(outMsg.msg)
4✔
2643
                        if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
4✔
2644
                                p.log.Debugf("Write timeout detected for "+
×
2645
                                        "peer, first write for message "+
×
2646
                                        "attempted %v ago",
×
2647
                                        time.Since(startTime))
×
2648

×
2649
                                // If we received a timeout error, this implies
×
2650
                                // that the message was buffered on the
×
2651
                                // connection successfully and that a flush was
×
2652
                                // attempted. We'll set the message to nil so
×
2653
                                // that on a subsequent pass we only try to
×
2654
                                // flush the buffered message, and forgo
×
2655
                                // reserializing or reencrypting it.
×
2656
                                outMsg.msg = nil
×
2657

×
2658
                                goto retry
×
2659
                        }
2660

2661
                        // The write succeeded, reset the idle timer to prevent
2662
                        // us from disconnecting the peer.
2663
                        if !idleTimer.Stop() {
4✔
2664
                                select {
×
2665
                                case <-idleTimer.C:
×
2666
                                default:
×
2667
                                }
2668
                        }
2669
                        idleTimer.Reset(idleTimeout)
4✔
2670

4✔
2671
                        // If the peer requested a synchronous write, respond
4✔
2672
                        // with the error.
4✔
2673
                        if outMsg.errChan != nil {
5✔
2674
                                outMsg.errChan <- err
1✔
2675
                        }
1✔
2676

2677
                        if err != nil {
4✔
2678
                                exitErr = fmt.Errorf("unable to write "+
×
2679
                                        "message: %v", err)
×
2680
                                break out
×
2681
                        }
2682

NEW
2683
                case <-p.cg.Done():
×
UNCOV
2684
                        exitErr = lnpeer.ErrPeerExiting
×
UNCOV
2685
                        break out
×
2686
                }
2687
        }
2688

2689
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2690
        // disconnect.
NEW
2691
        p.cg.WgDone()
×
UNCOV
2692

×
UNCOV
2693
        p.Disconnect(exitErr)
×
UNCOV
2694

×
UNCOV
2695
        p.log.Trace("writeHandler for peer done")
×
2696
}
2697

2698
// queueHandler is responsible for accepting messages from outside subsystems
2699
// to be eventually sent out on the wire by the writeHandler.
2700
//
2701
// NOTE: This method MUST be run as a goroutine.
2702
func (p *Brontide) queueHandler() {
3✔
2703
        defer p.cg.WgDone()
3✔
2704

3✔
2705
        // priorityMsgs holds an in order list of messages deemed high-priority
3✔
2706
        // to be added to the sendQueue. This predominately includes messages
3✔
2707
        // from the funding manager and htlcswitch.
3✔
2708
        priorityMsgs := list.New()
3✔
2709

3✔
2710
        // lazyMsgs holds an in order list of messages deemed low-priority to be
3✔
2711
        // added to the sendQueue only after all high-priority messages have
3✔
2712
        // been queued. This predominately includes messages from the gossiper.
3✔
2713
        lazyMsgs := list.New()
3✔
2714

3✔
2715
        for {
14✔
2716
                // Examine the front of the priority queue, if it is empty check
11✔
2717
                // the low priority queue.
11✔
2718
                elem := priorityMsgs.Front()
11✔
2719
                if elem == nil {
19✔
2720
                        elem = lazyMsgs.Front()
8✔
2721
                }
8✔
2722

2723
                if elem != nil {
15✔
2724
                        front := elem.Value.(outgoingMsg)
4✔
2725

4✔
2726
                        // There's an element on the queue, try adding
4✔
2727
                        // it to the sendQueue. We also watch for
4✔
2728
                        // messages on the outgoingQueue, in case the
4✔
2729
                        // writeHandler cannot accept messages on the
4✔
2730
                        // sendQueue.
4✔
2731
                        select {
4✔
2732
                        case p.sendQueue <- front:
4✔
2733
                                if front.priority {
7✔
2734
                                        priorityMsgs.Remove(elem)
3✔
2735
                                } else {
4✔
2736
                                        lazyMsgs.Remove(elem)
1✔
2737
                                }
1✔
UNCOV
2738
                        case msg := <-p.outgoingQueue:
×
UNCOV
2739
                                if msg.priority {
×
UNCOV
2740
                                        priorityMsgs.PushBack(msg)
×
UNCOV
2741
                                } else {
×
UNCOV
2742
                                        lazyMsgs.PushBack(msg)
×
UNCOV
2743
                                }
×
NEW
2744
                        case <-p.cg.Done():
×
2745
                                return
×
2746
                        }
2747
                } else {
7✔
2748
                        // If there weren't any messages to send to the
7✔
2749
                        // writeHandler, then we'll accept a new message
7✔
2750
                        // into the queue from outside sub-systems.
7✔
2751
                        select {
7✔
2752
                        case msg := <-p.outgoingQueue:
4✔
2753
                                if msg.priority {
7✔
2754
                                        priorityMsgs.PushBack(msg)
3✔
2755
                                } else {
4✔
2756
                                        lazyMsgs.PushBack(msg)
1✔
2757
                                }
1✔
NEW
2758
                        case <-p.cg.Done():
×
UNCOV
2759
                                return
×
2760
                        }
2761
                }
2762
        }
2763
}
2764

2765
// PingTime returns the estimated ping time to the peer in microseconds.
UNCOV
2766
func (p *Brontide) PingTime() int64 {
×
UNCOV
2767
        return p.pingManager.GetPingTimeMicroSeconds()
×
UNCOV
2768
}
×
2769

2770
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2771
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2772
// or failed to write, and nil otherwise.
2773
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
25✔
2774
        p.queue(true, msg, errChan)
25✔
2775
}
25✔
2776

2777
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2778
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2779
// queue or failed to write, and nil otherwise.
2780
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
1✔
2781
        p.queue(false, msg, errChan)
1✔
2782
}
1✔
2783

2784
// queue sends a given message to the queueHandler using the passed priority. If
2785
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2786
// failed to write, and nil otherwise.
2787
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2788
        errChan chan error) {
26✔
2789

26✔
2790
        select {
26✔
2791
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
25✔
NEW
2792
        case <-p.cg.Done():
×
2793
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
×
2794
                        spew.Sdump(msg))
×
2795
                if errChan != nil {
×
2796
                        errChan <- lnpeer.ErrPeerExiting
×
2797
                }
×
2798
        }
2799
}
2800

2801
// ChannelSnapshots returns a slice of channel snapshots detailing all
2802
// currently active channels maintained with the remote peer.
UNCOV
2803
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
×
UNCOV
2804
        snapshots := make(
×
UNCOV
2805
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
×
UNCOV
2806
        )
×
UNCOV
2807

×
UNCOV
2808
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
×
UNCOV
2809
                activeChan *lnwallet.LightningChannel) error {
×
UNCOV
2810

×
UNCOV
2811
                // If the activeChan is nil, then we skip it as the channel is
×
UNCOV
2812
                // pending.
×
UNCOV
2813
                if activeChan == nil {
×
UNCOV
2814
                        return nil
×
UNCOV
2815
                }
×
2816

2817
                // We'll only return a snapshot for channels that are
2818
                // *immediately* available for routing payments over.
UNCOV
2819
                if activeChan.RemoteNextRevocation() == nil {
×
UNCOV
2820
                        return nil
×
UNCOV
2821
                }
×
2822

UNCOV
2823
                snapshot := activeChan.StateSnapshot()
×
UNCOV
2824
                snapshots = append(snapshots, snapshot)
×
UNCOV
2825

×
UNCOV
2826
                return nil
×
2827
        })
2828

UNCOV
2829
        return snapshots
×
2830
}
2831

2832
// genDeliveryScript returns a new script to be used to send our funds to in
2833
// the case of a cooperative channel close negotiation.
2834
func (p *Brontide) genDeliveryScript() ([]byte, error) {
6✔
2835
        // We'll send a normal p2wkh address unless we've negotiated the
6✔
2836
        // shutdown-any-segwit feature.
6✔
2837
        addrType := lnwallet.WitnessPubKey
6✔
2838
        if p.taprootShutdownAllowed() {
6✔
UNCOV
2839
                addrType = lnwallet.TaprootPubkey
×
UNCOV
2840
        }
×
2841

2842
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
6✔
2843
                addrType, false, lnwallet.DefaultAccountName,
6✔
2844
        )
6✔
2845
        if err != nil {
6✔
2846
                return nil, err
×
2847
        }
×
2848
        p.log.Infof("Delivery addr for channel close: %v",
6✔
2849
                deliveryAddr)
6✔
2850

6✔
2851
        return txscript.PayToAddrScript(deliveryAddr)
6✔
2852
}
2853

2854
// channelManager is goroutine dedicated to handling all requests/signals
2855
// pertaining to the opening, cooperative closing, and force closing of all
2856
// channels maintained with the remote peer.
2857
//
2858
// NOTE: This method MUST be run as a goroutine.
2859
func (p *Brontide) channelManager() {
17✔
2860
        defer p.cg.WgDone()
17✔
2861

17✔
2862
        // reenableTimeout will fire once after the configured channel status
17✔
2863
        // interval has elapsed. This will trigger us to sign new channel
17✔
2864
        // updates and broadcast them with the "disabled" flag unset.
17✔
2865
        reenableTimeout := time.After(p.cfg.ChanActiveTimeout)
17✔
2866

17✔
2867
out:
17✔
2868
        for {
55✔
2869
                select {
38✔
2870
                // A new pending channel has arrived which means we are about
2871
                // to complete a funding workflow and is waiting for the final
2872
                // `ChannelReady` messages to be exchanged. We will add this
2873
                // channel to the `activeChannels` with a nil value to indicate
2874
                // this is a pending channel.
2875
                case req := <-p.newPendingChannel:
1✔
2876
                        p.handleNewPendingChannel(req)
1✔
2877

2878
                // A new channel has arrived which means we've just completed a
2879
                // funding workflow. We'll initialize the necessary local
2880
                // state, and notify the htlc switch of a new link.
UNCOV
2881
                case req := <-p.newActiveChannel:
×
UNCOV
2882
                        p.handleNewActiveChannel(req)
×
2883

2884
                // The funding flow for a pending channel is failed, we will
2885
                // remove it from Brontide.
2886
                case req := <-p.removePendingChannel:
1✔
2887
                        p.handleRemovePendingChannel(req)
1✔
2888

2889
                // We've just received a local request to close an active
2890
                // channel. It will either kick of a cooperative channel
2891
                // closure negotiation, or be a notification of a breached
2892
                // contract that should be abandoned.
2893
                case req := <-p.localCloseChanReqs:
7✔
2894
                        p.handleLocalCloseReq(req)
7✔
2895

2896
                // We've received a link failure from a link that was added to
2897
                // the switch. This will initiate the teardown of the link, and
2898
                // initiate any on-chain closures if necessary.
UNCOV
2899
                case failure := <-p.linkFailures:
×
UNCOV
2900
                        p.handleLinkFailure(failure)
×
2901

2902
                // We've received a new cooperative channel closure related
2903
                // message from the remote peer, we'll use this message to
2904
                // advance the chan closer state machine.
2905
                case closeMsg := <-p.chanCloseMsgs:
13✔
2906
                        p.handleCloseMsg(closeMsg)
13✔
2907

2908
                // The channel reannounce delay has elapsed, broadcast the
2909
                // reenabled channel updates to the network. This should only
2910
                // fire once, so we set the reenableTimeout channel to nil to
2911
                // mark it for garbage collection. If the peer is torn down
2912
                // before firing, reenabling will not be attempted.
2913
                // TODO(conner): consolidate reenables timers inside chan status
2914
                // manager
UNCOV
2915
                case <-reenableTimeout:
×
UNCOV
2916
                        p.reenableActiveChannels()
×
UNCOV
2917

×
UNCOV
2918
                        // Since this channel will never fire again during the
×
UNCOV
2919
                        // lifecycle of the peer, we nil the channel to mark it
×
UNCOV
2920
                        // eligible for garbage collection, and make this
×
UNCOV
2921
                        // explicitly ineligible to receive in future calls to
×
UNCOV
2922
                        // select. This also shaves a few CPU cycles since the
×
UNCOV
2923
                        // select will ignore this case entirely.
×
UNCOV
2924
                        reenableTimeout = nil
×
UNCOV
2925

×
UNCOV
2926
                        // Once the reenabling is attempted, we also cancel the
×
UNCOV
2927
                        // channel event subscription to free up the overflow
×
UNCOV
2928
                        // queue used in channel notifier.
×
UNCOV
2929
                        //
×
UNCOV
2930
                        // NOTE: channelEventClient will be nil if the
×
UNCOV
2931
                        // reenableTimeout is greater than 1 minute.
×
UNCOV
2932
                        if p.channelEventClient != nil {
×
UNCOV
2933
                                p.channelEventClient.Cancel()
×
UNCOV
2934
                        }
×
2935

NEW
2936
                case <-p.cg.Done():
×
UNCOV
2937
                        // As, we've been signalled to exit, we'll reset all
×
UNCOV
2938
                        // our active channel back to their default state.
×
UNCOV
2939
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
×
UNCOV
2940
                                lc *lnwallet.LightningChannel) error {
×
UNCOV
2941

×
UNCOV
2942
                                // Exit if the channel is nil as it's a pending
×
UNCOV
2943
                                // channel.
×
UNCOV
2944
                                if lc == nil {
×
UNCOV
2945
                                        return nil
×
UNCOV
2946
                                }
×
2947

UNCOV
2948
                                lc.ResetState()
×
UNCOV
2949

×
UNCOV
2950
                                return nil
×
2951
                        })
2952

UNCOV
2953
                        break out
×
2954
                }
2955
        }
2956
}
2957

2958
// reenableActiveChannels searches the index of channels maintained with this
2959
// peer, and reenables each public, non-pending channel. This is done at the
2960
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
2961
// No message will be sent if the channel is already enabled.
UNCOV
2962
func (p *Brontide) reenableActiveChannels() {
×
UNCOV
2963
        // First, filter all known channels with this peer for ones that are
×
UNCOV
2964
        // both public and not pending.
×
UNCOV
2965
        activePublicChans := p.filterChannelsToEnable()
×
UNCOV
2966

×
UNCOV
2967
        // Create a map to hold channels that needs to be retried.
×
UNCOV
2968
        retryChans := make(map[wire.OutPoint]struct{}, len(activePublicChans))
×
UNCOV
2969

×
UNCOV
2970
        // For each of the public, non-pending channels, set the channel
×
UNCOV
2971
        // disabled bit to false and send out a new ChannelUpdate. If this
×
UNCOV
2972
        // channel is already active, the update won't be sent.
×
UNCOV
2973
        for _, chanPoint := range activePublicChans {
×
UNCOV
2974
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
UNCOV
2975

×
UNCOV
2976
                switch {
×
2977
                // No error occurred, continue to request the next channel.
UNCOV
2978
                case err == nil:
×
UNCOV
2979
                        continue
×
2980

2981
                // Cannot auto enable a manually disabled channel so we do
2982
                // nothing but proceed to the next channel.
UNCOV
2983
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
×
UNCOV
2984
                        p.log.Debugf("Channel(%v) was manually disabled, "+
×
UNCOV
2985
                                "ignoring automatic enable request", chanPoint)
×
UNCOV
2986

×
UNCOV
2987
                        continue
×
2988

2989
                // If the channel is reported as inactive, we will give it
2990
                // another chance. When handling the request, ChanStatusManager
2991
                // will check whether the link is active or not. One of the
2992
                // conditions is whether the link has been marked as
2993
                // reestablished, which happens inside a goroutine(htlcManager)
2994
                // after the link is started. And we may get a false negative
2995
                // saying the link is not active because that goroutine hasn't
2996
                // reached the line to mark the reestablishment. Thus we give
2997
                // it a second chance to send the request.
2998
                case errors.Is(err, netann.ErrEnableInactiveChan):
×
2999
                        // If we don't have a client created, it means we
×
3000
                        // shouldn't retry enabling the channel.
×
3001
                        if p.channelEventClient == nil {
×
3002
                                p.log.Errorf("Channel(%v) request enabling "+
×
3003
                                        "failed due to inactive link",
×
3004
                                        chanPoint)
×
3005

×
3006
                                continue
×
3007
                        }
3008

3009
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
3010
                                "ChanStatusManager reported inactive, retrying")
×
3011

×
3012
                        // Add the channel to the retry map.
×
3013
                        retryChans[chanPoint] = struct{}{}
×
3014
                }
3015
        }
3016

3017
        // Retry the channels if we have any.
UNCOV
3018
        if len(retryChans) != 0 {
×
3019
                p.retryRequestEnable(retryChans)
×
3020
        }
×
3021
}
3022

3023
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
3024
// for the target channel ID. If the channel isn't active an error is returned.
3025
// Otherwise, either an existing state machine will be returned, or a new one
3026
// will be created.
3027
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
3028
        *chanCloserFsm, error) {
13✔
3029

13✔
3030
        chanCloser, found := p.activeChanCloses.Load(chanID)
13✔
3031
        if found {
23✔
3032
                // An entry will only be found if the closer has already been
10✔
3033
                // created for a non-pending channel or for a channel that had
10✔
3034
                // previously started the shutdown process but the connection
10✔
3035
                // was restarted.
10✔
3036
                return &chanCloser, nil
10✔
3037
        }
10✔
3038

3039
        // First, we'll ensure that we actually know of the target channel. If
3040
        // not, we'll ignore this message.
3041
        channel, ok := p.activeChannels.Load(chanID)
3✔
3042

3✔
3043
        // If the channel isn't in the map or the channel is nil, return
3✔
3044
        // ErrChannelNotFound as the channel is pending.
3✔
3045
        if !ok || channel == nil {
3✔
UNCOV
3046
                return nil, ErrChannelNotFound
×
UNCOV
3047
        }
×
3048

3049
        // We'll create a valid closing state machine in order to respond to
3050
        // the initiated cooperative channel closure. First, we set the
3051
        // delivery script that our funds will be paid out to. If an upfront
3052
        // shutdown script was set, we will use it. Otherwise, we get a fresh
3053
        // delivery script.
3054
        //
3055
        // TODO: Expose option to allow upfront shutdown script from watch-only
3056
        // accounts.
3057
        deliveryScript := channel.LocalUpfrontShutdownScript()
3✔
3058
        if len(deliveryScript) == 0 {
6✔
3059
                var err error
3✔
3060
                deliveryScript, err = p.genDeliveryScript()
3✔
3061
                if err != nil {
3✔
3062
                        p.log.Errorf("unable to gen delivery script: %v",
×
3063
                                err)
×
3064
                        return nil, fmt.Errorf("close addr unavailable")
×
3065
                }
×
3066
        }
3067

3068
        // In order to begin fee negotiations, we'll first compute our target
3069
        // ideal fee-per-kw.
3070
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
3071
                p.cfg.CoopCloseTargetConfs,
3✔
3072
        )
3✔
3073
        if err != nil {
3✔
3074
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3075
                return nil, fmt.Errorf("unable to estimate fee")
×
3076
        }
×
3077

3078
        addr, err := p.addrWithInternalKey(deliveryScript)
3✔
3079
        if err != nil {
3✔
3080
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3081
        }
×
3082
        negotiateChanCloser, err := p.createChanCloser(
3✔
3083
                channel, addr, feePerKw, nil, lntypes.Remote,
3✔
3084
        )
3✔
3085
        if err != nil {
3✔
3086
                p.log.Errorf("unable to create chan closer: %v", err)
×
3087
                return nil, fmt.Errorf("unable to create chan closer")
×
3088
        }
×
3089

3090
        chanCloser = makeNegotiateCloser(negotiateChanCloser)
3✔
3091

3✔
3092
        p.activeChanCloses.Store(chanID, chanCloser)
3✔
3093

3✔
3094
        return &chanCloser, nil
3✔
3095
}
3096

3097
// filterChannelsToEnable filters a list of channels to be enabled upon start.
3098
// The filtered channels are active channels that's neither private nor
3099
// pending.
UNCOV
3100
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
×
UNCOV
3101
        var activePublicChans []wire.OutPoint
×
UNCOV
3102

×
UNCOV
3103
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
×
UNCOV
3104
                lnChan *lnwallet.LightningChannel) bool {
×
UNCOV
3105

×
UNCOV
3106
                // If the lnChan is nil, continue as this is a pending channel.
×
UNCOV
3107
                if lnChan == nil {
×
UNCOV
3108
                        return true
×
UNCOV
3109
                }
×
3110

UNCOV
3111
                dbChan := lnChan.State()
×
UNCOV
3112
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
×
UNCOV
3113
                if !isPublic || dbChan.IsPending {
×
3114
                        return true
×
3115
                }
×
3116

3117
                // We'll also skip any channels added during this peer's
3118
                // lifecycle since they haven't waited out the timeout. Their
3119
                // first announcement will be enabled, and the chan status
3120
                // manager will begin monitoring them passively since they exist
3121
                // in the database.
UNCOV
3122
                if _, ok := p.addedChannels.Load(chanID); ok {
×
UNCOV
3123
                        return true
×
UNCOV
3124
                }
×
3125

UNCOV
3126
                activePublicChans = append(
×
UNCOV
3127
                        activePublicChans, dbChan.FundingOutpoint,
×
UNCOV
3128
                )
×
UNCOV
3129

×
UNCOV
3130
                return true
×
3131
        })
3132

UNCOV
3133
        return activePublicChans
×
3134
}
3135

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

×
3143
        // retryEnable is a helper closure that sends an enable request and
×
3144
        // removes the channel from the map if it's matched.
×
3145
        retryEnable := func(chanPoint wire.OutPoint) error {
×
3146
                // If this is an active channel event, check whether it's in
×
3147
                // our targeted channels map.
×
3148
                _, found := activeChans[chanPoint]
×
3149

×
3150
                // If this channel is irrelevant, return nil so the loop can
×
3151
                // jump to next iteration.
×
3152
                if !found {
×
3153
                        return nil
×
3154
                }
×
3155

3156
                // Otherwise we've just received an active signal for a channel
3157
                // that's previously failed to be enabled, we send the request
3158
                // again.
3159
                //
3160
                // We only give the channel one more shot, so we delete it from
3161
                // our map first to keep it from being attempted again.
3162
                delete(activeChans, chanPoint)
×
3163

×
3164
                // Send the request.
×
3165
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3166
                if err != nil {
×
3167
                        return fmt.Errorf("request enabling channel %v "+
×
3168
                                "failed: %w", chanPoint, err)
×
3169
                }
×
3170

3171
                return nil
×
3172
        }
3173

3174
        for {
×
3175
                // If activeChans is empty, we've done processing all the
×
3176
                // channels.
×
3177
                if len(activeChans) == 0 {
×
3178
                        p.log.Debug("Finished retry enabling channels")
×
3179
                        return
×
3180
                }
×
3181

3182
                select {
×
3183
                // A new event has been sent by the ChannelNotifier. We now
3184
                // check whether it's an active or inactive channel event.
3185
                case e := <-p.channelEventClient.Updates():
×
3186
                        // If this is an active channel event, try enable the
×
3187
                        // channel then jump to the next iteration.
×
3188
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
3189
                        if ok {
×
3190
                                chanPoint := *active.ChannelPoint
×
3191

×
3192
                                // If we received an error for this particular
×
3193
                                // channel, we log an error and won't quit as
×
3194
                                // we still want to retry other channels.
×
3195
                                if err := retryEnable(chanPoint); err != nil {
×
3196
                                        p.log.Errorf("Retry failed: %v", err)
×
3197
                                }
×
3198

3199
                                continue
×
3200
                        }
3201

3202
                        // Otherwise check for inactive link event, and jump to
3203
                        // next iteration if it's not.
3204
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3205
                        if !ok {
×
3206
                                continue
×
3207
                        }
3208

3209
                        // Found an inactive link event, if this is our
3210
                        // targeted channel, remove it from our map.
3211
                        chanPoint := *inactive.ChannelPoint
×
3212
                        _, found := activeChans[chanPoint]
×
3213
                        if !found {
×
3214
                                continue
×
3215
                        }
3216

3217
                        delete(activeChans, chanPoint)
×
3218
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3219
                                "inactive link event", chanPoint)
×
3220

NEW
3221
                case <-p.cg.Done():
×
3222
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3223
                        return
×
3224
                }
3225
        }
3226
}
3227

3228
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3229
// a suitable script to close out to. This may be nil if neither script is
3230
// set. If both scripts are set, this function will error if they do not match.
3231
func chooseDeliveryScript(upfront, requested lnwire.DeliveryAddress,
3232
        genDeliveryScript func() ([]byte, error),
3233
) (lnwire.DeliveryAddress, error) {
12✔
3234

12✔
3235
        switch {
12✔
3236
        // If no script was provided, then we'll generate a new delivery script.
3237
        case len(upfront) == 0 && len(requested) == 0:
4✔
3238
                return genDeliveryScript()
4✔
3239

3240
        // If no upfront shutdown script was provided, return the user
3241
        // requested address (which may be nil).
3242
        case len(upfront) == 0:
2✔
3243
                return requested, nil
2✔
3244

3245
        // If an upfront shutdown script was provided, and the user did not
3246
        // request a custom shutdown script, return the upfront address.
3247
        case len(requested) == 0:
2✔
3248
                return upfront, nil
2✔
3249

3250
        // If both an upfront shutdown script and a custom close script were
3251
        // provided, error if the user provided shutdown script does not match
3252
        // the upfront shutdown script (because closing out to a different
3253
        // script would violate upfront shutdown).
3254
        case !bytes.Equal(upfront, requested):
2✔
3255
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
3256

3257
        // The user requested script matches the upfront shutdown script, so we
3258
        // can return it without error.
3259
        default:
2✔
3260
                return upfront, nil
2✔
3261
        }
3262
}
3263

3264
// restartCoopClose checks whether we need to restart the cooperative close
3265
// process for a given channel.
3266
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3267
        *lnwire.Shutdown, error) {
×
3268

×
3269
        // If this channel has status ChanStatusCoopBroadcasted and does not
×
3270
        // have a closing transaction, then the cooperative close process was
×
3271
        // started but never finished. We'll re-create the chanCloser state
×
3272
        // machine and resend Shutdown. BOLT#2 requires that we retransmit
×
3273
        // Shutdown exactly, but doing so would mean persisting the RPC
×
3274
        // provided close script. Instead use the LocalUpfrontShutdownScript
×
3275
        // or generate a script.
×
3276
        c := lnChan.State()
×
3277
        _, err := c.BroadcastedCooperative()
×
3278
        if err != nil && err != channeldb.ErrNoCloseTx {
×
3279
                // An error other than ErrNoCloseTx was encountered.
×
3280
                return nil, err
×
NEW
3281
        } else if err == nil && !p.rbfCoopCloseAllowed() {
×
NEW
3282
                // This is a channel that doesn't support RBF coop close, and it
×
NEW
3283
                // already had a coop close txn broadcast. As a result, we can
×
NEW
3284
                // just exit here as all we can do is wait for it to confirm.
×
3285
                return nil, nil
×
3286
        }
×
3287

NEW
3288
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
×
NEW
3289

×
3290
        var deliveryScript []byte
×
3291

×
3292
        shutdownInfo, err := c.ShutdownInfo()
×
3293
        switch {
×
3294
        // We have previously stored the delivery script that we need to use
3295
        // in the shutdown message. Re-use this script.
3296
        case err == nil:
×
3297
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
×
3298
                        deliveryScript = info.DeliveryScript.Val
×
3299
                })
×
3300

3301
        // An error other than ErrNoShutdownInfo was returned
3302
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3303
                return nil, err
×
3304

3305
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3306
                deliveryScript = c.LocalShutdownScript
×
3307
                if len(deliveryScript) == 0 {
×
3308
                        var err error
×
3309
                        deliveryScript, err = p.genDeliveryScript()
×
3310
                        if err != nil {
×
3311
                                p.log.Errorf("unable to gen delivery script: "+
×
3312
                                        "%v", err)
×
3313

×
3314
                                return nil, fmt.Errorf("close addr unavailable")
×
3315
                        }
×
3316
                }
3317
        }
3318

3319
        // If the new RBF co-op close is negotiated, then we'll init and start
3320
        // that state machine, skipping the steps for the negotiate machine
3321
        // below.
NEW
3322
        if p.rbfCoopCloseAllowed() {
×
NEW
3323
                _, err := p.initRbfChanCloser(lnChan)
×
NEW
3324
                if err != nil {
×
NEW
3325
                        return nil, fmt.Errorf("unable to init rbf chan "+
×
NEW
3326
                                "closer during restart: %w", err)
×
NEW
3327
                }
×
3328

NEW
3329
                shutdownDesc := fn.MapOption(
×
NEW
3330
                        newRestartShutdownInit,
×
NEW
3331
                )(shutdownInfo)
×
NEW
3332

×
NEW
3333
                err = p.startRbfChanCloser(
×
NEW
3334
                        fn.FlattenOption(shutdownDesc), lnChan.ChannelPoint(),
×
NEW
3335
                )
×
NEW
3336

×
NEW
3337
                return nil, err
×
3338
        }
3339

3340
        // Compute an ideal fee.
3341
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
3342
                p.cfg.CoopCloseTargetConfs,
×
3343
        )
×
3344
        if err != nil {
×
3345
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3346
                return nil, fmt.Errorf("unable to estimate fee")
×
3347
        }
×
3348

3349
        // Determine whether we or the peer are the initiator of the coop
3350
        // close attempt by looking at the channel's status.
3351
        closingParty := lntypes.Remote
×
3352
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3353
                closingParty = lntypes.Local
×
3354
        }
×
3355

3356
        addr, err := p.addrWithInternalKey(deliveryScript)
×
3357
        if err != nil {
×
3358
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3359
        }
×
3360
        chanCloser, err := p.createChanCloser(
×
3361
                lnChan, addr, feePerKw, nil, closingParty,
×
3362
        )
×
3363
        if err != nil {
×
3364
                p.log.Errorf("unable to create chan closer: %v", err)
×
3365
                return nil, fmt.Errorf("unable to create chan closer")
×
3366
        }
×
3367

NEW
3368
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
×
UNCOV
3369

×
3370
        // Create the Shutdown message.
×
3371
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3372
        if err != nil {
×
3373
                p.log.Errorf("unable to create shutdown message: %v", err)
×
NEW
3374
                p.activeChanCloses.Delete(chanID)
×
3375
                return nil, err
×
3376
        }
×
3377

3378
        return shutdownMsg, nil
×
3379
}
3380

3381
// createChanCloser constructs a ChanCloser from the passed parameters and is
3382
// used to de-duplicate code.
3383
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3384
        deliveryScript *chancloser.DeliveryAddrWithKey,
3385
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3386
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
9✔
3387

9✔
3388
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
9✔
3389
        if err != nil {
9✔
3390
                p.log.Errorf("unable to obtain best block: %v", err)
×
3391
                return nil, fmt.Errorf("cannot obtain best block")
×
3392
        }
×
3393

3394
        // The req will only be set if we initiated the co-op closing flow.
3395
        var maxFee chainfee.SatPerKWeight
9✔
3396
        if req != nil {
15✔
3397
                maxFee = req.MaxFee
6✔
3398
        }
6✔
3399

3400
        chanCloser := chancloser.NewChanCloser(
9✔
3401
                chancloser.ChanCloseCfg{
9✔
3402
                        Channel:      channel,
9✔
3403
                        MusigSession: NewMusigChanCloser(channel),
9✔
3404
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
9✔
3405
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
9✔
3406
                        AuxCloser:    p.cfg.AuxChanCloser,
9✔
3407
                        DisableChannel: func(op wire.OutPoint) error {
18✔
3408
                                return p.cfg.ChanStatusMgr.RequestDisable(
9✔
3409
                                        op, false,
9✔
3410
                                )
9✔
3411
                        },
9✔
3412
                        MaxFee: maxFee,
3413
                        Disconnect: func() error {
×
3414
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
3415
                        },
×
3416
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3417
                },
3418
                *deliveryScript,
3419
                fee,
3420
                uint32(startingHeight),
3421
                req,
3422
                closer,
3423
        )
3424

3425
        return chanCloser, nil
9✔
3426
}
3427

3428
// initNegotiateChanCloser initializes the channel closer for a channel that is
3429
// using the original "negotiation" based protocol. This path is used when
3430
// we're the one initiating the channel close.
3431
//
3432
// TODO(roasbeef): can make a MsgEndpoint for existing handling logic to
3433
// further abstract.
3434
func (p *Brontide) initNegotiateChanCloser(req *htlcswitch.ChanClose,
3435
        channel *lnwallet.LightningChannel) error {
7✔
3436

7✔
3437
        // First, we'll choose a delivery address that we'll use to send the
7✔
3438
        // funds to in the case of a successful negotiation.
7✔
3439

7✔
3440
        // An upfront shutdown and user provided script are both optional, but
7✔
3441
        // must be equal if both set  (because we cannot serve a request to
7✔
3442
        // close out to a script which violates upfront shutdown). Get the
7✔
3443
        // appropriate address to close out to (which may be nil if neither are
7✔
3444
        // set) and error if they are both set and do not match.
7✔
3445
        deliveryScript, err := chooseDeliveryScript(
7✔
3446
                channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
7✔
3447
                p.genDeliveryScript,
7✔
3448
        )
7✔
3449
        if err != nil {
8✔
3450
                return fmt.Errorf("cannot obtain delivery script: %w", err)
1✔
3451
        }
1✔
3452

3453
        addr, err := p.addrWithInternalKey(deliveryScript)
6✔
3454
        if err != nil {
6✔
NEW
3455
                return fmt.Errorf("unable to parse addr for channel "+
×
NEW
3456
                        "%v: %w", req.ChanPoint, err)
×
NEW
3457
        }
×
3458

3459
        chanCloser, err := p.createChanCloser(
6✔
3460
                channel, addr, req.TargetFeePerKw, req, lntypes.Local,
6✔
3461
        )
6✔
3462
        if err != nil {
6✔
NEW
3463
                return fmt.Errorf("unable to make chan closer: %w", err)
×
NEW
3464
        }
×
3465

3466
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
6✔
3467
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
6✔
3468

6✔
3469
        // Finally, we'll initiate the channel shutdown within the
6✔
3470
        // chanCloser, and send the shutdown message to the remote
6✔
3471
        // party to kick things off.
6✔
3472
        shutdownMsg, err := chanCloser.ShutdownChan()
6✔
3473
        if err != nil {
6✔
NEW
3474
                // As we were unable to shutdown the channel, we'll return it
×
NEW
3475
                // back to its normal state.
×
NEW
3476
                defer channel.ResetState()
×
NEW
3477

×
NEW
3478
                p.activeChanCloses.Delete(chanID)
×
NEW
3479

×
NEW
3480
                return fmt.Errorf("unable to shutdown channel: %w", err)
×
NEW
3481
        }
×
3482

3483
        link := p.fetchLinkFromKeyAndCid(chanID)
6✔
3484
        if link == nil {
6✔
NEW
3485
                // If the link is nil then it means it was already removed from
×
NEW
3486
                // the switch or it never existed in the first place. The
×
NEW
3487
                // latter case is handled at the beginning of this function, so
×
NEW
3488
                // in the case where it has already been removed, we can skip
×
NEW
3489
                // adding the commit hook to queue a Shutdown message.
×
NEW
3490
                p.log.Warnf("link not found during attempted closure: "+
×
NEW
3491
                        "%v", chanID)
×
NEW
3492
                return nil
×
NEW
3493
        }
×
3494

3495
        if !link.DisableAdds(htlcswitch.Outgoing) {
6✔
NEW
3496
                p.log.Warnf("Outgoing link adds already "+
×
NEW
3497
                        "disabled: %v", link.ChanID())
×
NEW
3498
        }
×
3499

3500
        link.OnCommitOnce(htlcswitch.Outgoing, func() {
12✔
3501
                p.queueMsg(shutdownMsg, nil)
6✔
3502
        })
6✔
3503

3504
        return nil
6✔
3505
}
3506

3507
// chooseAddr returns the provided address if it is non-zero length, otherwise
3508
// None.
NEW
3509
func chooseAddr(addr lnwire.DeliveryAddress) fn.Option[lnwire.DeliveryAddress] {
×
NEW
3510
        if len(addr) == 0 {
×
NEW
3511
                return fn.None[lnwire.DeliveryAddress]()
×
NEW
3512
        }
×
3513

NEW
3514
        return fn.Some(addr)
×
3515
}
3516

3517
// observeRbfCloseUpdates observes the channel for any updates that may
3518
// indicate that a new txid has been broadcasted, or the channel fully closed
3519
// on chain.
3520
func (p *Brontide) observeRbfCloseUpdates(chanCloser *chancloser.RbfChanCloser,
NEW
3521
        closeReq *htlcswitch.ChanClose) {
×
NEW
3522

×
NEW
3523
        coopCloseStates := chanCloser.RegisterStateEvents()
×
NEW
3524
        defer chanCloser.RemoveStateSub(coopCloseStates)
×
NEW
3525

×
NEW
3526
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
×
NEW
3527

×
NEW
3528
        var (
×
NEW
3529
                lastTxids    lntypes.Dual[chainhash.Hash]
×
NEW
3530
                lastFeeRates lntypes.Dual[chainfee.SatPerVByte]
×
NEW
3531
        )
×
NEW
3532

×
NEW
3533
        maybeNotifyTxBroadcast := func(state chancloser.AsymmetricPeerState,
×
NEW
3534
                party lntypes.ChannelParty) {
×
NEW
3535

×
NEW
3536
                // First, check to see if we have an error to report to the
×
NEW
3537
                // caller. If so, then we''ll return that error and exit, as the
×
NEW
3538
                // stream will exit as well.
×
NEW
3539
                if closeErr, ok := state.(*chancloser.CloseErr); ok {
×
NEW
3540
                        // We hit an error during the last state transition, so
×
NEW
3541
                        // we'll extract the error then send it to the
×
NEW
3542
                        // user.
×
NEW
3543
                        err := closeErr.Err()
×
NEW
3544

×
NEW
3545
                        peerLog.Warnf("ChannelPoint(%v): encountered close "+
×
NEW
3546
                                "err: %v", closeReq.ChanPoint, err)
×
NEW
3547

×
NEW
3548
                        select {
×
NEW
3549
                        case closeReq.Err <- err:
×
NEW
3550
                        case <-closeReq.Ctx.Done():
×
NEW
3551
                        case <-p.cg.Done():
×
3552
                        }
3553

NEW
3554
                        return
×
3555
                }
3556

NEW
3557
                closePending, ok := state.(*chancloser.ClosePending)
×
NEW
3558

×
NEW
3559
                // If this isn't the close pending state, we aren't at the
×
NEW
3560
                // terminal state yet.
×
NEW
3561
                if !ok {
×
NEW
3562
                        return
×
NEW
3563
                }
×
3564

3565
                // Only notify if the fee rate is greater.
NEW
3566
                newFeeRate := closePending.FeeRate
×
NEW
3567
                lastFeeRate := lastFeeRates.GetForParty(party)
×
NEW
3568
                if newFeeRate <= lastFeeRate {
×
NEW
3569
                        peerLog.Debugf("ChannelPoint(%v): remote party made "+
×
NEW
3570
                                "update for fee rate %v, but we already have "+
×
NEW
3571
                                "a higher fee rate of %v", newFeeRate,
×
NEW
3572
                                lastFeeRate)
×
NEW
3573

×
NEW
3574
                        return
×
NEW
3575
                }
×
3576

NEW
3577
                feeRate := closePending.FeeRate
×
NEW
3578
                lastFeeRates.SetForParty(party, feeRate)
×
NEW
3579

×
NEW
3580
                // At this point, we'll have a txid that we can use to notify
×
NEW
3581
                // the client, but only if it's different from the last one we
×
NEW
3582
                // sent. If the user attempted to bump, but was rejected due to
×
NEW
3583
                // RBF, then we'll send a redundant update.
×
NEW
3584
                closingTxid := closePending.CloseTx.TxHash()
×
NEW
3585
                lastTxid := lastTxids.GetForParty(party)
×
NEW
3586
                if closeReq != nil && closingTxid != lastTxid {
×
NEW
3587
                        select {
×
3588
                        case closeReq.Updates <- &PendingUpdate{
3589
                                Txid:        closingTxid[:],
3590
                                FeePerVbyte: fn.Some(closePending.FeeRate),
3591
                                IsLocalCloseTx: fn.Some(
3592
                                        party == lntypes.Local,
3593
                                ),
NEW
3594
                        }:
×
3595

NEW
3596
                        case <-closeReq.Ctx.Done():
×
NEW
3597
                                return
×
3598

NEW
3599
                        case <-p.cg.Done():
×
NEW
3600
                                return
×
3601
                        }
3602
                }
3603

NEW
3604
                lastTxids.SetForParty(party, closingTxid)
×
3605
        }
3606

NEW
3607
        peerLog.Infof("Observing RBF close updates for channel %v",
×
NEW
3608
                closeReq.ChanPoint)
×
NEW
3609

×
NEW
3610
        // We'll consume each new incoming state to send out the appropriate
×
NEW
3611
        // RPC update.
×
NEW
3612
        for {
×
NEW
3613
                select {
×
NEW
3614
                case newState := <-newStateChan:
×
NEW
3615

×
NEW
3616
                        switch closeState := newState.(type) {
×
3617
                        // Once we've reached the state of pending close, we
3618
                        // have a txid that we broadcasted.
NEW
3619
                        case *chancloser.ClosingNegotiation:
×
NEW
3620
                                peerState := closeState.PeerState
×
NEW
3621

×
NEW
3622
                                // Each side may have gained a new co-op close
×
NEW
3623
                                // tx, so we'll examine both to see if they've
×
NEW
3624
                                // changed.
×
NEW
3625
                                maybeNotifyTxBroadcast(
×
NEW
3626
                                        peerState.GetForParty(lntypes.Local),
×
NEW
3627
                                        lntypes.Local,
×
NEW
3628
                                )
×
NEW
3629
                                maybeNotifyTxBroadcast(
×
NEW
3630
                                        peerState.GetForParty(lntypes.Remote),
×
NEW
3631
                                        lntypes.Remote,
×
NEW
3632
                                )
×
3633

3634
                        // Otherwise, if we're transition to CloseFin, then we
3635
                        // know that we're done.
NEW
3636
                        case *chancloser.CloseFin:
×
NEW
3637
                                // To clean up, we'll remove the chan closer
×
NEW
3638
                                // from the active map, and send the final
×
NEW
3639
                                // update to the client.
×
NEW
3640
                                closingTxid := closeState.ConfirmedTx.TxHash()
×
NEW
3641
                                if closeReq != nil {
×
NEW
3642
                                        select {
×
3643
                                        case closeReq.Updates <- &ChannelCloseUpdate{ //nolint:ll
3644
                                                ClosingTxid: closingTxid[:],
3645
                                                Success:     true,
NEW
3646
                                        }:
×
NEW
3647
                                        case <-p.cg.Done():
×
NEW
3648
                                                return
×
3649
                                        }
3650
                                }
NEW
3651
                                chanID := lnwire.NewChanIDFromOutPoint(
×
NEW
3652
                                        *closeReq.ChanPoint,
×
NEW
3653
                                )
×
NEW
3654
                                p.activeChanCloses.Delete(chanID)
×
NEW
3655

×
NEW
3656
                                return
×
3657
                        }
3658

NEW
3659
                case <-closeReq.Ctx.Done():
×
NEW
3660
                        return
×
3661

NEW
3662
                case <-p.cg.Done():
×
NEW
3663
                        return
×
3664
                }
3665
        }
3666
}
3667

3668
// chanErrorReporter is a simple implementation of the
3669
// chancloser.ErrorReporter. This is bound to a single channel by the channel
3670
// ID.
3671
type chanErrorReporter struct {
3672
        chanID lnwire.ChannelID
3673
        peer   *Brontide
3674
}
3675

3676
// newChanErrorReporter creates a new instance of the chanErrorReporter.
3677
func newChanErrorReporter(chanID lnwire.ChannelID,
NEW
3678
        peer *Brontide) *chanErrorReporter {
×
NEW
3679

×
NEW
3680
        return &chanErrorReporter{
×
NEW
3681
                chanID: chanID,
×
NEW
3682
                peer:   peer,
×
NEW
3683
        }
×
NEW
3684
}
×
3685

3686
// ReportError is a method that's used to report an error that occurred during
3687
// state machine execution. This is used by the RBF close state machine to
3688
// terminate the state machine and send an error to the remote peer.
3689
//
3690
// This is a part of the chancloser.ErrorReporter interface.
NEW
3691
func (c *chanErrorReporter) ReportError(chanErr error) {
×
NEW
3692
        c.peer.log.Errorf("coop close error for channel %v: %v",
×
NEW
3693
                c.chanID, chanErr)
×
NEW
3694

×
NEW
3695
        var errMsg []byte
×
NEW
3696
        if errors.Is(chanErr, chancloser.ErrInvalidStateTransition) {
×
NEW
3697
                errMsg = []byte("unexpected protocol message")
×
NEW
3698
        } else {
×
NEW
3699
                errMsg = []byte(chanErr.Error())
×
NEW
3700
        }
×
3701

NEW
3702
        _ = c.peer.SendMessageLazy(false, &lnwire.Error{
×
NEW
3703
                ChanID: c.chanID,
×
NEW
3704
                Data:   errMsg,
×
NEW
3705
        })
×
NEW
3706

×
NEW
3707
        // After we send the error message to the peer, we'll re-initialize the
×
NEW
3708
        // coop close state machine as they may send a shutdown message to
×
NEW
3709
        // retry the coop close.
×
NEW
3710
        lnChan, ok := c.peer.activeChannels.Load(c.chanID)
×
NEW
3711
        if !ok {
×
NEW
3712
                return
×
NEW
3713
        }
×
3714

NEW
3715
        if lnChan == nil {
×
NEW
3716
                c.peer.log.Debugf("channel %v is pending, not "+
×
NEW
3717
                        "re-initializing coop close state machine",
×
NEW
3718
                        c.chanID)
×
NEW
3719

×
NEW
3720
                return
×
NEW
3721
        }
×
3722

NEW
3723
        if _, err := c.peer.initRbfChanCloser(lnChan); err != nil {
×
NEW
3724
                c.peer.activeChanCloses.Delete(c.chanID)
×
NEW
3725

×
NEW
3726
                c.peer.log.Errorf("unable to init RBF chan closer after "+
×
NEW
3727
                        "error case: %v", err)
×
NEW
3728
        }
×
3729
}
3730

3731
// chanFlushEventSentinel is used to send the RBF coop close state machine the
3732
// channel flushed event. We'll wait until the state machine enters the
3733
// ChannelFlushing state, then request the link to send the event once flushed.
3734
func (p *Brontide) chanFlushEventSentinel(chanCloser *chancloser.RbfChanCloser,
3735
        link htlcswitch.ChannelUpdateHandler,
NEW
3736
        channel *lnwallet.LightningChannel) {
×
NEW
3737

×
NEW
3738
        // If there's no link, then the channel has already been flushed, so we
×
NEW
3739
        // don't need to continue.
×
NEW
3740
        if link == nil {
×
NEW
3741
                return
×
NEW
3742
        }
×
3743

NEW
3744
        coopCloseStates := chanCloser.RegisterStateEvents()
×
NEW
3745
        defer chanCloser.RemoveStateSub(coopCloseStates)
×
NEW
3746

×
NEW
3747
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
×
NEW
3748

×
NEW
3749
        sendChanFlushed := func() {
×
NEW
3750
                chanState := channel.StateSnapshot()
×
NEW
3751

×
NEW
3752
                peerLog.Infof("ChannelPoint(%v) has been flushed for co-op "+
×
NEW
3753
                        "close, sending event to chan closer",
×
NEW
3754
                        channel.ChannelPoint())
×
NEW
3755

×
NEW
3756
                chanBalances := chancloser.ShutdownBalances{
×
NEW
3757
                        LocalBalance:  chanState.LocalBalance,
×
NEW
3758
                        RemoteBalance: chanState.RemoteBalance,
×
NEW
3759
                }
×
NEW
3760
                ctx, _ := p.cg.Create(context.Background())
×
NEW
3761
                chanCloser.SendEvent(ctx, &chancloser.ChannelFlushed{
×
NEW
3762
                        ShutdownBalances: chanBalances,
×
NEW
3763
                        FreshFlush:       true,
×
NEW
3764
                })
×
NEW
3765
        }
×
3766

3767
        // We'll wait until the channel enters the ChannelFlushing state. We
3768
        // exit after a success loop. As after the first RBF iteration, the
3769
        // channel will always be flushed.
NEW
3770
        for newState := range newStateChan {
×
NEW
3771
                if _, ok := newState.(*chancloser.ChannelFlushing); ok {
×
NEW
3772
                        peerLog.Infof("ChannelPoint(%v): rbf coop "+
×
NEW
3773
                                "close is awaiting a flushed state, "+
×
NEW
3774
                                "registering with link..., ",
×
NEW
3775
                                channel.ChannelPoint())
×
NEW
3776

×
NEW
3777
                        // Request the link to send the event once the channel
×
NEW
3778
                        // is flushed. We only need this event sent once, so we
×
NEW
3779
                        // can exit now.
×
NEW
3780
                        link.OnFlushedOnce(sendChanFlushed)
×
NEW
3781

×
NEW
3782
                        return
×
NEW
3783
                }
×
3784
        }
3785
}
3786

3787
// initRbfChanCloser initializes the channel closer for a channel that
3788
// is using the new RBF based co-op close protocol. This only creates the chan
3789
// closer, but doesn't attempt to trigger any manual state transitions.
3790
func (p *Brontide) initRbfChanCloser(
NEW
3791
        channel *lnwallet.LightningChannel) (*chancloser.RbfChanCloser, error) {
×
NEW
3792

×
NEW
3793
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
×
NEW
3794

×
NEW
3795
        link := p.fetchLinkFromKeyAndCid(chanID)
×
NEW
3796

×
NEW
3797
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
×
NEW
3798
        if err != nil {
×
NEW
3799
                return nil, fmt.Errorf("cannot obtain best block: %w", err)
×
NEW
3800
        }
×
3801

NEW
3802
        defaultFeePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
NEW
3803
                p.cfg.CoopCloseTargetConfs,
×
NEW
3804
        )
×
NEW
3805
        if err != nil {
×
NEW
3806
                return nil, fmt.Errorf("unable to estimate fee: %w", err)
×
NEW
3807
        }
×
3808

NEW
3809
        thawHeight, err := channel.AbsoluteThawHeight()
×
NEW
3810
        if err != nil {
×
NEW
3811
                return nil, fmt.Errorf("unable to get thaw height: %w", err)
×
NEW
3812
        }
×
3813

NEW
3814
        peerPub := *p.IdentityKey()
×
NEW
3815

×
NEW
3816
        msgMapper := chancloser.NewRbfMsgMapper(
×
NEW
3817
                uint32(startingHeight), chanID, peerPub,
×
NEW
3818
        )
×
NEW
3819

×
NEW
3820
        initialState := chancloser.ChannelActive{}
×
NEW
3821

×
NEW
3822
        scid := channel.ZeroConfRealScid().UnwrapOr(
×
NEW
3823
                channel.ShortChanID(),
×
NEW
3824
        )
×
NEW
3825

×
NEW
3826
        env := chancloser.Environment{
×
NEW
3827
                ChainParams:    p.cfg.Wallet.Cfg.NetParams,
×
NEW
3828
                ChanPeer:       peerPub,
×
NEW
3829
                ChanPoint:      channel.ChannelPoint(),
×
NEW
3830
                ChanID:         chanID,
×
NEW
3831
                Scid:           scid,
×
NEW
3832
                ChanType:       channel.ChanType(),
×
NEW
3833
                DefaultFeeRate: defaultFeePerKw.FeePerVByte(),
×
NEW
3834
                ThawHeight:     fn.Some(thawHeight),
×
NEW
3835
                RemoteUpfrontShutdown: chooseAddr(
×
NEW
3836
                        channel.RemoteUpfrontShutdownScript(),
×
NEW
3837
                ),
×
NEW
3838
                LocalUpfrontShutdown: chooseAddr(
×
NEW
3839
                        channel.LocalUpfrontShutdownScript(),
×
NEW
3840
                ),
×
NEW
3841
                NewDeliveryScript: func() (lnwire.DeliveryAddress, error) {
×
NEW
3842
                        return p.genDeliveryScript()
×
NEW
3843
                },
×
3844
                FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
3845
                CloseSigner:  channel,
3846
                ChanObserver: newChanObserver(
3847
                        channel, link, p.cfg.ChanStatusMgr,
3848
                ),
3849
        }
3850

NEW
3851
        spendEvent := protofsm.RegisterSpend[chancloser.ProtocolEvent]{
×
NEW
3852
                OutPoint:   channel.ChannelPoint(),
×
NEW
3853
                PkScript:   channel.FundingTxOut().PkScript,
×
NEW
3854
                HeightHint: channel.DeriveHeightHint(),
×
NEW
3855
                PostSpendEvent: fn.Some[chancloser.RbfSpendMapper](
×
NEW
3856
                        chancloser.SpendMapper,
×
NEW
3857
                ),
×
NEW
3858
        }
×
NEW
3859

×
NEW
3860
        daemonAdapters := NewLndDaemonAdapters(LndAdapterCfg{
×
NEW
3861
                MsgSender:          newPeerMsgSender(peerPub, p),
×
NEW
3862
                TxBroadcaster:      p.cfg.Wallet,
×
NEW
3863
                LinkNetworkControl: p.cfg.ChanStatusMgr,
×
NEW
3864
                ChainNotifier:      p.cfg.ChainNotifier,
×
NEW
3865
        })
×
NEW
3866

×
NEW
3867
        protoCfg := chancloser.RbfChanCloserCfg{
×
NEW
3868
                Daemon:        daemonAdapters,
×
NEW
3869
                InitialState:  &initialState,
×
NEW
3870
                Env:           &env,
×
NEW
3871
                InitEvent:     fn.Some[protofsm.DaemonEvent](&spendEvent),
×
NEW
3872
                ErrorReporter: newChanErrorReporter(chanID, p),
×
NEW
3873
                MsgMapper: fn.Some[protofsm.MsgMapper[chancloser.ProtocolEvent]]( //nolint:ll
×
NEW
3874
                        msgMapper,
×
NEW
3875
                ),
×
NEW
3876
        }
×
NEW
3877

×
NEW
3878
        chanCloser := protofsm.NewStateMachine(protoCfg)
×
NEW
3879

×
NEW
3880
        ctx, _ := p.cg.Create(context.Background())
×
NEW
3881
        chanCloser.Start(ctx)
×
NEW
3882

×
NEW
3883
        // Finally, we'll register this new endpoint with the message router so
×
NEW
3884
        // future co-op close messages are handled by this state machine.
×
NEW
3885
        err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
×
NEW
3886
                _ = r.UnregisterEndpoint(chanCloser.Name())
×
NEW
3887

×
NEW
3888
                return r.RegisterEndpoint(&chanCloser)
×
NEW
3889
        })
×
NEW
3890
        if err != nil {
×
NEW
3891
                chanCloser.Stop()
×
NEW
3892
                p.activeChanCloses.Delete(chanID)
×
NEW
3893

×
NEW
3894
                return nil, fmt.Errorf("unable to register endpoint for co-op "+
×
NEW
3895
                        "close: %w", err)
×
NEW
3896
        }
×
3897

NEW
3898
        p.activeChanCloses.Store(chanID, makeRbfCloser(&chanCloser))
×
NEW
3899

×
NEW
3900
        // Now that we've created the rbf closer state machine, we'll launch a
×
NEW
3901
        // new goroutine to eventually send in the ChannelFlushed event once
×
NEW
3902
        // needed.
×
NEW
3903
        p.cg.WgAdd(1)
×
NEW
3904
        go func() {
×
NEW
3905
                defer p.cg.WgDone()
×
NEW
3906
                go p.chanFlushEventSentinel(&chanCloser, link, channel)
×
NEW
3907
        }()
×
3908

NEW
3909
        return &chanCloser, nil
×
3910
}
3911

3912
// shutdownInit describes the two ways we can initiate a new shutdown. Either we
3913
// got an RPC request to do so (left), or we sent a shutdown message to the
3914
// party (for w/e reason), but crashed before the close was complete.
3915
//
3916
//nolint:ll
3917
type shutdownInit = fn.Option[fn.Either[*htlcswitch.ChanClose, channeldb.ShutdownInfo]]
3918

3919
// shutdownStartFeeRate returns the fee rate that should be used for the
3920
// shutdown.  This returns a doubly wrapped option as the shutdown info might
3921
// be none, and the fee rate is only defined for the user initiated shutdown.
NEW
3922
func shutdownStartFeeRate(s shutdownInit) fn.Option[chainfee.SatPerKWeight] {
×
NEW
3923
        feeRateOpt := fn.MapOption(func(init fn.Either[*htlcswitch.ChanClose,
×
NEW
3924
                channeldb.ShutdownInfo]) fn.Option[chainfee.SatPerKWeight] {
×
NEW
3925

×
NEW
3926
                var feeRate fn.Option[chainfee.SatPerKWeight]
×
NEW
3927
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
×
NEW
3928
                        feeRate = fn.Some(req.TargetFeePerKw)
×
NEW
3929
                })
×
3930

NEW
3931
                return feeRate
×
3932
        })(s)
3933

NEW
3934
        return fn.FlattenOption(feeRateOpt)
×
3935
}
3936

3937
// shutdownStartAddr returns the delivery address that should be used when
3938
// restarting the shutdown process.  If we didn't send a shutdown before we
3939
// restarted, and the user didn't initiate one either, then None is returned.
NEW
3940
func shutdownStartAddr(s shutdownInit) fn.Option[lnwire.DeliveryAddress] {
×
NEW
3941
        addrOpt := fn.MapOption(func(init fn.Either[*htlcswitch.ChanClose,
×
NEW
3942
                channeldb.ShutdownInfo]) fn.Option[lnwire.DeliveryAddress] {
×
NEW
3943

×
NEW
3944
                var addr fn.Option[lnwire.DeliveryAddress]
×
NEW
3945
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
×
NEW
3946
                        if len(req.DeliveryScript) != 0 {
×
NEW
3947
                                addr = fn.Some(req.DeliveryScript)
×
NEW
3948
                        }
×
3949
                })
NEW
3950
                init.WhenRight(func(info channeldb.ShutdownInfo) {
×
NEW
3951
                        addr = fn.Some(info.DeliveryScript.Val)
×
NEW
3952
                })
×
3953

NEW
3954
                return addr
×
3955
        })(s)
3956

NEW
3957
        return fn.FlattenOption(addrOpt)
×
3958
}
3959

3960
// whenRPCShutdown registers a callback to be executed when the shutdown init
3961
// type is and RPC request.
NEW
3962
func whenRPCShutdown(s shutdownInit, f func(r *htlcswitch.ChanClose)) {
×
NEW
3963
        s.WhenSome(func(init fn.Either[*htlcswitch.ChanClose,
×
NEW
3964
                channeldb.ShutdownInfo]) {
×
NEW
3965

×
NEW
3966
                init.WhenLeft(f)
×
NEW
3967
        })
×
3968
}
3969

3970
// newRestartShutdownInit creates a new shutdownInit for the case where we need
3971
// to restart the shutdown flow after a restart.
NEW
3972
func newRestartShutdownInit(info channeldb.ShutdownInfo) shutdownInit {
×
NEW
3973
        return fn.Some(fn.NewRight[*htlcswitch.ChanClose](info))
×
NEW
3974
}
×
3975

3976
// newRPCShutdownInit creates a new shutdownInit for the case where we
3977
// initiated the shutdown via an RPC client.
NEW
3978
func newRPCShutdownInit(req *htlcswitch.ChanClose) shutdownInit {
×
NEW
3979
        return fn.Some(
×
NEW
3980
                fn.NewLeft[*htlcswitch.ChanClose, channeldb.ShutdownInfo](req),
×
NEW
3981
        )
×
NEW
3982
}
×
3983

3984
// startRbfChanCloser kicks off the co-op close process using the new RBF based
3985
// co-op close protocol. This is called when we're the one that's initiating
3986
// the cooperative channel close.
3987
//
3988
// TODO(roasbeef): just accept the two shutdown pointer params instead??
3989
func (p *Brontide) startRbfChanCloser(shutdown shutdownInit,
NEW
3990
        chanPoint wire.OutPoint) error {
×
NEW
3991

×
NEW
3992
        // Unlike the old negotiate chan closer, we'll always create the RBF
×
NEW
3993
        // chan closer on startup, so we can skip init here.
×
NEW
3994
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
NEW
3995
        chanCloser, found := p.activeChanCloses.Load(chanID)
×
NEW
3996
        if !found {
×
NEW
3997
                return fmt.Errorf("rbf can closer not found for channel %v",
×
NEW
3998
                        chanPoint)
×
NEW
3999
        }
×
4000

NEW
4001
        defaultFeePerKw, err := shutdownStartFeeRate(
×
NEW
4002
                shutdown,
×
NEW
4003
        ).UnwrapOrFuncErr(func() (chainfee.SatPerKWeight, error) {
×
NEW
4004
                return p.cfg.FeeEstimator.EstimateFeePerKW(
×
NEW
4005
                        p.cfg.CoopCloseTargetConfs,
×
NEW
4006
                )
×
NEW
4007
        })
×
NEW
4008
        if err != nil {
×
NEW
4009
                return fmt.Errorf("unable to estimate fee: %w", err)
×
NEW
4010
        }
×
4011

NEW
4012
        chanCloser.WhenRight(func(rbfCloser *chancloser.RbfChanCloser) {
×
NEW
4013
                peerLog.Infof("ChannelPoint(%v): rbf-coop close requested, "+
×
NEW
4014
                        "sending shutdown", chanPoint)
×
NEW
4015

×
NEW
4016
                rbfState, err := rbfCloser.CurrentState()
×
NEW
4017
                if err != nil {
×
NEW
4018
                        peerLog.Warnf("ChannelPoint(%v): unable to get "+
×
NEW
4019
                                "current state for rbf-coop close: %v",
×
NEW
4020
                                chanPoint, err)
×
NEW
4021

×
NEW
4022
                        return
×
NEW
4023
                }
×
4024

4025
                // Before we send our event below, we'll launch a goroutine to
4026
                // watch for the final terminal state to send updates to the RPC
4027
                // client. We only need to do this if there's an RPC caller.
NEW
4028
                whenRPCShutdown(
×
NEW
4029
                        shutdown,
×
NEW
4030
                        func(req *htlcswitch.ChanClose) {
×
NEW
4031
                                p.cg.WgAdd(1)
×
NEW
4032
                                go func() {
×
NEW
4033
                                        defer p.cg.WgDone()
×
NEW
4034
                                        p.observeRbfCloseUpdates(
×
NEW
4035
                                                rbfCloser, req,
×
NEW
4036
                                        )
×
NEW
4037
                                }()
×
4038
                        },
4039
                )
4040

NEW
4041
                ctx, _ := p.cg.Create(context.Background())
×
NEW
4042
                feeRate := defaultFeePerKw.FeePerVByte()
×
NEW
4043

×
NEW
4044
                // Depending on the state of the state machine, we'll either
×
NEW
4045
                // kick things off by sending shutdown, or attempt to send a new
×
NEW
4046
                // offer to the remote party.
×
NEW
4047
                switch rbfState.(type) {
×
4048
                // The channel is still active, so we'll now kick off the co-op
4049
                // close process by instructing it to send a shutdown message to
4050
                // the remote party.
NEW
4051
                case *chancloser.ChannelActive:
×
NEW
4052
                        rbfCloser.SendEvent(
×
NEW
4053
                                context.Background(),
×
NEW
4054
                                &chancloser.SendShutdown{
×
NEW
4055
                                        IdealFeeRate: feeRate,
×
NEW
4056
                                        DeliveryAddr: shutdownStartAddr(
×
NEW
4057
                                                shutdown,
×
NEW
4058
                                        ),
×
NEW
4059
                                },
×
NEW
4060
                        )
×
4061

4062
                // If we haven't yet sent an offer (didn't have enough funds at
4063
                // the prior fee rate), or we've sent an offer, then we'll
4064
                // trigger a new offer event.
NEW
4065
                case *chancloser.ClosingNegotiation:
×
NEW
4066
                        event := chancloser.ProtocolEvent(
×
NEW
4067
                                &chancloser.SendOfferEvent{
×
NEW
4068
                                        TargetFeeRate: feeRate,
×
NEW
4069
                                },
×
NEW
4070
                        )
×
NEW
4071
                        rbfCloser.SendEvent(ctx, event)
×
4072

NEW
4073
                default:
×
NEW
4074
                        peerLog.Warnf("ChannelPoint(%v): unexpected state "+
×
NEW
4075
                                "for rbf-coop close: %T", chanPoint, rbfState)
×
4076
                }
4077
        })
4078

NEW
4079
        return nil
×
4080
}
4081

4082
// handleLocalCloseReq kicks-off the workflow to execute a cooperative or
4083
// forced unilateral closure of the channel initiated by a local subsystem.
4084
func (p *Brontide) handleLocalCloseReq(req *htlcswitch.ChanClose) {
7✔
4085
        chanID := lnwire.NewChanIDFromOutPoint(*req.ChanPoint)
7✔
4086

7✔
4087
        channel, ok := p.activeChannels.Load(chanID)
7✔
4088

7✔
4089
        // Though this function can't be called for pending channels, we still
7✔
4090
        // check whether channel is nil for safety.
7✔
4091
        if !ok || channel == nil {
7✔
4092
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
×
4093
                        "unknown", chanID)
×
4094
                p.log.Errorf(err.Error())
×
4095
                req.Err <- err
×
4096
                return
×
4097
        }
×
4098

4099
        switch req.CloseType {
7✔
4100
        // A type of CloseRegular indicates that the user has opted to close
4101
        // out this channel on-chain, so we execute the cooperative channel
4102
        // closure workflow.
4103
        case contractcourt.CloseRegular:
7✔
4104
                var err error
7✔
4105
                switch {
7✔
4106
                // If this is the RBF coop state machine, then we'll instruct
4107
                // it to send the shutdown message. This also might be an RBF
4108
                // iteration, in which case we'll be obtaining a new
4109
                // transaction w/ a higher fee rate.
NEW
4110
                case p.rbfCoopCloseAllowed():
×
NEW
4111
                        err = p.startRbfChanCloser(
×
NEW
4112
                                newRPCShutdownInit(req), channel.ChannelPoint(),
×
NEW
4113
                        )
×
4114
                default:
7✔
4115
                        err = p.initNegotiateChanCloser(req, channel)
7✔
4116
                }
4117

4118
                if err != nil {
8✔
4119
                        p.log.Errorf(err.Error())
1✔
4120
                        req.Err <- err
1✔
4121
                }
1✔
4122

4123
        // A type of CloseBreach indicates that the counterparty has breached
4124
        // the channel therefore we need to clean up our local state.
4125
        case contractcourt.CloseBreach:
×
4126
                // TODO(roasbeef): no longer need with newer beach logic?
×
4127
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
×
4128
                        "channel", req.ChanPoint)
×
4129
                p.WipeChannel(req.ChanPoint)
×
4130
        }
4131
}
4132

4133
// linkFailureReport is sent to the channelManager whenever a link reports a
4134
// link failure, and is forced to exit. The report houses the necessary
4135
// information to clean up the channel state, send back the error message, and
4136
// force close if necessary.
4137
type linkFailureReport struct {
4138
        chanPoint   wire.OutPoint
4139
        chanID      lnwire.ChannelID
4140
        shortChanID lnwire.ShortChannelID
4141
        linkErr     htlcswitch.LinkFailureError
4142
}
4143

4144
// handleLinkFailure processes a link failure report when a link in the switch
4145
// fails. It facilitates the removal of all channel state within the peer,
4146
// force closing the channel depending on severity, and sending the error
4147
// message back to the remote party.
UNCOV
4148
func (p *Brontide) handleLinkFailure(failure linkFailureReport) {
×
UNCOV
4149
        // Retrieve the channel from the map of active channels. We do this to
×
UNCOV
4150
        // have access to it even after WipeChannel remove it from the map.
×
UNCOV
4151
        chanID := lnwire.NewChanIDFromOutPoint(failure.chanPoint)
×
UNCOV
4152
        lnChan, _ := p.activeChannels.Load(chanID)
×
UNCOV
4153

×
UNCOV
4154
        // We begin by wiping the link, which will remove it from the switch,
×
UNCOV
4155
        // such that it won't be attempted used for any more updates.
×
UNCOV
4156
        //
×
UNCOV
4157
        // TODO(halseth): should introduce a way to atomically stop/pause the
×
UNCOV
4158
        // link and cancel back any adds in its mailboxes such that we can
×
UNCOV
4159
        // safely force close without the link being added again and updates
×
UNCOV
4160
        // being applied.
×
UNCOV
4161
        p.WipeChannel(&failure.chanPoint)
×
UNCOV
4162

×
UNCOV
4163
        // If the error encountered was severe enough, we'll now force close
×
UNCOV
4164
        // the channel to prevent reading it to the switch in the future.
×
UNCOV
4165
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureForceClose {
×
UNCOV
4166
                p.log.Warnf("Force closing link(%v)", failure.shortChanID)
×
UNCOV
4167

×
UNCOV
4168
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
×
UNCOV
4169
                        failure.chanPoint,
×
UNCOV
4170
                )
×
UNCOV
4171
                if err != nil {
×
UNCOV
4172
                        p.log.Errorf("unable to force close "+
×
UNCOV
4173
                                "link(%v): %v", failure.shortChanID, err)
×
UNCOV
4174
                } else {
×
UNCOV
4175
                        p.log.Infof("channel(%v) force "+
×
UNCOV
4176
                                "closed with txid %v",
×
UNCOV
4177
                                failure.shortChanID, closeTx.TxHash())
×
UNCOV
4178
                }
×
4179
        }
4180

4181
        // If this is a permanent failure, we will mark the channel borked.
UNCOV
4182
        if failure.linkErr.PermanentFailure && lnChan != nil {
×
4183
                p.log.Warnf("Marking link(%v) borked due to permanent "+
×
4184
                        "failure", failure.shortChanID)
×
4185

×
4186
                if err := lnChan.State().MarkBorked(); err != nil {
×
4187
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
4188
                                failure.shortChanID, err)
×
4189
                }
×
4190
        }
4191

4192
        // Send an error to the peer, why we failed the channel.
UNCOV
4193
        if failure.linkErr.ShouldSendToPeer() {
×
UNCOV
4194
                // If SendData is set, send it to the peer. If not, we'll use
×
UNCOV
4195
                // the standard error messages in the payload. We only include
×
UNCOV
4196
                // sendData in the cases where the error data does not contain
×
UNCOV
4197
                // sensitive information.
×
UNCOV
4198
                data := []byte(failure.linkErr.Error())
×
UNCOV
4199
                if failure.linkErr.SendData != nil {
×
4200
                        data = failure.linkErr.SendData
×
4201
                }
×
4202

UNCOV
4203
                var networkMsg lnwire.Message
×
UNCOV
4204
                if failure.linkErr.Warning {
×
4205
                        networkMsg = &lnwire.Warning{
×
4206
                                ChanID: failure.chanID,
×
4207
                                Data:   data,
×
4208
                        }
×
UNCOV
4209
                } else {
×
UNCOV
4210
                        networkMsg = &lnwire.Error{
×
UNCOV
4211
                                ChanID: failure.chanID,
×
UNCOV
4212
                                Data:   data,
×
UNCOV
4213
                        }
×
UNCOV
4214
                }
×
4215

UNCOV
4216
                err := p.SendMessage(true, networkMsg)
×
UNCOV
4217
                if err != nil {
×
4218
                        p.log.Errorf("unable to send msg to "+
×
4219
                                "remote peer: %v", err)
×
4220
                }
×
4221
        }
4222

4223
        // If the failure action is disconnect, then we'll execute that now. If
4224
        // we had to send an error above, it was a sync call, so we expect the
4225
        // message to be flushed on the wire by now.
UNCOV
4226
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
×
4227
                p.Disconnect(fmt.Errorf("link requested disconnect"))
×
4228
        }
×
4229
}
4230

4231
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
4232
// public key and the channel id.
4233
func (p *Brontide) fetchLinkFromKeyAndCid(
4234
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
19✔
4235

19✔
4236
        var chanLink htlcswitch.ChannelUpdateHandler
19✔
4237

19✔
4238
        // We don't need to check the error here, and can instead just loop
19✔
4239
        // over the slice and return nil.
19✔
4240
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
19✔
4241
        for _, link := range links {
37✔
4242
                if link.ChanID() == cid {
36✔
4243
                        chanLink = link
18✔
4244
                        break
18✔
4245
                }
4246
        }
4247

4248
        return chanLink
19✔
4249
}
4250

4251
// finalizeChanClosure performs the final clean up steps once the cooperative
4252
// closure transaction has been fully broadcast. The finalized closing state
4253
// machine should be passed in. Once the transaction has been sufficiently
4254
// confirmed, the channel will be marked as fully closed within the database,
4255
// and any clients will be notified of updates to the closing state.
4256
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
4✔
4257
        closeReq := chanCloser.CloseRequest()
4✔
4258

4✔
4259
        // First, we'll clear all indexes related to the channel in question.
4✔
4260
        chanPoint := chanCloser.Channel().ChannelPoint()
4✔
4261
        p.WipeChannel(&chanPoint)
4✔
4262

4✔
4263
        // Also clear the activeChanCloses map of this channel.
4✔
4264
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
4265
        p.activeChanCloses.Delete(cid)
4✔
4266

4✔
4267
        // Next, we'll launch a goroutine which will request to be notified by
4✔
4268
        // the ChainNotifier once the closure transaction obtains a single
4✔
4269
        // confirmation.
4✔
4270
        notifier := p.cfg.ChainNotifier
4✔
4271

4✔
4272
        // If any error happens during waitForChanToClose, forward it to
4✔
4273
        // closeReq. If this channel closure is not locally initiated, closeReq
4✔
4274
        // will be nil, so just ignore the error.
4✔
4275
        errChan := make(chan error, 1)
4✔
4276
        if closeReq != nil {
6✔
4277
                errChan = closeReq.Err
2✔
4278
        }
2✔
4279

4280
        closingTx, err := chanCloser.ClosingTx()
4✔
4281
        if err != nil {
4✔
4282
                if closeReq != nil {
×
4283
                        p.log.Error(err)
×
4284
                        closeReq.Err <- err
×
4285
                }
×
4286
        }
4287

4288
        closingTxid := closingTx.TxHash()
4✔
4289

4✔
4290
        // If this is a locally requested shutdown, update the caller with a
4✔
4291
        // new event detailing the current pending state of this request.
4✔
4292
        if closeReq != nil {
6✔
4293
                closeReq.Updates <- &PendingUpdate{
2✔
4294
                        Txid: closingTxid[:],
2✔
4295
                }
2✔
4296
        }
2✔
4297

4298
        localOut := chanCloser.LocalCloseOutput()
4✔
4299
        remoteOut := chanCloser.RemoteCloseOutput()
4✔
4300
        auxOut := chanCloser.AuxOutputs()
4✔
4301
        go WaitForChanToClose(
4✔
4302
                chanCloser.NegotiationHeight(), notifier, errChan,
4✔
4303
                &chanPoint, &closingTxid, closingTx.TxOut[0].PkScript, func() {
8✔
4304
                        // Respond to the local subsystem which requested the
4✔
4305
                        // channel closure.
4✔
4306
                        if closeReq != nil {
6✔
4307
                                closeReq.Updates <- &ChannelCloseUpdate{
2✔
4308
                                        ClosingTxid:       closingTxid[:],
2✔
4309
                                        Success:           true,
2✔
4310
                                        LocalCloseOutput:  localOut,
2✔
4311
                                        RemoteCloseOutput: remoteOut,
2✔
4312
                                        AuxOutputs:        auxOut,
2✔
4313
                                }
2✔
4314
                        }
2✔
4315
                },
4316
        )
4317
}
4318

4319
// WaitForChanToClose uses the passed notifier to wait until the channel has
4320
// been detected as closed on chain and then concludes by executing the
4321
// following actions: the channel point will be sent over the settleChan, and
4322
// finally the callback will be executed. If any error is encountered within
4323
// the function, then it will be sent over the errChan.
4324
func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
4325
        errChan chan error, chanPoint *wire.OutPoint,
4326
        closingTxID *chainhash.Hash, closeScript []byte, cb func()) {
4✔
4327

4✔
4328
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
4✔
4329
                "with txid: %v", chanPoint, closingTxID)
4✔
4330

4✔
4331
        // TODO(roasbeef): add param for num needed confs
4✔
4332
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
4✔
4333
                closingTxID, closeScript, 1, bestHeight,
4✔
4334
        )
4✔
4335
        if err != nil {
4✔
4336
                if errChan != nil {
×
4337
                        errChan <- err
×
4338
                }
×
4339
                return
×
4340
        }
4341

4342
        // In the case that the ChainNotifier is shutting down, all subscriber
4343
        // notification channels will be closed, generating a nil receive.
4344
        height, ok := <-confNtfn.Confirmed
4✔
4345
        if !ok {
4✔
UNCOV
4346
                return
×
UNCOV
4347
        }
×
4348

4349
        // The channel has been closed, remove it from any active indexes, and
4350
        // the database state.
4351
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
4✔
4352
                "height %v", chanPoint, height.BlockHeight)
4✔
4353

4✔
4354
        // Finally, execute the closure call back to mark the confirmation of
4✔
4355
        // the transaction closing the contract.
4✔
4356
        cb()
4✔
4357
}
4358

4359
// WipeChannel removes the passed channel point from all indexes associated with
4360
// the peer and the switch.
4361
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
4✔
4362
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
4✔
4363

4✔
4364
        p.activeChannels.Delete(chanID)
4✔
4365

4✔
4366
        // Instruct the HtlcSwitch to close this link as the channel is no
4✔
4367
        // longer active.
4✔
4368
        p.cfg.Switch.RemoveLink(chanID)
4✔
4369
}
4✔
4370

4371
// handleInitMsg handles the incoming init message which contains global and
4372
// local feature vectors. If feature vectors are incompatible then disconnect.
4373
func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
3✔
4374
        // First, merge any features from the legacy global features field into
3✔
4375
        // those presented in the local features fields.
3✔
4376
        err := msg.Features.Merge(msg.GlobalFeatures)
3✔
4377
        if err != nil {
3✔
4378
                return fmt.Errorf("unable to merge legacy global features: %w",
×
4379
                        err)
×
4380
        }
×
4381

4382
        // Then, finalize the remote feature vector providing the flattened
4383
        // feature bit namespace.
4384
        p.remoteFeatures = lnwire.NewFeatureVector(
3✔
4385
                msg.Features, lnwire.Features,
3✔
4386
        )
3✔
4387

3✔
4388
        // Now that we have their features loaded, we'll ensure that they
3✔
4389
        // didn't set any required bits that we don't know of.
3✔
4390
        err = feature.ValidateRequired(p.remoteFeatures)
3✔
4391
        if err != nil {
3✔
4392
                return fmt.Errorf("invalid remote features: %w", err)
×
4393
        }
×
4394

4395
        // Ensure the remote party's feature vector contains all transitive
4396
        // dependencies. We know ours are correct since they are validated
4397
        // during the feature manager's instantiation.
4398
        err = feature.ValidateDeps(p.remoteFeatures)
3✔
4399
        if err != nil {
3✔
4400
                return fmt.Errorf("invalid remote features: %w", err)
×
4401
        }
×
4402

4403
        // Now that we know we understand their requirements, we'll check to
4404
        // see if they don't support anything that we deem to be mandatory.
4405
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
3✔
4406
                return fmt.Errorf("data loss protection required")
×
4407
        }
×
4408

4409
        return nil
3✔
4410
}
4411

4412
// LocalFeatures returns the set of global features that has been advertised by
4413
// the local node. This allows sub-systems that use this interface to gate their
4414
// behavior off the set of negotiated feature bits.
4415
//
4416
// NOTE: Part of the lnpeer.Peer interface.
UNCOV
4417
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
×
UNCOV
4418
        return p.cfg.Features
×
UNCOV
4419
}
×
4420

4421
// RemoteFeatures returns the set of global features that has been advertised by
4422
// the remote node. This allows sub-systems that use this interface to gate
4423
// their behavior off the set of negotiated feature bits.
4424
//
4425
// NOTE: Part of the lnpeer.Peer interface.
4426
func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector {
13✔
4427
        return p.remoteFeatures
13✔
4428
}
13✔
4429

4430
// hasNegotiatedScidAlias returns true if we've negotiated the
4431
// option-scid-alias feature bit with the peer.
4432
func (p *Brontide) hasNegotiatedScidAlias() bool {
3✔
4433
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
3✔
4434
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
3✔
4435
        return peerHas && localHas
3✔
4436
}
3✔
4437

4438
// sendInitMsg sends the Init message to the remote peer. This message contains
4439
// our currently supported local and global features.
4440
func (p *Brontide) sendInitMsg(legacyChan bool) error {
7✔
4441
        features := p.cfg.Features.Clone()
7✔
4442
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
7✔
4443

7✔
4444
        // If we have a legacy channel open with a peer, we downgrade static
7✔
4445
        // remote required to optional in case the peer does not understand the
7✔
4446
        // required feature bit. If we do not do this, the peer will reject our
7✔
4447
        // connection because it does not understand a required feature bit, and
7✔
4448
        // our channel will be unusable.
7✔
4449
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
8✔
4450
                p.log.Infof("Legacy channel open with peer, " +
1✔
4451
                        "downgrading static remote required feature bit to " +
1✔
4452
                        "optional")
1✔
4453

1✔
4454
                // Unset and set in both the local and global features to
1✔
4455
                // ensure both sets are consistent and merge able by old and
1✔
4456
                // new nodes.
1✔
4457
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4458
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4459

1✔
4460
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
4461
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
4462
        }
1✔
4463

4464
        msg := lnwire.NewInitMessage(
7✔
4465
                legacyFeatures.RawFeatureVector,
7✔
4466
                features.RawFeatureVector,
7✔
4467
        )
7✔
4468

7✔
4469
        return p.writeMessage(msg)
7✔
4470
}
4471

4472
// resendChanSyncMsg will attempt to find a channel sync message for the closed
4473
// channel and resend it to our peer.
UNCOV
4474
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
×
UNCOV
4475
        // If we already re-sent the mssage for this channel, we won't do it
×
UNCOV
4476
        // again.
×
UNCOV
4477
        if _, ok := p.resentChanSyncMsg[cid]; ok {
×
UNCOV
4478
                return nil
×
UNCOV
4479
        }
×
4480

4481
        // Check if we have any channel sync messages stored for this channel.
UNCOV
4482
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
×
UNCOV
4483
        if err != nil {
×
UNCOV
4484
                return fmt.Errorf("unable to fetch channel sync messages for "+
×
UNCOV
4485
                        "peer %v: %v", p, err)
×
UNCOV
4486
        }
×
4487

UNCOV
4488
        if c.LastChanSyncMsg == nil {
×
4489
                return fmt.Errorf("no chan sync message stored for channel %v",
×
4490
                        cid)
×
4491
        }
×
4492

UNCOV
4493
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
×
4494
                return fmt.Errorf("ignoring channel reestablish from "+
×
4495
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
4496
        }
×
4497

UNCOV
4498
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
×
UNCOV
4499
                "peer", cid)
×
UNCOV
4500

×
UNCOV
4501
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
×
4502
                return fmt.Errorf("failed resending channel sync "+
×
4503
                        "message to peer %v: %v", p, err)
×
4504
        }
×
4505

UNCOV
4506
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
×
UNCOV
4507
                cid)
×
UNCOV
4508

×
UNCOV
4509
        // Note down that we sent the message, so we won't resend it again for
×
UNCOV
4510
        // this connection.
×
UNCOV
4511
        p.resentChanSyncMsg[cid] = struct{}{}
×
UNCOV
4512

×
UNCOV
4513
        return nil
×
4514
}
4515

4516
// SendMessage sends a variadic number of high-priority messages to the remote
4517
// peer. The first argument denotes if the method should block until the
4518
// messages have been sent to the remote peer or an error is returned,
4519
// otherwise it returns immediately after queuing.
4520
//
4521
// NOTE: Part of the lnpeer.Peer interface.
4522
func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error {
3✔
4523
        return p.sendMessage(sync, true, msgs...)
3✔
4524
}
3✔
4525

4526
// SendMessageLazy sends a variadic number of low-priority messages to the
4527
// remote peer. The first argument denotes if the method should block until
4528
// the messages have been sent to the remote peer or an error is returned,
4529
// otherwise it returns immediately after queueing.
4530
//
4531
// NOTE: Part of the lnpeer.Peer interface.
4532
func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
1✔
4533
        return p.sendMessage(sync, false, msgs...)
1✔
4534
}
1✔
4535

4536
// sendMessage queues a variadic number of messages using the passed priority
4537
// to the remote peer. If sync is true, this method will block until the
4538
// messages have been sent to the remote peer or an error is returned, otherwise
4539
// it returns immediately after queueing.
4540
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
4✔
4541
        // Add all incoming messages to the outgoing queue. A list of error
4✔
4542
        // chans is populated for each message if the caller requested a sync
4✔
4543
        // send.
4✔
4544
        var errChans []chan error
4✔
4545
        if sync {
5✔
4546
                errChans = make([]chan error, 0, len(msgs))
1✔
4547
        }
1✔
4548
        for _, msg := range msgs {
8✔
4549
                // If a sync send was requested, create an error chan to listen
4✔
4550
                // for an ack from the writeHandler.
4✔
4551
                var errChan chan error
4✔
4552
                if sync {
5✔
4553
                        errChan = make(chan error, 1)
1✔
4554
                        errChans = append(errChans, errChan)
1✔
4555
                }
1✔
4556

4557
                if priority {
7✔
4558
                        p.queueMsg(msg, errChan)
3✔
4559
                } else {
4✔
4560
                        p.queueMsgLazy(msg, errChan)
1✔
4561
                }
1✔
4562
        }
4563

4564
        // Wait for all replies from the writeHandler. For async sends, this
4565
        // will be a NOP as the list of error chans is nil.
4566
        for _, errChan := range errChans {
5✔
4567
                select {
1✔
4568
                case err := <-errChan:
1✔
4569
                        return err
1✔
NEW
4570
                case <-p.cg.Done():
×
4571
                        return lnpeer.ErrPeerExiting
×
4572
                case <-p.cfg.Quit:
×
4573
                        return lnpeer.ErrPeerExiting
×
4574
                }
4575
        }
4576

4577
        return nil
3✔
4578
}
4579

4580
// PubKey returns the pubkey of the peer in compressed serialized format.
4581
//
4582
// NOTE: Part of the lnpeer.Peer interface.
4583
func (p *Brontide) PubKey() [33]byte {
2✔
4584
        return p.cfg.PubKeyBytes
2✔
4585
}
2✔
4586

4587
// IdentityKey returns the public key of the remote peer.
4588
//
4589
// NOTE: Part of the lnpeer.Peer interface.
4590
func (p *Brontide) IdentityKey() *btcec.PublicKey {
15✔
4591
        return p.cfg.Addr.IdentityKey
15✔
4592
}
15✔
4593

4594
// Address returns the network address of the remote peer.
4595
//
4596
// NOTE: Part of the lnpeer.Peer interface.
UNCOV
4597
func (p *Brontide) Address() net.Addr {
×
UNCOV
4598
        return p.cfg.Addr.Address
×
UNCOV
4599
}
×
4600

4601
// AddNewChannel adds a new channel to the peer. The channel should fail to be
4602
// added if the cancel channel is closed.
4603
//
4604
// NOTE: Part of the lnpeer.Peer interface.
4605
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
UNCOV
4606
        cancel <-chan struct{}) error {
×
UNCOV
4607

×
UNCOV
4608
        errChan := make(chan error, 1)
×
UNCOV
4609
        newChanMsg := &newChannelMsg{
×
UNCOV
4610
                channel: newChan,
×
UNCOV
4611
                err:     errChan,
×
UNCOV
4612
        }
×
UNCOV
4613

×
UNCOV
4614
        select {
×
UNCOV
4615
        case p.newActiveChannel <- newChanMsg:
×
4616
        case <-cancel:
×
4617
                return errors.New("canceled adding new channel")
×
NEW
4618
        case <-p.cg.Done():
×
4619
                return lnpeer.ErrPeerExiting
×
4620
        }
4621

4622
        // We pause here to wait for the peer to recognize the new channel
4623
        // before we close the channel barrier corresponding to the channel.
UNCOV
4624
        select {
×
UNCOV
4625
        case err := <-errChan:
×
UNCOV
4626
                return err
×
NEW
4627
        case <-p.cg.Done():
×
4628
                return lnpeer.ErrPeerExiting
×
4629
        }
4630
}
4631

4632
// AddPendingChannel adds a pending open channel to the peer. The channel
4633
// should fail to be added if the cancel channel is closed.
4634
//
4635
// NOTE: Part of the lnpeer.Peer interface.
4636
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
UNCOV
4637
        cancel <-chan struct{}) error {
×
UNCOV
4638

×
UNCOV
4639
        errChan := make(chan error, 1)
×
UNCOV
4640
        newChanMsg := &newChannelMsg{
×
UNCOV
4641
                channelID: cid,
×
UNCOV
4642
                err:       errChan,
×
UNCOV
4643
        }
×
UNCOV
4644

×
UNCOV
4645
        select {
×
UNCOV
4646
        case p.newPendingChannel <- newChanMsg:
×
4647

4648
        case <-cancel:
×
4649
                return errors.New("canceled adding pending channel")
×
4650

NEW
4651
        case <-p.cg.Done():
×
4652
                return lnpeer.ErrPeerExiting
×
4653
        }
4654

4655
        // We pause here to wait for the peer to recognize the new pending
4656
        // channel before we close the channel barrier corresponding to the
4657
        // channel.
UNCOV
4658
        select {
×
UNCOV
4659
        case err := <-errChan:
×
UNCOV
4660
                return err
×
4661

4662
        case <-cancel:
×
4663
                return errors.New("canceled adding pending channel")
×
4664

NEW
4665
        case <-p.cg.Done():
×
4666
                return lnpeer.ErrPeerExiting
×
4667
        }
4668
}
4669

4670
// RemovePendingChannel removes a pending open channel from the peer.
4671
//
4672
// NOTE: Part of the lnpeer.Peer interface.
UNCOV
4673
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
×
UNCOV
4674
        errChan := make(chan error, 1)
×
UNCOV
4675
        newChanMsg := &newChannelMsg{
×
UNCOV
4676
                channelID: cid,
×
UNCOV
4677
                err:       errChan,
×
UNCOV
4678
        }
×
UNCOV
4679

×
UNCOV
4680
        select {
×
UNCOV
4681
        case p.removePendingChannel <- newChanMsg:
×
NEW
4682
        case <-p.cg.Done():
×
4683
                return lnpeer.ErrPeerExiting
×
4684
        }
4685

4686
        // We pause here to wait for the peer to respond to the cancellation of
4687
        // the pending channel before we close the channel barrier
4688
        // corresponding to the channel.
UNCOV
4689
        select {
×
UNCOV
4690
        case err := <-errChan:
×
UNCOV
4691
                return err
×
4692

NEW
4693
        case <-p.cg.Done():
×
4694
                return lnpeer.ErrPeerExiting
×
4695
        }
4696
}
4697

4698
// StartTime returns the time at which the connection was established if the
4699
// peer started successfully, and zero otherwise.
UNCOV
4700
func (p *Brontide) StartTime() time.Time {
×
UNCOV
4701
        return p.startTime
×
UNCOV
4702
}
×
4703

4704
// handleCloseMsg is called when a new cooperative channel closure related
4705
// message is received from the remote peer. We'll use this message to advance
4706
// the chan closer state machine.
4707
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
13✔
4708
        link := p.fetchLinkFromKeyAndCid(msg.cid)
13✔
4709

13✔
4710
        // We'll now fetch the matching closing state machine in order to
13✔
4711
        // continue, or finalize the channel closure process.
13✔
4712
        chanCloserE, err := p.fetchActiveChanCloser(msg.cid)
13✔
4713
        if err != nil {
13✔
NEW
4714
                // If the channel is not known to us, we'll simply ignore this
×
NEW
4715
                // message.
×
UNCOV
4716
                if err == ErrChannelNotFound {
×
UNCOV
4717
                        return
×
UNCOV
4718
                }
×
4719

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

×
4722
                errMsg := &lnwire.Error{
×
4723
                        ChanID: msg.cid,
×
4724
                        Data:   lnwire.ErrorData(err.Error()),
×
4725
                }
×
4726
                p.queueMsg(errMsg, nil)
×
4727
                return
×
4728
        }
4729

4730
        if chanCloserE.IsRight() {
13✔
NEW
4731
                // TODO(roasbeef): assert?
×
NEW
4732
                return
×
NEW
4733
        }
×
4734

4735
        // At this point, we'll only enter this call path if a negotiate chan
4736
        // closer was used. So we'll extract that from the either now.
4737
        //
4738
        // TODO(roabeef): need extra helper func for either to make cleaner
4739
        var chanCloser *chancloser.ChanCloser
13✔
4740
        chanCloserE.WhenLeft(func(c *chancloser.ChanCloser) {
26✔
4741
                chanCloser = c
13✔
4742
        })
13✔
4743

4744
        handleErr := func(err error) {
13✔
UNCOV
4745
                err = fmt.Errorf("unable to process close msg: %w", err)
×
UNCOV
4746
                p.log.Error(err)
×
UNCOV
4747

×
NEW
4748
                // As the negotiations failed, we'll reset the channel state
×
NEW
4749
                // machine to ensure we act to on-chain events as normal.
×
UNCOV
4750
                chanCloser.Channel().ResetState()
×
UNCOV
4751
                if chanCloser.CloseRequest() != nil {
×
UNCOV
4752
                        chanCloser.CloseRequest().Err <- err
×
4753
                }
×
4754

NEW
4755
                p.activeChanCloses.Delete(msg.cid)
×
UNCOV
4756

×
UNCOV
4757
                p.Disconnect(err)
×
4758
        }
4759

4760
        // Next, we'll process the next message using the target state machine.
4761
        // We'll either continue negotiation, or halt.
4762
        switch typed := msg.msg.(type) {
13✔
4763
        case *lnwire.Shutdown:
5✔
4764
                // Disable incoming adds immediately.
5✔
4765
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
5✔
4766
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
4767
                                link.ChanID())
×
4768
                }
×
4769

4770
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
5✔
4771
                if err != nil {
5✔
4772
                        handleErr(err)
×
4773
                        return
×
4774
                }
×
4775

4776
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
8✔
4777
                        // If the link is nil it means we can immediately queue
3✔
4778
                        // the Shutdown message since we don't have to wait for
3✔
4779
                        // commitment transaction synchronization.
3✔
4780
                        if link == nil {
4✔
4781
                                p.queueMsg(&msg, nil)
1✔
4782
                                return
1✔
4783
                        }
1✔
4784

4785
                        // Immediately disallow any new HTLC's from being added
4786
                        // in the outgoing direction.
4787
                        if !link.DisableAdds(htlcswitch.Outgoing) {
2✔
4788
                                p.log.Warnf("Outgoing link adds already "+
×
4789
                                        "disabled: %v", link.ChanID())
×
4790
                        }
×
4791

4792
                        // When we have a Shutdown to send, we defer it till the
4793
                        // next time we send a CommitSig to remain spec
4794
                        // compliant.
4795
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
4✔
4796
                                p.queueMsg(&msg, nil)
2✔
4797
                        })
2✔
4798
                })
4799

4800
                beginNegotiation := func() {
10✔
4801
                        oClosingSigned, err := chanCloser.BeginNegotiation()
5✔
4802
                        if err != nil {
5✔
4803
                                handleErr(err)
×
4804
                                return
×
4805
                        }
×
4806

4807
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
10✔
4808
                                p.queueMsg(&msg, nil)
5✔
4809
                        })
5✔
4810
                }
4811

4812
                if link == nil {
6✔
4813
                        beginNegotiation()
1✔
4814
                } else {
5✔
4815
                        // Now we register a flush hook to advance the
4✔
4816
                        // ChanCloser and possibly send out a ClosingSigned
4✔
4817
                        // when the link finishes draining.
4✔
4818
                        link.OnFlushedOnce(func() {
8✔
4819
                                // Remove link in goroutine to prevent deadlock.
4✔
4820
                                go p.cfg.Switch.RemoveLink(msg.cid)
4✔
4821
                                beginNegotiation()
4✔
4822
                        })
4✔
4823
                }
4824

4825
        case *lnwire.ClosingSigned:
8✔
4826
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
8✔
4827
                if err != nil {
8✔
UNCOV
4828
                        handleErr(err)
×
UNCOV
4829
                        return
×
UNCOV
4830
                }
×
4831

4832
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
16✔
4833
                        p.queueMsg(&msg, nil)
8✔
4834
                })
8✔
4835

4836
        default:
×
4837
                panic("impossible closeMsg type")
×
4838
        }
4839

4840
        // If we haven't finished close negotiations, then we'll continue as we
4841
        // can't yet finalize the closure.
4842
        if _, err := chanCloser.ClosingTx(); err != nil {
20✔
4843
                return
8✔
4844
        }
8✔
4845

4846
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
4847
        // the channel closure by notifying relevant sub-systems and launching a
4848
        // goroutine to wait for close tx conf.
4849
        p.finalizeChanClosure(chanCloser)
4✔
4850
}
4851

4852
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
4853
// the channelManager goroutine, which will shut down the link and possibly
4854
// close the channel.
UNCOV
4855
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
×
UNCOV
4856
        select {
×
UNCOV
4857
        case p.localCloseChanReqs <- req:
×
UNCOV
4858
                p.log.Info("Local close channel request is going to be " +
×
UNCOV
4859
                        "delivered to the peer")
×
NEW
4860
        case <-p.cg.Done():
×
4861
                p.log.Info("Unable to deliver local close channel request " +
×
4862
                        "to peer")
×
4863
        }
4864
}
4865

4866
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
UNCOV
4867
func (p *Brontide) NetAddress() *lnwire.NetAddress {
×
UNCOV
4868
        return p.cfg.Addr
×
UNCOV
4869
}
×
4870

4871
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
UNCOV
4872
func (p *Brontide) Inbound() bool {
×
UNCOV
4873
        return p.cfg.Inbound
×
UNCOV
4874
}
×
4875

4876
// ConnReq is a getter for the Brontide's connReq in cfg.
UNCOV
4877
func (p *Brontide) ConnReq() *connmgr.ConnReq {
×
UNCOV
4878
        return p.cfg.ConnReq
×
UNCOV
4879
}
×
4880

4881
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
UNCOV
4882
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
×
UNCOV
4883
        return p.cfg.ErrorBuffer
×
UNCOV
4884
}
×
4885

4886
// SetAddress sets the remote peer's address given an address.
4887
func (p *Brontide) SetAddress(address net.Addr) {
×
4888
        p.cfg.Addr.Address = address
×
4889
}
×
4890

4891
// ActiveSignal returns the peer's active signal.
UNCOV
4892
func (p *Brontide) ActiveSignal() chan struct{} {
×
UNCOV
4893
        return p.activeSignal
×
UNCOV
4894
}
×
4895

4896
// Conn returns a pointer to the peer's connection struct.
UNCOV
4897
func (p *Brontide) Conn() net.Conn {
×
UNCOV
4898
        return p.cfg.Conn
×
UNCOV
4899
}
×
4900

4901
// BytesReceived returns the number of bytes received from the peer.
UNCOV
4902
func (p *Brontide) BytesReceived() uint64 {
×
UNCOV
4903
        return atomic.LoadUint64(&p.bytesReceived)
×
UNCOV
4904
}
×
4905

4906
// BytesSent returns the number of bytes sent to the peer.
UNCOV
4907
func (p *Brontide) BytesSent() uint64 {
×
UNCOV
4908
        return atomic.LoadUint64(&p.bytesSent)
×
UNCOV
4909
}
×
4910

4911
// LastRemotePingPayload returns the last payload the remote party sent as part
4912
// of their ping.
UNCOV
4913
func (p *Brontide) LastRemotePingPayload() []byte {
×
UNCOV
4914
        pingPayload := p.lastPingPayload.Load()
×
UNCOV
4915
        if pingPayload == nil {
×
UNCOV
4916
                return []byte{}
×
UNCOV
4917
        }
×
4918

4919
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
4920
        if !ok {
×
4921
                return nil
×
4922
        }
×
4923

4924
        return pingBytes
×
4925
}
4926

4927
// attachChannelEventSubscription creates a channel event subscription and
4928
// attaches to client to Brontide if the reenableTimeout is no greater than 1
4929
// minute.
4930
func (p *Brontide) attachChannelEventSubscription() error {
3✔
4931
        // If the timeout is greater than 1 minute, it's unlikely that the link
3✔
4932
        // hasn't yet finished its reestablishment. Return a nil without
3✔
4933
        // creating the client to specify that we don't want to retry.
3✔
4934
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
3✔
UNCOV
4935
                return nil
×
UNCOV
4936
        }
×
4937

4938
        // When the reenable timeout is less than 1 minute, it's likely the
4939
        // channel link hasn't finished its reestablishment yet. In that case,
4940
        // we'll give it a second chance by subscribing to the channel update
4941
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
4942
        // enabling the channel again.
4943
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
3✔
4944
        if err != nil {
3✔
4945
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
4946
        }
×
4947

4948
        p.channelEventClient = sub
3✔
4949

3✔
4950
        return nil
3✔
4951
}
4952

4953
// updateNextRevocation updates the existing channel's next revocation if it's
4954
// nil.
4955
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
3✔
4956
        chanPoint := c.FundingOutpoint
3✔
4957
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4958

3✔
4959
        // Read the current channel.
3✔
4960
        currentChan, loaded := p.activeChannels.Load(chanID)
3✔
4961

3✔
4962
        // currentChan should exist, but we perform a check anyway to avoid nil
3✔
4963
        // pointer dereference.
3✔
4964
        if !loaded {
4✔
4965
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
4966
                        chanID)
1✔
4967
        }
1✔
4968

4969
        // currentChan should not be nil, but we perform a check anyway to
4970
        // avoid nil pointer dereference.
4971
        if currentChan == nil {
3✔
4972
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
4973
                        chanID)
1✔
4974
        }
1✔
4975

4976
        // If we're being sent a new channel, and our existing channel doesn't
4977
        // have the next revocation, then we need to update the current
4978
        // existing channel.
4979
        if currentChan.RemoteNextRevocation() != nil {
1✔
4980
                return nil
×
4981
        }
×
4982

4983
        p.log.Infof("Processing retransmitted ChannelReady for "+
1✔
4984
                "ChannelPoint(%v)", chanPoint)
1✔
4985

1✔
4986
        nextRevoke := c.RemoteNextRevocation
1✔
4987

1✔
4988
        err := currentChan.InitNextRevocation(nextRevoke)
1✔
4989
        if err != nil {
1✔
4990
                return fmt.Errorf("unable to init next revocation: %w", err)
×
4991
        }
×
4992

4993
        return nil
1✔
4994
}
4995

4996
// addActiveChannel adds a new active channel to the `activeChannels` map. It
4997
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
4998
// it and assembles it with a channel link.
UNCOV
4999
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
×
UNCOV
5000
        chanPoint := c.FundingOutpoint
×
UNCOV
5001
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
5002

×
UNCOV
5003
        // If we've reached this point, there are two possible scenarios.  If
×
UNCOV
5004
        // the channel was in the active channels map as nil, then it was
×
UNCOV
5005
        // loaded from disk and we need to send reestablish. Else, it was not
×
UNCOV
5006
        // loaded from disk and we don't need to send reestablish as this is a
×
UNCOV
5007
        // fresh channel.
×
UNCOV
5008
        shouldReestablish := p.isLoadedFromDisk(chanID)
×
UNCOV
5009

×
UNCOV
5010
        chanOpts := c.ChanOpts
×
UNCOV
5011
        if shouldReestablish {
×
UNCOV
5012
                // If we have to do the reestablish dance for this channel,
×
UNCOV
5013
                // ensure that we don't try to call InitRemoteMusigNonces twice
×
UNCOV
5014
                // by calling SkipNonceInit.
×
UNCOV
5015
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
×
UNCOV
5016
        }
×
5017

UNCOV
5018
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
×
5019
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
5020
        })
×
UNCOV
5021
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
×
5022
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
5023
        })
×
UNCOV
5024
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
×
5025
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
5026
        })
×
5027

5028
        // If not already active, we'll add this channel to the set of active
5029
        // channels, so we can look it up later easily according to its channel
5030
        // ID.
UNCOV
5031
        lnChan, err := lnwallet.NewLightningChannel(
×
UNCOV
5032
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
×
UNCOV
5033
        )
×
UNCOV
5034
        if err != nil {
×
5035
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
5036
        }
×
5037

5038
        // Store the channel in the activeChannels map.
UNCOV
5039
        p.activeChannels.Store(chanID, lnChan)
×
UNCOV
5040

×
UNCOV
5041
        p.log.Infof("New channel active ChannelPoint(%v) with peer", chanPoint)
×
UNCOV
5042

×
UNCOV
5043
        // Next, we'll assemble a ChannelLink along with the necessary items it
×
UNCOV
5044
        // needs to function.
×
UNCOV
5045
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
×
UNCOV
5046
        if err != nil {
×
5047
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
5048
                        err)
×
5049
        }
×
5050

5051
        // We'll query the channel DB for the new channel's initial forwarding
5052
        // policies to determine the policy we start out with.
UNCOV
5053
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
×
UNCOV
5054
        if err != nil {
×
5055
                return fmt.Errorf("unable to query for initial forwarding "+
×
5056
                        "policy: %v", err)
×
5057
        }
×
5058

5059
        // Create the link and add it to the switch.
UNCOV
5060
        err = p.addLink(
×
UNCOV
5061
                &chanPoint, lnChan, initialPolicy, chainEvents,
×
UNCOV
5062
                shouldReestablish, fn.None[lnwire.Shutdown](),
×
UNCOV
5063
        )
×
UNCOV
5064
        if err != nil {
×
5065
                return fmt.Errorf("can't register new channel link(%v) with "+
×
5066
                        "peer", chanPoint)
×
5067
        }
×
5068

5069
        // We're using the old co-op close, so we don't need to init the new
5070
        // RBF chan closer.
NEW
5071
        if !p.rbfCoopCloseAllowed() {
×
NEW
5072
                return nil
×
NEW
5073
        }
×
5074

5075
        // Now that the link has been added above, we'll also init an RBF chan
5076
        // closer for this channel, but only if the new close feature is
5077
        // negotiated.
5078
        //
5079
        // Creating this here ensures that any shutdown messages sent will be
5080
        // automatically routed by the msg router.
NEW
5081
        if _, err := p.initRbfChanCloser(lnChan); err != nil {
×
NEW
5082
                p.activeChanCloses.Delete(chanID)
×
NEW
5083

×
NEW
5084
                return fmt.Errorf("unable to init RBF chan closer for new "+
×
NEW
5085
                        "chan: %w", err)
×
NEW
5086
        }
×
5087

UNCOV
5088
        return nil
×
5089
}
5090

5091
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
5092
// know this channel ID or not, we'll either add it to the `activeChannels` map
5093
// or init the next revocation for it.
UNCOV
5094
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
×
UNCOV
5095
        newChan := req.channel
×
UNCOV
5096
        chanPoint := newChan.FundingOutpoint
×
UNCOV
5097
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
5098

×
UNCOV
5099
        // Only update RemoteNextRevocation if the channel is in the
×
UNCOV
5100
        // activeChannels map and if we added the link to the switch. Only
×
UNCOV
5101
        // active channels will be added to the switch.
×
UNCOV
5102
        if p.isActiveChannel(chanID) {
×
UNCOV
5103
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
×
UNCOV
5104
                        chanPoint)
×
UNCOV
5105

×
UNCOV
5106
                // Handle it and close the err chan on the request.
×
UNCOV
5107
                close(req.err)
×
UNCOV
5108

×
UNCOV
5109
                // Update the next revocation point.
×
UNCOV
5110
                err := p.updateNextRevocation(newChan.OpenChannel)
×
UNCOV
5111
                if err != nil {
×
5112
                        p.log.Errorf(err.Error())
×
5113
                }
×
5114

UNCOV
5115
                return
×
5116
        }
5117

5118
        // This is a new channel, we now add it to the map.
UNCOV
5119
        if err := p.addActiveChannel(req.channel); err != nil {
×
5120
                // Log and send back the error to the request.
×
5121
                p.log.Errorf(err.Error())
×
5122
                req.err <- err
×
5123

×
5124
                return
×
5125
        }
×
5126

5127
        // Close the err chan if everything went fine.
UNCOV
5128
        close(req.err)
×
5129
}
5130

5131
// handleNewPendingChannel takes a `newChannelMsg` request and add it to
5132
// `activeChannels` map with nil value. This pending channel will be saved as
5133
// it may become active in the future. Once active, the funding manager will
5134
// send it again via `AddNewChannel`, and we'd handle the link creation there.
5135
func (p *Brontide) handleNewPendingChannel(req *newChannelMsg) {
4✔
5136
        defer close(req.err)
4✔
5137

4✔
5138
        chanID := req.channelID
4✔
5139

4✔
5140
        // If we already have this channel, something is wrong with the funding
4✔
5141
        // flow as it will only be marked as active after `ChannelReady` is
4✔
5142
        // handled. In this case, we will do nothing but log an error, just in
4✔
5143
        // case this is a legit channel.
4✔
5144
        if p.isActiveChannel(chanID) {
5✔
5145
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
5146
                        "pending channel request", chanID)
1✔
5147

1✔
5148
                return
1✔
5149
        }
1✔
5150

5151
        // The channel has already been added, we will do nothing and return.
5152
        if p.isPendingChannel(chanID) {
4✔
5153
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
5154
                        "pending channel request", chanID)
1✔
5155

1✔
5156
                return
1✔
5157
        }
1✔
5158

5159
        // This is a new channel, we now add it to the map `activeChannels`
5160
        // with nil value and mark it as a newly added channel in
5161
        // `addedChannels`.
5162
        p.activeChannels.Store(chanID, nil)
2✔
5163
        p.addedChannels.Store(chanID, struct{}{})
2✔
5164
}
5165

5166
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
5167
// from `activeChannels` map. The request will be ignored if the channel is
5168
// considered active by Brontide. Noop if the channel ID cannot be found.
5169
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
4✔
5170
        defer close(req.err)
4✔
5171

4✔
5172
        chanID := req.channelID
4✔
5173

4✔
5174
        // If we already have this channel, something is wrong with the funding
4✔
5175
        // flow as it will only be marked as active after `ChannelReady` is
4✔
5176
        // handled. In this case, we will log an error and exit.
4✔
5177
        if p.isActiveChannel(chanID) {
5✔
5178
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
5179
                        chanID)
1✔
5180
                return
1✔
5181
        }
1✔
5182

5183
        // The channel has not been added yet, we will log a warning as there
5184
        // is an unexpected call from funding manager.
5185
        if !p.isPendingChannel(chanID) {
4✔
5186
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
1✔
5187
        }
1✔
5188

5189
        // Remove the record of this pending channel.
5190
        p.activeChannels.Delete(chanID)
3✔
5191
        p.addedChannels.Delete(chanID)
3✔
5192
}
5193

5194
// sendLinkUpdateMsg sends a message that updates the channel to the
5195
// channel's message stream.
UNCOV
5196
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
×
UNCOV
5197
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
×
UNCOV
5198

×
UNCOV
5199
        chanStream, ok := p.activeMsgStreams[cid]
×
UNCOV
5200
        if !ok {
×
UNCOV
5201
                // If a stream hasn't yet been created, then we'll do so, add
×
UNCOV
5202
                // it to the map, and finally start it.
×
UNCOV
5203
                chanStream = newChanMsgStream(p, cid)
×
UNCOV
5204
                p.activeMsgStreams[cid] = chanStream
×
UNCOV
5205
                chanStream.Start()
×
UNCOV
5206

×
UNCOV
5207
                // Stop the stream when quit.
×
UNCOV
5208
                go func() {
×
NEW
5209
                        <-p.cg.Done()
×
UNCOV
5210
                        chanStream.Stop()
×
UNCOV
5211
                }()
×
5212
        }
5213

5214
        // With the stream obtained, add the message to the stream so we can
5215
        // continue processing message.
UNCOV
5216
        chanStream.AddMsg(msg)
×
5217
}
5218

5219
// scaleTimeout multiplies the argument duration by a constant factor depending
5220
// on variious heuristics. Currently this is only used to check whether our peer
5221
// appears to be connected over Tor and relaxes the timout deadline. However,
5222
// this is subject to change and should be treated as opaque.
5223
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
67✔
5224
        if p.isTorConnection {
67✔
UNCOV
5225
                return timeout * time.Duration(torTimeoutMultiplier)
×
UNCOV
5226
        }
×
5227

5228
        return timeout
67✔
5229
}
5230

5231
// CoopCloseUpdates is a struct used to communicate updates for an active close
5232
// to the caller.
5233
type CoopCloseUpdates struct {
5234
        UpdateChan chan interface{}
5235

5236
        ErrChan chan error
5237
}
5238

5239
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5240
// point has an active RBF chan closer.
NEW
5241
func (p *Brontide) ChanHasRbfCoopCloser(chanPoint wire.OutPoint) bool {
×
NEW
5242
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
NEW
5243
        chanCloser, found := p.activeChanCloses.Load(chanID)
×
NEW
5244
        if !found {
×
NEW
5245
                return false
×
NEW
5246
        }
×
5247

NEW
5248
        return chanCloser.IsRight()
×
5249
}
5250

5251
// TriggerCoopCloseRbfBump given a chan ID, and the params needed to trigger a
5252
// new RBF co-op close update, a bump is attempted. A channel used for updates,
5253
// along with one used to o=communicate any errors is returned. If no chan
5254
// closer is found, then false is returned for the second argument.
5255
func (p *Brontide) TriggerCoopCloseRbfBump(ctx context.Context,
5256
        chanPoint wire.OutPoint, feeRate chainfee.SatPerKWeight,
NEW
5257
        deliveryScript lnwire.DeliveryAddress) (*CoopCloseUpdates, error) {
×
NEW
5258

×
NEW
5259
        // If RBF coop close isn't permitted, then we'll an error.
×
NEW
5260
        if !p.rbfCoopCloseAllowed() {
×
NEW
5261
                return nil, fmt.Errorf("rbf coop close not enabled for " +
×
NEW
5262
                        "channel")
×
NEW
5263
        }
×
5264

NEW
5265
        closeUpdates := &CoopCloseUpdates{
×
NEW
5266
                UpdateChan: make(chan interface{}, 1),
×
NEW
5267
                ErrChan:    make(chan error, 1),
×
NEW
5268
        }
×
NEW
5269

×
NEW
5270
        // We'll re-use the existing switch struct here, even though we're
×
NEW
5271
        // bypassing the switch entirely.
×
NEW
5272
        closeReq := htlcswitch.ChanClose{
×
NEW
5273
                CloseType:      contractcourt.CloseRegular,
×
NEW
5274
                ChanPoint:      &chanPoint,
×
NEW
5275
                TargetFeePerKw: feeRate,
×
NEW
5276
                DeliveryScript: deliveryScript,
×
NEW
5277
                Updates:        closeUpdates.UpdateChan,
×
NEW
5278
                Err:            closeUpdates.ErrChan,
×
NEW
5279
                Ctx:            ctx,
×
NEW
5280
        }
×
NEW
5281

×
NEW
5282
        err := p.startRbfChanCloser(newRPCShutdownInit(&closeReq), chanPoint)
×
NEW
5283
        if err != nil {
×
NEW
5284
                return nil, err
×
NEW
5285
        }
×
5286

NEW
5287
        return closeUpdates, nil
×
5288
}
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