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

lightningnetwork / lnd / 21485572389

29 Jan 2026 04:09PM UTC coverage: 65.247% (+0.2%) from 65.074%
21485572389

Pull #10089

github

web-flow
Merge 22d34d15e into 19b2ad797
Pull Request #10089: Onion message forwarding

1152 of 1448 new or added lines in 23 files covered. (79.56%)

4109 existing lines in 29 files now uncovered.

139515 of 213825 relevant lines covered (65.25%)

20529.09 hits per line

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

78.36
/peer/brontide.go
1
package peer
2

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

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

62
const (
63
        // pingInterval is the interval at which ping messages are sent.
64
        pingInterval = 1 * time.Minute
65

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

72
        // idleTimeout is the duration of inactivity before we time out a peer.
73
        idleTimeout = 5 * time.Minute
74

75
        // writeMessageTimeout is the timeout used when writing a message to the
76
        // peer.
77
        writeMessageTimeout = 5 * time.Second
78

79
        // readMessageTimeout is the timeout used when reading a message from a
80
        // peer.
81
        readMessageTimeout = 5 * time.Second
82

83
        // handshakeTimeout is the timeout used when waiting for the peer's init
84
        // message.
85
        handshakeTimeout = 15 * time.Second
86

87
        // ErrorBufferSize is the number of historic peer errors that we store.
88
        ErrorBufferSize = 10
89

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

96
        // torTimeoutMultiplier is the scaling factor we use on network timeouts
97
        // for Tor peers.
98
        torTimeoutMultiplier = 3
99

100
        // msgStreamSize is the size of the message streams.
101
        msgStreamSize = 50
102
)
103

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

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

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

127
        // channelID is used when there's a new pending channel.
128
        channelID lnwire.ChannelID
129

130
        err chan error
131
}
132

133
type customMsg struct {
134
        peer [33]byte
135
        msg  lnwire.Custom
136
}
137

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

146
// PendingUpdate describes the pending state of a closing channel.
147
type PendingUpdate struct {
148
        // Txid is the txid of the closing transaction.
149
        Txid []byte
150

151
        // OutputIndex is the output index of our output in the closing
152
        // transaction.
153
        OutputIndex uint32
154

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

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

166
// ChannelCloseUpdate contains the outcome of the close channel operation.
167
type ChannelCloseUpdate struct {
168
        ClosingTxid []byte
169
        Success     bool
170

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

176
        // RemoteCloseOutput is an optional, additional output on the closing
177
        // transaction that the remote party should be paid to. This will only
178
        // be populated if the remote balance isn't dust.
179
        RemoteCloseOutput fn.Option[types.CloseOutput]
180

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

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

194
// Config defines configuration fields that are necessary for a peer object
195
// to function.
196
type Config struct {
197
        // Conn is the underlying network connection for this peer.
198
        Conn MessageConn
199

200
        // ConnReq stores information related to the persistent connection request
201
        // for this peer.
202
        ConnReq *connmgr.ConnReq
203

204
        // PubKeyBytes is the serialized, compressed public key of this peer.
205
        PubKeyBytes [33]byte
206

207
        // Addr is the network address of the peer.
208
        Addr *lnwire.NetAddress
209

210
        // Inbound indicates whether or not the peer is an inbound peer.
211
        Inbound bool
212

213
        // Features is the set of features that we advertise to the remote party.
214
        Features *lnwire.FeatureVector
215

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

223
        // OutgoingCltvRejectDelta defines the number of blocks before expiry of
224
        // an htlc where we don't offer it anymore.
225
        OutgoingCltvRejectDelta uint32
226

227
        // ChanActiveTimeout specifies the duration the peer will wait to request
228
        // a channel reenable, beginning from the time the peer was started.
229
        ChanActiveTimeout time.Duration
230

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

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

245
        // ReadPool is the task pool that manages reuse of read buffers.
246
        ReadPool *pool.Read
247

248
        // Switch is a pointer to the htlcswitch. It is used to setup, get, and
249
        // tear-down ChannelLinks.
250
        Switch messageSwitch
251

252
        // InterceptSwitch is a pointer to the InterceptableSwitch, a wrapper around
253
        // the regular Switch. We only export it here to pass ForwardPackets to the
254
        // ChannelLinkConfig.
255
        InterceptSwitch *htlcswitch.InterceptableSwitch
256

257
        // ChannelDB is used to fetch opened channels, and closed channels.
258
        ChannelDB *channeldb.ChannelStateDB
259

260
        // ChannelGraph is a pointer to the channel graph which is used to
261
        // query information about the set of known active channels.
262
        ChannelGraph *graphdb.ChannelGraph
263

264
        // ChainArb is used to subscribe to channel events, update contract signals,
265
        // and force close channels.
266
        ChainArb *contractcourt.ChainArbitrator
267

268
        // AuthGossiper is needed so that the Brontide impl can register with the
269
        // gossiper and process remote channel announcements.
270
        AuthGossiper *discovery.AuthenticatedGossiper
271

272
        // ChanStatusMgr is used to set or un-set the disabled bit in channel
273
        // updates.
274
        ChanStatusMgr *netann.ChanStatusManager
275

276
        // ChainIO is used to retrieve the best block.
277
        ChainIO lnwallet.BlockChainIO
278

279
        // FeeEstimator is used to compute our target ideal fee-per-kw when
280
        // initializing the coop close process.
281
        FeeEstimator chainfee.Estimator
282

283
        // Signer is used when creating *lnwallet.LightningChannel instances.
284
        Signer input.Signer
285

286
        // SigPool is used when creating *lnwallet.LightningChannel instances.
287
        SigPool *lnwallet.SigPool
288

289
        // Wallet is used to publish transactions and generates delivery
290
        // scripts during the coop close process.
291
        Wallet *lnwallet.LightningWallet
292

293
        // ChainNotifier is used to receive confirmations of a coop close
294
        // transaction.
295
        ChainNotifier chainntnfs.ChainNotifier
296

297
        // BestBlockView is used to efficiently query for up-to-date
298
        // blockchain state information
299
        BestBlockView chainntnfs.BestBlockView
300

301
        // RoutingPolicy is used to set the forwarding policy for links created by
302
        // the Brontide.
303
        RoutingPolicy models.ForwardingPolicy
304

305
        // SphinxPayment is used when setting up ChannelLinks so they can decode
306
        // sphinx onion blobs.
307
        SphinxPayment *hop.OnionProcessor
308

309
        // OnionEndpoint handles incoming onion messages and routes them to the
310
        // appropriate peer actor for forwarding or processes them locally.
311
        OnionEndpoint *onionmessage.OnionEndpoint
312

313
        // WitnessBeacon is used when setting up ChannelLinks so they can add any
314
        // preimages that they learn.
315
        WitnessBeacon contractcourt.WitnessBeacon
316

317
        // Invoices is passed to the ChannelLink on creation and handles all
318
        // invoice-related logic.
319
        Invoices *invoices.InvoiceRegistry
320

321
        // ChannelNotifier is used by the link to notify other sub-systems about
322
        // channel-related events and by the Brontide to subscribe to
323
        // ActiveLinkEvents.
324
        ChannelNotifier *channelnotifier.ChannelNotifier
325

326
        // HtlcNotifier is used when creating a ChannelLink.
327
        HtlcNotifier *htlcswitch.HtlcNotifier
328

329
        // TowerClient is used to backup revoked states.
330
        TowerClient wtclient.ClientManager
331

332
        // DisconnectPeer is used to disconnect this peer if the cooperative close
333
        // process fails.
334
        DisconnectPeer func(*btcec.PublicKey) error
335

336
        // GenNodeAnnouncement is used to send our node announcement to the remote
337
        // on startup.
338
        GenNodeAnnouncement func(...netann.NodeAnnModifier) (
339
                lnwire.NodeAnnouncement1, error)
340

341
        // PrunePersistentPeerConnection is used to remove all internal state
342
        // related to this peer in the server.
343
        PrunePersistentPeerConnection func([33]byte)
344

345
        // FetchLastChanUpdate fetches our latest channel update for a target
346
        // channel.
347
        FetchLastChanUpdate func(lnwire.ShortChannelID) (*lnwire.ChannelUpdate1,
348
                error)
349

350
        // FundingManager is an implementation of the funding.Controller interface.
351
        FundingManager funding.Controller
352

353
        // Hodl is used when creating ChannelLinks to specify HodlFlags as
354
        // breakpoints in dev builds.
355
        Hodl *hodl.Config
356

357
        // UnsafeReplay is used when creating ChannelLinks to specify whether or
358
        // not to replay adds on its commitment tx.
359
        UnsafeReplay bool
360

361
        // MaxOutgoingCltvExpiry is used when creating ChannelLinks and is the max
362
        // number of blocks that funds could be locked up for when forwarding
363
        // payments.
364
        MaxOutgoingCltvExpiry uint32
365

366
        // MaxChannelFeeAllocation is used when creating ChannelLinks and is the
367
        // maximum percentage of total funds that can be allocated to a channel's
368
        // commitment fee. This only applies for the initiator of the channel.
369
        MaxChannelFeeAllocation float64
370

371
        // MaxAnchorsCommitFeeRate is the maximum fee rate we'll use as an
372
        // initiator for anchor channel commitments.
373
        MaxAnchorsCommitFeeRate chainfee.SatPerKWeight
374

375
        // CoopCloseTargetConfs is the confirmation target that will be used
376
        // to estimate the fee rate to use during a cooperative channel
377
        // closure initiated by the remote peer.
378
        CoopCloseTargetConfs uint32
379

380
        // ChannelCloseConfs is an optional override for the number of
381
        // confirmations required for channel closes. When set, this overrides
382
        // the normal capacity-based scaling. This is only available in
383
        // dev/integration builds for testing purposes.
384
        ChannelCloseConfs fn.Option[uint32]
385

386
        // ServerPubKey is the serialized, compressed public key of our lnd node.
387
        // It is used to determine which policy (channel edge) to pass to the
388
        // ChannelLink.
389
        ServerPubKey [33]byte
390

391
        // ChannelCommitInterval is the maximum time that is allowed to pass between
392
        // receiving a channel state update and signing the next commitment.
393
        // Setting this to a longer duration allows for more efficient channel
394
        // operations at the cost of latency.
395
        ChannelCommitInterval time.Duration
396

397
        // PendingCommitInterval is the maximum time that is allowed to pass
398
        // while waiting for the remote party to revoke a locally initiated
399
        // commitment state. Setting this to a longer duration if a slow
400
        // response is expected from the remote party or large number of
401
        // payments are attempted at the same time.
402
        PendingCommitInterval time.Duration
403

404
        // ChannelCommitBatchSize is the maximum number of channel state updates
405
        // that is accumulated before signing a new commitment.
406
        ChannelCommitBatchSize uint32
407

408
        // HandleCustomMessage is called whenever a custom message is received
409
        // from the peer.
410
        HandleCustomMessage func(peer [33]byte, msg *lnwire.Custom) error
411

412
        // GetAliases is passed to created links so the Switch and link can be
413
        // aware of the channel's aliases.
414
        GetAliases func(base lnwire.ShortChannelID) []lnwire.ShortChannelID
415

416
        // RequestAlias allows the Brontide struct to request an alias to send
417
        // to the peer.
418
        RequestAlias func() (lnwire.ShortChannelID, error)
419

420
        // AddLocalAlias persists an alias to an underlying alias store.
421
        AddLocalAlias func(alias, base lnwire.ShortChannelID, gossip,
422
                liveUpdate bool, opts ...aliasmgr.AddLocalAliasOption) error
423

424
        // AuxLeafStore is an optional store that can be used to store auxiliary
425
        // leaves for certain custom channel types.
426
        AuxLeafStore fn.Option[lnwallet.AuxLeafStore]
427

428
        // AuxSigner is an optional signer that can be used to sign auxiliary
429
        // leaves for certain custom channel types.
430
        AuxSigner fn.Option[lnwallet.AuxSigner]
431

432
        // AuxResolver is an optional interface that can be used to modify the
433
        // way contracts are resolved.
434
        AuxResolver fn.Option[lnwallet.AuxContractResolver]
435

436
        // AuxTrafficShaper is an optional auxiliary traffic shaper that can be
437
        // used to manage the bandwidth of peer links.
438
        AuxTrafficShaper fn.Option[htlcswitch.AuxTrafficShaper]
439

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

446
        // Adds the option to disable forwarding payments in blinded routes
447
        // by failing back any blinding-related payloads as if they were
448
        // invalid.
449
        DisallowRouteBlinding bool
450

451
        // DisallowQuiescence is a flag that indicates whether the Brontide
452
        // should have the quiescence feature disabled.
453
        DisallowQuiescence bool
454

455
        // QuiescenceTimeout is the max duration that the channel can be
456
        // quiesced. Any dependent protocols (dynamic commitments, splicing,
457
        // etc.) must finish their operations under this timeout value,
458
        // otherwise the node will disconnect.
459
        QuiescenceTimeout time.Duration
460

461
        // MaxFeeExposure limits the number of outstanding fees in a channel.
462
        // This value will be passed to created links.
463
        MaxFeeExposure lnwire.MilliSatoshi
464

465
        // MsgRouter is an optional instance of the main message router that
466
        // the peer will use. If None, then a new default version will be used
467
        // in place.
468
        MsgRouter fn.Option[msgmux.Router]
469

470
        // AuxChanCloser is an optional instance of an abstraction that can be
471
        // used to modify the way the co-op close transaction is constructed.
472
        AuxChanCloser fn.Option[chancloser.AuxChanCloser]
473

474
        // AuxChannelNegotiator is an optional interface that allows aux channel
475
        // implementations to inject and process custom records over channel
476
        // related wire messages.
477
        AuxChannelNegotiator fn.Option[lnwallet.AuxChannelNegotiator]
478

479
        // ShouldFwdExpAccountability is a closure that indicates whether
480
        // experimental accountability signals should be set.
481
        ShouldFwdExpAccountability func() bool
482

483
        // ActorSystem is the server wide actor system.
484
        ActorSystem *actor.ActorSystem
485

486
        // NoDisconnectOnPongFailure indicates whether the peer should *not* be
487
        // disconnected if a pong is not received in time or is mismatched.
488
        NoDisconnectOnPongFailure bool
489

490
        // Quit is the server's quit channel. If this is closed, we halt operation.
491
        Quit chan struct{}
492
}
493

494
// chanCloserFsm is a union-like type that can hold the two versions of co-op
495
// close we support: negotiation, and RBF based.
496
//
497
// TODO(roasbeef): rename to chancloser.Negotiator and chancloser.RBF?
498
type chanCloserFsm = fn.Either[*chancloser.ChanCloser, *chancloser.RbfChanCloser] //nolint:ll
499

500
// makeNegotiateCloser creates a new negotiate closer from a
501
// chancloser.ChanCloser.
502
func makeNegotiateCloser(chanCloser *chancloser.ChanCloser) chanCloserFsm {
11✔
503
        return fn.NewLeft[*chancloser.ChanCloser, *chancloser.RbfChanCloser](
11✔
504
                chanCloser,
11✔
505
        )
11✔
506
}
11✔
507

508
// makeRbfCloser creates a new RBF closer from a chancloser.RbfChanCloser.
509
func makeRbfCloser(rbfCloser *chancloser.RbfChanCloser) chanCloserFsm {
2✔
510
        return fn.NewRight[*chancloser.ChanCloser](
2✔
511
                rbfCloser,
2✔
512
        )
2✔
513
}
2✔
514

515
// Brontide is an active peer on the Lightning Network. This struct is responsible
516
// for managing any channel state related to this peer. To do so, it has
517
// several helper goroutines to handle events such as HTLC timeouts, new
518
// funding workflow, and detecting an uncooperative closure of any active
519
// channels.
520
type Brontide struct {
521
        // MUST be used atomically.
522
        started    int32
523
        disconnect int32
524

525
        // MUST be used atomically.
526
        bytesReceived uint64
527
        bytesSent     uint64
528

529
        // isTorConnection is a flag that indicates whether or not we believe
530
        // the remote peer is a tor connection. It is not always possible to
531
        // know this with certainty but we have heuristics we use that should
532
        // catch most cases.
533
        //
534
        // NOTE: We judge the tor-ness of a connection by if the remote peer has
535
        // ".onion" in the address OR if it's connected over localhost.
536
        // This will miss cases where our peer is connected to our clearnet
537
        // address over the tor network (via exit nodes). It will also misjudge
538
        // actual localhost connections as tor. We need to include this because
539
        // inbound connections to our tor address will appear to come from the
540
        // local socks5 proxy. This heuristic is only used to expand the timeout
541
        // window for peers so it is OK to misjudge this. If you use this field
542
        // for any other purpose you should seriously consider whether or not
543
        // this heuristic is good enough for your use case.
544
        isTorConnection bool
545

546
        pingManager *PingManager
547

548
        // lastPingPayload stores an unsafe pointer wrapped as an atomic
549
        // variable which points to the last payload the remote party sent us
550
        // as their ping.
551
        //
552
        // MUST be used atomically.
553
        lastPingPayload atomic.Value
554

555
        cfg Config
556

557
        // activeSignal when closed signals that the peer is now active and
558
        // ready to process messages.
559
        activeSignal chan struct{}
560

561
        // startTime is the time this peer connection was successfully established.
562
        // It will be zero for peers that did not successfully call Start().
563
        startTime time.Time
564

565
        // sendQueue is the channel which is used to queue outgoing messages to be
566
        // written onto the wire. Note that this channel is unbuffered.
567
        sendQueue chan outgoingMsg
568

569
        // outgoingQueue is a buffered channel which allows second/third party
570
        // objects to queue messages to be sent out on the wire.
571
        outgoingQueue chan outgoingMsg
572

573
        // activeChannels is a map which stores the state machines of all
574
        // active channels. Channels are indexed into the map by the txid of
575
        // the funding transaction which opened the channel.
576
        //
577
        // NOTE: On startup, pending channels are stored as nil in this map.
578
        // Confirmed channels have channel data populated in the map. This means
579
        // that accesses to this map should nil-check the LightningChannel to
580
        // see if this is a pending channel or not. The tradeoff here is either
581
        // having two maps everywhere (one for pending, one for confirmed chans)
582
        // or having an extra nil-check per access.
583
        activeChannels *lnutils.SyncMap[
584
                lnwire.ChannelID, *lnwallet.LightningChannel]
585

586
        // addedChannels tracks any new channels opened during this peer's
587
        // lifecycle. We use this to filter out these new channels when the time
588
        // comes to request a reenable for active channels, since they will have
589
        // waited a shorter duration.
590
        addedChannels *lnutils.SyncMap[lnwire.ChannelID, struct{}]
591

592
        // newActiveChannel is used by the fundingManager to send fully opened
593
        // channels to the source peer which handled the funding workflow.
594
        newActiveChannel chan *newChannelMsg
595

596
        // newPendingChannel is used by the fundingManager to send pending open
597
        // channels to the source peer which handled the funding workflow.
598
        newPendingChannel chan *newChannelMsg
599

600
        // removePendingChannel is used by the fundingManager to cancel pending
601
        // open channels to the source peer when the funding flow is failed.
602
        removePendingChannel chan *newChannelMsg
603

604
        // activeMsgStreams is a map from channel id to the channel streams that
605
        // proxy messages to individual, active links.
606
        activeMsgStreams map[lnwire.ChannelID]*msgStream
607

608
        // activeChanCloses is a map that keeps track of all the active
609
        // cooperative channel closures. Any channel closing messages are directed
610
        // to one of these active state machines. Once the channel has been closed,
611
        // the state machine will be deleted from the map.
612
        activeChanCloses *lnutils.SyncMap[lnwire.ChannelID, chanCloserFsm]
613

614
        // localCloseChanReqs is a channel in which any local requests to close
615
        // a particular channel are sent over.
616
        localCloseChanReqs chan *htlcswitch.ChanClose
617

618
        // linkFailures receives all reported channel failures from the switch,
619
        // and instructs the channelManager to clean remaining channel state.
620
        linkFailures chan linkFailureReport
621

622
        // chanCloseMsgs is a channel that any message related to channel
623
        // closures are sent over. This includes lnwire.Shutdown message as
624
        // well as lnwire.ClosingSigned messages.
625
        chanCloseMsgs chan *closeMsg
626

627
        // remoteFeatures is the feature vector received from the peer during
628
        // the connection handshake.
629
        remoteFeatures *lnwire.FeatureVector
630

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

637
        // channelEventClient is the channel event subscription client that's
638
        // used to assist retry enabling the channels. This client is only
639
        // created when the reenableTimeout is no greater than 1 minute. Once
640
        // created, it is canceled once the reenabling has been finished.
641
        //
642
        // NOTE: we choose to create the client conditionally to avoid
643
        // potentially holding lots of un-consumed events.
644
        channelEventClient *subscribe.Client
645

646
        // msgRouter is an instance of the msgmux.Router which is used to send
647
        // off new wire messages for handing.
648
        msgRouter fn.Option[msgmux.Router]
649

650
        // globalMsgRouter is a flag that indicates whether we have a global
651
        // msg router. If so, then we don't worry about stopping the msg router
652
        // when a peer disconnects.
653
        globalMsgRouter bool
654

655
        startReady chan struct{}
656

657
        // cg is a helper that encapsulates a wait group and quit channel and
658
        // allows contexts that either block or cancel on those depending on
659
        // the use case.
660
        cg *fn.ContextGuard
661

662
        // log is a peer-specific logging instance.
663
        log btclog.Logger
664
}
665

666
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer
667
// interface.
668
var _ lnpeer.Peer = (*Brontide)(nil)
669

670
// NewBrontide creates a new Brontide from a peer.Config struct.
671
func NewBrontide(cfg Config) *Brontide {
27✔
672
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
27✔
673

27✔
674
        // We have a global message router if one was passed in via the config.
27✔
675
        // In this case, we don't need to attempt to tear it down when the peer
27✔
676
        // is stopped.
27✔
677
        globalMsgRouter := cfg.MsgRouter.IsSome()
27✔
678

27✔
679
        // We'll either use the msg router instance passed in, or create a new
27✔
680
        // blank instance.
27✔
681
        msgRouter := cfg.MsgRouter.Alt(fn.Some[msgmux.Router](
27✔
682
                msgmux.NewMultiMsgRouter(),
27✔
683
        ))
27✔
684

27✔
685
        p := &Brontide{
27✔
686
                cfg:           cfg,
27✔
687
                activeSignal:  make(chan struct{}),
27✔
688
                sendQueue:     make(chan outgoingMsg),
27✔
689
                outgoingQueue: make(chan outgoingMsg),
27✔
690
                addedChannels: &lnutils.SyncMap[lnwire.ChannelID, struct{}]{},
27✔
691
                activeChannels: &lnutils.SyncMap[
27✔
692
                        lnwire.ChannelID, *lnwallet.LightningChannel,
27✔
693
                ]{},
27✔
694
                newActiveChannel:     make(chan *newChannelMsg, 1),
27✔
695
                newPendingChannel:    make(chan *newChannelMsg, 1),
27✔
696
                removePendingChannel: make(chan *newChannelMsg),
27✔
697

27✔
698
                activeMsgStreams: make(map[lnwire.ChannelID]*msgStream),
27✔
699
                activeChanCloses: &lnutils.SyncMap[
27✔
700
                        lnwire.ChannelID, chanCloserFsm,
27✔
701
                ]{},
27✔
702
                localCloseChanReqs: make(chan *htlcswitch.ChanClose),
27✔
703
                linkFailures:       make(chan linkFailureReport),
27✔
704
                chanCloseMsgs:      make(chan *closeMsg),
27✔
705
                resentChanSyncMsg:  make(map[lnwire.ChannelID]struct{}),
27✔
706
                startReady:         make(chan struct{}),
27✔
707
                log:                peerLog.WithPrefix(logPrefix),
27✔
708
                msgRouter:          msgRouter,
27✔
709
                globalMsgRouter:    globalMsgRouter,
27✔
710
                cg:                 fn.NewContextGuard(),
27✔
711
        }
27✔
712

27✔
713
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
29✔
714
                remoteAddr := cfg.Conn.RemoteAddr().String()
2✔
715
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
2✔
716
                        strings.Contains(remoteAddr, "127.0.0.1")
2✔
717
        }
2✔
718

719
        var (
27✔
720
                lastBlockHeader           *wire.BlockHeader
27✔
721
                lastSerializedBlockHeader [wire.MaxBlockHeaderPayload]byte
27✔
722
        )
27✔
723
        newPingPayload := func() []byte {
27✔
724
                // We query the BestBlockHeader from our BestBlockView each time
×
725
                // this is called, and update our serialized block header if
×
726
                // they differ.  Over time, we'll use this to disseminate the
×
UNCOV
727
                // latest block header between all our peers, which can later be
×
728
                // used to cross-check our own view of the network to mitigate
×
729
                // various types of eclipse attacks.
×
730
                header, err := p.cfg.BestBlockView.BestBlockHeader()
×
731
                if err != nil && header == lastBlockHeader {
×
732
                        return lastSerializedBlockHeader[:]
×
733
                }
×
734

735
                buf := bytes.NewBuffer(lastSerializedBlockHeader[0:0])
×
736
                err = header.Serialize(buf)
×
737
                if err == nil {
×
UNCOV
738
                        lastBlockHeader = header
×
739
                } else {
×
UNCOV
740
                        p.log.Warn("unable to serialize current block" +
×
UNCOV
741
                                "header for ping payload generation." +
×
UNCOV
742
                                "This should be impossible and means" +
×
UNCOV
743
                                "there is an implementation bug.")
×
UNCOV
744
                }
×
745

UNCOV
746
                return lastSerializedBlockHeader[:]
×
747
        }
748

749
        // TODO(roasbeef): make dynamic in order to create fake cover traffic.
750
        //
751
        // NOTE(proofofkeags): this was changed to be dynamic to allow better
752
        // pong identification, however, more thought is needed to make this
753
        // actually usable as a traffic decoy.
754
        randPongSize := func() uint16 {
27✔
UNCOV
755
                return uint16(
×
UNCOV
756
                        // We don't need cryptographic randomness here.
×
UNCOV
757
                        /* #nosec */
×
UNCOV
758
                        rand.Intn(pongSizeCeiling) + 1,
×
UNCOV
759
                )
×
UNCOV
760
        }
×
761

762
        p.pingManager = NewPingManager(&PingManagerConfig{
27✔
763
                NewPingPayload:   newPingPayload,
27✔
764
                NewPongSize:      randPongSize,
27✔
765
                IntervalDuration: p.scaleTimeout(pingInterval),
27✔
766
                TimeoutDuration:  p.scaleTimeout(pingTimeout),
27✔
767
                SendPing: func(ping *lnwire.Ping) {
27✔
768
                        p.queueMsg(ping, nil)
×
769
                },
×
770
                OnPongFailure: func(reason error,
771
                        timeWaitedForPong time.Duration,
772
                        lastKnownRTT time.Duration) {
×
773

×
774
                        logMsg := fmt.Sprintf("pong response "+
×
775
                                "failure for %s: %v. Time waited for this "+
×
776
                                "pong: %v. Last successful RTT: %v.",
×
777
                                p, reason, timeWaitedForPong, lastKnownRTT)
×
778

×
779
                        // If NoDisconnectOnPongFailure is true, we don't
×
UNCOV
780
                        // disconnect. Otherwise (if it's false, the default),
×
781
                        // we disconnect.
×
782
                        if p.cfg.NoDisconnectOnPongFailure {
×
783
                                p.log.Warnf("%s -- not disconnecting "+
×
UNCOV
784
                                        "due to config", logMsg)
×
UNCOV
785
                                return
×
UNCOV
786
                        }
×
787

UNCOV
788
                        p.log.Warnf("%s -- disconnecting", logMsg)
×
UNCOV
789

×
UNCOV
790
                        go p.Disconnect(fmt.Errorf("pong failure: %w", reason))
×
791
                },
792
        })
793

794
        return p
27✔
795
}
796

797
// Start starts all helper goroutines the peer needs for normal operations.  In
798
// the case this peer has already been started, then this function is a noop.
799
func (p *Brontide) Start() error {
5✔
800
        if atomic.AddInt32(&p.started, 1) != 1 {
5✔
UNCOV
801
                return nil
×
UNCOV
802
        }
×
803

804
        // Once we've finished starting up the peer, we'll signal to other
805
        // goroutines that the they can move forward to tear down the peer, or
806
        // carry out other relevant changes.
807
        defer close(p.startReady)
5✔
808

5✔
809
        p.log.Tracef("starting with conn[%v->%v]",
5✔
810
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
5✔
811

5✔
812
        // Fetch and then load all the active channels we have with this remote
5✔
813
        // peer from the database.
5✔
814
        activeChans, err := p.cfg.ChannelDB.FetchOpenChannels(
5✔
815
                p.cfg.Addr.IdentityKey,
5✔
816
        )
5✔
817
        if err != nil {
5✔
UNCOV
818
                p.log.Errorf("Unable to fetch active chans "+
×
UNCOV
819
                        "for peer: %v", err)
×
UNCOV
820
                return err
×
UNCOV
821
        }
×
822

823
        if len(activeChans) == 0 {
8✔
824
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
3✔
825
        }
3✔
826

827
        // Quickly check if we have any existing legacy channels with this
828
        // peer.
829
        haveLegacyChan := false
5✔
830
        for _, c := range activeChans {
9✔
831
                if c.ChanType.IsTweakless() {
8✔
832
                        continue
4✔
833
                }
834

835
                haveLegacyChan = true
2✔
836
                break
2✔
837
        }
838

839
        // Exchange local and global features, the init message should be very
840
        // first between two nodes.
841
        if err := p.sendInitMsg(haveLegacyChan); err != nil {
7✔
842
                return fmt.Errorf("unable to send init msg: %w", err)
2✔
843
        }
2✔
844

845
        // Before we launch any of the helper goroutines off the peer struct,
846
        // we'll first ensure proper adherence to the p2p protocol. The init
847
        // message MUST be sent before any other message.
848
        readErr := make(chan error, 1)
5✔
849
        msgChan := make(chan lnwire.Message, 1)
5✔
850
        p.cg.WgAdd(1)
5✔
851
        go func() {
10✔
852
                defer p.cg.WgDone()
5✔
853

5✔
854
                msg, err := p.readNextMessage()
5✔
855
                if err != nil {
7✔
856
                        readErr <- err
2✔
857
                        msgChan <- nil
2✔
858
                        return
2✔
859
                }
2✔
860
                readErr <- nil
5✔
861
                msgChan <- msg
5✔
862
        }()
863

864
        select {
5✔
865
        // In order to avoid blocking indefinitely, we'll give the other peer
866
        // an upper timeout to respond before we bail out early.
UNCOV
867
        case <-time.After(handshakeTimeout):
×
UNCOV
868
                return fmt.Errorf("peer did not complete handshake within %v",
×
UNCOV
869
                        handshakeTimeout)
×
870
        case err := <-readErr:
5✔
871
                if err != nil {
7✔
872
                        return fmt.Errorf("unable to read init msg: %w", err)
2✔
873
                }
2✔
874
        }
875

876
        // Once the init message arrives, we can parse it so we can figure out
877
        // the negotiation of features for this session.
878
        msg := <-msgChan
5✔
879
        if msg, ok := msg.(*lnwire.Init); ok {
10✔
880
                if err := p.handleInitMsg(msg); err != nil {
5✔
UNCOV
881
                        p.storeError(err)
×
UNCOV
882
                        return err
×
UNCOV
883
                }
×
UNCOV
884
        } else {
×
UNCOV
885
                return errors.New("very first message between nodes " +
×
UNCOV
886
                        "must be init message")
×
UNCOV
887
        }
×
888

889
        // Next, load all the active channels we have with this peer,
890
        // registering them with the switch and launching the necessary
891
        // goroutines required to operate them.
892
        p.log.Debugf("Loaded %v active channels from database",
5✔
893
                len(activeChans))
5✔
894

5✔
895
        // Conditionally subscribe to channel events before loading channels so
5✔
896
        // we won't miss events. This subscription is used to listen to active
5✔
897
        // channel event when reenabling channels. Once the reenabling process
5✔
898
        // is finished, this subscription will be canceled.
5✔
899
        //
5✔
900
        // NOTE: ChannelNotifier must be started before subscribing events
5✔
901
        // otherwise we'd panic here.
5✔
902
        if err := p.attachChannelEventSubscription(); err != nil {
5✔
UNCOV
903
                return err
×
UNCOV
904
        }
×
905

906
        // Register the message router now as we may need to register some
907
        // endpoints while loading the channels below.
908
        p.msgRouter.WhenSome(func(router msgmux.Router) {
10✔
909
                router.Start(context.Background())
5✔
910
        })
5✔
911

912
        msgs, err := p.loadActiveChannels(activeChans)
5✔
913
        if err != nil {
5✔
NEW
914
                return fmt.Errorf("unable to load channels: %w", err)
×
NEW
915
        }
×
916

917
        // If the remote peer supports onion messages, then we'll spawn the
918
        // onion peer actor, which will be used to send onion messages **to**
919
        // the remote peer.
920
        if p.remoteFeatures.HasFeature(lnwire.OnionMessagesOptional) {
7✔
921
                p.log.Infof("Remote peer supports onion messages, " +
2✔
922
                        "registering onion message actor")
2✔
923
                sender := func(msg *lnwire.OnionMessage) {
4✔
924
                        if err := p.SendMessageLazy(false, msg); err != nil {
2✔
NEW
925
                                p.log.Warnf("Failed to send onion message: %v",
×
UNCOV
926
                                        err)
×
NEW
927
                        }
×
928
                }
929
                onionmessage.SpawnOnionPeerActor(
2✔
930
                        p.cfg.ActorSystem, sender, p.PubKey(),
2✔
931
                )
2✔
932
        }
933

934
        // Register the onion message endpoint with this peer's message router.
935
        // The endpoint is shared across all peers and handles incoming onion
936
        // messages by routing them to the appropriate peer actor for forwarding
937
        // or processing them locally. Skip if onion messaging is disabled.
938
        if p.cfg.OnionEndpoint != nil {
10✔
939
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
10✔
940
                        _ = r.UnregisterEndpoint(p.cfg.OnionEndpoint.Name())
5✔
941

5✔
942
                        return r.RegisterEndpoint(p.cfg.OnionEndpoint)
5✔
943
                })
5✔
944
                if err != nil {
5✔
UNCOV
945
                        return fmt.Errorf("unable to register endpoint for "+
×
UNCOV
946
                                "onion messaging: %w", err)
×
UNCOV
947
                }
×
948
        }
949

950
        p.startTime = time.Now()
5✔
951

5✔
952
        // Before launching the writeHandler goroutine, we send any channel
5✔
953
        // sync messages that must be resent for borked channels. We do this to
5✔
954
        // avoid data races with WriteMessage & Flush calls.
5✔
955
        if len(msgs) > 0 {
9✔
956
                p.log.Infof("Sending %d channel sync messages to peer after "+
4✔
957
                        "loading active channels", len(msgs))
4✔
958

4✔
959
                // Send the messages directly via writeMessage and bypass the
4✔
960
                // writeHandler goroutine.
4✔
961
                for _, msg := range msgs {
8✔
962
                        if err := p.writeMessage(msg); err != nil {
4✔
UNCOV
963
                                return fmt.Errorf("unable to send "+
×
964
                                        "reestablish msg: %v", err)
×
965
                        }
×
966
                }
967
        }
968

969
        err = p.pingManager.Start()
5✔
970
        if err != nil {
5✔
UNCOV
971
                return fmt.Errorf("could not start ping manager %w", err)
×
UNCOV
972
        }
×
973

974
        p.cg.WgAdd(4)
5✔
975
        go p.queueHandler()
5✔
976
        go p.writeHandler()
5✔
977
        go p.channelManager()
5✔
978
        go p.readHandler()
5✔
979

5✔
980
        // Signal to any external processes that the peer is now active.
5✔
981
        close(p.activeSignal)
5✔
982

5✔
983
        // Node announcements don't propagate very well throughout the network
5✔
984
        // as there isn't a way to efficiently query for them through their
5✔
985
        // timestamp, mostly affecting nodes that were offline during the time
5✔
986
        // of broadcast. We'll resend our node announcement to the remote peer
5✔
987
        // as a best-effort delivery such that it can also propagate to their
5✔
988
        // peers. To ensure they can successfully process it in most cases,
5✔
989
        // we'll only resend it as long as we have at least one confirmed
5✔
990
        // advertised channel with the remote peer.
5✔
991
        //
5✔
992
        // TODO(wilmer): Remove this once we're able to query for node
5✔
993
        // announcements through their timestamps.
5✔
994
        p.cg.WgAdd(2)
5✔
995
        go p.maybeSendNodeAnn(activeChans)
5✔
996
        go p.maybeSendChannelUpdates()
5✔
997

5✔
998
        return nil
5✔
999
}
1000

1001
// initGossipSync initializes either a gossip syncer or an initial routing
1002
// dump, depending on the negotiated synchronization method.
1003
func (p *Brontide) initGossipSync() {
5✔
1004
        // If the remote peer knows of the new gossip queries feature, then
5✔
1005
        // we'll create a new gossipSyncer in the AuthenticatedGossiper for it.
5✔
1006
        if p.remoteFeatures.HasFeature(lnwire.GossipQueriesOptional) {
10✔
1007
                p.log.Info("Negotiated chan series queries")
5✔
1008

5✔
1009
                if p.cfg.AuthGossiper == nil {
8✔
1010
                        // This should only ever be hit in the unit tests.
3✔
1011
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
3✔
1012
                                "gossip sync.")
3✔
1013
                        return
3✔
1014
                }
3✔
1015

1016
                // Register the peer's gossip syncer with the gossiper.
1017
                // This blocks synchronously to ensure the gossip syncer is
1018
                // registered with the gossiper before attempting to read
1019
                // messages from the remote peer.
1020
                //
1021
                // TODO(wilmer): Only sync updates from non-channel peers. This
1022
                // requires an improved version of the current network
1023
                // bootstrapper to ensure we can find and connect to non-channel
1024
                // peers.
1025
                p.cfg.AuthGossiper.InitSyncState(p)
2✔
1026
        }
1027
}
1028

1029
// taprootShutdownAllowed returns true if both parties have negotiated the
1030
// shutdown-any-segwit feature.
1031
func (p *Brontide) taprootShutdownAllowed() bool {
8✔
1032
        return p.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
8✔
1033
                p.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
8✔
1034
}
8✔
1035

1036
// rbfCoopCloseAllowed returns true if both parties have negotiated the new RBF
1037
// coop close feature.
1038
func (p *Brontide) rbfCoopCloseAllowed() bool {
9✔
1039
        bothHaveBit := func(bit lnwire.FeatureBit) bool {
25✔
1040
                return p.RemoteFeatures().HasFeature(bit) &&
16✔
1041
                        p.LocalFeatures().HasFeature(bit)
16✔
1042
        }
16✔
1043

1044
        return bothHaveBit(lnwire.RbfCoopCloseOptional) ||
9✔
1045
                bothHaveBit(lnwire.RbfCoopCloseOptionalStaging)
9✔
1046
}
1047

1048
// QuitSignal is a method that should return a channel which will be sent upon
1049
// or closed once the backing peer exits. This allows callers using the
1050
// interface to cancel any processing in the event the backing implementation
1051
// exits.
1052
//
1053
// NOTE: Part of the lnpeer.Peer interface.
1054
func (p *Brontide) QuitSignal() <-chan struct{} {
2✔
1055
        return p.cg.Done()
2✔
1056
}
2✔
1057

1058
// addrWithInternalKey takes a delivery script, then attempts to supplement it
1059
// with information related to the internal key for the addr, but only if it's
1060
// a taproot addr.
1061
func (p *Brontide) addrWithInternalKey(
1062
        deliveryScript []byte) (*chancloser.DeliveryAddrWithKey, error) {
11✔
1063

11✔
1064
        // Currently, custom channels cannot be created with external upfront
11✔
1065
        // shutdown addresses, so this shouldn't be an issue. We only require
11✔
1066
        // the internal key for taproot addresses to be able to provide a non
11✔
1067
        // inclusion proof of any scripts.
11✔
1068
        internalKeyDesc, err := lnwallet.InternalKeyForAddr(
11✔
1069
                p.cfg.Wallet, &p.cfg.Wallet.Cfg.NetParams, deliveryScript,
11✔
1070
        )
11✔
1071
        if err != nil {
11✔
UNCOV
1072
                return nil, fmt.Errorf("unable to fetch internal key: %w", err)
×
UNCOV
1073
        }
×
1074

1075
        return &chancloser.DeliveryAddrWithKey{
11✔
1076
                DeliveryAddress: deliveryScript,
11✔
1077
                InternalKey: fn.MapOption(
11✔
1078
                        func(desc keychain.KeyDescriptor) btcec.PublicKey {
13✔
1079
                                return *desc.PubKey
2✔
1080
                        },
2✔
1081
                )(internalKeyDesc),
1082
        }, nil
1083
}
1084

1085
// loadActiveChannels creates indexes within the peer for tracking all active
1086
// channels returned by the database. It returns a slice of channel reestablish
1087
// messages that should be sent to the peer immediately, in case we have borked
1088
// channels that haven't been closed yet.
1089
func (p *Brontide) loadActiveChannels(chans []*channeldb.OpenChannel) (
1090
        []lnwire.Message, error) {
5✔
1091

5✔
1092
        // Return a slice of messages to send to the peers in case the channel
5✔
1093
        // cannot be loaded normally.
5✔
1094
        var msgs []lnwire.Message
5✔
1095

5✔
1096
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
5✔
1097

5✔
1098
        for _, dbChan := range chans {
9✔
1099
                hasScidFeature := dbChan.ChanType.HasScidAliasFeature()
4✔
1100
                if scidAliasNegotiated && !hasScidFeature {
6✔
1101
                        // We'll request and store an alias, making sure that a
2✔
1102
                        // gossiper mapping is not created for the alias to the
2✔
1103
                        // real SCID. This is done because the peer and funding
2✔
1104
                        // manager are not aware of each other's states and if
2✔
1105
                        // we did not do this, we would accept alias channel
2✔
1106
                        // updates after 6 confirmations, which would be buggy.
2✔
1107
                        // We'll queue a channel_ready message with the new
2✔
1108
                        // alias. This should technically be done *after* the
2✔
1109
                        // reestablish, but this behavior is pre-existing since
2✔
1110
                        // the funding manager may already queue a
2✔
1111
                        // channel_ready before the channel_reestablish.
2✔
1112
                        if !dbChan.IsPending {
4✔
1113
                                aliasScid, err := p.cfg.RequestAlias()
2✔
1114
                                if err != nil {
2✔
UNCOV
1115
                                        return nil, err
×
1116
                                }
×
1117

1118
                                err = p.cfg.AddLocalAlias(
2✔
1119
                                        aliasScid, dbChan.ShortChanID(), false,
2✔
1120
                                        false,
2✔
1121
                                )
2✔
1122
                                if err != nil {
2✔
UNCOV
1123
                                        return nil, err
×
UNCOV
1124
                                }
×
1125

1126
                                chanID := lnwire.NewChanIDFromOutPoint(
2✔
1127
                                        dbChan.FundingOutpoint,
2✔
1128
                                )
2✔
1129

2✔
1130
                                // Fetch the second commitment point to send in
2✔
1131
                                // the channel_ready message.
2✔
1132
                                second, err := dbChan.SecondCommitmentPoint()
2✔
1133
                                if err != nil {
2✔
UNCOV
1134
                                        return nil, err
×
UNCOV
1135
                                }
×
1136

1137
                                channelReadyMsg := lnwire.NewChannelReady(
2✔
1138
                                        chanID, second,
2✔
1139
                                )
2✔
1140
                                channelReadyMsg.AliasScid = &aliasScid
2✔
1141

2✔
1142
                                msgs = append(msgs, channelReadyMsg)
2✔
1143
                        }
1144

1145
                        // If we've negotiated the option-scid-alias feature
1146
                        // and this channel does not have ScidAliasFeature set
1147
                        // to true due to an upgrade where the feature bit was
1148
                        // turned on, we'll update the channel's database
1149
                        // state.
1150
                        err := dbChan.MarkScidAliasNegotiated()
2✔
1151
                        if err != nil {
2✔
1152
                                return nil, err
×
UNCOV
1153
                        }
×
1154
                }
1155

1156
                var chanOpts []lnwallet.ChannelOpt
4✔
1157
                p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
4✔
1158
                        chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
1159
                })
×
1160
                p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
4✔
1161
                        chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
UNCOV
1162
                })
×
1163
                p.cfg.AuxResolver.WhenSome(
4✔
1164
                        func(s lnwallet.AuxContractResolver) {
4✔
UNCOV
1165
                                chanOpts = append(
×
UNCOV
1166
                                        chanOpts, lnwallet.WithAuxResolver(s),
×
UNCOV
1167
                                )
×
1168
                        },
×
1169
                )
1170

1171
                lnChan, err := lnwallet.NewLightningChannel(
4✔
1172
                        p.cfg.Signer, dbChan, p.cfg.SigPool, chanOpts...,
4✔
1173
                )
4✔
1174
                if err != nil {
4✔
UNCOV
1175
                        return nil, fmt.Errorf("unable to create channel "+
×
UNCOV
1176
                                "state machine: %w", err)
×
UNCOV
1177
                }
×
1178

1179
                chanPoint := dbChan.FundingOutpoint
4✔
1180

4✔
1181
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
1182

4✔
1183
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
4✔
1184
                        chanPoint, lnChan.IsPending())
4✔
1185

4✔
1186
                // Skip adding any permanently irreconcilable channels to the
4✔
1187
                // htlcswitch.
4✔
1188
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
4✔
1189
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
8✔
1190

4✔
1191
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
4✔
1192
                                "start.", chanPoint, dbChan.ChanStatus())
4✔
1193

4✔
1194
                        // To help our peer recover from a potential data loss,
4✔
1195
                        // we resend our channel reestablish message if the
4✔
1196
                        // channel is in a borked state. We won't process any
4✔
1197
                        // channel reestablish message sent from the peer, but
4✔
1198
                        // that's okay since the assumption is that we did when
4✔
1199
                        // marking the channel borked.
4✔
1200
                        chanSync, err := dbChan.ChanSyncMsg()
4✔
1201
                        if err != nil {
4✔
UNCOV
1202
                                p.log.Errorf("Unable to create channel "+
×
UNCOV
1203
                                        "reestablish message for channel %v: "+
×
UNCOV
1204
                                        "%v", chanPoint, err)
×
UNCOV
1205
                                continue
×
1206
                        }
1207

1208
                        msgs = append(msgs, chanSync)
4✔
1209

4✔
1210
                        // Check if this channel needs to have the cooperative
4✔
1211
                        // close process restarted. If so, we'll need to send
4✔
1212
                        // the Shutdown message that is returned.
4✔
1213
                        if dbChan.HasChanStatus(
4✔
1214
                                channeldb.ChanStatusCoopBroadcasted,
4✔
1215
                        ) {
6✔
1216

2✔
1217
                                shutdownMsg, err := p.restartCoopClose(lnChan)
2✔
1218
                                if err != nil {
2✔
UNCOV
1219
                                        p.log.Errorf("Unable to restart "+
×
UNCOV
1220
                                                "coop close for channel: %v",
×
UNCOV
1221
                                                err)
×
UNCOV
1222
                                        continue
×
1223
                                }
1224

1225
                                if shutdownMsg == nil {
4✔
1226
                                        continue
2✔
1227
                                }
1228

1229
                                // Append the message to the set of messages to
1230
                                // send.
UNCOV
1231
                                msgs = append(msgs, shutdownMsg)
×
1232
                        }
1233

1234
                        continue
4✔
1235
                }
1236

1237
                // Before we register this new link with the HTLC Switch, we'll
1238
                // need to fetch its current link-layer forwarding policy from
1239
                // the database.
1240
                graph := p.cfg.ChannelGraph
2✔
1241
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
2✔
1242
                        &chanPoint,
2✔
1243
                )
2✔
1244
                if err != nil && !errors.Is(err, graphdb.ErrEdgeNotFound) {
2✔
UNCOV
1245
                        return nil, err
×
UNCOV
1246
                }
×
1247

1248
                // We'll filter out our policy from the directional channel
1249
                // edges based whom the edge connects to. If it doesn't connect
1250
                // to us, then we know that we were the one that advertised the
1251
                // policy.
1252
                //
1253
                // TODO(roasbeef): can add helper method to get policy for
1254
                // particular channel.
1255
                var selfPolicy *models.ChannelEdgePolicy
2✔
1256
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
2✔
1257
                        p.cfg.ServerPubKey[:]) {
4✔
1258

2✔
1259
                        selfPolicy = p1
2✔
1260
                } else {
4✔
1261
                        selfPolicy = p2
2✔
1262
                }
2✔
1263

1264
                // If we don't yet have an advertised routing policy, then
1265
                // we'll use the current default, otherwise we'll translate the
1266
                // routing policy into a forwarding policy.
1267
                var forwardingPolicy *models.ForwardingPolicy
2✔
1268
                if selfPolicy != nil {
4✔
1269
                        forwardingPolicy = &models.ForwardingPolicy{
2✔
1270
                                MinHTLCOut:    selfPolicy.MinHTLC,
2✔
1271
                                MaxHTLC:       selfPolicy.MaxHTLC,
2✔
1272
                                BaseFee:       selfPolicy.FeeBaseMSat,
2✔
1273
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
2✔
1274
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
2✔
1275
                        }
2✔
1276
                        selfPolicy.InboundFee.WhenSome(func(fee lnwire.Fee) {
2✔
UNCOV
1277
                                inboundFee := models.NewInboundFeeFromWire(fee)
×
UNCOV
1278
                                forwardingPolicy.InboundFee = inboundFee
×
UNCOV
1279
                        })
×
1280
                } else {
2✔
1281
                        p.log.Warnf("Unable to find our forwarding policy "+
2✔
1282
                                "for channel %v, using default values",
2✔
1283
                                chanPoint)
2✔
1284
                        forwardingPolicy = &p.cfg.RoutingPolicy
2✔
1285
                }
2✔
1286

1287
                p.log.Tracef("Using link policy of: %v",
2✔
1288
                        lnutils.SpewLogClosure(forwardingPolicy))
2✔
1289

2✔
1290
                // If the channel is pending, set the value to nil in the
2✔
1291
                // activeChannels map. This is done to signify that the channel
2✔
1292
                // is pending. We don't add the link to the switch here - it's
2✔
1293
                // the funding manager's responsibility to spin up pending
2✔
1294
                // channels. Adding them here would just be extra work as we'll
2✔
1295
                // tear them down when creating + adding the final link.
2✔
1296
                if lnChan.IsPending() {
4✔
1297
                        p.activeChannels.Store(chanID, nil)
2✔
1298

2✔
1299
                        continue
2✔
1300
                }
1301

1302
                shutdownInfo, err := lnChan.State().ShutdownInfo()
2✔
1303
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
2✔
UNCOV
1304
                        return nil, err
×
UNCOV
1305
                }
×
1306

1307
                isTaprootChan := lnChan.ChanType().IsTaproot()
2✔
1308

2✔
1309
                var (
2✔
1310
                        shutdownMsg     fn.Option[lnwire.Shutdown]
2✔
1311
                        shutdownInfoErr error
2✔
1312
                )
2✔
1313
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
4✔
1314
                        // If we can use the new RBF close feature, we don't
2✔
1315
                        // need to create the legacy closer. However for taproot
2✔
1316
                        // channels, we'll continue to use the legacy closer.
2✔
1317
                        if p.rbfCoopCloseAllowed() && !isTaprootChan {
4✔
1318
                                return
2✔
1319
                        }
2✔
1320

1321
                        // Compute an ideal fee.
1322
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
2✔
1323
                                p.cfg.CoopCloseTargetConfs,
2✔
1324
                        )
2✔
1325
                        if err != nil {
2✔
UNCOV
1326
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
UNCOV
1327
                                        "estimate fee: %w", err)
×
UNCOV
1328

×
1329
                                return
×
1330
                        }
×
1331

1332
                        addr, err := p.addrWithInternalKey(
2✔
1333
                                info.DeliveryScript.Val,
2✔
1334
                        )
2✔
1335
                        if err != nil {
2✔
UNCOV
1336
                                shutdownInfoErr = fmt.Errorf("unable to make "+
×
UNCOV
1337
                                        "delivery addr: %w", err)
×
1338
                                return
×
1339
                        }
×
1340
                        negotiateChanCloser, err := p.createChanCloser(
2✔
1341
                                lnChan, addr, feePerKw, nil,
2✔
1342
                                info.Closer(),
2✔
1343
                        )
2✔
1344
                        if err != nil {
2✔
UNCOV
1345
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
UNCOV
1346
                                        "create chan closer: %w", err)
×
UNCOV
1347

×
UNCOV
1348
                                return
×
UNCOV
1349
                        }
×
1350

1351
                        chanID := lnwire.NewChanIDFromOutPoint(
2✔
1352
                                lnChan.State().FundingOutpoint,
2✔
1353
                        )
2✔
1354

2✔
1355
                        p.activeChanCloses.Store(chanID, makeNegotiateCloser(
2✔
1356
                                negotiateChanCloser,
2✔
1357
                        ))
2✔
1358

2✔
1359
                        // Create the Shutdown message.
2✔
1360
                        shutdown, err := negotiateChanCloser.ShutdownChan()
2✔
1361
                        if err != nil {
2✔
UNCOV
1362
                                p.activeChanCloses.Delete(chanID)
×
UNCOV
1363
                                shutdownInfoErr = err
×
1364

×
1365
                                return
×
UNCOV
1366
                        }
×
1367

1368
                        shutdownMsg = fn.Some(*shutdown)
2✔
1369
                })
1370
                if shutdownInfoErr != nil {
2✔
UNCOV
1371
                        return nil, shutdownInfoErr
×
1372
                }
×
1373

1374
                // Subscribe to the set of on-chain events for this channel.
1375
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
2✔
1376
                        chanPoint,
2✔
1377
                )
2✔
1378
                if err != nil {
2✔
UNCOV
1379
                        return nil, err
×
1380
                }
×
1381

1382
                err = p.addLink(
2✔
1383
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
2✔
1384
                        true, shutdownMsg,
2✔
1385
                )
2✔
1386
                if err != nil {
2✔
UNCOV
1387
                        return nil, fmt.Errorf("unable to add link %v to "+
×
UNCOV
1388
                                "switch: %v", chanPoint, err)
×
UNCOV
1389
                }
×
1390

1391
                p.activeChannels.Store(chanID, lnChan)
2✔
1392

2✔
1393
                // We're using the old co-op close, so we don't need to init
2✔
1394
                // the new RBF chan closer. If we have a taproot chan, then
2✔
1395
                // we'll also use the legacy type, so we don't need to make the
2✔
1396
                // new closer.
2✔
1397
                if !p.rbfCoopCloseAllowed() || isTaprootChan {
4✔
1398
                        continue
2✔
1399
                }
1400

1401
                // Now that the link has been added above, we'll also init an
1402
                // RBF chan closer for this channel, but only if the new close
1403
                // feature is negotiated.
1404
                //
1405
                // Creating this here ensures that any shutdown messages sent
1406
                // will be automatically routed by the msg router.
1407
                if _, err := p.initRbfChanCloser(lnChan); err != nil {
2✔
UNCOV
1408
                        p.activeChanCloses.Delete(chanID)
×
UNCOV
1409

×
UNCOV
1410
                        return nil, fmt.Errorf("unable to init RBF chan "+
×
UNCOV
1411
                                "closer during peer connect: %w", err)
×
UNCOV
1412
                }
×
1413

1414
                // If the shutdown info isn't blank, then we should kick things
1415
                // off by sending a shutdown message to the remote party to
1416
                // continue the old shutdown flow.
1417
                restartShutdown := func(s channeldb.ShutdownInfo) error {
4✔
1418
                        return p.startRbfChanCloser(
2✔
1419
                                newRestartShutdownInit(s),
2✔
1420
                                lnChan.ChannelPoint(),
2✔
1421
                        )
2✔
1422
                }
2✔
1423
                err = fn.MapOptionZ(shutdownInfo, restartShutdown)
2✔
1424
                if err != nil {
2✔
UNCOV
1425
                        return nil, fmt.Errorf("unable to start RBF "+
×
UNCOV
1426
                                "chan closer: %w", err)
×
UNCOV
1427
                }
×
1428
        }
1429

1430
        return msgs, nil
5✔
1431
}
1432

1433
// addLink creates and adds a new ChannelLink from the specified channel.
1434
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1435
        lnChan *lnwallet.LightningChannel,
1436
        forwardingPolicy *models.ForwardingPolicy,
1437
        chainEvents *contractcourt.ChainEventSubscription,
1438
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
2✔
1439

2✔
1440
        // onChannelFailure will be called by the link in case the channel
2✔
1441
        // fails for some reason.
2✔
1442
        onChannelFailure := func(chanID lnwire.ChannelID,
2✔
1443
                shortChanID lnwire.ShortChannelID,
2✔
1444
                linkErr htlcswitch.LinkFailureError) {
4✔
1445

2✔
1446
                failure := linkFailureReport{
2✔
1447
                        chanPoint:   *chanPoint,
2✔
1448
                        chanID:      chanID,
2✔
1449
                        shortChanID: shortChanID,
2✔
1450
                        linkErr:     linkErr,
2✔
1451
                }
2✔
1452

2✔
1453
                select {
2✔
1454
                case p.linkFailures <- failure:
2✔
UNCOV
1455
                case <-p.cg.Done():
×
UNCOV
1456
                case <-p.cfg.Quit:
×
1457
                }
1458
        }
1459

1460
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
4✔
1461
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
2✔
1462
        }
2✔
1463

1464
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
4✔
1465
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
2✔
1466
        }
2✔
1467

1468
        //nolint:ll
1469
        linkCfg := htlcswitch.ChannelLinkConfig{
2✔
1470
                Peer:                   p,
2✔
1471
                DecodeHopIterators:     p.cfg.SphinxPayment.DecodeHopIterators,
2✔
1472
                ExtractErrorEncrypter:  p.cfg.SphinxPayment.ExtractErrorEncrypter,
2✔
1473
                FetchLastChannelUpdate: p.cfg.FetchLastChanUpdate,
2✔
1474
                HodlMask:               p.cfg.Hodl.Mask(),
2✔
1475
                Registry:               p.cfg.Invoices,
2✔
1476
                BestHeight:             p.cfg.Switch.BestHeight,
2✔
1477
                Circuits:               p.cfg.Switch.CircuitModifier(),
2✔
1478
                ForwardPackets:         p.cfg.InterceptSwitch.ForwardPackets,
2✔
1479
                FwrdingPolicy:          *forwardingPolicy,
2✔
1480
                FeeEstimator:           p.cfg.FeeEstimator,
2✔
1481
                PreimageCache:          p.cfg.WitnessBeacon,
2✔
1482
                ChainEvents:            chainEvents,
2✔
1483
                UpdateContractSignals:  updateContractSignals,
2✔
1484
                NotifyContractUpdate:   notifyContractUpdate,
2✔
1485
                OnChannelFailure:       onChannelFailure,
2✔
1486
                SyncStates:             syncStates,
2✔
1487
                BatchTicker:            ticker.New(p.cfg.ChannelCommitInterval),
2✔
1488
                FwdPkgGCTicker:         ticker.New(time.Hour),
2✔
1489
                PendingCommitTicker: ticker.New(
2✔
1490
                        p.cfg.PendingCommitInterval,
2✔
1491
                ),
2✔
1492
                BatchSize:                  p.cfg.ChannelCommitBatchSize,
2✔
1493
                UnsafeReplay:               p.cfg.UnsafeReplay,
2✔
1494
                MinUpdateTimeout:           htlcswitch.DefaultMinLinkFeeUpdateTimeout,
2✔
1495
                MaxUpdateTimeout:           htlcswitch.DefaultMaxLinkFeeUpdateTimeout,
2✔
1496
                OutgoingCltvRejectDelta:    p.cfg.OutgoingCltvRejectDelta,
2✔
1497
                TowerClient:                p.cfg.TowerClient,
2✔
1498
                MaxOutgoingCltvExpiry:      p.cfg.MaxOutgoingCltvExpiry,
2✔
1499
                MaxFeeAllocation:           p.cfg.MaxChannelFeeAllocation,
2✔
1500
                MaxAnchorsCommitFeeRate:    p.cfg.MaxAnchorsCommitFeeRate,
2✔
1501
                NotifyActiveLink:           p.cfg.ChannelNotifier.NotifyActiveLinkEvent,
2✔
1502
                NotifyActiveChannel:        p.cfg.ChannelNotifier.NotifyActiveChannelEvent,
2✔
1503
                NotifyInactiveChannel:      p.cfg.ChannelNotifier.NotifyInactiveChannelEvent,
2✔
1504
                NotifyInactiveLinkEvent:    p.cfg.ChannelNotifier.NotifyInactiveLinkEvent,
2✔
1505
                HtlcNotifier:               p.cfg.HtlcNotifier,
2✔
1506
                GetAliases:                 p.cfg.GetAliases,
2✔
1507
                PreviouslySentShutdown:     shutdownMsg,
2✔
1508
                DisallowRouteBlinding:      p.cfg.DisallowRouteBlinding,
2✔
1509
                MaxFeeExposure:             p.cfg.MaxFeeExposure,
2✔
1510
                ShouldFwdExpAccountability: p.cfg.ShouldFwdExpAccountability,
2✔
1511
                DisallowQuiescence: p.cfg.DisallowQuiescence ||
2✔
1512
                        !p.remoteFeatures.HasFeature(lnwire.QuiescenceOptional),
2✔
1513
                AuxTrafficShaper:     p.cfg.AuxTrafficShaper,
2✔
1514
                AuxChannelNegotiator: p.cfg.AuxChannelNegotiator,
2✔
1515
                QuiescenceTimeout:    p.cfg.QuiescenceTimeout,
2✔
1516
        }
2✔
1517

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

2✔
1525
        // With the channel link created, we'll now notify the htlc switch so
2✔
1526
        // this channel can be used to dispatch local payments and also
2✔
1527
        // passively forward payments.
2✔
1528
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
2✔
1529
}
1530

1531
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1532
// one confirmed public channel exists with them.
1533
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
5✔
1534
        defer p.cg.WgDone()
5✔
1535

5✔
1536
        hasConfirmedPublicChan := false
5✔
1537
        for _, channel := range channels {
9✔
1538
                if channel.IsPending {
6✔
1539
                        continue
2✔
1540
                }
1541
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
8✔
1542
                        continue
4✔
1543
                }
1544

1545
                hasConfirmedPublicChan = true
2✔
1546
                break
2✔
1547
        }
1548
        if !hasConfirmedPublicChan {
10✔
1549
                return
5✔
1550
        }
5✔
1551

1552
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
2✔
1553
        if err != nil {
2✔
UNCOV
1554
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
UNCOV
1555
                return
×
UNCOV
1556
        }
×
1557

1558
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
2✔
UNCOV
1559
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
UNCOV
1560
        }
×
1561
}
1562

1563
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1564
// have any active channels with them.
1565
func (p *Brontide) maybeSendChannelUpdates() {
5✔
1566
        defer p.cg.WgDone()
5✔
1567

5✔
1568
        // If we don't have any active channels, then we can exit early.
5✔
1569
        if p.activeChannels.Len() == 0 {
8✔
1570
                return
3✔
1571
        }
3✔
1572

1573
        maybeSendUpd := func(cid lnwire.ChannelID,
4✔
1574
                lnChan *lnwallet.LightningChannel) error {
8✔
1575

4✔
1576
                // Nil channels are pending, so we'll skip them.
4✔
1577
                if lnChan == nil {
6✔
1578
                        return nil
2✔
1579
                }
2✔
1580

1581
                dbChan := lnChan.State()
4✔
1582
                scid := func() lnwire.ShortChannelID {
8✔
1583
                        switch {
4✔
1584
                        // Otherwise if it's a zero conf channel and confirmed,
1585
                        // then we need to use the "real" scid.
1586
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
2✔
1587
                                return dbChan.ZeroConfRealScid()
2✔
1588

1589
                        // Otherwise, we can use the normal scid.
1590
                        default:
4✔
1591
                                return dbChan.ShortChanID()
4✔
1592
                        }
1593
                }()
1594

1595
                // Now that we know the channel is in a good state, we'll try
1596
                // to fetch the update to send to the remote peer. If the
1597
                // channel is pending, and not a zero conf channel, we'll get
1598
                // an error here which we'll ignore.
1599
                chanUpd, err := p.cfg.FetchLastChanUpdate(scid)
4✔
1600
                if err != nil {
6✔
1601
                        p.log.Debugf("Unable to fetch channel update for "+
2✔
1602
                                "ChannelPoint(%v), scid=%v: %v",
2✔
1603
                                dbChan.FundingOutpoint, dbChan.ShortChanID, err)
2✔
1604

2✔
1605
                        return nil
2✔
1606
                }
2✔
1607

1608
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
4✔
1609
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
4✔
1610

4✔
1611
                // We'll send it as a normal message instead of using the lazy
4✔
1612
                // queue to prioritize transmission of the fresh update.
4✔
1613
                if err := p.SendMessage(false, chanUpd); err != nil {
4✔
1614
                        err := fmt.Errorf("unable to send channel update for "+
×
UNCOV
1615
                                "ChannelPoint(%v), scid=%v: %w",
×
UNCOV
1616
                                dbChan.FundingOutpoint, dbChan.ShortChanID(),
×
UNCOV
1617
                                err)
×
UNCOV
1618
                        p.log.Errorf(err.Error())
×
UNCOV
1619

×
UNCOV
1620
                        return err
×
UNCOV
1621
                }
×
1622

1623
                return nil
4✔
1624
        }
1625

1626
        p.activeChannels.ForEach(maybeSendUpd)
4✔
1627
}
1628

1629
// WaitForDisconnect waits until the peer has disconnected. A peer may be
1630
// disconnected if the local or remote side terminates the connection, or an
1631
// irrecoverable protocol error has been encountered. This method will only
1632
// begin watching the peer's waitgroup after the ready channel or the peer's
1633
// quit channel are signaled. The ready channel should only be signaled if a
1634
// call to Start returns no error. Otherwise, if the peer fails to start,
1635
// calling Disconnect will signal the quit channel and the method will not
1636
// block, since no goroutines were spawned.
1637
func (p *Brontide) WaitForDisconnect(ready chan struct{}) {
2✔
1638
        // Before we try to call the `Wait` goroutine, we'll make sure the main
2✔
1639
        // set of goroutines are already active.
2✔
1640
        select {
2✔
1641
        case <-p.startReady:
2✔
UNCOV
1642
        case <-p.cg.Done():
×
UNCOV
1643
                return
×
1644
        }
1645

1646
        select {
2✔
1647
        case <-ready:
2✔
1648
        case <-p.cg.Done():
2✔
1649
        }
1650

1651
        p.cg.WgWait()
2✔
1652
}
1653

1654
// Disconnect terminates the connection with the remote peer. Additionally, a
1655
// signal is sent to the server and htlcSwitch indicating the resources
1656
// allocated to the peer can now be cleaned up.
1657
//
1658
// NOTE: Be aware that this method will block if the peer is still starting up.
1659
// Therefore consider starting it in a goroutine if you cannot guarantee that
1660
// the peer has finished starting up before calling this method.
1661
func (p *Brontide) Disconnect(reason error) {
3✔
1662
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
5✔
1663
                return
2✔
1664
        }
2✔
1665

1666
        // Make sure initialization has completed before we try to tear things
1667
        // down.
1668
        //
1669
        // NOTE: We only read the `startReady` chan if the peer has been
1670
        // started, otherwise we will skip reading it as this chan won't be
1671
        // closed, hence blocks forever.
1672
        if atomic.LoadInt32(&p.started) == 1 {
5✔
1673
                p.log.Debugf("Peer hasn't finished starting up yet, waiting " +
2✔
1674
                        "on startReady signal before closing connection")
2✔
1675

2✔
1676
                select {
2✔
1677
                case <-p.startReady:
2✔
UNCOV
1678
                case <-p.cg.Done():
×
UNCOV
1679
                        return
×
1680
                }
1681
        }
1682

1683
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
3✔
1684
        p.storeError(err)
3✔
1685

3✔
1686
        p.log.Infof(err.Error())
3✔
1687

3✔
1688
        // Stop PingManager before closing TCP connection.
3✔
1689
        p.pingManager.Stop()
3✔
1690

3✔
1691
        // Ensure that the TCP connection is properly closed before continuing.
3✔
1692
        p.cfg.Conn.Close()
3✔
1693

3✔
1694
        p.cg.Quit()
3✔
1695

3✔
1696
        // If our msg router isn't global (local to this instance), then we'll
3✔
1697
        // stop it. Otherwise, we'll leave it running.
3✔
1698
        if !p.globalMsgRouter {
6✔
1699
                p.msgRouter.WhenSome(func(router msgmux.Router) {
6✔
1700
                        router.Stop()
3✔
1701
                })
3✔
1702
        }
1703

1704
        // Stop the onion peer actor if one was spawned for this peer.
1705
        onionmessage.StopPeerActor(p.cfg.ActorSystem, p.PubKey())
3✔
1706
}
1707

1708
// String returns the string representation of this peer.
1709
func (p *Brontide) String() string {
3✔
1710
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
3✔
1711
}
3✔
1712

1713
// readNextMessage reads, and returns the next message on the wire along with
1714
// any additional raw payload.
1715
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
9✔
1716
        noiseConn := p.cfg.Conn
9✔
1717
        err := noiseConn.SetReadDeadline(time.Time{})
9✔
1718
        if err != nil {
9✔
UNCOV
1719
                return nil, err
×
UNCOV
1720
        }
×
1721

1722
        pktLen, err := noiseConn.ReadNextHeader()
9✔
1723
        if err != nil {
11✔
1724
                return nil, fmt.Errorf("read next header: %w", err)
2✔
1725
        }
2✔
1726

1727
        // First we'll read the next _full_ message. We do this rather than
1728
        // reading incrementally from the stream as the Lightning wire protocol
1729
        // is message oriented and allows nodes to pad on additional data to
1730
        // the message stream.
1731
        var (
6✔
1732
                nextMsg lnwire.Message
6✔
1733
                msgLen  uint64
6✔
1734
        )
6✔
1735
        err = p.cfg.ReadPool.Submit(func(buf *buffer.Read) error {
12✔
1736
                // Before reading the body of the message, set the read timeout
6✔
1737
                // accordingly to ensure we don't block other readers using the
6✔
1738
                // pool. We do so only after the task has been scheduled to
6✔
1739
                // ensure the deadline doesn't expire while the message is in
6✔
1740
                // the process of being scheduled.
6✔
1741
                readDeadline := time.Now().Add(
6✔
1742
                        p.scaleTimeout(readMessageTimeout),
6✔
1743
                )
6✔
1744
                readErr := noiseConn.SetReadDeadline(readDeadline)
6✔
1745
                if readErr != nil {
6✔
UNCOV
1746
                        return readErr
×
UNCOV
1747
                }
×
1748

1749
                // The ReadNextBody method will actually end up re-using the
1750
                // buffer, so within this closure, we can continue to use
1751
                // rawMsg as it's just a slice into the buf from the buffer
1752
                // pool.
1753
                rawMsg, readErr := noiseConn.ReadNextBody(buf[:pktLen])
6✔
1754
                if readErr != nil {
6✔
UNCOV
1755
                        return fmt.Errorf("read next body: %w", readErr)
×
UNCOV
1756
                }
×
1757
                msgLen = uint64(len(rawMsg))
6✔
1758

6✔
1759
                // Next, create a new io.Reader implementation from the raw
6✔
1760
                // message, and use this to decode the message directly from.
6✔
1761
                msgReader := bytes.NewReader(rawMsg)
6✔
1762
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
6✔
1763
                if err != nil {
8✔
1764
                        return err
2✔
1765
                }
2✔
1766

1767
                // At this point, rawMsg and buf will be returned back to the
1768
                // buffer pool for re-use.
1769
                return nil
6✔
1770
        })
1771
        atomic.AddUint64(&p.bytesReceived, msgLen)
6✔
1772
        if err != nil {
8✔
1773
                return nil, err
2✔
1774
        }
2✔
1775

1776
        p.logWireMessage(nextMsg, true)
6✔
1777

6✔
1778
        return nextMsg, nil
6✔
1779
}
1780

1781
// msgStream implements a goroutine-safe, in-order stream of messages to be
1782
// delivered via closure to a receiver. These messages MUST be in order due to
1783
// the nature of the lightning channel commitment and gossiper state machines.
1784
// TODO(conner): use stream handler interface to abstract out stream
1785
// state/logging.
1786
type msgStream struct {
1787
        streamShutdown int32 // To be used atomically.
1788

1789
        peer *Brontide
1790

1791
        apply func(lnwire.Message)
1792

1793
        startMsg string
1794
        stopMsg  string
1795

1796
        msgCond *sync.Cond
1797
        msgs    []lnwire.Message
1798

1799
        mtx sync.Mutex
1800

1801
        producerSema chan struct{}
1802

1803
        wg   sync.WaitGroup
1804
        quit chan struct{}
1805
}
1806

1807
// newMsgStream creates a new instance of a chanMsgStream for a particular
1808
// channel identified by its channel ID. bufSize is the max number of messages
1809
// that should be buffered in the internal queue. Callers should set this to a
1810
// sane value that avoids blocking unnecessarily, but doesn't allow an
1811
// unbounded amount of memory to be allocated to buffer incoming messages.
1812
func newMsgStream(p *Brontide, startMsg, stopMsg string, bufSize uint32,
1813
        apply func(lnwire.Message)) *msgStream {
5✔
1814

5✔
1815
        stream := &msgStream{
5✔
1816
                peer:         p,
5✔
1817
                apply:        apply,
5✔
1818
                startMsg:     startMsg,
5✔
1819
                stopMsg:      stopMsg,
5✔
1820
                producerSema: make(chan struct{}, bufSize),
5✔
1821
                quit:         make(chan struct{}),
5✔
1822
        }
5✔
1823
        stream.msgCond = sync.NewCond(&stream.mtx)
5✔
1824

5✔
1825
        // Before we return the active stream, we'll populate the producer's
5✔
1826
        // semaphore channel. We'll use this to ensure that the producer won't
5✔
1827
        // attempt to allocate memory in the queue for an item until it has
5✔
1828
        // sufficient extra space.
5✔
1829
        for i := uint32(0); i < bufSize; i++ {
157✔
1830
                stream.producerSema <- struct{}{}
152✔
1831
        }
152✔
1832

1833
        return stream
5✔
1834
}
1835

1836
// Start starts the chanMsgStream.
1837
func (ms *msgStream) Start() {
5✔
1838
        ms.wg.Add(1)
5✔
1839
        go ms.msgConsumer()
5✔
1840
}
5✔
1841

1842
// Stop stops the chanMsgStream.
1843
func (ms *msgStream) Stop() {
2✔
1844
        // TODO(roasbeef): signal too?
2✔
1845

2✔
1846
        close(ms.quit)
2✔
1847

2✔
1848
        // Now that we've closed the channel, we'll repeatedly signal the msg
2✔
1849
        // consumer until we've detected that it has exited.
2✔
1850
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
4✔
1851
                ms.msgCond.Signal()
2✔
1852
                time.Sleep(time.Millisecond * 100)
2✔
1853
        }
2✔
1854

1855
        ms.wg.Wait()
2✔
1856
}
1857

1858
// msgConsumer is the main goroutine that streams messages from the peer's
1859
// readHandler directly to the target channel.
1860
func (ms *msgStream) msgConsumer() {
5✔
1861
        defer ms.wg.Done()
5✔
1862
        defer peerLog.Tracef(ms.stopMsg)
5✔
1863
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
5✔
1864

5✔
1865
        peerLog.Tracef(ms.startMsg)
5✔
1866

5✔
1867
        for {
10✔
1868
                // First, we'll check our condition. If the queue of messages
5✔
1869
                // is empty, then we'll wait until a new item is added.
5✔
1870
                ms.msgCond.L.Lock()
5✔
1871
                for len(ms.msgs) == 0 {
10✔
1872
                        ms.msgCond.Wait()
5✔
1873

5✔
1874
                        // If we woke up in order to exit, then we'll do so.
5✔
1875
                        // Otherwise, we'll check the message queue for any new
5✔
1876
                        // items.
5✔
1877
                        select {
5✔
1878
                        case <-ms.peer.cg.Done():
2✔
1879
                                ms.msgCond.L.Unlock()
2✔
1880
                                return
2✔
1881
                        case <-ms.quit:
2✔
1882
                                ms.msgCond.L.Unlock()
2✔
1883
                                return
2✔
1884
                        default:
2✔
1885
                        }
1886
                }
1887

1888
                // Grab the message off the front of the queue, shifting the
1889
                // slice's reference down one in order to remove the message
1890
                // from the queue.
1891
                msg := ms.msgs[0]
2✔
1892
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
2✔
1893
                ms.msgs = ms.msgs[1:]
2✔
1894

2✔
1895
                ms.msgCond.L.Unlock()
2✔
1896

2✔
1897
                ms.apply(msg)
2✔
1898

2✔
1899
                // We've just successfully processed an item, so we'll signal
2✔
1900
                // to the producer that a new slot in the buffer. We'll use
2✔
1901
                // this to bound the size of the buffer to avoid allowing it to
2✔
1902
                // grow indefinitely.
2✔
1903
                select {
2✔
1904
                case ms.producerSema <- struct{}{}:
2✔
1905
                case <-ms.peer.cg.Done():
2✔
1906
                        return
2✔
1907
                case <-ms.quit:
2✔
1908
                        return
2✔
1909
                }
1910
        }
1911
}
1912

1913
// AddMsg adds a new message to the msgStream. This function is safe for
1914
// concurrent access.
1915
func (ms *msgStream) AddMsg(msg lnwire.Message) {
2✔
1916
        // First, we'll attempt to receive from the producerSema struct. This
2✔
1917
        // acts as a semaphore to prevent us from indefinitely buffering
2✔
1918
        // incoming items from the wire. Either the msg queue isn't full, and
2✔
1919
        // we'll not block, or the queue is full, and we'll block until either
2✔
1920
        // we're signalled to quit, or a slot is freed up.
2✔
1921
        select {
2✔
1922
        case <-ms.producerSema:
2✔
UNCOV
1923
        case <-ms.peer.cg.Done():
×
UNCOV
1924
                return
×
UNCOV
1925
        case <-ms.quit:
×
UNCOV
1926
                return
×
1927
        }
1928

1929
        // Next, we'll lock the condition, and add the message to the end of
1930
        // the message queue.
1931
        ms.msgCond.L.Lock()
2✔
1932
        ms.msgs = append(ms.msgs, msg)
2✔
1933
        ms.msgCond.L.Unlock()
2✔
1934

2✔
1935
        // With the message added, we signal to the msgConsumer that there are
2✔
1936
        // additional messages to consume.
2✔
1937
        ms.msgCond.Signal()
2✔
1938
}
1939

1940
// waitUntilLinkActive waits until the target link is active and returns a
1941
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1942
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1943
func waitUntilLinkActive(p *Brontide,
1944
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
2✔
1945

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

2✔
1948
        // Subscribe to receive channel events.
2✔
1949
        //
2✔
1950
        // NOTE: If the link is already active by SubscribeChannelEvents, then
2✔
1951
        // GetLink will retrieve the link and we can send messages. If the link
2✔
1952
        // becomes active between SubscribeChannelEvents and GetLink, then GetLink
2✔
1953
        // will retrieve the link. If the link becomes active after GetLink, then
2✔
1954
        // we will get an ActiveLinkEvent notification and retrieve the link. If
2✔
1955
        // the call to GetLink is before SubscribeChannelEvents, however, there
2✔
1956
        // will be a race condition.
2✔
1957
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
2✔
1958
        if err != nil {
4✔
1959
                // If we have a non-nil error, then the server is shutting down and we
2✔
1960
                // can exit here and return nil. This means no message will be delivered
2✔
1961
                // to the link.
2✔
1962
                return nil
2✔
1963
        }
2✔
1964
        defer sub.Cancel()
2✔
1965

2✔
1966
        // The link may already be active by this point, and we may have missed the
2✔
1967
        // ActiveLinkEvent. Check if the link exists.
2✔
1968
        link := p.fetchLinkFromKeyAndCid(cid)
2✔
1969
        if link != nil {
4✔
1970
                return link
2✔
1971
        }
2✔
1972

1973
        // If the link is nil, we must wait for it to be active.
1974
        for {
4✔
1975
                select {
2✔
1976
                // A new event has been sent by the ChannelNotifier. We first check
1977
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1978
                // that the event is for this channel. Otherwise, we discard the
1979
                // message.
1980
                case e := <-sub.Updates():
2✔
1981
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
2✔
1982
                        if !ok {
4✔
1983
                                // Ignore this notification.
2✔
1984
                                continue
2✔
1985
                        }
1986

1987
                        chanPoint := event.ChannelPoint
2✔
1988

2✔
1989
                        // Check whether the retrieved chanPoint matches the target
2✔
1990
                        // channel id.
2✔
1991
                        if !cid.IsChanPoint(chanPoint) {
2✔
UNCOV
1992
                                continue
×
1993
                        }
1994

1995
                        // The link shouldn't be nil as we received an
1996
                        // ActiveLinkEvent. If it is nil, we return nil and the
1997
                        // calling function should catch it.
1998
                        return p.fetchLinkFromKeyAndCid(cid)
2✔
1999

2000
                case <-p.cg.Done():
2✔
2001
                        return nil
2✔
2002
                }
2003
        }
2004
}
2005

2006
// newChanMsgStream is used to create a msgStream between the peer and
2007
// particular channel link in the htlcswitch. We utilize additional
2008
// synchronization with the fundingManager to ensure we don't attempt to
2009
// dispatch a message to a channel before it is fully active. A reference to the
2010
// channel this stream forwards to is held in scope to prevent unnecessary
2011
// lookups.
2012
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
2✔
2013
        var chanLink htlcswitch.ChannelUpdateHandler
2✔
2014

2✔
2015
        apply := func(msg lnwire.Message) {
4✔
2016
                // This check is fine because if the link no longer exists, it will
2✔
2017
                // be removed from the activeChannels map and subsequent messages
2✔
2018
                // shouldn't reach the chan msg stream.
2✔
2019
                if chanLink == nil {
4✔
2020
                        chanLink = waitUntilLinkActive(p, cid)
2✔
2021

2✔
2022
                        // If the link is still not active and the calling function
2✔
2023
                        // errored out, just return.
2✔
2024
                        if chanLink == nil {
4✔
2025
                                p.log.Warnf("Link=%v is not active", cid)
2✔
2026
                                return
2✔
2027
                        }
2✔
2028
                }
2029

2030
                // In order to avoid unnecessarily delivering message
2031
                // as the peer is exiting, we'll check quickly to see
2032
                // if we need to exit.
2033
                select {
2✔
UNCOV
2034
                case <-p.cg.Done():
×
UNCOV
2035
                        return
×
2036
                default:
2✔
2037
                }
2038

2039
                chanLink.HandleChannelUpdate(msg)
2✔
2040
        }
2041

2042
        return newMsgStream(p,
2✔
2043
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
2✔
2044
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
2✔
2045
                msgStreamSize,
2✔
2046
                apply,
2✔
2047
        )
2✔
2048
}
2049

2050
// newDiscMsgStream is used to setup a msgStream between the peer and the
2051
// authenticated gossiper. This stream should be used to forward all remote
2052
// channel announcements.
2053
func newDiscMsgStream(p *Brontide) *msgStream {
5✔
2054
        apply := func(msg lnwire.Message) {
7✔
2055
                // TODO(elle): thread contexts through the peer system properly
2✔
2056
                // so that a parent context can be passed in here.
2✔
2057
                ctx := context.TODO()
2✔
2058

2✔
2059
                // Processing here means we send it to the gossiper which then
2✔
2060
                // decides whether this message is processed immediately or
2✔
2061
                // waits for dependent messages to be processed. It can also
2✔
2062
                // happen that the message is not processed at all if it is
2✔
2063
                // premature and the LRU cache fills up and the message is
2✔
2064
                // deleted.
2✔
2065
                p.log.Debugf("Processing remote msg %T", msg)
2✔
2066

2✔
2067
                // TODO(ziggie): ProcessRemoteAnnouncement returns an error
2✔
2068
                // channel, but we cannot rely on it being written to.
2✔
2069
                // Because some messages might never be processed (e.g.
2✔
2070
                // premature channel updates). We should change the design here
2✔
2071
                // and use the actor model pattern as soon as it is available.
2✔
2072
                // So for now we should NOT use the error channel.
2✔
2073
                // See https://github.com/lightningnetwork/lnd/pull/9820.
2✔
2074
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(ctx, msg, p)
2✔
2075
        }
2✔
2076

2077
        return newMsgStream(
5✔
2078
                p,
5✔
2079
                "Update stream for gossiper created",
5✔
2080
                "Update stream for gossiper exited",
5✔
2081
                msgStreamSize,
5✔
2082
                apply,
5✔
2083
        )
5✔
2084
}
2085

2086
// readHandler is responsible for reading messages off the wire in series, then
2087
// properly dispatching the handling of the message to the proper subsystem.
2088
//
2089
// NOTE: This method MUST be run as a goroutine.
2090
func (p *Brontide) readHandler() {
5✔
2091
        defer p.cg.WgDone()
5✔
2092

5✔
2093
        // We'll stop the timer after a new messages is received, and also
5✔
2094
        // reset it after we process the next message.
5✔
2095
        idleTimer := time.AfterFunc(idleTimeout, func() {
5✔
UNCOV
2096
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
UNCOV
2097
                        p, idleTimeout)
×
UNCOV
2098
                p.Disconnect(err)
×
UNCOV
2099
        })
×
2100

2101
        // Initialize our negotiated gossip sync method before reading messages
2102
        // off the wire. When using gossip queries, this ensures a gossip
2103
        // syncer is active by the time query messages arrive.
2104
        //
2105
        // TODO(conner): have peer store gossip syncer directly and bypass
2106
        // gossiper?
2107
        p.initGossipSync()
5✔
2108

5✔
2109
        discStream := newDiscMsgStream(p)
5✔
2110
        discStream.Start()
5✔
2111
        defer discStream.Stop()
5✔
2112
out:
5✔
2113
        for atomic.LoadInt32(&p.disconnect) == 0 {
11✔
2114
                nextMsg, err := p.readNextMessage()
6✔
2115
                if !idleTimer.Stop() {
8✔
2116
                        select {
2✔
UNCOV
2117
                        case <-idleTimer.C:
×
2118
                        default:
2✔
2119
                        }
2120
                }
2121
                if err != nil {
5✔
2122
                        p.log.Infof("unable to read message from peer: %v", err)
2✔
2123

2✔
2124
                        // If we could not read our peer's message due to an
2✔
2125
                        // unknown type or invalid alias, we continue processing
2✔
2126
                        // as normal. We store unknown message and address
2✔
2127
                        // types, as they may provide debugging insight.
2✔
2128
                        switch e := err.(type) {
2✔
2129
                        // If this is just a message we don't yet recognize,
2130
                        // we'll continue processing as normal as this allows
2131
                        // us to introduce new messages in a forwards
2132
                        // compatible manner.
2133
                        case *lnwire.UnknownMessage:
2✔
2134
                                p.storeError(e)
2✔
2135
                                idleTimer.Reset(idleTimeout)
2✔
2136
                                continue
2✔
2137

2138
                        // If they sent us an address type that we don't yet
2139
                        // know of, then this isn't a wire error, so we'll
2140
                        // simply continue parsing the remainder of their
2141
                        // messages.
UNCOV
2142
                        case *lnwire.ErrUnknownAddrType:
×
UNCOV
2143
                                p.storeError(e)
×
UNCOV
2144
                                idleTimer.Reset(idleTimeout)
×
2145
                                continue
×
2146

2147
                        // If the NodeAnnouncement1 has an invalid alias, then
2148
                        // we'll log that error above and continue so we can
2149
                        // continue to read messages from the peer. We do not
2150
                        // store this error because it is of little debugging
2151
                        // value.
UNCOV
2152
                        case *lnwire.ErrInvalidNodeAlias:
×
UNCOV
2153
                                idleTimer.Reset(idleTimeout)
×
UNCOV
2154
                                continue
×
2155

2156
                        // If the error we encountered wasn't just a message we
2157
                        // didn't recognize, then we'll stop all processing as
2158
                        // this is a fatal error.
2159
                        default:
2✔
2160
                                break out
2✔
2161
                        }
2162
                }
2163

2164
                // If a message router is active, then we'll try to have it
2165
                // handle this message. If it can, then we're able to skip the
2166
                // rest of the message handling logic.
2167
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
6✔
2168
                        return r.RouteMsg(msgmux.PeerMsg{
3✔
2169
                                PeerPub: *p.IdentityKey(),
3✔
2170
                                Message: nextMsg,
3✔
2171
                        })
3✔
2172
                })
3✔
2173

2174
                // No error occurred, and the message was handled by the
2175
                // router.
2176
                if err == nil {
5✔
2177
                        continue
2✔
2178
                }
2179

2180
                var (
3✔
2181
                        targetChan   lnwire.ChannelID
3✔
2182
                        isLinkUpdate bool
3✔
2183
                )
3✔
2184

3✔
2185
                switch msg := nextMsg.(type) {
3✔
2186
                case *lnwire.Pong:
×
2187
                        // When we receive a Pong message in response to our
×
2188
                        // last ping message, we send it to the pingManager
×
2189
                        p.pingManager.ReceivedPong(msg)
×
2190

2191
                case *lnwire.Ping:
×
2192
                        // First, we'll store their latest ping payload within
×
UNCOV
2193
                        // the relevant atomic variable.
×
UNCOV
2194
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
UNCOV
2195

×
UNCOV
2196
                        // Next, we'll send over the amount of specified pong
×
UNCOV
2197
                        // bytes.
×
UNCOV
2198
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
×
UNCOV
2199
                        p.queueMsg(pong, nil)
×
2200

2201
                case *lnwire.OpenChannel,
2202
                        *lnwire.AcceptChannel,
2203
                        *lnwire.FundingCreated,
2204
                        *lnwire.FundingSigned,
2205
                        *lnwire.ChannelReady:
2✔
2206

2✔
2207
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
2✔
2208

2209
                case *lnwire.Shutdown:
2✔
2210
                        select {
2✔
2211
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
2✔
2212
                        case <-p.cg.Done():
×
UNCOV
2213
                                break out
×
2214
                        }
2215
                case *lnwire.ClosingSigned:
2✔
2216
                        select {
2✔
2217
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
2✔
UNCOV
2218
                        case <-p.cg.Done():
×
UNCOV
2219
                                break out
×
2220
                        }
2221

UNCOV
2222
                case *lnwire.Warning:
×
UNCOV
2223
                        targetChan = msg.ChanID
×
UNCOV
2224
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2225

2226
                case *lnwire.Error:
2✔
2227
                        targetChan = msg.ChanID
2✔
2228
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
2✔
2229

2230
                case *lnwire.ChannelReestablish:
2✔
2231
                        targetChan = msg.ChanID
2✔
2232
                        isLinkUpdate = p.hasChannel(targetChan)
2✔
2233

2✔
2234
                        // If we failed to find the link in question, and the
2✔
2235
                        // message received was a channel sync message, then
2✔
2236
                        // this might be a peer trying to resync closed channel.
2✔
2237
                        // In this case we'll try to resend our last channel
2✔
2238
                        // sync message, such that the peer can recover funds
2✔
2239
                        // from the closed channel.
2✔
2240
                        if !isLinkUpdate {
4✔
2241
                                err := p.resendChanSyncMsg(targetChan)
2✔
2242
                                if err != nil {
4✔
2243
                                        // TODO(halseth): send error to peer?
2✔
2244
                                        p.log.Errorf("resend failed: %v",
2✔
2245
                                                err)
2✔
2246
                                }
2✔
2247
                        }
2248

2249
                // For messages that implement the LinkUpdater interface, we
2250
                // will consider them as link updates and send them to
2251
                // chanStream. These messages will be queued inside chanStream
2252
                // if the channel is not active yet.
2253
                case lnwire.LinkUpdater:
2✔
2254
                        targetChan = msg.TargetChanID()
2✔
2255
                        isLinkUpdate = p.hasChannel(targetChan)
2✔
2256

2✔
2257
                        // Log an error if we don't have this channel. This
2✔
2258
                        // means the peer has sent us a message with unknown
2✔
2259
                        // channel ID.
2✔
2260
                        if !isLinkUpdate {
4✔
2261
                                p.log.Errorf("Unknown channel ID: %v found "+
2✔
2262
                                        "in received msg=%s", targetChan,
2✔
2263
                                        nextMsg.MsgType())
2✔
2264
                        }
2✔
2265

2266
                case *lnwire.ChannelUpdate1,
2267
                        *lnwire.ChannelAnnouncement1,
2268
                        *lnwire.NodeAnnouncement1,
2269
                        *lnwire.AnnounceSignatures1,
2270
                        *lnwire.GossipTimestampRange,
2271
                        *lnwire.QueryShortChanIDs,
2272
                        *lnwire.QueryChannelRange,
2273
                        *lnwire.ReplyChannelRange,
2274
                        *lnwire.ReplyShortChanIDsEnd:
2✔
2275

2✔
2276
                        discStream.AddMsg(msg)
2✔
2277

2278
                case *lnwire.Custom:
3✔
2279
                        err := p.handleCustomMessage(msg)
3✔
2280
                        if err != nil {
3✔
2281
                                p.storeError(err)
×
2282
                                p.log.Errorf("%v", err)
×
2283
                        }
×
2284

2285
                default:
×
UNCOV
2286
                        // If the message we received is unknown to us, store
×
UNCOV
2287
                        // the type to track the failure.
×
UNCOV
2288
                        err := fmt.Errorf("unknown message type %v received",
×
UNCOV
2289
                                uint16(msg.MsgType()))
×
UNCOV
2290
                        p.storeError(err)
×
UNCOV
2291

×
UNCOV
2292
                        p.log.Errorf("%v", err)
×
2293
                }
2294

2295
                if isLinkUpdate {
5✔
2296
                        // If this is a channel update, then we need to feed it
2✔
2297
                        // into the channel's in-order message stream.
2✔
2298
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
2✔
2299
                }
2✔
2300

2301
                idleTimer.Reset(idleTimeout)
3✔
2302
        }
2303

2304
        p.Disconnect(errors.New("read handler closed"))
2✔
2305

2✔
2306
        p.log.Trace("readHandler for peer done")
2✔
2307
}
2308

2309
// handleCustomMessage handles the given custom message if a handler is
2310
// registered.
2311
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
3✔
2312
        if p.cfg.HandleCustomMessage == nil {
3✔
UNCOV
2313
                return fmt.Errorf("no custom message handler for "+
×
UNCOV
2314
                        "message type %v", uint16(msg.MsgType()))
×
UNCOV
2315
        }
×
2316

2317
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
3✔
2318
}
2319

2320
// isLoadedFromDisk returns true if the provided channel ID is loaded from
2321
// disk.
2322
//
2323
// NOTE: only returns true for pending channels.
2324
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
2✔
2325
        // If this is a newly added channel, no need to reestablish.
2✔
2326
        _, added := p.addedChannels.Load(chanID)
2✔
2327
        if added {
4✔
2328
                return false
2✔
2329
        }
2✔
2330

2331
        // Return false if the channel is unknown.
2332
        channel, ok := p.activeChannels.Load(chanID)
2✔
2333
        if !ok {
2✔
UNCOV
2334
                return false
×
UNCOV
2335
        }
×
2336

2337
        // During startup, we will use a nil value to mark a pending channel
2338
        // that's loaded from disk.
2339
        return channel == nil
2✔
2340
}
2341

2342
// isActiveChannel returns true if the provided channel id is active, otherwise
2343
// returns false.
2344
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
10✔
2345
        // The channel would be nil if,
10✔
2346
        // - the channel doesn't exist, or,
10✔
2347
        // - the channel exists, but is pending. In this case, we don't
10✔
2348
        //   consider this channel active.
10✔
2349
        channel, _ := p.activeChannels.Load(chanID)
10✔
2350

10✔
2351
        return channel != nil
10✔
2352
}
10✔
2353

2354
// isPendingChannel returns true if the provided channel ID is pending, and
2355
// returns false if the channel is active or unknown.
2356
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
8✔
2357
        // Return false if the channel is unknown.
8✔
2358
        channel, ok := p.activeChannels.Load(chanID)
8✔
2359
        if !ok {
13✔
2360
                return false
5✔
2361
        }
5✔
2362

2363
        return channel == nil
5✔
2364
}
2365

2366
// hasChannel returns true if the peer has a pending/active channel specified
2367
// by the channel ID.
2368
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
2✔
2369
        _, ok := p.activeChannels.Load(chanID)
2✔
2370
        return ok
2✔
2371
}
2✔
2372

2373
// storeError stores an error in our peer's buffer of recent errors with the
2374
// current timestamp. Errors are only stored if we have at least one active
2375
// channel with the peer to mitigate a dos vector where a peer costlessly
2376
// connects to us and spams us with errors.
2377
func (p *Brontide) storeError(err error) {
3✔
2378
        var haveChannels bool
3✔
2379

3✔
2380
        p.activeChannels.Range(func(_ lnwire.ChannelID,
3✔
2381
                channel *lnwallet.LightningChannel) bool {
6✔
2382

3✔
2383
                // Pending channels will be nil in the activeChannels map.
3✔
2384
                if channel == nil {
5✔
2385
                        // Return true to continue the iteration.
2✔
2386
                        return true
2✔
2387
                }
2✔
2388

2389
                haveChannels = true
3✔
2390

3✔
2391
                // Return false to break the iteration.
3✔
2392
                return false
3✔
2393
        })
2394

2395
        // If we do not have any active channels with the peer, we do not store
2396
        // errors as a dos mitigation.
2397
        if !haveChannels {
5✔
2398
                p.log.Trace("no channels with peer, not storing err")
2✔
2399
                return
2✔
2400
        }
2✔
2401

2402
        p.cfg.ErrorBuffer.Add(
3✔
2403
                &TimestampedError{Timestamp: time.Now(), Error: err},
3✔
2404
        )
3✔
2405
}
2406

2407
// handleWarningOrError processes a warning or error msg and returns true if
2408
// msg should be forwarded to the associated channel link. False is returned if
2409
// any necessary forwarding of msg was already handled by this method. If msg is
2410
// an error from a peer with an active channel, we'll store it in memory.
2411
//
2412
// NOTE: This method should only be called from within the readHandler.
2413
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
2414
        msg lnwire.Message) bool {
2✔
2415

2✔
2416
        if errMsg, ok := msg.(*lnwire.Error); ok {
4✔
2417
                p.storeError(errMsg)
2✔
2418
        }
2✔
2419

2420
        switch {
2✔
2421
        // Connection wide messages should be forwarded to all channel links
2422
        // with this peer.
UNCOV
2423
        case chanID == lnwire.ConnectionWideID:
×
UNCOV
2424
                for _, chanStream := range p.activeMsgStreams {
×
UNCOV
2425
                        chanStream.AddMsg(msg)
×
UNCOV
2426
                }
×
2427

UNCOV
2428
                return false
×
2429

2430
        // If the channel ID for the message corresponds to a pending channel,
2431
        // then the funding manager will handle it.
2432
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
2✔
2433
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
2✔
2434
                return false
2✔
2435

2436
        // If not we hand the message to the channel link for this channel.
2437
        case p.isActiveChannel(chanID):
2✔
2438
                return true
2✔
2439

2440
        default:
2✔
2441
                return false
2✔
2442
        }
2443
}
2444

2445
// messageSummary returns a human-readable string that summarizes a
2446
// incoming/outgoing message. Not all messages will have a summary, only those
2447
// which have additional data that can be informative at a glance.
2448
func messageSummary(msg lnwire.Message) string {
2✔
2449
        switch msg := msg.(type) {
2✔
2450
        case *lnwire.Init:
2✔
2451
                // No summary.
2✔
2452
                return ""
2✔
2453

2454
        case *lnwire.OpenChannel:
2✔
2455
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
2✔
2456
                        "push_amt=%v, reserve=%v, flags=%v",
2✔
2457
                        msg.PendingChannelID[:], msg.ChainHash,
2✔
2458
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
2✔
2459
                        msg.ChannelReserve, msg.ChannelFlags)
2✔
2460

2461
        case *lnwire.AcceptChannel:
2✔
2462
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
2✔
2463
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
2✔
2464
                        msg.MinAcceptDepth)
2✔
2465

2466
        case *lnwire.FundingCreated:
2✔
2467
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
2✔
2468
                        msg.PendingChannelID[:], msg.FundingPoint)
2✔
2469

2470
        case *lnwire.FundingSigned:
2✔
2471
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
2✔
2472

2473
        case *lnwire.ChannelReady:
2✔
2474
                return fmt.Sprintf("chan_id=%v, next_point=%x",
2✔
2475
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
2✔
2476

2477
        case *lnwire.Shutdown:
2✔
2478
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
2✔
2479
                        msg.Address[:])
2✔
2480

2481
        case *lnwire.ClosingComplete:
2✔
2482
                return fmt.Sprintf("chan_id=%v, fee_sat=%v, locktime=%v",
2✔
2483
                        msg.ChannelID, msg.FeeSatoshis, msg.LockTime)
2✔
2484

2485
        case *lnwire.ClosingSig:
2✔
2486
                return fmt.Sprintf("chan_id=%v", msg.ChannelID)
2✔
2487

2488
        case *lnwire.ClosingSigned:
2✔
2489
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
2✔
2490
                        msg.FeeSatoshis)
2✔
2491

2492
        case *lnwire.UpdateAddHTLC:
2✔
2493
                var blindingPoint []byte
2✔
2494
                msg.BlindingPoint.WhenSome(
2✔
2495
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
2✔
2496
                                *btcec.PublicKey]) {
4✔
2497

2✔
2498
                                blindingPoint = b.Val.SerializeCompressed()
2✔
2499
                        },
2✔
2500
                )
2501

2502
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
2✔
2503
                        "hash=%x, blinding_point=%x, custom_records=%v",
2✔
2504
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
2✔
2505
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
2✔
2506

2507
        case *lnwire.UpdateFailHTLC:
2✔
2508
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
2✔
2509
                        msg.ID, msg.Reason)
2✔
2510

2511
        case *lnwire.UpdateFulfillHTLC:
2✔
2512
                return fmt.Sprintf("chan_id=%v, id=%v, preimage=%x, "+
2✔
2513
                        "custom_records=%v", msg.ChanID, msg.ID,
2✔
2514
                        msg.PaymentPreimage[:], msg.CustomRecords)
2✔
2515

2516
        case *lnwire.CommitSig:
2✔
2517
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
2✔
2518
                        len(msg.HtlcSigs))
2✔
2519

2520
        case *lnwire.RevokeAndAck:
2✔
2521
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
2✔
2522
                        msg.ChanID, msg.Revocation[:],
2✔
2523
                        msg.NextRevocationKey.SerializeCompressed())
2✔
2524

2525
        case *lnwire.UpdateFailMalformedHTLC:
2✔
2526
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
2✔
2527
                        msg.ChanID, msg.ID, msg.FailureCode)
2✔
2528

UNCOV
2529
        case *lnwire.Warning:
×
UNCOV
2530
                return fmt.Sprintf("%v", msg.Warning())
×
2531

2532
        case *lnwire.Error:
2✔
2533
                return fmt.Sprintf("%v", msg.Error())
2✔
2534

2535
        case *lnwire.AnnounceSignatures1:
2✔
2536
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
2✔
2537
                        msg.ShortChannelID.ToUint64())
2✔
2538

2539
        case *lnwire.ChannelAnnouncement1:
2✔
2540
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
2✔
2541
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
2✔
2542

2543
        case *lnwire.ChannelUpdate1:
2✔
2544
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
2✔
2545
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
2✔
2546
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
2✔
2547
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
2✔
2548

2549
        case *lnwire.NodeAnnouncement1:
2✔
2550
                return fmt.Sprintf("node=%x, update_time=%v",
2✔
2551
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
2✔
2552

2553
        case *lnwire.Ping:
×
2554
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
2555

UNCOV
2556
        case *lnwire.Pong:
×
UNCOV
2557
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
×
2558

UNCOV
2559
        case *lnwire.UpdateFee:
×
UNCOV
2560
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
UNCOV
2561
                        msg.ChanID, int64(msg.FeePerKw))
×
2562

2563
        case *lnwire.ChannelReestablish:
2✔
2564
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
2✔
2565
                        "remote_tail_height=%v", msg.ChanID,
2✔
2566
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
2✔
2567

2568
        case *lnwire.ReplyShortChanIDsEnd:
2✔
2569
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
2✔
2570
                        msg.Complete)
2✔
2571

2572
        case *lnwire.ReplyChannelRange:
2✔
2573
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
2✔
2574
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
2✔
2575
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
2✔
2576
                        msg.EncodingType)
2✔
2577

2578
        case *lnwire.QueryShortChanIDs:
2✔
2579
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
2✔
2580
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
2✔
2581

2582
        case *lnwire.QueryChannelRange:
2✔
2583
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
2✔
2584
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
2✔
2585
                        msg.LastBlockHeight())
2✔
2586

2587
        case *lnwire.GossipTimestampRange:
2✔
2588
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
2✔
2589
                        "stamp_range=%v", msg.ChainHash,
2✔
2590
                        time.Unix(int64(msg.FirstTimestamp), 0),
2✔
2591
                        msg.TimestampRange)
2✔
2592

2593
        case *lnwire.Stfu:
2✔
2594
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
2✔
2595
                        msg.Initiator)
2✔
2596

2597
        case *lnwire.Custom:
2✔
2598
                return fmt.Sprintf("type=%d", msg.Type)
2✔
2599
        }
2600

2601
        return fmt.Sprintf("unknown msg type=%T", msg)
2✔
2602
}
2603

2604
// logWireMessage logs the receipt or sending of particular wire message. This
2605
// function is used rather than just logging the message in order to produce
2606
// less spammy log messages in trace mode by setting the 'Curve" parameter to
2607
// nil. Doing this avoids printing out each of the field elements in the curve
2608
// parameters for secp256k1.
2609
func (p *Brontide) logWireMessage(msg lnwire.Message, read bool) {
19✔
2610
        summaryPrefix := "Received"
19✔
2611
        if !read {
34✔
2612
                summaryPrefix = "Sending"
15✔
2613
        }
15✔
2614

2615
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
21✔
2616
                // Debug summary of message.
2✔
2617
                summary := messageSummary(msg)
2✔
2618
                if len(summary) > 0 {
4✔
2619
                        summary = "(" + summary + ")"
2✔
2620
                }
2✔
2621

2622
                preposition := "to"
2✔
2623
                if read {
4✔
2624
                        preposition = "from"
2✔
2625
                }
2✔
2626

2627
                var msgType string
2✔
2628
                if msg.MsgType() < lnwire.CustomTypeStart {
4✔
2629
                        msgType = msg.MsgType().String()
2✔
2630
                } else {
4✔
2631
                        msgType = "custom"
2✔
2632
                }
2✔
2633

2634
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
2✔
2635
                        msgType, summary, preposition, p)
2✔
2636
        }))
2637

2638
        prefix := "readMessage from peer"
19✔
2639
        if !read {
34✔
2640
                prefix = "writeMessage to peer"
15✔
2641
        }
15✔
2642

2643
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
19✔
2644
}
2645

2646
// writeMessage writes and flushes the target lnwire.Message to the remote peer.
2647
// If the passed message is nil, this method will only try to flush an existing
2648
// message buffered on the connection. It is safe to call this method again
2649
// with a nil message iff a timeout error is returned. This will continue to
2650
// flush the pending message to the wire.
2651
//
2652
// NOTE:
2653
// Besides its usage in Start, this function should not be used elsewhere
2654
// except in writeHandler. If multiple goroutines call writeMessage at the same
2655
// time, panics can occur because WriteMessage and Flush don't use any locking
2656
// internally.
2657
func (p *Brontide) writeMessage(msg lnwire.Message) error {
15✔
2658
        // Only log the message on the first attempt.
15✔
2659
        if msg != nil {
30✔
2660
                p.logWireMessage(msg, false)
15✔
2661
        }
15✔
2662

2663
        noiseConn := p.cfg.Conn
15✔
2664

15✔
2665
        flushMsg := func() error {
30✔
2666
                // Ensure the write deadline is set before we attempt to send
15✔
2667
                // the message.
15✔
2668
                writeDeadline := time.Now().Add(
15✔
2669
                        p.scaleTimeout(writeMessageTimeout),
15✔
2670
                )
15✔
2671
                err := noiseConn.SetWriteDeadline(writeDeadline)
15✔
2672
                if err != nil {
15✔
UNCOV
2673
                        return err
×
UNCOV
2674
                }
×
2675

2676
                // Flush the pending message to the wire. If an error is
2677
                // encountered, e.g. write timeout, the number of bytes written
2678
                // so far will be returned.
2679
                n, err := noiseConn.Flush()
15✔
2680

15✔
2681
                // Record the number of bytes written on the wire, if any.
15✔
2682
                if n > 0 {
17✔
2683
                        atomic.AddUint64(&p.bytesSent, uint64(n))
2✔
2684
                }
2✔
2685

2686
                return err
15✔
2687
        }
2688

2689
        // If the current message has already been serialized, encrypted, and
2690
        // buffered on the underlying connection we will skip straight to
2691
        // flushing it to the wire.
2692
        if msg == nil {
15✔
UNCOV
2693
                return flushMsg()
×
UNCOV
2694
        }
×
2695

2696
        // Otherwise, this is a new message. We'll acquire a write buffer to
2697
        // serialize the message and buffer the ciphertext on the connection.
2698
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
30✔
2699
                // Using a buffer allocated by the write pool, encode the
15✔
2700
                // message directly into the buffer.
15✔
2701
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
15✔
2702
                if writeErr != nil {
15✔
UNCOV
2703
                        return writeErr
×
UNCOV
2704
                }
×
2705

2706
                // Finally, write the message itself in a single swoop. This
2707
                // will buffer the ciphertext on the underlying connection. We
2708
                // will defer flushing the message until the write pool has been
2709
                // released.
2710
                return noiseConn.WriteMessage(buf.Bytes())
15✔
2711
        })
2712
        if err != nil {
15✔
UNCOV
2713
                return err
×
UNCOV
2714
        }
×
2715

2716
        return flushMsg()
15✔
2717
}
2718

2719
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2720
// queue, and writing them out to the wire. This goroutine coordinates with the
2721
// queueHandler in order to ensure the incoming message queue is quickly
2722
// drained.
2723
//
2724
// NOTE: This method MUST be run as a goroutine.
2725
func (p *Brontide) writeHandler() {
5✔
2726
        // We'll stop the timer after a new messages is sent, and also reset it
5✔
2727
        // after we process the next message.
5✔
2728
        idleTimer := time.AfterFunc(idleTimeout, func() {
5✔
UNCOV
2729
                err := fmt.Errorf("peer %s no write for %s -- disconnecting",
×
UNCOV
2730
                        p, idleTimeout)
×
UNCOV
2731
                p.Disconnect(err)
×
UNCOV
2732
        })
×
2733

2734
        var exitErr error
5✔
2735

5✔
2736
out:
5✔
2737
        for {
14✔
2738
                select {
9✔
2739
                case outMsg := <-p.sendQueue:
6✔
2740
                        // Record the time at which we first attempt to send the
6✔
2741
                        // message.
6✔
2742
                        startTime := time.Now()
6✔
2743

6✔
2744
                retry:
6✔
2745
                        // Write out the message to the socket. If a timeout
2746
                        // error is encountered, we will catch this and retry
2747
                        // after backing off in case the remote peer is just
2748
                        // slow to process messages from the wire.
2749
                        err := p.writeMessage(outMsg.msg)
6✔
2750
                        if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
6✔
2751
                                p.log.Debugf("Write timeout detected for "+
×
2752
                                        "peer, first write for message "+
×
2753
                                        "attempted %v ago",
×
2754
                                        time.Since(startTime))
×
2755

×
2756
                                // If we received a timeout error, this implies
×
2757
                                // that the message was buffered on the
×
2758
                                // connection successfully and that a flush was
×
UNCOV
2759
                                // attempted. We'll set the message to nil so
×
UNCOV
2760
                                // that on a subsequent pass we only try to
×
UNCOV
2761
                                // flush the buffered message, and forgo
×
UNCOV
2762
                                // reserializing or reencrypting it.
×
UNCOV
2763
                                outMsg.msg = nil
×
UNCOV
2764

×
UNCOV
2765
                                goto retry
×
2766
                        }
2767

2768
                        // Message has either been successfully sent or an
2769
                        // unrecoverable error occurred.  Either way, we can
2770
                        // free the memory used to store the message.
2771
                        if bConn, ok := p.cfg.Conn.(*brontide.Conn); ok {
8✔
2772
                                bConn.ClearPendingSend()
2✔
2773
                        }
2✔
2774

2775
                        // The write succeeded, reset the idle timer to prevent
2776
                        // us from disconnecting the peer.
2777
                        if !idleTimer.Stop() {
6✔
UNCOV
2778
                                select {
×
UNCOV
2779
                                case <-idleTimer.C:
×
UNCOV
2780
                                default:
×
2781
                                }
2782
                        }
2783
                        idleTimer.Reset(idleTimeout)
6✔
2784

6✔
2785
                        // If the peer requested a synchronous write, respond
6✔
2786
                        // with the error.
6✔
2787
                        if outMsg.errChan != nil {
9✔
2788
                                outMsg.errChan <- err
3✔
2789
                        }
3✔
2790

2791
                        if err != nil {
6✔
UNCOV
2792
                                exitErr = fmt.Errorf("unable to write "+
×
UNCOV
2793
                                        "message: %v", err)
×
UNCOV
2794
                                break out
×
2795
                        }
2796

2797
                case <-p.cg.Done():
2✔
2798
                        exitErr = lnpeer.ErrPeerExiting
2✔
2799
                        break out
2✔
2800
                }
2801
        }
2802

2803
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2804
        // disconnect.
2805
        p.cg.WgDone()
2✔
2806

2✔
2807
        p.Disconnect(exitErr)
2✔
2808

2✔
2809
        p.log.Trace("writeHandler for peer done")
2✔
2810
}
2811

2812
// queueHandler is responsible for accepting messages from outside subsystems
2813
// to be eventually sent out on the wire by the writeHandler.
2814
//
2815
// NOTE: This method MUST be run as a goroutine.
2816
func (p *Brontide) queueHandler() {
5✔
2817
        defer p.cg.WgDone()
5✔
2818

5✔
2819
        // priorityMsgs holds an in order list of messages deemed high-priority
5✔
2820
        // to be added to the sendQueue. This predominately includes messages
5✔
2821
        // from the funding manager and htlcswitch.
5✔
2822
        priorityMsgs := list.New()
5✔
2823

5✔
2824
        // lazyMsgs holds an in order list of messages deemed low-priority to be
5✔
2825
        // added to the sendQueue only after all high-priority messages have
5✔
2826
        // been queued. This predominately includes messages from the gossiper.
5✔
2827
        lazyMsgs := list.New()
5✔
2828

5✔
2829
        for {
18✔
2830
                // Examine the front of the priority queue, if it is empty check
13✔
2831
                // the low priority queue.
13✔
2832
                elem := priorityMsgs.Front()
13✔
2833
                if elem == nil {
23✔
2834
                        elem = lazyMsgs.Front()
10✔
2835
                }
10✔
2836

2837
                if elem != nil {
19✔
2838
                        front := elem.Value.(outgoingMsg)
6✔
2839

6✔
2840
                        // There's an element on the queue, try adding
6✔
2841
                        // it to the sendQueue. We also watch for
6✔
2842
                        // messages on the outgoingQueue, in case the
6✔
2843
                        // writeHandler cannot accept messages on the
6✔
2844
                        // sendQueue.
6✔
2845
                        select {
6✔
2846
                        case p.sendQueue <- front:
6✔
2847
                                if front.priority {
11✔
2848
                                        priorityMsgs.Remove(elem)
5✔
2849
                                } else {
8✔
2850
                                        lazyMsgs.Remove(elem)
3✔
2851
                                }
3✔
2852
                        case msg := <-p.outgoingQueue:
2✔
2853
                                if msg.priority {
4✔
2854
                                        priorityMsgs.PushBack(msg)
2✔
2855
                                } else {
4✔
2856
                                        lazyMsgs.PushBack(msg)
2✔
2857
                                }
2✔
UNCOV
2858
                        case <-p.cg.Done():
×
UNCOV
2859
                                return
×
2860
                        }
2861
                } else {
9✔
2862
                        // If there weren't any messages to send to the
9✔
2863
                        // writeHandler, then we'll accept a new message
9✔
2864
                        // into the queue from outside sub-systems.
9✔
2865
                        select {
9✔
2866
                        case msg := <-p.outgoingQueue:
6✔
2867
                                if msg.priority {
11✔
2868
                                        priorityMsgs.PushBack(msg)
5✔
2869
                                } else {
8✔
2870
                                        lazyMsgs.PushBack(msg)
3✔
2871
                                }
3✔
2872
                        case <-p.cg.Done():
2✔
2873
                                return
2✔
2874
                        }
2875
                }
2876
        }
2877
}
2878

2879
// PingTime returns the estimated ping time to the peer in microseconds.
2880
func (p *Brontide) PingTime() int64 {
2✔
2881
        return p.pingManager.GetPingTimeMicroSeconds()
2✔
2882
}
2✔
2883

2884
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2885
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2886
// or failed to write, and nil otherwise.
2887
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
26✔
2888
        p.queue(true, msg, errChan)
26✔
2889
}
26✔
2890

2891
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2892
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2893
// queue or failed to write, and nil otherwise.
2894
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
3✔
2895
        p.queue(false, msg, errChan)
3✔
2896
}
3✔
2897

2898
// queue sends a given message to the queueHandler using the passed priority. If
2899
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2900
// failed to write, and nil otherwise.
2901
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2902
        errChan chan error) {
27✔
2903

27✔
2904
        select {
27✔
2905
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
27✔
UNCOV
2906
        case <-p.cg.Done():
×
UNCOV
2907
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
×
UNCOV
2908
                        lnutils.SpewLogClosure(msg))
×
UNCOV
2909
                if errChan != nil {
×
UNCOV
2910
                        errChan <- lnpeer.ErrPeerExiting
×
UNCOV
2911
                }
×
2912
        }
2913
}
2914

2915
// ChannelSnapshots returns a slice of channel snapshots detailing all
2916
// currently active channels maintained with the remote peer.
2917
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
2✔
2918
        snapshots := make(
2✔
2919
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
2✔
2920
        )
2✔
2921

2✔
2922
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
2✔
2923
                activeChan *lnwallet.LightningChannel) error {
4✔
2924

2✔
2925
                // If the activeChan is nil, then we skip it as the channel is
2✔
2926
                // pending.
2✔
2927
                if activeChan == nil {
4✔
2928
                        return nil
2✔
2929
                }
2✔
2930

2931
                // We'll only return a snapshot for channels that are
2932
                // *immediately* available for routing payments over.
2933
                if activeChan.RemoteNextRevocation() == nil {
4✔
2934
                        return nil
2✔
2935
                }
2✔
2936

2937
                snapshot := activeChan.StateSnapshot()
2✔
2938
                snapshots = append(snapshots, snapshot)
2✔
2939

2✔
2940
                return nil
2✔
2941
        })
2942

2943
        return snapshots
2✔
2944
}
2945

2946
// genDeliveryScript returns a new script to be used to send our funds to in
2947
// the case of a cooperative channel close negotiation.
2948
func (p *Brontide) genDeliveryScript() ([]byte, error) {
8✔
2949
        // We'll send a normal p2wkh address unless we've negotiated the
8✔
2950
        // shutdown-any-segwit feature.
8✔
2951
        addrType := lnwallet.WitnessPubKey
8✔
2952
        if p.taprootShutdownAllowed() {
10✔
2953
                addrType = lnwallet.TaprootPubkey
2✔
2954
        }
2✔
2955

2956
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
8✔
2957
                addrType, false, lnwallet.DefaultAccountName,
8✔
2958
        )
8✔
2959
        if err != nil {
8✔
UNCOV
2960
                return nil, err
×
UNCOV
2961
        }
×
2962
        p.log.Infof("Delivery addr for channel close: %v",
8✔
2963
                deliveryAddr)
8✔
2964

8✔
2965
        return txscript.PayToAddrScript(deliveryAddr)
8✔
2966
}
2967

2968
// channelManager is goroutine dedicated to handling all requests/signals
2969
// pertaining to the opening, cooperative closing, and force closing of all
2970
// channels maintained with the remote peer.
2971
//
2972
// NOTE: This method MUST be run as a goroutine.
2973
func (p *Brontide) channelManager() {
19✔
2974
        defer p.cg.WgDone()
19✔
2975

19✔
2976
        // reenableTimeout will fire once after the configured channel status
19✔
2977
        // interval has elapsed. This will trigger us to sign new channel
19✔
2978
        // updates and broadcast them with the "disabled" flag unset.
19✔
2979
        reenableTimeout := time.After(p.cfg.ChanActiveTimeout)
19✔
2980

19✔
2981
out:
19✔
2982
        for {
60✔
2983
                select {
41✔
2984
                // A new pending channel has arrived which means we are about
2985
                // to complete a funding workflow and is waiting for the final
2986
                // `ChannelReady` messages to be exchanged. We will add this
2987
                // channel to the `activeChannels` with a nil value to indicate
2988
                // this is a pending channel.
2989
                case req := <-p.newPendingChannel:
3✔
2990
                        p.handleNewPendingChannel(req)
3✔
2991

2992
                // A new channel has arrived which means we've just completed a
2993
                // funding workflow. We'll initialize the necessary local
2994
                // state, and notify the htlc switch of a new link.
2995
                case req := <-p.newActiveChannel:
2✔
2996
                        p.handleNewActiveChannel(req)
2✔
2997

2998
                // The funding flow for a pending channel is failed, we will
2999
                // remove it from Brontide.
3000
                case req := <-p.removePendingChannel:
3✔
3001
                        p.handleRemovePendingChannel(req)
3✔
3002

3003
                // We've just received a local request to close an active
3004
                // channel. It will either kick of a cooperative channel
3005
                // closure negotiation, or be a notification of a breached
3006
                // contract that should be abandoned.
3007
                case req := <-p.localCloseChanReqs:
9✔
3008
                        p.handleLocalCloseReq(req)
9✔
3009

3010
                // We've received a link failure from a link that was added to
3011
                // the switch. This will initiate the teardown of the link, and
3012
                // initiate any on-chain closures if necessary.
3013
                case failure := <-p.linkFailures:
2✔
3014
                        p.handleLinkFailure(failure)
2✔
3015

3016
                // We've received a new cooperative channel closure related
3017
                // message from the remote peer, we'll use this message to
3018
                // advance the chan closer state machine.
3019
                case closeMsg := <-p.chanCloseMsgs:
15✔
3020
                        p.handleCloseMsg(closeMsg)
15✔
3021

3022
                // The channel reannounce delay has elapsed, broadcast the
3023
                // reenabled channel updates to the network. This should only
3024
                // fire once, so we set the reenableTimeout channel to nil to
3025
                // mark it for garbage collection. If the peer is torn down
3026
                // before firing, reenabling will not be attempted.
3027
                // TODO(conner): consolidate reenables timers inside chan status
3028
                // manager
3029
                case <-reenableTimeout:
2✔
3030
                        p.reenableActiveChannels()
2✔
3031

2✔
3032
                        // Since this channel will never fire again during the
2✔
3033
                        // lifecycle of the peer, we nil the channel to mark it
2✔
3034
                        // eligible for garbage collection, and make this
2✔
3035
                        // explicitly ineligible to receive in future calls to
2✔
3036
                        // select. This also shaves a few CPU cycles since the
2✔
3037
                        // select will ignore this case entirely.
2✔
3038
                        reenableTimeout = nil
2✔
3039

2✔
3040
                        // Once the reenabling is attempted, we also cancel the
2✔
3041
                        // channel event subscription to free up the overflow
2✔
3042
                        // queue used in channel notifier.
2✔
3043
                        //
2✔
3044
                        // NOTE: channelEventClient will be nil if the
2✔
3045
                        // reenableTimeout is greater than 1 minute.
2✔
3046
                        if p.channelEventClient != nil {
4✔
3047
                                p.channelEventClient.Cancel()
2✔
3048
                        }
2✔
3049

3050
                case <-p.cg.Done():
3✔
3051
                        // As, we've been signalled to exit, we'll reset all
3✔
3052
                        // our active channel back to their default state.
3✔
3053
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
3054
                                lc *lnwallet.LightningChannel) error {
6✔
3055

3✔
3056
                                // Exit if the channel is nil as it's a pending
3✔
3057
                                // channel.
3✔
3058
                                if lc == nil {
5✔
3059
                                        return nil
2✔
3060
                                }
2✔
3061

3062
                                lc.ResetState()
3✔
3063

3✔
3064
                                return nil
3✔
3065
                        })
3066

3067
                        break out
3✔
3068
                }
3069
        }
3070
}
3071

3072
// reenableActiveChannels searches the index of channels maintained with this
3073
// peer, and reenables each public, non-pending channel. This is done at the
3074
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
3075
// No message will be sent if the channel is already enabled.
3076
func (p *Brontide) reenableActiveChannels() {
2✔
3077
        // First, filter all known channels with this peer for ones that are
2✔
3078
        // both public and not pending.
2✔
3079
        activePublicChans := p.filterChannelsToEnable()
2✔
3080

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

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

2✔
3090
                switch {
2✔
3091
                // No error occurred, continue to request the next channel.
3092
                case err == nil:
2✔
3093
                        continue
2✔
3094

3095
                // Cannot auto enable a manually disabled channel so we do
3096
                // nothing but proceed to the next channel.
3097
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
2✔
3098
                        p.log.Debugf("Channel(%v) was manually disabled, "+
2✔
3099
                                "ignoring automatic enable request", chanPoint)
2✔
3100

2✔
3101
                        continue
2✔
3102

3103
                // If the channel is reported as inactive, we will give it
3104
                // another chance. When handling the request, ChanStatusManager
3105
                // will check whether the link is active or not. One of the
3106
                // conditions is whether the link has been marked as
3107
                // reestablished, which happens inside a goroutine(htlcManager)
3108
                // after the link is started. And we may get a false negative
3109
                // saying the link is not active because that goroutine hasn't
3110
                // reached the line to mark the reestablishment. Thus we give
3111
                // it a second chance to send the request.
3112
                case errors.Is(err, netann.ErrEnableInactiveChan):
×
3113
                        // If we don't have a client created, it means we
×
UNCOV
3114
                        // shouldn't retry enabling the channel.
×
UNCOV
3115
                        if p.channelEventClient == nil {
×
3116
                                p.log.Errorf("Channel(%v) request enabling "+
×
3117
                                        "failed due to inactive link",
×
3118
                                        chanPoint)
×
3119

×
3120
                                continue
×
3121
                        }
3122

UNCOV
3123
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
UNCOV
3124
                                "ChanStatusManager reported inactive, retrying")
×
UNCOV
3125

×
3126
                        // Add the channel to the retry map.
×
3127
                        retryChans[chanPoint] = struct{}{}
×
3128
                }
3129
        }
3130

3131
        // Retry the channels if we have any.
3132
        if len(retryChans) != 0 {
2✔
UNCOV
3133
                p.retryRequestEnable(retryChans)
×
UNCOV
3134
        }
×
3135
}
3136

3137
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
3138
// for the target channel ID. If the channel isn't active an error is returned.
3139
// Otherwise, either an existing state machine will be returned, or a new one
3140
// will be created.
3141
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
3142
        *chanCloserFsm, error) {
15✔
3143

15✔
3144
        chanCloser, found := p.activeChanCloses.Load(chanID)
15✔
3145
        if found {
27✔
3146
                // An entry will only be found if the closer has already been
12✔
3147
                // created for a non-pending channel or for a channel that had
12✔
3148
                // previously started the shutdown process but the connection
12✔
3149
                // was restarted.
12✔
3150
                return &chanCloser, nil
12✔
3151
        }
12✔
3152

3153
        // First, we'll ensure that we actually know of the target channel. If
3154
        // not, we'll ignore this message.
3155
        channel, ok := p.activeChannels.Load(chanID)
5✔
3156

5✔
3157
        // If the channel isn't in the map or the channel is nil, return
5✔
3158
        // ErrChannelNotFound as the channel is pending.
5✔
3159
        if !ok || channel == nil {
7✔
3160
                return nil, ErrChannelNotFound
2✔
3161
        }
2✔
3162

3163
        // We'll create a valid closing state machine in order to respond to
3164
        // the initiated cooperative channel closure. First, we set the
3165
        // delivery script that our funds will be paid out to. If an upfront
3166
        // shutdown script was set, we will use it. Otherwise, we get a fresh
3167
        // delivery script.
3168
        //
3169
        // TODO: Expose option to allow upfront shutdown script from watch-only
3170
        // accounts.
3171
        deliveryScript := channel.LocalUpfrontShutdownScript()
5✔
3172
        if len(deliveryScript) == 0 {
10✔
3173
                var err error
5✔
3174
                deliveryScript, err = p.genDeliveryScript()
5✔
3175
                if err != nil {
5✔
UNCOV
3176
                        p.log.Errorf("unable to gen delivery script: %v",
×
UNCOV
3177
                                err)
×
UNCOV
3178
                        return nil, fmt.Errorf("close addr unavailable")
×
UNCOV
3179
                }
×
3180
        }
3181

3182
        // In order to begin fee negotiations, we'll first compute our target
3183
        // ideal fee-per-kw.
3184
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
5✔
3185
                p.cfg.CoopCloseTargetConfs,
5✔
3186
        )
5✔
3187
        if err != nil {
5✔
3188
                p.log.Errorf("unable to query fee estimator: %v", err)
×
UNCOV
3189
                return nil, fmt.Errorf("unable to estimate fee")
×
UNCOV
3190
        }
×
3191

3192
        addr, err := p.addrWithInternalKey(deliveryScript)
5✔
3193
        if err != nil {
5✔
3194
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3195
        }
×
3196
        negotiateChanCloser, err := p.createChanCloser(
5✔
3197
                channel, addr, feePerKw, nil, lntypes.Remote,
5✔
3198
        )
5✔
3199
        if err != nil {
5✔
UNCOV
3200
                p.log.Errorf("unable to create chan closer: %v", err)
×
UNCOV
3201
                return nil, fmt.Errorf("unable to create chan closer")
×
UNCOV
3202
        }
×
3203

3204
        chanCloser = makeNegotiateCloser(negotiateChanCloser)
5✔
3205

5✔
3206
        p.activeChanCloses.Store(chanID, chanCloser)
5✔
3207

5✔
3208
        return &chanCloser, nil
5✔
3209
}
3210

3211
// filterChannelsToEnable filters a list of channels to be enabled upon start.
3212
// The filtered channels are active channels that's neither private nor
3213
// pending.
3214
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
2✔
3215
        var activePublicChans []wire.OutPoint
2✔
3216

2✔
3217
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
2✔
3218
                lnChan *lnwallet.LightningChannel) bool {
4✔
3219

2✔
3220
                // If the lnChan is nil, continue as this is a pending channel.
2✔
3221
                if lnChan == nil {
3✔
3222
                        return true
1✔
3223
                }
1✔
3224

3225
                dbChan := lnChan.State()
2✔
3226
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
2✔
3227
                if !isPublic || dbChan.IsPending {
2✔
UNCOV
3228
                        return true
×
UNCOV
3229
                }
×
3230

3231
                // We'll also skip any channels added during this peer's
3232
                // lifecycle since they haven't waited out the timeout. Their
3233
                // first announcement will be enabled, and the chan status
3234
                // manager will begin monitoring them passively since they exist
3235
                // in the database.
3236
                if _, ok := p.addedChannels.Load(chanID); ok {
3✔
3237
                        return true
1✔
3238
                }
1✔
3239

3240
                activePublicChans = append(
2✔
3241
                        activePublicChans, dbChan.FundingOutpoint,
2✔
3242
                )
2✔
3243

2✔
3244
                return true
2✔
3245
        })
3246

3247
        return activePublicChans
2✔
3248
}
3249

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

×
3257
        // retryEnable is a helper closure that sends an enable request and
×
3258
        // removes the channel from the map if it's matched.
×
3259
        retryEnable := func(chanPoint wire.OutPoint) error {
×
3260
                // If this is an active channel event, check whether it's in
×
3261
                // our targeted channels map.
×
UNCOV
3262
                _, found := activeChans[chanPoint]
×
UNCOV
3263

×
UNCOV
3264
                // If this channel is irrelevant, return nil so the loop can
×
UNCOV
3265
                // jump to next iteration.
×
UNCOV
3266
                if !found {
×
UNCOV
3267
                        return nil
×
UNCOV
3268
                }
×
3269

3270
                // Otherwise we've just received an active signal for a channel
3271
                // that's previously failed to be enabled, we send the request
3272
                // again.
3273
                //
3274
                // We only give the channel one more shot, so we delete it from
3275
                // our map first to keep it from being attempted again.
3276
                delete(activeChans, chanPoint)
×
UNCOV
3277

×
3278
                // Send the request.
×
UNCOV
3279
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
UNCOV
3280
                if err != nil {
×
3281
                        return fmt.Errorf("request enabling channel %v "+
×
3282
                                "failed: %w", chanPoint, err)
×
3283
                }
×
3284

3285
                return nil
×
3286
        }
3287

UNCOV
3288
        for {
×
3289
                // If activeChans is empty, we've done processing all the
×
UNCOV
3290
                // channels.
×
UNCOV
3291
                if len(activeChans) == 0 {
×
3292
                        p.log.Debug("Finished retry enabling channels")
×
3293
                        return
×
3294
                }
×
3295

3296
                select {
×
3297
                // A new event has been sent by the ChannelNotifier. We now
3298
                // check whether it's an active or inactive channel event.
3299
                case e := <-p.channelEventClient.Updates():
×
3300
                        // If this is an active channel event, try enable the
×
3301
                        // channel then jump to the next iteration.
×
3302
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
3303
                        if ok {
×
3304
                                chanPoint := *active.ChannelPoint
×
UNCOV
3305

×
3306
                                // If we received an error for this particular
×
UNCOV
3307
                                // channel, we log an error and won't quit as
×
UNCOV
3308
                                // we still want to retry other channels.
×
UNCOV
3309
                                if err := retryEnable(chanPoint); err != nil {
×
UNCOV
3310
                                        p.log.Errorf("Retry failed: %v", err)
×
3311
                                }
×
3312

3313
                                continue
×
3314
                        }
3315

3316
                        // Otherwise check for inactive link event, and jump to
3317
                        // next iteration if it's not.
3318
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3319
                        if !ok {
×
3320
                                continue
×
3321
                        }
3322

3323
                        // Found an inactive link event, if this is our
3324
                        // targeted channel, remove it from our map.
3325
                        chanPoint := *inactive.ChannelPoint
×
3326
                        _, found := activeChans[chanPoint]
×
UNCOV
3327
                        if !found {
×
3328
                                continue
×
3329
                        }
3330

UNCOV
3331
                        delete(activeChans, chanPoint)
×
UNCOV
3332
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
UNCOV
3333
                                "inactive link event", chanPoint)
×
3334

UNCOV
3335
                case <-p.cg.Done():
×
UNCOV
3336
                        p.log.Debugf("Peer shutdown during retry enabling")
×
UNCOV
3337
                        return
×
3338
                }
3339
        }
3340
}
3341

3342
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3343
// a suitable script to close out to. This may be nil if neither script is
3344
// set. If both scripts are set, this function will error if they do not match.
3345
func chooseDeliveryScript(upfront, requested lnwire.DeliveryAddress,
3346
        genDeliveryScript func() ([]byte, error),
3347
) (lnwire.DeliveryAddress, error) {
14✔
3348

14✔
3349
        switch {
14✔
3350
        // If no script was provided, then we'll generate a new delivery script.
3351
        case len(upfront) == 0 && len(requested) == 0:
6✔
3352
                return genDeliveryScript()
6✔
3353

3354
        // If no upfront shutdown script was provided, return the user
3355
        // requested address (which may be nil).
3356
        case len(upfront) == 0:
4✔
3357
                return requested, nil
4✔
3358

3359
        // If an upfront shutdown script was provided, and the user did not
3360
        // request a custom shutdown script, return the upfront address.
3361
        case len(requested) == 0:
4✔
3362
                return upfront, nil
4✔
3363

3364
        // If both an upfront shutdown script and a custom close script were
3365
        // provided, error if the user provided shutdown script does not match
3366
        // the upfront shutdown script (because closing out to a different
3367
        // script would violate upfront shutdown).
3368
        case !bytes.Equal(upfront, requested):
2✔
3369
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
3370

3371
        // The user requested script matches the upfront shutdown script, so we
3372
        // can return it without error.
3373
        default:
2✔
3374
                return upfront, nil
2✔
3375
        }
3376
}
3377

3378
// restartCoopClose checks whether we need to restart the cooperative close
3379
// process for a given channel.
3380
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3381
        *lnwire.Shutdown, error) {
2✔
3382

2✔
3383
        isTaprootChan := lnChan.ChanType().IsTaproot()
2✔
3384

2✔
3385
        // If this channel has status ChanStatusCoopBroadcasted and does not
2✔
3386
        // have a closing transaction, then the cooperative close process was
2✔
3387
        // started but never finished. We'll re-create the chanCloser state
2✔
3388
        // machine and resend Shutdown. BOLT#2 requires that we retransmit
2✔
3389
        // Shutdown exactly, but doing so would mean persisting the RPC
2✔
3390
        // provided close script. Instead use the LocalUpfrontShutdownScript
2✔
3391
        // or generate a script.
2✔
3392
        c := lnChan.State()
2✔
3393
        _, err := c.BroadcastedCooperative()
2✔
3394
        if err != nil && err != channeldb.ErrNoCloseTx {
2✔
3395
                // An error other than ErrNoCloseTx was encountered.
×
UNCOV
3396
                return nil, err
×
3397
        } else if err == nil && !p.rbfCoopCloseAllowed() {
2✔
UNCOV
3398
                // This is a channel that doesn't support RBF coop close, and it
×
UNCOV
3399
                // already had a coop close txn broadcast. As a result, we can
×
UNCOV
3400
                // just exit here as all we can do is wait for it to confirm.
×
UNCOV
3401
                return nil, nil
×
UNCOV
3402
        }
×
3403

3404
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
2✔
3405

2✔
3406
        var deliveryScript []byte
2✔
3407

2✔
3408
        shutdownInfo, err := c.ShutdownInfo()
2✔
3409
        switch {
2✔
3410
        // We have previously stored the delivery script that we need to use
3411
        // in the shutdown message. Re-use this script.
3412
        case err == nil:
2✔
3413
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
4✔
3414
                        deliveryScript = info.DeliveryScript.Val
2✔
3415
                })
2✔
3416

3417
        // An error other than ErrNoShutdownInfo was returned
3418
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3419
                return nil, err
×
3420

3421
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3422
                deliveryScript = c.LocalShutdownScript
×
3423
                if len(deliveryScript) == 0 {
×
3424
                        var err error
×
UNCOV
3425
                        deliveryScript, err = p.genDeliveryScript()
×
UNCOV
3426
                        if err != nil {
×
UNCOV
3427
                                p.log.Errorf("unable to gen delivery script: "+
×
UNCOV
3428
                                        "%v", err)
×
UNCOV
3429

×
UNCOV
3430
                                return nil, fmt.Errorf("close addr unavailable")
×
UNCOV
3431
                        }
×
3432
                }
3433
        }
3434

3435
        // If the new RBF co-op close is negotiated, then we'll init and start
3436
        // that state machine, skipping the steps for the negotiate machine
3437
        // below. We don't support this close type for taproot channels though.
3438
        if p.rbfCoopCloseAllowed() && !isTaprootChan {
4✔
3439
                _, err := p.initRbfChanCloser(lnChan)
2✔
3440
                if err != nil {
2✔
UNCOV
3441
                        return nil, fmt.Errorf("unable to init rbf chan "+
×
UNCOV
3442
                                "closer during restart: %w", err)
×
UNCOV
3443
                }
×
3444

3445
                shutdownDesc := fn.MapOption(
2✔
3446
                        newRestartShutdownInit,
2✔
3447
                )(shutdownInfo)
2✔
3448

2✔
3449
                err = p.startRbfChanCloser(
2✔
3450
                        fn.FlattenOption(shutdownDesc), lnChan.ChannelPoint(),
2✔
3451
                )
2✔
3452

2✔
3453
                return nil, err
2✔
3454
        }
3455

3456
        // Compute an ideal fee.
UNCOV
3457
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
UNCOV
3458
                p.cfg.CoopCloseTargetConfs,
×
UNCOV
3459
        )
×
3460
        if err != nil {
×
3461
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3462
                return nil, fmt.Errorf("unable to estimate fee")
×
3463
        }
×
3464

3465
        // Determine whether we or the peer are the initiator of the coop
3466
        // close attempt by looking at the channel's status.
3467
        closingParty := lntypes.Remote
×
3468
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3469
                closingParty = lntypes.Local
×
3470
        }
×
3471

3472
        addr, err := p.addrWithInternalKey(deliveryScript)
×
3473
        if err != nil {
×
3474
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3475
        }
×
UNCOV
3476
        chanCloser, err := p.createChanCloser(
×
3477
                lnChan, addr, feePerKw, nil, closingParty,
×
3478
        )
×
3479
        if err != nil {
×
3480
                p.log.Errorf("unable to create chan closer: %v", err)
×
3481
                return nil, fmt.Errorf("unable to create chan closer")
×
3482
        }
×
3483

3484
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
×
3485

×
UNCOV
3486
        // Create the Shutdown message.
×
3487
        shutdownMsg, err := chanCloser.ShutdownChan()
×
UNCOV
3488
        if err != nil {
×
UNCOV
3489
                p.log.Errorf("unable to create shutdown message: %v", err)
×
UNCOV
3490
                p.activeChanCloses.Delete(chanID)
×
UNCOV
3491
                return nil, err
×
UNCOV
3492
        }
×
3493

UNCOV
3494
        return shutdownMsg, nil
×
3495
}
3496

3497
// createChanCloser constructs a ChanCloser from the passed parameters and is
3498
// used to de-duplicate code.
3499
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3500
        deliveryScript *chancloser.DeliveryAddrWithKey,
3501
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3502
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
11✔
3503

11✔
3504
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
11✔
3505
        if err != nil {
11✔
UNCOV
3506
                p.log.Errorf("unable to obtain best block: %v", err)
×
UNCOV
3507
                return nil, fmt.Errorf("cannot obtain best block")
×
UNCOV
3508
        }
×
3509

3510
        // The req will only be set if we initiated the co-op closing flow.
3511
        var maxFee chainfee.SatPerKWeight
11✔
3512
        if req != nil {
19✔
3513
                maxFee = req.MaxFee
8✔
3514
        }
8✔
3515

3516
        chanCloser := chancloser.NewChanCloser(
11✔
3517
                chancloser.ChanCloseCfg{
11✔
3518
                        Channel:      channel,
11✔
3519
                        MusigSession: NewMusigChanCloser(channel),
11✔
3520
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
11✔
3521
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
11✔
3522
                        AuxCloser:    p.cfg.AuxChanCloser,
11✔
3523
                        DisableChannel: func(op wire.OutPoint) error {
22✔
3524
                                return p.cfg.ChanStatusMgr.RequestDisable(
11✔
3525
                                        op, false,
11✔
3526
                                )
11✔
3527
                        },
11✔
3528
                        MaxFee: maxFee,
UNCOV
3529
                        Disconnect: func() error {
×
UNCOV
3530
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
UNCOV
3531
                        },
×
3532
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3533
                },
3534
                *deliveryScript,
3535
                fee,
3536
                uint32(startingHeight),
3537
                req,
3538
                closer,
3539
        )
3540

3541
        return chanCloser, nil
11✔
3542
}
3543

3544
// initNegotiateChanCloser initializes the channel closer for a channel that is
3545
// using the original "negotiation" based protocol. This path is used when
3546
// we're the one initiating the channel close.
3547
//
3548
// TODO(roasbeef): can make a MsgEndpoint for existing handling logic to
3549
// further abstract.
3550
func (p *Brontide) initNegotiateChanCloser(req *htlcswitch.ChanClose,
3551
        channel *lnwallet.LightningChannel) error {
9✔
3552

9✔
3553
        // First, we'll choose a delivery address that we'll use to send the
9✔
3554
        // funds to in the case of a successful negotiation.
9✔
3555

9✔
3556
        // An upfront shutdown and user provided script are both optional, but
9✔
3557
        // must be equal if both set  (because we cannot serve a request to
9✔
3558
        // close out to a script which violates upfront shutdown). Get the
9✔
3559
        // appropriate address to close out to (which may be nil if neither are
9✔
3560
        // set) and error if they are both set and do not match.
9✔
3561
        deliveryScript, err := chooseDeliveryScript(
9✔
3562
                channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
9✔
3563
                p.genDeliveryScript,
9✔
3564
        )
9✔
3565
        if err != nil {
10✔
3566
                return fmt.Errorf("cannot close channel %v: %w",
1✔
3567
                        req.ChanPoint, err)
1✔
3568
        }
1✔
3569

3570
        addr, err := p.addrWithInternalKey(deliveryScript)
8✔
3571
        if err != nil {
8✔
UNCOV
3572
                return fmt.Errorf("unable to parse addr for channel "+
×
3573
                        "%v: %w", req.ChanPoint, err)
×
3574
        }
×
3575

3576
        chanCloser, err := p.createChanCloser(
8✔
3577
                channel, addr, req.TargetFeePerKw, req, lntypes.Local,
8✔
3578
        )
8✔
3579
        if err != nil {
8✔
UNCOV
3580
                return fmt.Errorf("unable to make chan closer: %w", err)
×
UNCOV
3581
        }
×
3582

3583
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
8✔
3584
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
8✔
3585

8✔
3586
        // Finally, we'll initiate the channel shutdown within the
8✔
3587
        // chanCloser, and send the shutdown message to the remote
8✔
3588
        // party to kick things off.
8✔
3589
        shutdownMsg, err := chanCloser.ShutdownChan()
8✔
3590
        if err != nil {
8✔
3591
                // As we were unable to shutdown the channel, we'll return it
×
UNCOV
3592
                // back to its normal state.
×
UNCOV
3593
                defer channel.ResetState()
×
UNCOV
3594

×
3595
                p.activeChanCloses.Delete(chanID)
×
3596

×
3597
                return fmt.Errorf("unable to shutdown channel: %w", err)
×
3598
        }
×
3599

3600
        link := p.fetchLinkFromKeyAndCid(chanID)
8✔
3601
        if link == nil {
8✔
3602
                // If the link is nil then it means it was already removed from
×
3603
                // the switch or it never existed in the first place. The
×
UNCOV
3604
                // latter case is handled at the beginning of this function, so
×
UNCOV
3605
                // in the case where it has already been removed, we can skip
×
3606
                // adding the commit hook to queue a Shutdown message.
×
3607
                p.log.Warnf("link not found during attempted closure: "+
×
3608
                        "%v", chanID)
×
UNCOV
3609
                return nil
×
UNCOV
3610
        }
×
3611

3612
        if !link.DisableAdds(htlcswitch.Outgoing) {
8✔
UNCOV
3613
                p.log.Warnf("Outgoing link adds already "+
×
UNCOV
3614
                        "disabled: %v", link.ChanID())
×
UNCOV
3615
        }
×
3616

3617
        link.OnCommitOnce(htlcswitch.Outgoing, func() {
16✔
3618
                p.queueMsg(shutdownMsg, nil)
8✔
3619
        })
8✔
3620

3621
        return nil
8✔
3622
}
3623

3624
// ChooseAddr returns the provided address if it is non-zero length, otherwise
3625
// None.
3626
func ChooseAddr(addr lnwire.DeliveryAddress) fn.Option[lnwire.DeliveryAddress] {
2✔
3627
        if len(addr) == 0 {
4✔
3628
                return fn.None[lnwire.DeliveryAddress]()
2✔
3629
        }
2✔
3630

3631
        return fn.Some(addr)
2✔
3632
}
3633

3634
// observeRbfCloseUpdates observes the channel for any updates that may
3635
// indicate that a new txid has been broadcasted, or the channel fully closed
3636
// on chain.
3637
func (p *Brontide) observeRbfCloseUpdates(chanCloser *chancloser.RbfChanCloser,
3638
        closeReq *htlcswitch.ChanClose,
3639
        coopCloseStates chancloser.RbfStateSub) {
2✔
3640

2✔
3641
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
2✔
3642
        defer chanCloser.RemoveStateSub(coopCloseStates)
2✔
3643

2✔
3644
        var (
2✔
3645
                lastTxids    lntypes.Dual[chainhash.Hash]
2✔
3646
                lastFeeRates lntypes.Dual[chainfee.SatPerVByte]
2✔
3647
        )
2✔
3648

2✔
3649
        maybeNotifyTxBroadcast := func(state chancloser.AsymmetricPeerState,
2✔
3650
                party lntypes.ChannelParty) {
4✔
3651

2✔
3652
                // First, check to see if we have an error to report to the
2✔
3653
                // caller. If so, then we''ll return that error and exit, as the
2✔
3654
                // stream will exit as well.
2✔
3655
                if closeErr, ok := state.(*chancloser.CloseErr); ok {
4✔
3656
                        // We hit an error during the last state transition, so
2✔
3657
                        // we'll extract the error then send it to the
2✔
3658
                        // user.
2✔
3659
                        err := closeErr.Err()
2✔
3660

2✔
3661
                        peerLog.Warnf("ChannelPoint(%v): encountered close "+
2✔
3662
                                "err: %v", closeReq.ChanPoint, err)
2✔
3663

2✔
3664
                        select {
2✔
3665
                        case closeReq.Err <- err:
2✔
UNCOV
3666
                        case <-closeReq.Ctx.Done():
×
UNCOV
3667
                        case <-p.cg.Done():
×
3668
                        }
3669

3670
                        return
2✔
3671
                }
3672

3673
                closePending, ok := state.(*chancloser.ClosePending)
2✔
3674

2✔
3675
                // If this isn't the close pending state, we aren't at the
2✔
3676
                // terminal state yet.
2✔
3677
                if !ok {
4✔
3678
                        return
2✔
3679
                }
2✔
3680

3681
                // Only notify if the fee rate is greater.
3682
                newFeeRate := closePending.FeeRate
2✔
3683
                lastFeeRate := lastFeeRates.GetForParty(party)
2✔
3684
                if newFeeRate <= lastFeeRate {
4✔
3685
                        peerLog.Debugf("ChannelPoint(%v): remote party made "+
2✔
3686
                                "update for fee rate %v, but we already have "+
2✔
3687
                                "a higher fee rate of %v", closeReq.ChanPoint,
2✔
3688
                                newFeeRate, lastFeeRate)
2✔
3689

2✔
3690
                        return
2✔
3691
                }
2✔
3692

3693
                feeRate := closePending.FeeRate
2✔
3694
                lastFeeRates.SetForParty(party, feeRate)
2✔
3695

2✔
3696
                // At this point, we'll have a txid that we can use to notify
2✔
3697
                // the client, but only if it's different from the last one we
2✔
3698
                // sent. If the user attempted to bump, but was rejected due to
2✔
3699
                // RBF, then we'll send a redundant update.
2✔
3700
                closingTxid := closePending.CloseTx.TxHash()
2✔
3701
                lastTxid := lastTxids.GetForParty(party)
2✔
3702
                if closeReq != nil && closingTxid != lastTxid {
4✔
3703
                        select {
2✔
3704
                        case closeReq.Updates <- &PendingUpdate{
3705
                                Txid:        closingTxid[:],
3706
                                FeePerVbyte: fn.Some(closePending.FeeRate),
3707
                                IsLocalCloseTx: fn.Some(
3708
                                        party == lntypes.Local,
3709
                                ),
3710
                        }:
2✔
3711

UNCOV
3712
                        case <-closeReq.Ctx.Done():
×
UNCOV
3713
                                return
×
3714

UNCOV
3715
                        case <-p.cg.Done():
×
UNCOV
3716
                                return
×
3717
                        }
3718
                }
3719

3720
                lastTxids.SetForParty(party, closingTxid)
2✔
3721
        }
3722

3723
        peerLog.Infof("Observing RBF close updates for channel %v",
2✔
3724
                closeReq.ChanPoint)
2✔
3725

2✔
3726
        // We'll consume each new incoming state to send out the appropriate
2✔
3727
        // RPC update.
2✔
3728
        for {
4✔
3729
                select {
2✔
3730
                case newState := <-newStateChan:
2✔
3731

2✔
3732
                        switch closeState := newState.(type) {
2✔
3733
                        // Once we've reached the state of pending close, we
3734
                        // have a txid that we broadcasted.
3735
                        case *chancloser.ClosingNegotiation:
2✔
3736
                                peerState := closeState.PeerState
2✔
3737

2✔
3738
                                // Each side may have gained a new co-op close
2✔
3739
                                // tx, so we'll examine both to see if they've
2✔
3740
                                // changed.
2✔
3741
                                maybeNotifyTxBroadcast(
2✔
3742
                                        peerState.GetForParty(lntypes.Local),
2✔
3743
                                        lntypes.Local,
2✔
3744
                                )
2✔
3745
                                maybeNotifyTxBroadcast(
2✔
3746
                                        peerState.GetForParty(lntypes.Remote),
2✔
3747
                                        lntypes.Remote,
2✔
3748
                                )
2✔
3749

3750
                        // Otherwise, if we're transition to CloseFin, then we
3751
                        // know that we're done.
3752
                        case *chancloser.CloseFin:
2✔
3753
                                // To clean up, we'll remove the chan closer
2✔
3754
                                // from the active map, and send the final
2✔
3755
                                // update to the client.
2✔
3756
                                closingTxid := closeState.ConfirmedTx.TxHash()
2✔
3757
                                if closeReq != nil {
4✔
3758
                                        closeReq.Updates <- &ChannelCloseUpdate{
2✔
3759
                                                ClosingTxid: closingTxid[:],
2✔
3760
                                                Success:     true,
2✔
3761
                                        }
2✔
3762
                                }
2✔
3763
                                chanID := lnwire.NewChanIDFromOutPoint(
2✔
3764
                                        *closeReq.ChanPoint,
2✔
3765
                                )
2✔
3766
                                p.activeChanCloses.Delete(chanID)
2✔
3767

2✔
3768
                                return
2✔
3769
                        }
3770

3771
                case <-closeReq.Ctx.Done():
2✔
3772
                        return
2✔
3773

3774
                case <-p.cg.Done():
2✔
3775
                        return
2✔
3776
                }
3777
        }
3778
}
3779

3780
// chanErrorReporter is a simple implementation of the
3781
// chancloser.ErrorReporter. This is bound to a single channel by the channel
3782
// ID.
3783
type chanErrorReporter struct {
3784
        chanID lnwire.ChannelID
3785
        peer   *Brontide
3786
}
3787

3788
// newChanErrorReporter creates a new instance of the chanErrorReporter.
3789
func newChanErrorReporter(chanID lnwire.ChannelID,
3790
        peer *Brontide) *chanErrorReporter {
2✔
3791

2✔
3792
        return &chanErrorReporter{
2✔
3793
                chanID: chanID,
2✔
3794
                peer:   peer,
2✔
3795
        }
2✔
3796
}
2✔
3797

3798
// ReportError is a method that's used to report an error that occurred during
3799
// state machine execution. This is used by the RBF close state machine to
3800
// terminate the state machine and send an error to the remote peer.
3801
//
3802
// This is a part of the chancloser.ErrorReporter interface.
3803
func (c *chanErrorReporter) ReportError(chanErr error) {
×
3804
        c.peer.log.Errorf("coop close error for channel %v: %v",
×
3805
                c.chanID, chanErr)
×
UNCOV
3806

×
3807
        var errMsg []byte
×
3808
        if errors.Is(chanErr, chancloser.ErrInvalidStateTransition) {
×
3809
                errMsg = []byte("unexpected protocol message")
×
3810
        } else {
×
3811
                errMsg = []byte(chanErr.Error())
×
3812
        }
×
3813

3814
        err := c.peer.SendMessageLazy(false, &lnwire.Error{
×
UNCOV
3815
                ChanID: c.chanID,
×
UNCOV
3816
                Data:   errMsg,
×
UNCOV
3817
        })
×
UNCOV
3818
        if err != nil {
×
3819
                c.peer.log.Warnf("unable to send error message to peer: %v",
×
3820
                        err)
×
3821
        }
×
3822

3823
        // After we send the error message to the peer, we'll re-initialize the
3824
        // coop close state machine as they may send a shutdown message to
3825
        // retry the coop close.
3826
        lnChan, ok := c.peer.activeChannels.Load(c.chanID)
×
3827
        if !ok {
×
3828
                return
×
3829
        }
×
3830

UNCOV
3831
        if lnChan == nil {
×
3832
                c.peer.log.Debugf("channel %v is pending, not "+
×
3833
                        "re-initializing coop close state machine",
×
3834
                        c.chanID)
×
3835

×
3836
                return
×
3837
        }
×
3838

UNCOV
3839
        if _, err := c.peer.initRbfChanCloser(lnChan); err != nil {
×
UNCOV
3840
                c.peer.activeChanCloses.Delete(c.chanID)
×
UNCOV
3841

×
UNCOV
3842
                c.peer.log.Errorf("unable to init RBF chan closer after "+
×
UNCOV
3843
                        "error case: %v", err)
×
UNCOV
3844
        }
×
3845
}
3846

3847
// chanFlushEventSentinel is used to send the RBF coop close state machine the
3848
// channel flushed event. We'll wait until the state machine enters the
3849
// ChannelFlushing state, then request the link to send the event once flushed.
3850
//
3851
// NOTE: This MUST be run as a goroutine.
3852
func (p *Brontide) chanFlushEventSentinel(chanCloser *chancloser.RbfChanCloser,
3853
        link htlcswitch.ChannelUpdateHandler,
3854
        channel *lnwallet.LightningChannel) {
2✔
3855

2✔
3856
        defer p.cg.WgDone()
2✔
3857

2✔
3858
        // If there's no link, then the channel has already been flushed, so we
2✔
3859
        // don't need to continue.
2✔
3860
        if link == nil {
4✔
3861
                return
2✔
3862
        }
2✔
3863

3864
        coopCloseStates := chanCloser.RegisterStateEvents()
2✔
3865
        defer chanCloser.RemoveStateSub(coopCloseStates)
2✔
3866

2✔
3867
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
2✔
3868

2✔
3869
        sendChanFlushed := func() {
4✔
3870
                chanState := channel.StateSnapshot()
2✔
3871

2✔
3872
                peerLog.Infof("ChannelPoint(%v) has been flushed for co-op "+
2✔
3873
                        "close, sending event to chan closer",
2✔
3874
                        channel.ChannelPoint())
2✔
3875

2✔
3876
                chanBalances := chancloser.ShutdownBalances{
2✔
3877
                        LocalBalance:  chanState.LocalBalance,
2✔
3878
                        RemoteBalance: chanState.RemoteBalance,
2✔
3879
                }
2✔
3880
                ctx := context.Background()
2✔
3881
                chanCloser.SendEvent(ctx, &chancloser.ChannelFlushed{
2✔
3882
                        ShutdownBalances: chanBalances,
2✔
3883
                        FreshFlush:       true,
2✔
3884
                })
2✔
3885
        }
2✔
3886

3887
        // We'll wait until the channel enters the ChannelFlushing state. We
3888
        // exit after a success loop. As after the first RBF iteration, the
3889
        // channel will always be flushed.
3890
        for {
4✔
3891
                select {
2✔
3892
                case newState, ok := <-newStateChan:
2✔
3893
                        if !ok {
2✔
UNCOV
3894
                                return
×
UNCOV
3895
                        }
×
3896

3897
                        if _, ok := newState.(*chancloser.ChannelFlushing); ok {
4✔
3898
                                peerLog.Infof("ChannelPoint(%v): rbf coop "+
2✔
3899
                                        "close is awaiting a flushed state, "+
2✔
3900
                                        "registering with link..., ",
2✔
3901
                                        channel.ChannelPoint())
2✔
3902

2✔
3903
                                // Request the link to send the event once the
2✔
3904
                                // channel is flushed. We only need this event
2✔
3905
                                // sent once, so we can exit now.
2✔
3906
                                link.OnFlushedOnce(sendChanFlushed)
2✔
3907

2✔
3908
                                return
2✔
3909
                        }
2✔
3910

3911
                case <-p.cg.Done():
2✔
3912
                        return
2✔
3913
                }
3914
        }
3915
}
3916

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

2✔
3923
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
2✔
3924

2✔
3925
        link := p.fetchLinkFromKeyAndCid(chanID)
2✔
3926

2✔
3927
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
2✔
3928
        if err != nil {
2✔
3929
                return nil, fmt.Errorf("cannot obtain best block: %w", err)
×
3930
        }
×
3931

3932
        defaultFeePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
2✔
3933
                p.cfg.CoopCloseTargetConfs,
2✔
3934
        )
2✔
3935
        if err != nil {
2✔
UNCOV
3936
                return nil, fmt.Errorf("unable to estimate fee: %w", err)
×
UNCOV
3937
        }
×
3938

3939
        thawHeight, err := channel.AbsoluteThawHeight()
2✔
3940
        if err != nil {
2✔
UNCOV
3941
                return nil, fmt.Errorf("unable to get thaw height: %w", err)
×
UNCOV
3942
        }
×
3943

3944
        peerPub := *p.IdentityKey()
2✔
3945

2✔
3946
        msgMapper := chancloser.NewRbfMsgMapper(
2✔
3947
                uint32(startingHeight), chanID, peerPub,
2✔
3948
        )
2✔
3949

2✔
3950
        initialState := chancloser.ChannelActive{}
2✔
3951

2✔
3952
        scid := channel.ZeroConfRealScid().UnwrapOr(
2✔
3953
                channel.ShortChanID(),
2✔
3954
        )
2✔
3955

2✔
3956
        env := chancloser.Environment{
2✔
3957
                ChainParams:    p.cfg.Wallet.Cfg.NetParams,
2✔
3958
                ChanPeer:       peerPub,
2✔
3959
                ChanPoint:      channel.ChannelPoint(),
2✔
3960
                ChanID:         chanID,
2✔
3961
                Scid:           scid,
2✔
3962
                ChanType:       channel.ChanType(),
2✔
3963
                DefaultFeeRate: defaultFeePerKw.FeePerVByte(),
2✔
3964
                ThawHeight:     fn.Some(thawHeight),
2✔
3965
                RemoteUpfrontShutdown: ChooseAddr(
2✔
3966
                        channel.RemoteUpfrontShutdownScript(),
2✔
3967
                ),
2✔
3968
                LocalUpfrontShutdown: ChooseAddr(
2✔
3969
                        channel.LocalUpfrontShutdownScript(),
2✔
3970
                ),
2✔
3971
                NewDeliveryScript: func() (lnwire.DeliveryAddress, error) {
4✔
3972
                        return p.genDeliveryScript()
2✔
3973
                },
2✔
3974
                FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
3975
                CloseSigner:  channel,
3976
                ChanObserver: newChanObserver(
3977
                        channel, link, p.cfg.ChanStatusMgr,
3978
                ),
3979
        }
3980

3981
        spendEvent := protofsm.RegisterSpend[chancloser.ProtocolEvent]{
2✔
3982
                OutPoint:   channel.ChannelPoint(),
2✔
3983
                PkScript:   channel.FundingTxOut().PkScript,
2✔
3984
                HeightHint: channel.DeriveHeightHint(),
2✔
3985
                PostSpendEvent: fn.Some[chancloser.RbfSpendMapper](
2✔
3986
                        chancloser.SpendMapper,
2✔
3987
                ),
2✔
3988
        }
2✔
3989

2✔
3990
        daemonAdapters := NewLndDaemonAdapters(LndAdapterCfg{
2✔
3991
                MsgSender:     newPeerMsgSender(peerPub, p),
2✔
3992
                TxBroadcaster: p.cfg.Wallet,
2✔
3993
                ChainNotifier: p.cfg.ChainNotifier,
2✔
3994
        })
2✔
3995

2✔
3996
        protoCfg := chancloser.RbfChanCloserCfg{
2✔
3997
                Daemon:        daemonAdapters,
2✔
3998
                InitialState:  &initialState,
2✔
3999
                Env:           &env,
2✔
4000
                InitEvent:     fn.Some[protofsm.DaemonEvent](&spendEvent),
2✔
4001
                ErrorReporter: newChanErrorReporter(chanID, p),
2✔
4002
                MsgMapper: fn.Some[protofsm.MsgMapper[chancloser.ProtocolEvent]]( //nolint:ll
2✔
4003
                        msgMapper,
2✔
4004
                ),
2✔
4005
        }
2✔
4006

2✔
4007
        ctx := context.Background()
2✔
4008
        chanCloser := protofsm.NewStateMachine(protoCfg)
2✔
4009
        chanCloser.Start(ctx)
2✔
4010

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

2✔
4016
                return r.RegisterEndpoint(&chanCloser)
2✔
4017
        })
2✔
4018
        if err != nil {
2✔
UNCOV
4019
                chanCloser.Stop()
×
UNCOV
4020

×
UNCOV
4021
                return nil, fmt.Errorf("unable to register endpoint for co-op "+
×
UNCOV
4022
                        "close: %w", err)
×
UNCOV
4023
        }
×
4024

4025
        p.activeChanCloses.Store(chanID, makeRbfCloser(&chanCloser))
2✔
4026

2✔
4027
        // Now that we've created the rbf closer state machine, we'll launch a
2✔
4028
        // new goroutine to eventually send in the ChannelFlushed event once
2✔
4029
        // needed.
2✔
4030
        p.cg.WgAdd(1)
2✔
4031
        go p.chanFlushEventSentinel(&chanCloser, link, channel)
2✔
4032

2✔
4033
        return &chanCloser, nil
2✔
4034
}
4035

4036
// shutdownInit describes the two ways we can initiate a new shutdown. Either we
4037
// got an RPC request to do so (left), or we sent a shutdown message to the
4038
// party (for w/e reason), but crashed before the close was complete.
4039
//
4040
//nolint:ll
4041
type shutdownInit = fn.Option[fn.Either[*htlcswitch.ChanClose, channeldb.ShutdownInfo]]
4042

4043
// shutdownStartFeeRate returns the fee rate that should be used for the
4044
// shutdown.  This returns a doubly wrapped option as the shutdown info might
4045
// be none, and the fee rate is only defined for the user initiated shutdown.
4046
func shutdownStartFeeRate(s shutdownInit) fn.Option[chainfee.SatPerKWeight] {
2✔
4047
        feeRateOpt := fn.MapOption(func(init fn.Either[*htlcswitch.ChanClose,
2✔
4048
                channeldb.ShutdownInfo]) fn.Option[chainfee.SatPerKWeight] {
4✔
4049

2✔
4050
                var feeRate fn.Option[chainfee.SatPerKWeight]
2✔
4051
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
4✔
4052
                        feeRate = fn.Some(req.TargetFeePerKw)
2✔
4053
                })
2✔
4054

4055
                return feeRate
2✔
4056
        })(s)
4057

4058
        return fn.FlattenOption(feeRateOpt)
2✔
4059
}
4060

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

2✔
4068
                var addr fn.Option[lnwire.DeliveryAddress]
2✔
4069
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
4✔
4070
                        if len(req.DeliveryScript) != 0 {
4✔
4071
                                addr = fn.Some(req.DeliveryScript)
2✔
4072
                        }
2✔
4073
                })
4074
                init.WhenRight(func(info channeldb.ShutdownInfo) {
4✔
4075
                        addr = fn.Some(info.DeliveryScript.Val)
2✔
4076
                })
2✔
4077

4078
                return addr
2✔
4079
        })(s)
4080

4081
        return fn.FlattenOption(addrOpt)
2✔
4082
}
4083

4084
// whenRPCShutdown registers a callback to be executed when the shutdown init
4085
// type is and RPC request.
4086
func whenRPCShutdown(s shutdownInit, f func(r *htlcswitch.ChanClose)) {
2✔
4087
        s.WhenSome(func(init fn.Either[*htlcswitch.ChanClose,
2✔
4088
                channeldb.ShutdownInfo]) {
4✔
4089

2✔
4090
                init.WhenLeft(f)
2✔
4091
        })
2✔
4092
}
4093

4094
// newRestartShutdownInit creates a new shutdownInit for the case where we need
4095
// to restart the shutdown flow after a restart.
4096
func newRestartShutdownInit(info channeldb.ShutdownInfo) shutdownInit {
2✔
4097
        return fn.Some(fn.NewRight[*htlcswitch.ChanClose](info))
2✔
4098
}
2✔
4099

4100
// newRPCShutdownInit creates a new shutdownInit for the case where we
4101
// initiated the shutdown via an RPC client.
4102
func newRPCShutdownInit(req *htlcswitch.ChanClose) shutdownInit {
2✔
4103
        return fn.Some(
2✔
4104
                fn.NewLeft[*htlcswitch.ChanClose, channeldb.ShutdownInfo](req),
2✔
4105
        )
2✔
4106
}
2✔
4107

4108
// waitUntilRbfCoastClear waits until the RBF co-op close state machine has
4109
// advanced to a terminal state before attempting another fee bump.
4110
func waitUntilRbfCoastClear(ctx context.Context,
4111
        rbfCloser *chancloser.RbfChanCloser) error {
2✔
4112

2✔
4113
        coopCloseStates := rbfCloser.RegisterStateEvents()
2✔
4114
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
2✔
4115
        defer rbfCloser.RemoveStateSub(coopCloseStates)
2✔
4116

2✔
4117
        isTerminalState := func(newState chancloser.RbfState) bool {
4✔
4118
                // If we're not in the negotiation sub-state, then we aren't at
2✔
4119
                // the terminal state yet.
2✔
4120
                state, ok := newState.(*chancloser.ClosingNegotiation)
2✔
4121
                if !ok {
2✔
UNCOV
4122
                        return false
×
UNCOV
4123
                }
×
4124

4125
                localState := state.PeerState.GetForParty(lntypes.Local)
2✔
4126

2✔
4127
                // If this isn't the close pending state, we aren't at the
2✔
4128
                // terminal state yet.
2✔
4129
                _, ok = localState.(*chancloser.ClosePending)
2✔
4130

2✔
4131
                return ok
2✔
4132
        }
4133

4134
        // Before we enter the subscription loop below, check to see if we're
4135
        // already in the terminal state.
4136
        rbfState, err := rbfCloser.CurrentState()
2✔
4137
        if err != nil {
2✔
4138
                return err
×
4139
        }
×
4140
        if isTerminalState(rbfState) {
4✔
4141
                return nil
2✔
4142
        }
2✔
4143

4144
        peerLog.Debugf("Waiting for RBF iteration to complete...")
×
UNCOV
4145

×
4146
        for {
×
4147
                select {
×
UNCOV
4148
                case newState := <-newStateChan:
×
UNCOV
4149
                        if isTerminalState(newState) {
×
UNCOV
4150
                                return nil
×
UNCOV
4151
                        }
×
4152

UNCOV
4153
                case <-ctx.Done():
×
UNCOV
4154
                        return fmt.Errorf("context canceled")
×
4155
                }
4156
        }
4157
}
4158

4159
// startRbfChanCloser kicks off the co-op close process using the new RBF based
4160
// co-op close protocol. This is called when we're the one that's initiating
4161
// the cooperative channel close.
4162
//
4163
// TODO(roasbeef): just accept the two shutdown pointer params instead??
4164
func (p *Brontide) startRbfChanCloser(shutdown shutdownInit,
4165
        chanPoint wire.OutPoint) error {
2✔
4166

2✔
4167
        // Unlike the old negotiate chan closer, we'll always create the RBF
2✔
4168
        // chan closer on startup, so we can skip init here.
2✔
4169
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
4170
        chanCloser, found := p.activeChanCloses.Load(chanID)
2✔
4171
        if !found {
2✔
UNCOV
4172
                return fmt.Errorf("rbf chan closer not found for channel %v",
×
UNCOV
4173
                        chanPoint)
×
UNCOV
4174
        }
×
4175

4176
        defaultFeePerKw, err := shutdownStartFeeRate(
2✔
4177
                shutdown,
2✔
4178
        ).UnwrapOrFuncErr(func() (chainfee.SatPerKWeight, error) {
4✔
4179
                return p.cfg.FeeEstimator.EstimateFeePerKW(
2✔
4180
                        p.cfg.CoopCloseTargetConfs,
2✔
4181
                )
2✔
4182
        })
2✔
4183
        if err != nil {
2✔
UNCOV
4184
                return fmt.Errorf("unable to estimate fee: %w", err)
×
UNCOV
4185
        }
×
4186

4187
        chanCloser.WhenRight(func(rbfCloser *chancloser.RbfChanCloser) {
4✔
4188
                peerLog.Infof("ChannelPoint(%v): rbf-coop close requested, "+
2✔
4189
                        "sending shutdown", chanPoint)
2✔
4190

2✔
4191
                rbfState, err := rbfCloser.CurrentState()
2✔
4192
                if err != nil {
2✔
UNCOV
4193
                        peerLog.Warnf("ChannelPoint(%v): unable to get "+
×
UNCOV
4194
                                "current state for rbf-coop close: %v",
×
UNCOV
4195
                                chanPoint, err)
×
UNCOV
4196

×
UNCOV
4197
                        return
×
UNCOV
4198
                }
×
4199

4200
                coopCloseStates := rbfCloser.RegisterStateEvents()
2✔
4201

2✔
4202
                // Before we send our event below, we'll launch a goroutine to
2✔
4203
                // watch for the final terminal state to send updates to the RPC
2✔
4204
                // client. We only need to do this if there's an RPC caller.
2✔
4205
                var rpcShutdown bool
2✔
4206
                whenRPCShutdown(shutdown, func(req *htlcswitch.ChanClose) {
4✔
4207
                        rpcShutdown = true
2✔
4208

2✔
4209
                        p.cg.WgAdd(1)
2✔
4210
                        go func() {
4✔
4211
                                defer p.cg.WgDone()
2✔
4212

2✔
4213
                                p.observeRbfCloseUpdates(
2✔
4214
                                        rbfCloser, req, coopCloseStates,
2✔
4215
                                )
2✔
4216
                        }()
2✔
4217
                })
4218

4219
                if !rpcShutdown {
4✔
4220
                        defer rbfCloser.RemoveStateSub(coopCloseStates)
2✔
4221
                }
2✔
4222

4223
                ctx, _ := p.cg.Create(context.Background())
2✔
4224
                feeRate := defaultFeePerKw.FeePerVByte()
2✔
4225

2✔
4226
                // Depending on the state of the state machine, we'll either
2✔
4227
                // kick things off by sending shutdown, or attempt to send a new
2✔
4228
                // offer to the remote party.
2✔
4229
                switch rbfState.(type) {
2✔
4230
                // The channel is still active, so we'll now kick off the co-op
4231
                // close process by instructing it to send a shutdown message to
4232
                // the remote party.
4233
                case *chancloser.ChannelActive:
2✔
4234
                        rbfCloser.SendEvent(
2✔
4235
                                context.Background(),
2✔
4236
                                &chancloser.SendShutdown{
2✔
4237
                                        IdealFeeRate: feeRate,
2✔
4238
                                        DeliveryAddr: shutdownStartAddr(
2✔
4239
                                                shutdown,
2✔
4240
                                        ),
2✔
4241
                                },
2✔
4242
                        )
2✔
4243

4244
                // If we haven't yet sent an offer (didn't have enough funds at
4245
                // the prior fee rate), or we've sent an offer, then we'll
4246
                // trigger a new offer event.
4247
                case *chancloser.ClosingNegotiation:
2✔
4248
                        // Before we send the event below, we'll wait until
2✔
4249
                        // we're in a semi-terminal state.
2✔
4250
                        err := waitUntilRbfCoastClear(ctx, rbfCloser)
2✔
4251
                        if err != nil {
2✔
UNCOV
4252
                                peerLog.Warnf("ChannelPoint(%v): unable to "+
×
UNCOV
4253
                                        "wait for coast to clear: %v",
×
UNCOV
4254
                                        chanPoint, err)
×
UNCOV
4255

×
UNCOV
4256
                                return
×
UNCOV
4257
                        }
×
4258

4259
                        event := chancloser.ProtocolEvent(
2✔
4260
                                &chancloser.SendOfferEvent{
2✔
4261
                                        TargetFeeRate: feeRate,
2✔
4262
                                },
2✔
4263
                        )
2✔
4264
                        rbfCloser.SendEvent(ctx, event)
2✔
4265

UNCOV
4266
                default:
×
UNCOV
4267
                        peerLog.Warnf("ChannelPoint(%v): unexpected state "+
×
UNCOV
4268
                                "for rbf-coop close: %T", chanPoint, rbfState)
×
4269
                }
4270
        })
4271

4272
        return nil
2✔
4273
}
4274

4275
// handleLocalCloseReq kicks-off the workflow to execute a cooperative or
4276
// forced unilateral closure of the channel initiated by a local subsystem.
4277
func (p *Brontide) handleLocalCloseReq(req *htlcswitch.ChanClose) {
9✔
4278
        chanID := lnwire.NewChanIDFromOutPoint(*req.ChanPoint)
9✔
4279

9✔
4280
        channel, ok := p.activeChannels.Load(chanID)
9✔
4281

9✔
4282
        // Though this function can't be called for pending channels, we still
9✔
4283
        // check whether channel is nil for safety.
9✔
4284
        if !ok || channel == nil {
9✔
UNCOV
4285
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
×
UNCOV
4286
                        "unknown", chanID)
×
UNCOV
4287
                p.log.Errorf(err.Error())
×
UNCOV
4288
                req.Err <- err
×
UNCOV
4289
                return
×
UNCOV
4290
        }
×
4291

4292
        isTaprootChan := channel.ChanType().IsTaproot()
9✔
4293

9✔
4294
        switch req.CloseType {
9✔
4295
        // A type of CloseRegular indicates that the user has opted to close
4296
        // out this channel on-chain, so we execute the cooperative channel
4297
        // closure workflow.
4298
        case contractcourt.CloseRegular:
9✔
4299
                var err error
9✔
4300
                switch {
9✔
4301
                // If this is the RBF coop state machine, then we'll instruct
4302
                // it to send the shutdown message. This also might be an RBF
4303
                // iteration, in which case we'll be obtaining a new
4304
                // transaction w/ a higher fee rate.
4305
                //
4306
                // We don't support this close type for taproot channels yet
4307
                // however.
4308
                case !isTaprootChan && p.rbfCoopCloseAllowed():
2✔
4309
                        err = p.startRbfChanCloser(
2✔
4310
                                newRPCShutdownInit(req), channel.ChannelPoint(),
2✔
4311
                        )
2✔
4312
                default:
9✔
4313
                        err = p.initNegotiateChanCloser(req, channel)
9✔
4314
                }
4315

4316
                if err != nil {
10✔
4317
                        p.log.Errorf(err.Error())
1✔
4318
                        req.Err <- err
1✔
4319
                }
1✔
4320

4321
        // A type of CloseBreach indicates that the counterparty has breached
4322
        // the channel therefore we need to clean up our local state.
UNCOV
4323
        case contractcourt.CloseBreach:
×
UNCOV
4324
                // TODO(roasbeef): no longer need with newer beach logic?
×
UNCOV
4325
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
×
UNCOV
4326
                        "channel", req.ChanPoint)
×
UNCOV
4327
                p.WipeChannel(req.ChanPoint)
×
4328
        }
4329
}
4330

4331
// linkFailureReport is sent to the channelManager whenever a link reports a
4332
// link failure, and is forced to exit. The report houses the necessary
4333
// information to clean up the channel state, send back the error message, and
4334
// force close if necessary.
4335
type linkFailureReport struct {
4336
        chanPoint   wire.OutPoint
4337
        chanID      lnwire.ChannelID
4338
        shortChanID lnwire.ShortChannelID
4339
        linkErr     htlcswitch.LinkFailureError
4340
}
4341

4342
// handleLinkFailure processes a link failure report when a link in the switch
4343
// fails. It facilitates the removal of all channel state within the peer,
4344
// force closing the channel depending on severity, and sending the error
4345
// message back to the remote party.
4346
func (p *Brontide) handleLinkFailure(failure linkFailureReport) {
2✔
4347
        // Retrieve the channel from the map of active channels. We do this to
2✔
4348
        // have access to it even after WipeChannel remove it from the map.
2✔
4349
        chanID := lnwire.NewChanIDFromOutPoint(failure.chanPoint)
2✔
4350
        lnChan, _ := p.activeChannels.Load(chanID)
2✔
4351

2✔
4352
        // We begin by wiping the link, which will remove it from the switch,
2✔
4353
        // such that it won't be attempted used for any more updates.
2✔
4354
        //
2✔
4355
        // TODO(halseth): should introduce a way to atomically stop/pause the
2✔
4356
        // link and cancel back any adds in its mailboxes such that we can
2✔
4357
        // safely force close without the link being added again and updates
2✔
4358
        // being applied.
2✔
4359
        p.WipeChannel(&failure.chanPoint)
2✔
4360

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

2✔
4366
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
2✔
4367
                        failure.chanPoint,
2✔
4368
                )
2✔
4369
                if err != nil {
4✔
4370
                        p.log.Errorf("unable to force close "+
2✔
4371
                                "link(%v): %v", failure.shortChanID, err)
2✔
4372
                } else {
4✔
4373
                        p.log.Infof("channel(%v) force "+
2✔
4374
                                "closed with txid %v",
2✔
4375
                                failure.shortChanID, closeTx.TxHash())
2✔
4376
                }
2✔
4377
        }
4378

4379
        // If this is a permanent failure, we will mark the channel borked.
4380
        if failure.linkErr.PermanentFailure && lnChan != nil {
2✔
UNCOV
4381
                p.log.Warnf("Marking link(%v) borked due to permanent "+
×
UNCOV
4382
                        "failure", failure.shortChanID)
×
UNCOV
4383

×
UNCOV
4384
                if err := lnChan.State().MarkBorked(); err != nil {
×
UNCOV
4385
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
UNCOV
4386
                                failure.shortChanID, err)
×
UNCOV
4387
                }
×
4388
        }
4389

4390
        // Send an error to the peer, why we failed the channel.
4391
        if failure.linkErr.ShouldSendToPeer() {
4✔
4392
                // If SendData is set, send it to the peer. If not, we'll use
2✔
4393
                // the standard error messages in the payload. We only include
2✔
4394
                // sendData in the cases where the error data does not contain
2✔
4395
                // sensitive information.
2✔
4396
                data := []byte(failure.linkErr.Error())
2✔
4397
                if failure.linkErr.SendData != nil {
2✔
4398
                        data = failure.linkErr.SendData
×
4399
                }
×
4400

4401
                var networkMsg lnwire.Message
2✔
4402
                if failure.linkErr.Warning {
2✔
UNCOV
4403
                        networkMsg = &lnwire.Warning{
×
UNCOV
4404
                                ChanID: failure.chanID,
×
UNCOV
4405
                                Data:   data,
×
UNCOV
4406
                        }
×
4407
                } else {
2✔
4408
                        networkMsg = &lnwire.Error{
2✔
4409
                                ChanID: failure.chanID,
2✔
4410
                                Data:   data,
2✔
4411
                        }
2✔
4412
                }
2✔
4413

4414
                err := p.SendMessage(true, networkMsg)
2✔
4415
                if err != nil {
2✔
UNCOV
4416
                        p.log.Errorf("unable to send msg to "+
×
UNCOV
4417
                                "remote peer: %v", err)
×
4418
                }
×
4419
        }
4420

4421
        // If the failure action is disconnect, then we'll execute that now. If
4422
        // we had to send an error above, it was a sync call, so we expect the
4423
        // message to be flushed on the wire by now.
4424
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
2✔
UNCOV
4425
                p.Disconnect(fmt.Errorf("link requested disconnect"))
×
UNCOV
4426
        }
×
4427
}
4428

4429
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
4430
// public key and the channel id.
4431
func (p *Brontide) fetchLinkFromKeyAndCid(
4432
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
21✔
4433

21✔
4434
        var chanLink htlcswitch.ChannelUpdateHandler
21✔
4435

21✔
4436
        // We don't need to check the error here, and can instead just loop
21✔
4437
        // over the slice and return nil.
21✔
4438
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
21✔
4439
        for _, link := range links {
41✔
4440
                if link.ChanID() == cid {
40✔
4441
                        chanLink = link
20✔
4442
                        break
20✔
4443
                }
4444
        }
4445

4446
        return chanLink
21✔
4447
}
4448

4449
// finalizeChanClosure performs the final clean up steps once the cooperative
4450
// closure transaction has been fully broadcast. The finalized closing state
4451
// machine should be passed in. Once the transaction has been sufficiently
4452
// confirmed, the channel will be marked as fully closed within the database,
4453
// and any clients will be notified of updates to the closing state.
4454
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
6✔
4455
        closeReq := chanCloser.CloseRequest()
6✔
4456

6✔
4457
        // First, we'll clear all indexes related to the channel in question.
6✔
4458
        chanPoint := chanCloser.Channel().ChannelPoint()
6✔
4459
        p.WipeChannel(&chanPoint)
6✔
4460

6✔
4461
        // Also clear the activeChanCloses map of this channel.
6✔
4462
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
6✔
4463
        p.activeChanCloses.Delete(cid) // TODO(roasbeef): existing race
6✔
4464

6✔
4465
        // Next, we'll launch a goroutine which will request to be notified by
6✔
4466
        // the ChainNotifier once the closure transaction obtains a single
6✔
4467
        // confirmation.
6✔
4468
        notifier := p.cfg.ChainNotifier
6✔
4469

6✔
4470
        // If any error happens during waitForChanToClose, forward it to
6✔
4471
        // closeReq. If this channel closure is not locally initiated, closeReq
6✔
4472
        // will be nil, so just ignore the error.
6✔
4473
        errChan := make(chan error, 1)
6✔
4474
        if closeReq != nil {
10✔
4475
                errChan = closeReq.Err
4✔
4476
        }
4✔
4477

4478
        closingTx, err := chanCloser.ClosingTx()
6✔
4479
        if err != nil {
6✔
UNCOV
4480
                if closeReq != nil {
×
UNCOV
4481
                        p.log.Error(err)
×
UNCOV
4482
                        closeReq.Err <- err
×
UNCOV
4483
                }
×
4484
        }
4485

4486
        closingTxid := closingTx.TxHash()
6✔
4487

6✔
4488
        // If this is a locally requested shutdown, update the caller with a
6✔
4489
        // new event detailing the current pending state of this request.
6✔
4490
        if closeReq != nil {
10✔
4491
                closeReq.Updates <- &PendingUpdate{
4✔
4492
                        Txid: closingTxid[:],
4✔
4493
                }
4✔
4494
        }
4✔
4495

4496
        localOut := chanCloser.LocalCloseOutput()
6✔
4497
        remoteOut := chanCloser.RemoteCloseOutput()
6✔
4498
        auxOut := chanCloser.AuxOutputs()
6✔
4499

6✔
4500
        // Determine the number of confirmations to wait before signaling a
6✔
4501
        // successful cooperative close, scaled by channel capacity (see
6✔
4502
        // CloseConfsForCapacity). Check if we have a config override for
6✔
4503
        // testing purposes.
6✔
4504
        chanCapacity := chanCloser.Channel().Capacity
6✔
4505
        numConfs := p.cfg.ChannelCloseConfs.UnwrapOrFunc(func() uint32 {
12✔
4506
                // No override, use normal capacity-based scaling.
6✔
4507
                return lnwallet.CloseConfsForCapacity(chanCapacity)
6✔
4508
        })
6✔
4509

4510
        // Register for full confirmation to send the final update.
4511
        closeScript := closingTx.TxOut[0].PkScript
6✔
4512
        go WaitForChanToClose(
6✔
4513
                chanCloser.NegotiationHeight(), notifier, errChan,
6✔
4514
                &chanPoint, &closingTxid, closeScript, numConfs, func() {
12✔
4515
                        // Respond to the local subsystem which requested the
6✔
4516
                        // channel closure.
6✔
4517
                        if closeReq != nil {
10✔
4518
                                closeReq.Updates <- &ChannelCloseUpdate{
4✔
4519
                                        ClosingTxid:       closingTxid[:],
4✔
4520
                                        Success:           true,
4✔
4521
                                        LocalCloseOutput:  localOut,
4✔
4522
                                        RemoteCloseOutput: remoteOut,
4✔
4523
                                        AuxOutputs:        auxOut,
4✔
4524
                                }
4✔
4525
                        }
4✔
4526
                },
4527
        )
4528
}
4529

4530
// WaitForChanToClose uses the passed notifier to wait until the channel has
4531
// been detected as closed on chain and then concludes by executing the
4532
// following actions: the channel point will be sent over the settleChan, and
4533
// finally the callback will be executed. If any error is encountered within
4534
// the function, then it will be sent over the errChan.
4535
func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
4536
        errChan chan error, chanPoint *wire.OutPoint,
4537
        closingTxID *chainhash.Hash, closeScript []byte, numConfs uint32,
4538
        cb func()) {
6✔
4539

6✔
4540
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
6✔
4541
                "with txid: %v", chanPoint, closingTxID)
6✔
4542

6✔
4543
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
6✔
4544
                closingTxID, closeScript, numConfs, bestHeight,
6✔
4545
        )
6✔
4546
        if err != nil {
6✔
UNCOV
4547
                if errChan != nil {
×
UNCOV
4548
                        errChan <- err
×
UNCOV
4549
                }
×
UNCOV
4550
                return
×
4551
        }
4552

4553
        // In the case that the ChainNotifier is shutting down, all subscriber
4554
        // notification channels will be closed, generating a nil receive.
4555
        height, ok := <-confNtfn.Confirmed
6✔
4556
        if !ok {
8✔
4557
                return
2✔
4558
        }
2✔
4559

4560
        // The channel has been closed, remove it from any active indexes, and
4561
        // the database state.
4562
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
6✔
4563
                "height %v", chanPoint, height.BlockHeight)
6✔
4564

6✔
4565
        // Finally, execute the closure call back to mark the confirmation of
6✔
4566
        // the transaction closing the contract.
6✔
4567
        cb()
6✔
4568
}
4569

4570
// WipeChannel removes the passed channel point from all indexes associated with
4571
// the peer and the switch.
4572
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
6✔
4573
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
6✔
4574

6✔
4575
        p.activeChannels.Delete(chanID)
6✔
4576

6✔
4577
        // Instruct the HtlcSwitch to close this link as the channel is no
6✔
4578
        // longer active.
6✔
4579
        p.cfg.Switch.RemoveLink(chanID)
6✔
4580
}
6✔
4581

4582
// handleInitMsg handles the incoming init message which contains global and
4583
// local feature vectors. If feature vectors are incompatible then disconnect.
4584
func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
5✔
4585
        // First, merge any features from the legacy global features field into
5✔
4586
        // those presented in the local features fields.
5✔
4587
        err := msg.Features.Merge(msg.GlobalFeatures)
5✔
4588
        if err != nil {
5✔
UNCOV
4589
                return fmt.Errorf("unable to merge legacy global features: %w",
×
UNCOV
4590
                        err)
×
4591
        }
×
4592

4593
        // Then, finalize the remote feature vector providing the flattened
4594
        // feature bit namespace.
4595
        p.remoteFeatures = lnwire.NewFeatureVector(
5✔
4596
                msg.Features, lnwire.Features,
5✔
4597
        )
5✔
4598

5✔
4599
        // Now that we have their features loaded, we'll ensure that they
5✔
4600
        // didn't set any required bits that we don't know of.
5✔
4601
        err = feature.ValidateRequired(p.remoteFeatures)
5✔
4602
        if err != nil {
5✔
UNCOV
4603
                return fmt.Errorf("invalid remote features: %w", err)
×
4604
        }
×
4605

4606
        // Ensure the remote party's feature vector contains all transitive
4607
        // dependencies. We know ours are correct since they are validated
4608
        // during the feature manager's instantiation.
4609
        err = feature.ValidateDeps(p.remoteFeatures)
5✔
4610
        if err != nil {
5✔
4611
                return fmt.Errorf("invalid remote features: %w", err)
×
UNCOV
4612
        }
×
4613

4614
        // Now that we know we understand their requirements, we'll check to
4615
        // see if they don't support anything that we deem to be mandatory.
4616
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
5✔
UNCOV
4617
                return fmt.Errorf("data loss protection required")
×
UNCOV
4618
        }
×
4619

4620
        // If we have an AuxChannelNegotiator and the peer sent aux features,
4621
        // process them.
4622
        p.cfg.AuxChannelNegotiator.WhenSome(
5✔
4623
                func(acn lnwallet.AuxChannelNegotiator) {
5✔
UNCOV
4624
                        err = acn.ProcessInitRecords(
×
UNCOV
4625
                                p.cfg.PubKeyBytes, msg.CustomRecords.Copy(),
×
UNCOV
4626
                        )
×
UNCOV
4627
                },
×
4628
        )
4629
        if err != nil {
5✔
UNCOV
4630
                return fmt.Errorf("could not process init records: %w", err)
×
UNCOV
4631
        }
×
4632

4633
        return nil
5✔
4634
}
4635

4636
// LocalFeatures returns the set of global features that has been advertised by
4637
// the local node. This allows sub-systems that use this interface to gate their
4638
// behavior off the set of negotiated feature bits.
4639
//
4640
// NOTE: Part of the lnpeer.Peer interface.
4641
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
2✔
4642
        return p.cfg.Features
2✔
4643
}
2✔
4644

4645
// RemoteFeatures returns the set of global features that has been advertised by
4646
// the remote node. This allows sub-systems that use this interface to gate
4647
// their behavior off the set of negotiated feature bits.
4648
//
4649
// NOTE: Part of the lnpeer.Peer interface.
4650
func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector {
22✔
4651
        return p.remoteFeatures
22✔
4652
}
22✔
4653

4654
// hasNegotiatedScidAlias returns true if we've negotiated the
4655
// option-scid-alias feature bit with the peer.
4656
func (p *Brontide) hasNegotiatedScidAlias() bool {
5✔
4657
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
5✔
4658
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
5✔
4659
        return peerHas && localHas
5✔
4660
}
5✔
4661

4662
// sendInitMsg sends the Init message to the remote peer. This message contains
4663
// our currently supported local and global features.
4664
func (p *Brontide) sendInitMsg(legacyChan bool) error {
9✔
4665
        features := p.cfg.Features.Clone()
9✔
4666
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
9✔
4667

9✔
4668
        // If we have a legacy channel open with a peer, we downgrade static
9✔
4669
        // remote required to optional in case the peer does not understand the
9✔
4670
        // required feature bit. If we do not do this, the peer will reject our
9✔
4671
        // connection because it does not understand a required feature bit, and
9✔
4672
        // our channel will be unusable.
9✔
4673
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
10✔
4674
                p.log.Infof("Legacy channel open with peer, " +
1✔
4675
                        "downgrading static remote required feature bit to " +
1✔
4676
                        "optional")
1✔
4677

1✔
4678
                // Unset and set in both the local and global features to
1✔
4679
                // ensure both sets are consistent and merge able by old and
1✔
4680
                // new nodes.
1✔
4681
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4682
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4683

1✔
4684
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
4685
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
4686
        }
1✔
4687

4688
        msg := lnwire.NewInitMessage(
9✔
4689
                legacyFeatures.RawFeatureVector,
9✔
4690
                features.RawFeatureVector,
9✔
4691
        )
9✔
4692

9✔
4693
        var err error
9✔
4694

9✔
4695
        // If we have an AuxChannelNegotiator, get custom feature bits to
9✔
4696
        // include in the init message.
9✔
4697
        p.cfg.AuxChannelNegotiator.WhenSome(
9✔
4698
                func(negotiator lnwallet.AuxChannelNegotiator) {
9✔
UNCOV
4699
                        var auxRecords lnwire.CustomRecords
×
UNCOV
4700
                        auxRecords, err = negotiator.GetInitRecords(
×
UNCOV
4701
                                p.cfg.PubKeyBytes,
×
UNCOV
4702
                        )
×
UNCOV
4703
                        if err != nil {
×
UNCOV
4704
                                p.log.Warnf("Failed to get aux init features: "+
×
UNCOV
4705
                                        "%v", err)
×
UNCOV
4706
                                return
×
UNCOV
4707
                        }
×
4708

UNCOV
4709
                        mergedRecs := msg.CustomRecords.MergedCopy(auxRecords)
×
UNCOV
4710
                        msg.CustomRecords = mergedRecs
×
4711
                },
4712
        )
4713
        if err != nil {
9✔
UNCOV
4714
                return err
×
UNCOV
4715
        }
×
4716

4717
        return p.writeMessage(msg)
9✔
4718
}
4719

4720
// resendChanSyncMsg will attempt to find a channel sync message for the closed
4721
// channel and resend it to our peer.
4722
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
2✔
4723
        // If we already re-sent the mssage for this channel, we won't do it
2✔
4724
        // again.
2✔
4725
        if _, ok := p.resentChanSyncMsg[cid]; ok {
3✔
4726
                return nil
1✔
4727
        }
1✔
4728

4729
        // Check if we have any channel sync messages stored for this channel.
4730
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
2✔
4731
        if err != nil {
4✔
4732
                return fmt.Errorf("unable to fetch channel sync messages for "+
2✔
4733
                        "peer %v: %v", p, err)
2✔
4734
        }
2✔
4735

4736
        if c.LastChanSyncMsg == nil {
2✔
UNCOV
4737
                return fmt.Errorf("no chan sync message stored for channel %v",
×
UNCOV
4738
                        cid)
×
UNCOV
4739
        }
×
4740

4741
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
2✔
UNCOV
4742
                return fmt.Errorf("ignoring channel reestablish from "+
×
UNCOV
4743
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
UNCOV
4744
        }
×
4745

4746
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
2✔
4747
                "peer", cid)
2✔
4748

2✔
4749
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
2✔
UNCOV
4750
                return fmt.Errorf("failed resending channel sync "+
×
UNCOV
4751
                        "message to peer %v: %v", p, err)
×
UNCOV
4752
        }
×
4753

4754
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
2✔
4755
                cid)
2✔
4756

2✔
4757
        // Note down that we sent the message, so we won't resend it again for
2✔
4758
        // this connection.
2✔
4759
        p.resentChanSyncMsg[cid] = struct{}{}
2✔
4760

2✔
4761
        return nil
2✔
4762
}
4763

4764
// SendMessage sends a variadic number of high-priority messages to the remote
4765
// peer. The first argument denotes if the method should block until the
4766
// messages have been sent to the remote peer or an error is returned,
4767
// otherwise it returns immediately after queuing.
4768
//
4769
// NOTE: Part of the lnpeer.Peer interface.
4770
func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error {
5✔
4771
        return p.sendMessage(sync, true, msgs...)
5✔
4772
}
5✔
4773

4774
// SendMessageLazy sends a variadic number of low-priority messages to the
4775
// remote peer. The first argument denotes if the method should block until
4776
// the messages have been sent to the remote peer or an error is returned,
4777
// otherwise it returns immediately after queueing.
4778
//
4779
// NOTE: Part of the lnpeer.Peer interface.
4780
func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
3✔
4781
        return p.sendMessage(sync, false, msgs...)
3✔
4782
}
3✔
4783

4784
// sendMessage queues a variadic number of messages using the passed priority
4785
// to the remote peer. If sync is true, this method will block until the
4786
// messages have been sent to the remote peer or an error is returned, otherwise
4787
// it returns immediately after queueing.
4788
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
6✔
4789
        // Add all incoming messages to the outgoing queue. A list of error
6✔
4790
        // chans is populated for each message if the caller requested a sync
6✔
4791
        // send.
6✔
4792
        var errChans []chan error
6✔
4793
        if sync {
9✔
4794
                errChans = make([]chan error, 0, len(msgs))
3✔
4795
        }
3✔
4796
        for _, msg := range msgs {
12✔
4797
                // If a sync send was requested, create an error chan to listen
6✔
4798
                // for an ack from the writeHandler.
6✔
4799
                var errChan chan error
6✔
4800
                if sync {
9✔
4801
                        errChan = make(chan error, 1)
3✔
4802
                        errChans = append(errChans, errChan)
3✔
4803
                }
3✔
4804

4805
                if priority {
11✔
4806
                        p.queueMsg(msg, errChan)
5✔
4807
                } else {
8✔
4808
                        p.queueMsgLazy(msg, errChan)
3✔
4809
                }
3✔
4810
        }
4811

4812
        // Wait for all replies from the writeHandler. For async sends, this
4813
        // will be a NOP as the list of error chans is nil.
4814
        for _, errChan := range errChans {
9✔
4815
                select {
3✔
4816
                case err := <-errChan:
3✔
4817
                        return err
3✔
UNCOV
4818
                case <-p.cg.Done():
×
UNCOV
4819
                        return lnpeer.ErrPeerExiting
×
UNCOV
4820
                case <-p.cfg.Quit:
×
UNCOV
4821
                        return lnpeer.ErrPeerExiting
×
4822
                }
4823
        }
4824

4825
        return nil
5✔
4826
}
4827

4828
// PubKey returns the pubkey of the peer in compressed serialized format.
4829
//
4830
// NOTE: Part of the lnpeer.Peer interface.
4831
func (p *Brontide) PubKey() [33]byte {
5✔
4832
        return p.cfg.PubKeyBytes
5✔
4833
}
5✔
4834

4835
// IdentityKey returns the public key of the remote peer.
4836
//
4837
// NOTE: Part of the lnpeer.Peer interface.
4838
func (p *Brontide) IdentityKey() *btcec.PublicKey {
17✔
4839
        return p.cfg.Addr.IdentityKey
17✔
4840
}
17✔
4841

4842
// Address returns the network address of the remote peer.
4843
//
4844
// NOTE: Part of the lnpeer.Peer interface.
4845
func (p *Brontide) Address() net.Addr {
2✔
4846
        return p.cfg.Addr.Address
2✔
4847
}
2✔
4848

4849
// AddNewChannel adds a new channel to the peer. The channel should fail to be
4850
// added if the cancel channel is closed.
4851
//
4852
// NOTE: Part of the lnpeer.Peer interface.
4853
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
4854
        cancel <-chan struct{}) error {
2✔
4855

2✔
4856
        errChan := make(chan error, 1)
2✔
4857
        newChanMsg := &newChannelMsg{
2✔
4858
                channel: newChan,
2✔
4859
                err:     errChan,
2✔
4860
        }
2✔
4861

2✔
4862
        select {
2✔
4863
        case p.newActiveChannel <- newChanMsg:
2✔
UNCOV
4864
        case <-cancel:
×
UNCOV
4865
                return errors.New("canceled adding new channel")
×
UNCOV
4866
        case <-p.cg.Done():
×
UNCOV
4867
                return lnpeer.ErrPeerExiting
×
4868
        }
4869

4870
        // We pause here to wait for the peer to recognize the new channel
4871
        // before we close the channel barrier corresponding to the channel.
4872
        select {
2✔
4873
        case err := <-errChan:
2✔
4874
                return err
2✔
UNCOV
4875
        case <-p.cg.Done():
×
4876
                return lnpeer.ErrPeerExiting
×
4877
        }
4878
}
4879

4880
// AddPendingChannel adds a pending open channel to the peer. The channel
4881
// should fail to be added if the cancel channel is closed.
4882
//
4883
// NOTE: Part of the lnpeer.Peer interface.
4884
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
4885
        cancel <-chan struct{}) error {
2✔
4886

2✔
4887
        errChan := make(chan error, 1)
2✔
4888
        newChanMsg := &newChannelMsg{
2✔
4889
                channelID: cid,
2✔
4890
                err:       errChan,
2✔
4891
        }
2✔
4892

2✔
4893
        select {
2✔
4894
        case p.newPendingChannel <- newChanMsg:
2✔
4895

UNCOV
4896
        case <-cancel:
×
UNCOV
4897
                return errors.New("canceled adding pending channel")
×
4898

UNCOV
4899
        case <-p.cg.Done():
×
UNCOV
4900
                return lnpeer.ErrPeerExiting
×
4901
        }
4902

4903
        // We pause here to wait for the peer to recognize the new pending
4904
        // channel before we close the channel barrier corresponding to the
4905
        // channel.
4906
        select {
2✔
4907
        case err := <-errChan:
2✔
4908
                return err
2✔
4909

4910
        case <-cancel:
×
4911
                return errors.New("canceled adding pending channel")
×
4912

UNCOV
4913
        case <-p.cg.Done():
×
UNCOV
4914
                return lnpeer.ErrPeerExiting
×
4915
        }
4916
}
4917

4918
// RemovePendingChannel removes a pending open channel from the peer.
4919
//
4920
// NOTE: Part of the lnpeer.Peer interface.
4921
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
2✔
4922
        errChan := make(chan error, 1)
2✔
4923
        newChanMsg := &newChannelMsg{
2✔
4924
                channelID: cid,
2✔
4925
                err:       errChan,
2✔
4926
        }
2✔
4927

2✔
4928
        select {
2✔
4929
        case p.removePendingChannel <- newChanMsg:
2✔
UNCOV
4930
        case <-p.cg.Done():
×
UNCOV
4931
                return lnpeer.ErrPeerExiting
×
4932
        }
4933

4934
        // We pause here to wait for the peer to respond to the cancellation of
4935
        // the pending channel before we close the channel barrier
4936
        // corresponding to the channel.
4937
        select {
2✔
4938
        case err := <-errChan:
2✔
4939
                return err
2✔
4940

UNCOV
4941
        case <-p.cg.Done():
×
UNCOV
4942
                return lnpeer.ErrPeerExiting
×
4943
        }
4944
}
4945

4946
// StartTime returns the time at which the connection was established if the
4947
// peer started successfully, and zero otherwise.
4948
func (p *Brontide) StartTime() time.Time {
2✔
4949
        return p.startTime
2✔
4950
}
2✔
4951

4952
// handleCloseMsg is called when a new cooperative channel closure related
4953
// message is received from the remote peer. We'll use this message to advance
4954
// the chan closer state machine.
4955
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
15✔
4956
        link := p.fetchLinkFromKeyAndCid(msg.cid)
15✔
4957

15✔
4958
        // We'll now fetch the matching closing state machine in order to
15✔
4959
        // continue, or finalize the channel closure process.
15✔
4960
        chanCloserE, err := p.fetchActiveChanCloser(msg.cid)
15✔
4961
        if err != nil {
17✔
4962
                // If the channel is not known to us, we'll simply ignore this
2✔
4963
                // message.
2✔
4964
                if err == ErrChannelNotFound {
4✔
4965
                        return
2✔
4966
                }
2✔
4967

UNCOV
4968
                p.log.Errorf("Unable to respond to remote close msg: %v", err)
×
UNCOV
4969

×
UNCOV
4970
                errMsg := &lnwire.Error{
×
UNCOV
4971
                        ChanID: msg.cid,
×
UNCOV
4972
                        Data:   lnwire.ErrorData(err.Error()),
×
4973
                }
×
4974
                p.queueMsg(errMsg, nil)
×
4975
                return
×
4976
        }
4977

4978
        if chanCloserE.IsRight() {
15✔
4979
                // TODO(roasbeef): assert?
×
4980
                return
×
4981
        }
×
4982

4983
        // At this point, we'll only enter this call path if a negotiate chan
4984
        // closer was used. So we'll extract that from the either now.
4985
        //
4986
        // TODO(roabeef): need extra helper func for either to make cleaner
4987
        var chanCloser *chancloser.ChanCloser
15✔
4988
        chanCloserE.WhenLeft(func(c *chancloser.ChanCloser) {
30✔
4989
                chanCloser = c
15✔
4990
        })
15✔
4991

4992
        handleErr := func(err error) {
16✔
4993
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
4994
                p.log.Error(err)
1✔
4995

1✔
4996
                // As the negotiations failed, we'll reset the channel state
1✔
4997
                // machine to ensure we act to on-chain events as normal.
1✔
4998
                chanCloser.Channel().ResetState()
1✔
4999
                if chanCloser.CloseRequest() != nil {
1✔
5000
                        chanCloser.CloseRequest().Err <- err
×
5001
                }
×
5002

5003
                p.activeChanCloses.Delete(msg.cid)
1✔
5004

1✔
5005
                p.Disconnect(err)
1✔
5006
        }
5007

5008
        // Next, we'll process the next message using the target state machine.
5009
        // We'll either continue negotiation, or halt.
5010
        switch typed := msg.msg.(type) {
15✔
5011
        case *lnwire.Shutdown:
7✔
5012
                // Disable incoming adds immediately.
7✔
5013
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
7✔
UNCOV
5014
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
UNCOV
5015
                                link.ChanID())
×
5016
                }
×
5017

5018
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
7✔
5019
                if err != nil {
7✔
UNCOV
5020
                        handleErr(err)
×
UNCOV
5021
                        return
×
UNCOV
5022
                }
×
5023

5024
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
12✔
5025
                        // If the link is nil it means we can immediately queue
5✔
5026
                        // the Shutdown message since we don't have to wait for
5✔
5027
                        // commitment transaction synchronization.
5✔
5028
                        if link == nil {
6✔
5029
                                p.queueMsg(&msg, nil)
1✔
5030
                                return
1✔
5031
                        }
1✔
5032

5033
                        // Immediately disallow any new HTLC's from being added
5034
                        // in the outgoing direction.
5035
                        if !link.DisableAdds(htlcswitch.Outgoing) {
4✔
UNCOV
5036
                                p.log.Warnf("Outgoing link adds already "+
×
UNCOV
5037
                                        "disabled: %v", link.ChanID())
×
UNCOV
5038
                        }
×
5039

5040
                        // When we have a Shutdown to send, we defer it till the
5041
                        // next time we send a CommitSig to remain spec
5042
                        // compliant.
5043
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
8✔
5044
                                p.queueMsg(&msg, nil)
4✔
5045
                        })
4✔
5046
                })
5047

5048
                beginNegotiation := func() {
14✔
5049
                        oClosingSigned, err := chanCloser.BeginNegotiation()
7✔
5050
                        if err != nil {
8✔
5051
                                handleErr(err)
1✔
5052
                                return
1✔
5053
                        }
1✔
5054

5055
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
12✔
5056
                                p.queueMsg(&msg, nil)
6✔
5057
                        })
6✔
5058
                }
5059

5060
                if link == nil {
8✔
5061
                        beginNegotiation()
1✔
5062
                } else {
7✔
5063
                        // Now we register a flush hook to advance the
6✔
5064
                        // ChanCloser and possibly send out a ClosingSigned
6✔
5065
                        // when the link finishes draining.
6✔
5066
                        link.OnFlushedOnce(func() {
12✔
5067
                                // Remove link in goroutine to prevent deadlock.
6✔
5068
                                go p.cfg.Switch.RemoveLink(msg.cid)
6✔
5069
                                beginNegotiation()
6✔
5070
                        })
6✔
5071
                }
5072

5073
        case *lnwire.ClosingSigned:
10✔
5074
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
10✔
5075
                if err != nil {
10✔
UNCOV
5076
                        handleErr(err)
×
UNCOV
5077
                        return
×
UNCOV
5078
                }
×
5079

5080
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
20✔
5081
                        p.queueMsg(&msg, nil)
10✔
5082
                })
10✔
5083

UNCOV
5084
        default:
×
UNCOV
5085
                panic("impossible closeMsg type")
×
5086
        }
5087

5088
        // If we haven't finished close negotiations, then we'll continue as we
5089
        // can't yet finalize the closure.
5090
        if _, err := chanCloser.ClosingTx(); err != nil {
26✔
5091
                return
11✔
5092
        }
11✔
5093

5094
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
5095
        // the channel closure by notifying relevant sub-systems and launching a
5096
        // goroutine to wait for close tx conf.
5097
        p.finalizeChanClosure(chanCloser)
6✔
5098
}
5099

5100
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
5101
// the channelManager goroutine, which will shut down the link and possibly
5102
// close the channel.
5103
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
2✔
5104
        select {
2✔
5105
        case p.localCloseChanReqs <- req:
2✔
5106
                p.log.Info("Local close channel request is going to be " +
2✔
5107
                        "delivered to the peer")
2✔
UNCOV
5108
        case <-p.cg.Done():
×
UNCOV
5109
                p.log.Info("Unable to deliver local close channel request " +
×
UNCOV
5110
                        "to peer")
×
5111
        }
5112
}
5113

5114
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
5115
func (p *Brontide) NetAddress() *lnwire.NetAddress {
2✔
5116
        return p.cfg.Addr
2✔
5117
}
2✔
5118

5119
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
5120
func (p *Brontide) Inbound() bool {
2✔
5121
        return p.cfg.Inbound
2✔
5122
}
2✔
5123

5124
// ConnReq is a getter for the Brontide's connReq in cfg.
5125
func (p *Brontide) ConnReq() *connmgr.ConnReq {
2✔
5126
        return p.cfg.ConnReq
2✔
5127
}
2✔
5128

5129
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
5130
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
2✔
5131
        return p.cfg.ErrorBuffer
2✔
5132
}
2✔
5133

5134
// SetAddress sets the remote peer's address given an address.
UNCOV
5135
func (p *Brontide) SetAddress(address net.Addr) {
×
UNCOV
5136
        p.cfg.Addr.Address = address
×
UNCOV
5137
}
×
5138

5139
// ActiveSignal returns the peer's active signal.
5140
func (p *Brontide) ActiveSignal() chan struct{} {
2✔
5141
        return p.activeSignal
2✔
5142
}
2✔
5143

5144
// Conn returns a pointer to the peer's connection struct.
5145
func (p *Brontide) Conn() net.Conn {
2✔
5146
        return p.cfg.Conn
2✔
5147
}
2✔
5148

5149
// BytesReceived returns the number of bytes received from the peer.
5150
func (p *Brontide) BytesReceived() uint64 {
2✔
5151
        return atomic.LoadUint64(&p.bytesReceived)
2✔
5152
}
2✔
5153

5154
// BytesSent returns the number of bytes sent to the peer.
5155
func (p *Brontide) BytesSent() uint64 {
2✔
5156
        return atomic.LoadUint64(&p.bytesSent)
2✔
5157
}
2✔
5158

5159
// LastRemotePingPayload returns the last payload the remote party sent as part
5160
// of their ping.
5161
func (p *Brontide) LastRemotePingPayload() []byte {
2✔
5162
        pingPayload := p.lastPingPayload.Load()
2✔
5163
        if pingPayload == nil {
4✔
5164
                return []byte{}
2✔
5165
        }
2✔
5166

UNCOV
5167
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
UNCOV
5168
        if !ok {
×
UNCOV
5169
                return nil
×
UNCOV
5170
        }
×
5171

UNCOV
5172
        return pingBytes
×
5173
}
5174

5175
// attachChannelEventSubscription creates a channel event subscription and
5176
// attaches to client to Brontide if the reenableTimeout is no greater than 1
5177
// minute.
5178
func (p *Brontide) attachChannelEventSubscription() error {
5✔
5179
        // If the timeout is greater than 1 minute, it's unlikely that the link
5✔
5180
        // hasn't yet finished its reestablishment. Return a nil without
5✔
5181
        // creating the client to specify that we don't want to retry.
5✔
5182
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
7✔
5183
                return nil
2✔
5184
        }
2✔
5185

5186
        // When the reenable timeout is less than 1 minute, it's likely the
5187
        // channel link hasn't finished its reestablishment yet. In that case,
5188
        // we'll give it a second chance by subscribing to the channel update
5189
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
5190
        // enabling the channel again.
5191
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
5✔
5192
        if err != nil {
5✔
UNCOV
5193
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
UNCOV
5194
        }
×
5195

5196
        p.channelEventClient = sub
5✔
5197

5✔
5198
        return nil
5✔
5199
}
5200

5201
// updateNextRevocation updates the existing channel's next revocation if it's
5202
// nil.
5203
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
5✔
5204
        chanPoint := c.FundingOutpoint
5✔
5205
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
5✔
5206

5✔
5207
        // Read the current channel.
5✔
5208
        currentChan, loaded := p.activeChannels.Load(chanID)
5✔
5209

5✔
5210
        // currentChan should exist, but we perform a check anyway to avoid nil
5✔
5211
        // pointer dereference.
5✔
5212
        if !loaded {
6✔
5213
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
5214
                        chanID)
1✔
5215
        }
1✔
5216

5217
        // currentChan should not be nil, but we perform a check anyway to
5218
        // avoid nil pointer dereference.
5219
        if currentChan == nil {
5✔
5220
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
5221
                        chanID)
1✔
5222
        }
1✔
5223

5224
        // If we're being sent a new channel, and our existing channel doesn't
5225
        // have the next revocation, then we need to update the current
5226
        // existing channel.
5227
        if currentChan.RemoteNextRevocation() != nil {
3✔
UNCOV
5228
                return nil
×
UNCOV
5229
        }
×
5230

5231
        p.log.Infof("Processing retransmitted ChannelReady for "+
3✔
5232
                "ChannelPoint(%v)", chanPoint)
3✔
5233

3✔
5234
        nextRevoke := c.RemoteNextRevocation
3✔
5235

3✔
5236
        err := currentChan.InitNextRevocation(nextRevoke)
3✔
5237
        if err != nil {
3✔
UNCOV
5238
                return fmt.Errorf("unable to init next revocation: %w", err)
×
UNCOV
5239
        }
×
5240

5241
        return nil
3✔
5242
}
5243

5244
// addActiveChannel adds a new active channel to the `activeChannels` map. It
5245
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
5246
// it and assembles it with a channel link.
5247
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
2✔
5248
        chanPoint := c.FundingOutpoint
2✔
5249
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
5250

2✔
5251
        // If we've reached this point, there are two possible scenarios.  If
2✔
5252
        // the channel was in the active channels map as nil, then it was
2✔
5253
        // loaded from disk and we need to send reestablish. Else, it was not
2✔
5254
        // loaded from disk and we don't need to send reestablish as this is a
2✔
5255
        // fresh channel.
2✔
5256
        shouldReestablish := p.isLoadedFromDisk(chanID)
2✔
5257

2✔
5258
        chanOpts := c.ChanOpts
2✔
5259
        if shouldReestablish {
4✔
5260
                // If we have to do the reestablish dance for this channel,
2✔
5261
                // ensure that we don't try to call InitRemoteMusigNonces twice
2✔
5262
                // by calling SkipNonceInit.
2✔
5263
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
2✔
5264
        }
2✔
5265

5266
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
2✔
UNCOV
5267
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
UNCOV
5268
        })
×
5269
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
2✔
UNCOV
5270
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
UNCOV
5271
        })
×
5272
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
2✔
UNCOV
5273
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
UNCOV
5274
        })
×
5275

5276
        // If not already active, we'll add this channel to the set of active
5277
        // channels, so we can look it up later easily according to its channel
5278
        // ID.
5279
        lnChan, err := lnwallet.NewLightningChannel(
2✔
5280
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
2✔
5281
        )
2✔
5282
        if err != nil {
2✔
5283
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
5284
        }
×
5285

5286
        // Store the channel in the activeChannels map.
5287
        p.activeChannels.Store(chanID, lnChan)
2✔
5288

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

2✔
5291
        // Next, we'll assemble a ChannelLink along with the necessary items it
2✔
5292
        // needs to function.
2✔
5293
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
2✔
5294
        if err != nil {
2✔
5295
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
UNCOV
5296
                        err)
×
UNCOV
5297
        }
×
5298

5299
        // We'll query the channel DB for the new channel's initial forwarding
5300
        // policies to determine the policy we start out with.
5301
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
2✔
5302
        if err != nil {
2✔
UNCOV
5303
                return fmt.Errorf("unable to query for initial forwarding "+
×
UNCOV
5304
                        "policy: %v", err)
×
UNCOV
5305
        }
×
5306

5307
        // Create the link and add it to the switch.
5308
        err = p.addLink(
2✔
5309
                &chanPoint, lnChan, initialPolicy, chainEvents,
2✔
5310
                shouldReestablish, fn.None[lnwire.Shutdown](),
2✔
5311
        )
2✔
5312
        if err != nil {
2✔
5313
                return fmt.Errorf("can't register new channel link(%v) with "+
×
5314
                        "peer", chanPoint)
×
5315
        }
×
5316

5317
        isTaprootChan := c.ChanType.IsTaproot()
2✔
5318

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

5326
        // Now that the link has been added above, we'll also init an RBF chan
5327
        // closer for this channel, but only if the new close feature is
5328
        // negotiated.
5329
        //
5330
        // Creating this here ensures that any shutdown messages sent will be
5331
        // automatically routed by the msg router.
5332
        if _, err := p.initRbfChanCloser(lnChan); err != nil {
2✔
UNCOV
5333
                p.activeChanCloses.Delete(chanID)
×
UNCOV
5334

×
UNCOV
5335
                return fmt.Errorf("unable to init RBF chan closer for new "+
×
UNCOV
5336
                        "chan: %w", err)
×
UNCOV
5337
        }
×
5338

5339
        return nil
2✔
5340
}
5341

5342
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
5343
// know this channel ID or not, we'll either add it to the `activeChannels` map
5344
// or init the next revocation for it.
5345
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
2✔
5346
        newChan := req.channel
2✔
5347
        chanPoint := newChan.FundingOutpoint
2✔
5348
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
5349

2✔
5350
        // Only update RemoteNextRevocation if the channel is in the
2✔
5351
        // activeChannels map and if we added the link to the switch. Only
2✔
5352
        // active channels will be added to the switch.
2✔
5353
        if p.isActiveChannel(chanID) {
4✔
5354
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
2✔
5355
                        chanPoint)
2✔
5356

2✔
5357
                // Handle it and close the err chan on the request.
2✔
5358
                close(req.err)
2✔
5359

2✔
5360
                // Update the next revocation point.
2✔
5361
                err := p.updateNextRevocation(newChan.OpenChannel)
2✔
5362
                if err != nil {
2✔
UNCOV
5363
                        p.log.Errorf(err.Error())
×
UNCOV
5364
                }
×
5365

5366
                return
2✔
5367
        }
5368

5369
        // This is a new channel, we now add it to the map.
5370
        if err := p.addActiveChannel(req.channel); err != nil {
2✔
UNCOV
5371
                // Log and send back the error to the request.
×
UNCOV
5372
                p.log.Errorf(err.Error())
×
UNCOV
5373
                req.err <- err
×
UNCOV
5374

×
UNCOV
5375
                return
×
UNCOV
5376
        }
×
5377

5378
        // Close the err chan if everything went fine.
5379
        close(req.err)
2✔
5380
}
5381

5382
// handleNewPendingChannel takes a `newChannelMsg` request and add it to
5383
// `activeChannels` map with nil value. This pending channel will be saved as
5384
// it may become active in the future. Once active, the funding manager will
5385
// send it again via `AddNewChannel`, and we'd handle the link creation there.
5386
func (p *Brontide) handleNewPendingChannel(req *newChannelMsg) {
6✔
5387
        defer close(req.err)
6✔
5388

6✔
5389
        chanID := req.channelID
6✔
5390

6✔
5391
        // If we already have this channel, something is wrong with the funding
6✔
5392
        // flow as it will only be marked as active after `ChannelReady` is
6✔
5393
        // handled. In this case, we will do nothing but log an error, just in
6✔
5394
        // case this is a legit channel.
6✔
5395
        if p.isActiveChannel(chanID) {
7✔
5396
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
5397
                        "pending channel request", chanID)
1✔
5398

1✔
5399
                return
1✔
5400
        }
1✔
5401

5402
        // The channel has already been added, we will do nothing and return.
5403
        if p.isPendingChannel(chanID) {
6✔
5404
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
5405
                        "pending channel request", chanID)
1✔
5406

1✔
5407
                return
1✔
5408
        }
1✔
5409

5410
        // This is a new channel, we now add it to the map `activeChannels`
5411
        // with nil value and mark it as a newly added channel in
5412
        // `addedChannels`.
5413
        p.activeChannels.Store(chanID, nil)
4✔
5414
        p.addedChannels.Store(chanID, struct{}{})
4✔
5415
}
5416

5417
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
5418
// from `activeChannels` map. The request will be ignored if the channel is
5419
// considered active by Brontide. Noop if the channel ID cannot be found.
5420
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
6✔
5421
        defer close(req.err)
6✔
5422

6✔
5423
        chanID := req.channelID
6✔
5424

6✔
5425
        // If we already have this channel, something is wrong with the funding
6✔
5426
        // flow as it will only be marked as active after `ChannelReady` is
6✔
5427
        // handled. In this case, we will log an error and exit.
6✔
5428
        if p.isActiveChannel(chanID) {
7✔
5429
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
5430
                        chanID)
1✔
5431
                return
1✔
5432
        }
1✔
5433

5434
        // The channel has not been added yet, we will log a warning as there
5435
        // is an unexpected call from funding manager.
5436
        if !p.isPendingChannel(chanID) {
8✔
5437
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
3✔
5438
        }
3✔
5439

5440
        // Remove the record of this pending channel.
5441
        p.activeChannels.Delete(chanID)
5✔
5442
        p.addedChannels.Delete(chanID)
5✔
5443
}
5444

5445
// sendLinkUpdateMsg sends a message that updates the channel to the
5446
// channel's message stream.
5447
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
2✔
5448
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
2✔
5449

2✔
5450
        chanStream, ok := p.activeMsgStreams[cid]
2✔
5451
        if !ok {
4✔
5452
                // If a stream hasn't yet been created, then we'll do so, add
2✔
5453
                // it to the map, and finally start it.
2✔
5454
                chanStream = newChanMsgStream(p, cid)
2✔
5455
                p.activeMsgStreams[cid] = chanStream
2✔
5456
                chanStream.Start()
2✔
5457

2✔
5458
                // Stop the stream when quit.
2✔
5459
                go func() {
4✔
5460
                        <-p.cg.Done()
2✔
5461
                        chanStream.Stop()
2✔
5462
                }()
2✔
5463
        }
5464

5465
        // With the stream obtained, add the message to the stream so we can
5466
        // continue processing message.
5467
        chanStream.AddMsg(msg)
2✔
5468
}
5469

5470
// scaleTimeout multiplies the argument duration by a constant factor depending
5471
// on variious heuristics. Currently this is only used to check whether our peer
5472
// appears to be connected over Tor and relaxes the timout deadline. However,
5473
// this is subject to change and should be treated as opaque.
5474
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
69✔
5475
        if p.isTorConnection {
71✔
5476
                return timeout * time.Duration(torTimeoutMultiplier)
2✔
5477
        }
2✔
5478

5479
        return timeout
67✔
5480
}
5481

5482
// CoopCloseUpdates is a struct used to communicate updates for an active close
5483
// to the caller.
5484
type CoopCloseUpdates struct {
5485
        UpdateChan chan interface{}
5486

5487
        ErrChan chan error
5488
}
5489

5490
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5491
// point has an active RBF chan closer.
5492
func (p *Brontide) ChanHasRbfCoopCloser(chanPoint wire.OutPoint) bool {
2✔
5493
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
5494
        chanCloser, found := p.activeChanCloses.Load(chanID)
2✔
5495
        if !found {
4✔
5496
                return false
2✔
5497
        }
2✔
5498

5499
        return chanCloser.IsRight()
2✔
5500
}
5501

5502
// TriggerCoopCloseRbfBump given a chan ID, and the params needed to trigger a
5503
// new RBF co-op close update, a bump is attempted. A channel used for updates,
5504
// along with one used to o=communicate any errors is returned. If no chan
5505
// closer is found, then false is returned for the second argument.
5506
func (p *Brontide) TriggerCoopCloseRbfBump(ctx context.Context,
5507
        chanPoint wire.OutPoint, feeRate chainfee.SatPerKWeight,
5508
        deliveryScript lnwire.DeliveryAddress) (*CoopCloseUpdates, error) {
2✔
5509

2✔
5510
        // If RBF coop close isn't permitted, then we'll an error.
2✔
5511
        if !p.rbfCoopCloseAllowed() {
2✔
UNCOV
5512
                return nil, fmt.Errorf("rbf coop close not enabled for " +
×
UNCOV
5513
                        "channel")
×
UNCOV
5514
        }
×
5515

5516
        closeUpdates := &CoopCloseUpdates{
2✔
5517
                UpdateChan: make(chan interface{}, 1),
2✔
5518
                ErrChan:    make(chan error, 1),
2✔
5519
        }
2✔
5520

2✔
5521
        // We'll re-use the existing switch struct here, even though we're
2✔
5522
        // bypassing the switch entirely.
2✔
5523
        closeReq := htlcswitch.ChanClose{
2✔
5524
                CloseType:      contractcourt.CloseRegular,
2✔
5525
                ChanPoint:      &chanPoint,
2✔
5526
                TargetFeePerKw: feeRate,
2✔
5527
                DeliveryScript: deliveryScript,
2✔
5528
                Updates:        closeUpdates.UpdateChan,
2✔
5529
                Err:            closeUpdates.ErrChan,
2✔
5530
                Ctx:            ctx,
2✔
5531
        }
2✔
5532

2✔
5533
        err := p.startRbfChanCloser(newRPCShutdownInit(&closeReq), chanPoint)
2✔
5534
        if err != nil {
2✔
UNCOV
5535
                return nil, err
×
UNCOV
5536
        }
×
5537

5538
        return closeUpdates, nil
2✔
5539
}
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

© 2026 Coveralls, Inc