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

lightningnetwork / lnd / 15021367723

14 May 2025 01:00PM UTC coverage: 69.017% (+0.02%) from 68.997%
15021367723

Pull #9805

github

web-flow
Merge e75137dae into b0cba7dd0
Pull Request #9805: peer: only send pings if the connection is idle for one minute

16 of 25 new or added lines in 2 files covered. (64.0%)

59 existing lines in 17 files now uncovered.

133942 of 194071 relevant lines covered (69.02%)

22085.97 hits per line

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

78.95
/peer/brontide.go
1
package peer
2

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

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

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

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

68
        // writeMessageTimeout is the timeout used when writing a message to the
69
        // connection buffer.
70
        writeMessageTimeout = 5 * time.Second
71

72
        // writeFlushTimeout is the time we wait until a message is flushed.
73
        // Once the message is written to the connection, we will retry flushing
74
        // it until this timeout is hit.
75
        writeFlushTimeout = 5 * time.Minute
76

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

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

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

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

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

98
        // msgStreamSize is the size of the message streams.
99
        msgStreamSize = 5
100
)
101

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

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

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

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

128
        err chan error
129
}
130

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

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

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

149
        // OutputIndex is the output index of our output in the closing
150
        // transaction.
151
        OutputIndex uint32
152

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

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

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

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

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

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

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

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

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

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

205
        // Addr is the network address of the peer.
206
        Addr *lnwire.NetAddress
207

208
        // Inbound indicates whether or not the peer is an inbound peer.
209
        Inbound bool
210

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

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

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

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

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

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

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

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

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

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

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

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

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

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

274
        // ChainIO is used to retrieve the best block.
275
        ChainIO lnwallet.BlockChainIO
276

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

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

284
        // SigPool is used when creating *lnwallet.LightningChannel instances.
285
        SigPool *lnwallet.SigPool
286

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

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

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

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

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

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

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

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

320
        // HtlcNotifier is used when creating a ChannelLink.
321
        HtlcNotifier *htlcswitch.HtlcNotifier
322

323
        // TowerClient is used to backup revoked states.
324
        TowerClient wtclient.ClientManager
325

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

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

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

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

344
        // FundingManager is an implementation of the funding.Controller interface.
345
        FundingManager funding.Controller
346

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

443
        // MaxFeeExposure limits the number of outstanding fees in a channel.
444
        // This value will be passed to created links.
445
        MaxFeeExposure lnwire.MilliSatoshi
446

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

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

456
        // ShouldFwdExpEndorsement is a closure that indicates whether
457
        // experimental endorsement signals should be set.
458
        ShouldFwdExpEndorsement func() bool
459

460
        // Quit is the server's quit channel. If this is closed, we halt operation.
461
        Quit chan struct{}
462
}
463

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

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

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

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

495
        // MUST be used atomically.
496
        bytesReceived uint64
497
        bytesSent     uint64
498

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

516
        pingManager *PingManager
517

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

525
        cfg Config
526

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

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

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

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

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

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

562
        // newActiveChannel is used by the fundingManager to send fully opened
563
        // channels to the source peer which handled the funding workflow.
564
        newActiveChannel chan *newChannelMsg
565

566
        // newPendingChannel is used by the fundingManager to send pending open
567
        // channels to the source peer which handled the funding workflow.
568
        newPendingChannel chan *newChannelMsg
569

570
        // removePendingChannel is used by the fundingManager to cancel pending
571
        // open channels to the source peer when the funding flow is failed.
572
        removePendingChannel chan *newChannelMsg
573

574
        // activeMsgStreams is a map from channel id to the channel streams that
575
        // proxy messages to individual, active links.
576
        activeMsgStreams map[lnwire.ChannelID]*msgStream
577

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

584
        // localCloseChanReqs is a channel in which any local requests to close
585
        // a particular channel are sent over.
586
        localCloseChanReqs chan *htlcswitch.ChanClose
587

588
        // linkFailures receives all reported channel failures from the switch,
589
        // and instructs the channelManager to clean remaining channel state.
590
        linkFailures chan linkFailureReport
591

592
        // chanCloseMsgs is a channel that any message related to channel
593
        // closures are sent over. This includes lnwire.Shutdown message as
594
        // well as lnwire.ClosingSigned messages.
595
        chanCloseMsgs chan *closeMsg
596

597
        // remoteFeatures is the feature vector received from the peer during
598
        // the connection handshake.
599
        remoteFeatures *lnwire.FeatureVector
600

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

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

616
        // msgRouter is an instance of the msgmux.Router which is used to send
617
        // off new wire messages for handing.
618
        msgRouter fn.Option[msgmux.Router]
619

620
        // globalMsgRouter is a flag that indicates whether we have a global
621
        // msg router. If so, then we don't worry about stopping the msg router
622
        // when a peer disconnects.
623
        globalMsgRouter bool
624

625
        startReady chan struct{}
626

627
        // cg is a helper that encapsulates a wait group and quit channel and
628
        // allows contexts that either block or cancel on those depending on
629
        // the use case.
630
        cg *fn.ContextGuard
631

632
        // log is a peer-specific logging instance.
633
        log btclog.Logger
634
}
635

636
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer
637
// interface.
638
var _ lnpeer.Peer = (*Brontide)(nil)
639

640
// NewBrontide creates a new Brontide from a peer.Config struct.
641
func NewBrontide(cfg Config) *Brontide {
28✔
642
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
28✔
643

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

28✔
649
        // We'll either use the msg router instance passed in, or create a new
28✔
650
        // blank instance.
28✔
651
        msgRouter := cfg.MsgRouter.Alt(fn.Some[msgmux.Router](
28✔
652
                msgmux.NewMultiMsgRouter(),
28✔
653
        ))
28✔
654

28✔
655
        p := &Brontide{
28✔
656
                cfg:           cfg,
28✔
657
                activeSignal:  make(chan struct{}),
28✔
658
                sendQueue:     make(chan outgoingMsg),
28✔
659
                outgoingQueue: make(chan outgoingMsg),
28✔
660
                addedChannels: &lnutils.SyncMap[lnwire.ChannelID, struct{}]{},
28✔
661
                activeChannels: &lnutils.SyncMap[
28✔
662
                        lnwire.ChannelID, *lnwallet.LightningChannel,
28✔
663
                ]{},
28✔
664
                newActiveChannel:     make(chan *newChannelMsg, 1),
28✔
665
                newPendingChannel:    make(chan *newChannelMsg, 1),
28✔
666
                removePendingChannel: make(chan *newChannelMsg),
28✔
667

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

28✔
683
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
31✔
684
                remoteAddr := cfg.Conn.RemoteAddr().String()
3✔
685
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
3✔
686
                        strings.Contains(remoteAddr, "127.0.0.1")
3✔
687
        }
3✔
688

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

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

716
                return lastSerializedBlockHeader[:]
×
717
        }
718

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

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

748
        return p
28✔
749
}
750

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

758
        // Once we've finished starting up the peer, we'll signal to other
759
        // goroutines that the they can move forward to tear down the peer, or
760
        // carry out other relevant changes.
761
        defer close(p.startReady)
6✔
762

6✔
763
        p.log.Tracef("starting with conn[%v->%v]",
6✔
764
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
6✔
765

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

777
        if len(activeChans) == 0 {
10✔
778
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
4✔
779
        }
4✔
780

781
        // Quickly check if we have any existing legacy channels with this
782
        // peer.
783
        haveLegacyChan := false
6✔
784
        for _, c := range activeChans {
11✔
785
                if c.ChanType.IsTweakless() {
10✔
786
                        continue
5✔
787
                }
788

789
                haveLegacyChan = true
3✔
790
                break
3✔
791
        }
792

793
        // Exchange local and global features, the init message should be very
794
        // first between two nodes.
795
        if err := p.sendInitMsg(haveLegacyChan); err != nil {
8✔
796
                return fmt.Errorf("unable to send init msg: %w", err)
2✔
797
        }
2✔
798

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

6✔
808
                msg, err := p.readNextMessage()
6✔
809
                if err != nil {
7✔
810
                        readErr <- err
1✔
811
                        msgChan <- nil
1✔
812
                        return
1✔
813
                }
1✔
814
                readErr <- nil
6✔
815
                msgChan <- msg
6✔
816
        }()
817

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

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

843
        // Next, load all the active channels we have with this peer,
844
        // registering them with the switch and launching the necessary
845
        // goroutines required to operate them.
846
        p.log.Debugf("Loaded %v active channels from database",
6✔
847
                len(activeChans))
6✔
848

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

860
        // Register the message router now as we may need to register some
861
        // endpoints while loading the channels below.
862
        p.msgRouter.WhenSome(func(router msgmux.Router) {
12✔
863
                router.Start(context.Background())
6✔
864
        })
6✔
865

866
        msgs, err := p.loadActiveChannels(activeChans)
6✔
867
        if err != nil {
6✔
868
                return fmt.Errorf("unable to load channels: %w", err)
×
869
        }
×
870

871
        p.startTime = time.Now()
6✔
872

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

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

890
        err = p.pingManager.Start()
6✔
891
        if err != nil {
6✔
892
                return fmt.Errorf("could not start ping manager %w", err)
×
893
        }
×
894

895
        p.cg.WgAdd(4)
6✔
896
        go p.queueHandler()
6✔
897
        go p.writeHandler()
6✔
898
        go p.channelManager()
6✔
899
        go p.readHandler()
6✔
900

6✔
901
        // Signal to any external processes that the peer is now active.
6✔
902
        close(p.activeSignal)
6✔
903

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

6✔
919
        return nil
6✔
920
}
921

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

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

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

950
// taprootShutdownAllowed returns true if both parties have negotiated the
951
// shutdown-any-segwit feature.
952
func (p *Brontide) taprootShutdownAllowed() bool {
9✔
953
        return p.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
9✔
954
                p.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
9✔
955
}
9✔
956

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

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

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

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

994
        return &chancloser.DeliveryAddrWithKey{
12✔
995
                DeliveryAddress: deliveryScript,
12✔
996
                InternalKey: fn.MapOption(
12✔
997
                        func(desc keychain.KeyDescriptor) btcec.PublicKey {
15✔
998
                                return *desc.PubKey
3✔
999
                        },
3✔
1000
                )(internalKeyDesc),
1001
        }, nil
1002
}
1003

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

6✔
1011
        // Return a slice of messages to send to the peers in case the channel
6✔
1012
        // cannot be loaded normally.
6✔
1013
        var msgs []lnwire.Message
6✔
1014

6✔
1015
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
6✔
1016

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

1037
                                err = p.cfg.AddLocalAlias(
3✔
1038
                                        aliasScid, dbChan.ShortChanID(), false,
3✔
1039
                                        false,
3✔
1040
                                )
3✔
1041
                                if err != nil {
3✔
1042
                                        return nil, err
×
1043
                                }
×
1044

1045
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
1046
                                        dbChan.FundingOutpoint,
3✔
1047
                                )
3✔
1048

3✔
1049
                                // Fetch the second commitment point to send in
3✔
1050
                                // the channel_ready message.
3✔
1051
                                second, err := dbChan.SecondCommitmentPoint()
3✔
1052
                                if err != nil {
3✔
1053
                                        return nil, err
×
1054
                                }
×
1055

1056
                                channelReadyMsg := lnwire.NewChannelReady(
3✔
1057
                                        chanID, second,
3✔
1058
                                )
3✔
1059
                                channelReadyMsg.AliasScid = &aliasScid
3✔
1060

3✔
1061
                                msgs = append(msgs, channelReadyMsg)
3✔
1062
                        }
1063

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

1075
                var chanOpts []lnwallet.ChannelOpt
5✔
1076
                p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
5✔
1077
                        chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
1078
                })
×
1079
                p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
5✔
1080
                        chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
1081
                })
×
1082
                p.cfg.AuxResolver.WhenSome(
5✔
1083
                        func(s lnwallet.AuxContractResolver) {
5✔
1084
                                chanOpts = append(
×
1085
                                        chanOpts, lnwallet.WithAuxResolver(s),
×
1086
                                )
×
1087
                        },
×
1088
                )
1089

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

1098
                chanPoint := dbChan.FundingOutpoint
5✔
1099

5✔
1100
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
5✔
1101

5✔
1102
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
5✔
1103
                        chanPoint, lnChan.IsPending())
5✔
1104

5✔
1105
                // Skip adding any permanently irreconcilable channels to the
5✔
1106
                // htlcswitch.
5✔
1107
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
5✔
1108
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
10✔
1109

5✔
1110
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
5✔
1111
                                "start.", chanPoint, dbChan.ChanStatus())
5✔
1112

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

1127
                        msgs = append(msgs, chanSync)
5✔
1128

5✔
1129
                        // Check if this channel needs to have the cooperative
5✔
1130
                        // close process restarted. If so, we'll need to send
5✔
1131
                        // the Shutdown message that is returned.
5✔
1132
                        if dbChan.HasChanStatus(
5✔
1133
                                channeldb.ChanStatusCoopBroadcasted,
5✔
1134
                        ) {
8✔
1135

3✔
1136
                                shutdownMsg, err := p.restartCoopClose(lnChan)
3✔
1137
                                if err != nil {
3✔
1138
                                        p.log.Errorf("Unable to restart "+
×
1139
                                                "coop close for channel: %v",
×
1140
                                                err)
×
1141
                                        continue
×
1142
                                }
1143

1144
                                if shutdownMsg == nil {
6✔
1145
                                        continue
3✔
1146
                                }
1147

1148
                                // Append the message to the set of messages to
1149
                                // send.
1150
                                msgs = append(msgs, shutdownMsg)
×
1151
                        }
1152

1153
                        continue
5✔
1154
                }
1155

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

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

3✔
1178
                        selfPolicy = p1
3✔
1179
                } else {
6✔
1180
                        selfPolicy = p2
3✔
1181
                }
3✔
1182

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

1196
                        inboundFee := models.NewInboundFeeFromWire(
3✔
1197
                                inboundWireFee,
3✔
1198
                        )
3✔
1199

3✔
1200
                        forwardingPolicy = &models.ForwardingPolicy{
3✔
1201
                                MinHTLCOut:    selfPolicy.MinHTLC,
3✔
1202
                                MaxHTLC:       selfPolicy.MaxHTLC,
3✔
1203
                                BaseFee:       selfPolicy.FeeBaseMSat,
3✔
1204
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
3✔
1205
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
3✔
1206

3✔
1207
                                InboundFee: inboundFee,
3✔
1208
                        }
3✔
1209
                } else {
3✔
1210
                        p.log.Warnf("Unable to find our forwarding policy "+
3✔
1211
                                "for channel %v, using default values",
3✔
1212
                                chanPoint)
3✔
1213
                        forwardingPolicy = &p.cfg.RoutingPolicy
3✔
1214
                }
3✔
1215

1216
                p.log.Tracef("Using link policy of: %v",
3✔
1217
                        spew.Sdump(forwardingPolicy))
3✔
1218

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

3✔
1228
                        continue
3✔
1229
                }
1230

1231
                shutdownInfo, err := lnChan.State().ShutdownInfo()
3✔
1232
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
3✔
1233
                        return nil, err
×
1234
                }
×
1235

1236
                isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
1237

3✔
1238
                var (
3✔
1239
                        shutdownMsg     fn.Option[lnwire.Shutdown]
3✔
1240
                        shutdownInfoErr error
3✔
1241
                )
3✔
1242
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
6✔
1243
                        // If we can use the new RBF close feature, we don't
3✔
1244
                        // need to create the legacy closer. However for taproot
3✔
1245
                        // channels, we'll continue to use the legacy closer.
3✔
1246
                        if p.rbfCoopCloseAllowed() && !isTaprootChan {
6✔
1247
                                return
3✔
1248
                        }
3✔
1249

1250
                        // Compute an ideal fee.
1251
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
1252
                                p.cfg.CoopCloseTargetConfs,
3✔
1253
                        )
3✔
1254
                        if err != nil {
3✔
1255
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1256
                                        "estimate fee: %w", err)
×
1257

×
1258
                                return
×
1259
                        }
×
1260

1261
                        addr, err := p.addrWithInternalKey(
3✔
1262
                                info.DeliveryScript.Val,
3✔
1263
                        )
3✔
1264
                        if err != nil {
3✔
1265
                                shutdownInfoErr = fmt.Errorf("unable to make "+
×
1266
                                        "delivery addr: %w", err)
×
1267
                                return
×
1268
                        }
×
1269
                        negotiateChanCloser, err := p.createChanCloser(
3✔
1270
                                lnChan, addr, feePerKw, nil,
3✔
1271
                                info.Closer(),
3✔
1272
                        )
3✔
1273
                        if err != nil {
3✔
1274
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1275
                                        "create chan closer: %w", err)
×
1276

×
1277
                                return
×
1278
                        }
×
1279

1280
                        chanID := lnwire.NewChanIDFromOutPoint(
3✔
1281
                                lnChan.State().FundingOutpoint,
3✔
1282
                        )
3✔
1283

3✔
1284
                        p.activeChanCloses.Store(chanID, makeNegotiateCloser(
3✔
1285
                                negotiateChanCloser,
3✔
1286
                        ))
3✔
1287

3✔
1288
                        // Create the Shutdown message.
3✔
1289
                        shutdown, err := negotiateChanCloser.ShutdownChan()
3✔
1290
                        if err != nil {
3✔
1291
                                p.activeChanCloses.Delete(chanID)
×
1292
                                shutdownInfoErr = err
×
1293

×
1294
                                return
×
1295
                        }
×
1296

1297
                        shutdownMsg = fn.Some(*shutdown)
3✔
1298
                })
1299
                if shutdownInfoErr != nil {
3✔
1300
                        return nil, shutdownInfoErr
×
1301
                }
×
1302

1303
                // Subscribe to the set of on-chain events for this channel.
1304
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
3✔
1305
                        chanPoint,
3✔
1306
                )
3✔
1307
                if err != nil {
3✔
1308
                        return nil, err
×
1309
                }
×
1310

1311
                err = p.addLink(
3✔
1312
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
3✔
1313
                        true, shutdownMsg,
3✔
1314
                )
3✔
1315
                if err != nil {
3✔
1316
                        return nil, fmt.Errorf("unable to add link %v to "+
×
1317
                                "switch: %v", chanPoint, err)
×
1318
                }
×
1319

1320
                p.activeChannels.Store(chanID, lnChan)
3✔
1321

3✔
1322
                // We're using the old co-op close, so we don't need to init
3✔
1323
                // the new RBF chan closer. If we have a taproot chan, then
3✔
1324
                // we'll also use the legacy type, so we don't need to make the
3✔
1325
                // new closer.
3✔
1326
                if !p.rbfCoopCloseAllowed() || isTaprootChan {
6✔
1327
                        continue
3✔
1328
                }
1329

1330
                // Now that the link has been added above, we'll also init an
1331
                // RBF chan closer for this channel, but only if the new close
1332
                // feature is negotiated.
1333
                //
1334
                // Creating this here ensures that any shutdown messages sent
1335
                // will be automatically routed by the msg router.
1336
                if _, err := p.initRbfChanCloser(lnChan); err != nil {
3✔
1337
                        p.activeChanCloses.Delete(chanID)
×
1338

×
1339
                        return nil, fmt.Errorf("unable to init RBF chan "+
×
1340
                                "closer during peer connect: %w", err)
×
1341
                }
×
1342

1343
                // If the shutdown info isn't blank, then we should kick things
1344
                // off by sending a shutdown message to the remote party to
1345
                // continue the old shutdown flow.
1346
                restartShutdown := func(s channeldb.ShutdownInfo) error {
6✔
1347
                        return p.startRbfChanCloser(
3✔
1348
                                newRestartShutdownInit(s),
3✔
1349
                                lnChan.ChannelPoint(),
3✔
1350
                        )
3✔
1351
                }
3✔
1352
                err = fn.MapOptionZ(shutdownInfo, restartShutdown)
3✔
1353
                if err != nil {
3✔
1354
                        return nil, fmt.Errorf("unable to start RBF "+
×
1355
                                "chan closer: %w", err)
×
1356
                }
×
1357
        }
1358

1359
        return msgs, nil
6✔
1360
}
1361

1362
// addLink creates and adds a new ChannelLink from the specified channel.
1363
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1364
        lnChan *lnwallet.LightningChannel,
1365
        forwardingPolicy *models.ForwardingPolicy,
1366
        chainEvents *contractcourt.ChainEventSubscription,
1367
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
3✔
1368

3✔
1369
        // onChannelFailure will be called by the link in case the channel
3✔
1370
        // fails for some reason.
3✔
1371
        onChannelFailure := func(chanID lnwire.ChannelID,
3✔
1372
                shortChanID lnwire.ShortChannelID,
3✔
1373
                linkErr htlcswitch.LinkFailureError) {
6✔
1374

3✔
1375
                failure := linkFailureReport{
3✔
1376
                        chanPoint:   *chanPoint,
3✔
1377
                        chanID:      chanID,
3✔
1378
                        shortChanID: shortChanID,
3✔
1379
                        linkErr:     linkErr,
3✔
1380
                }
3✔
1381

3✔
1382
                select {
3✔
1383
                case p.linkFailures <- failure:
3✔
1384
                case <-p.cg.Done():
×
1385
                case <-p.cfg.Quit:
×
1386
                }
1387
        }
1388

1389
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
6✔
1390
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
3✔
1391
        }
3✔
1392

1393
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
6✔
1394
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
3✔
1395
        }
3✔
1396

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

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

3✔
1452
        // With the channel link created, we'll now notify the htlc switch so
3✔
1453
        // this channel can be used to dispatch local payments and also
3✔
1454
        // passively forward payments.
3✔
1455
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
3✔
1456
}
1457

1458
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1459
// one confirmed public channel exists with them.
1460
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
6✔
1461
        defer p.cg.WgDone()
6✔
1462

6✔
1463
        hasConfirmedPublicChan := false
6✔
1464
        for _, channel := range channels {
11✔
1465
                if channel.IsPending {
8✔
1466
                        continue
3✔
1467
                }
1468
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
10✔
1469
                        continue
5✔
1470
                }
1471

1472
                hasConfirmedPublicChan = true
3✔
1473
                break
3✔
1474
        }
1475
        if !hasConfirmedPublicChan {
12✔
1476
                return
6✔
1477
        }
6✔
1478

1479
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
3✔
1480
        if err != nil {
3✔
1481
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1482
                return
×
1483
        }
×
1484

1485
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
3✔
1486
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1487
        }
×
1488
}
1489

1490
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1491
// have any active channels with them.
1492
func (p *Brontide) maybeSendChannelUpdates() {
6✔
1493
        defer p.cg.WgDone()
6✔
1494

6✔
1495
        // If we don't have any active channels, then we can exit early.
6✔
1496
        if p.activeChannels.Len() == 0 {
10✔
1497
                return
4✔
1498
        }
4✔
1499

1500
        maybeSendUpd := func(cid lnwire.ChannelID,
5✔
1501
                lnChan *lnwallet.LightningChannel) error {
10✔
1502

5✔
1503
                // Nil channels are pending, so we'll skip them.
5✔
1504
                if lnChan == nil {
8✔
1505
                        return nil
3✔
1506
                }
3✔
1507

1508
                dbChan := lnChan.State()
5✔
1509
                scid := func() lnwire.ShortChannelID {
10✔
1510
                        switch {
5✔
1511
                        // Otherwise if it's a zero conf channel and confirmed,
1512
                        // then we need to use the "real" scid.
1513
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
3✔
1514
                                return dbChan.ZeroConfRealScid()
3✔
1515

1516
                        // Otherwise, we can use the normal scid.
1517
                        default:
5✔
1518
                                return dbChan.ShortChanID()
5✔
1519
                        }
1520
                }()
1521

1522
                // Now that we know the channel is in a good state, we'll try
1523
                // to fetch the update to send to the remote peer. If the
1524
                // channel is pending, and not a zero conf channel, we'll get
1525
                // an error here which we'll ignore.
1526
                chanUpd, err := p.cfg.FetchLastChanUpdate(scid)
5✔
1527
                if err != nil {
8✔
1528
                        p.log.Debugf("Unable to fetch channel update for "+
3✔
1529
                                "ChannelPoint(%v), scid=%v: %v",
3✔
1530
                                dbChan.FundingOutpoint, dbChan.ShortChanID, err)
3✔
1531

3✔
1532
                        return nil
3✔
1533
                }
3✔
1534

1535
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
5✔
1536
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
5✔
1537

5✔
1538
                // We'll send it as a normal message instead of using the lazy
5✔
1539
                // queue to prioritize transmission of the fresh update.
5✔
1540
                if err := p.SendMessage(false, chanUpd); err != nil {
5✔
1541
                        err := fmt.Errorf("unable to send channel update for "+
×
1542
                                "ChannelPoint(%v), scid=%v: %w",
×
1543
                                dbChan.FundingOutpoint, dbChan.ShortChanID(),
×
1544
                                err)
×
1545
                        p.log.Errorf(err.Error())
×
1546

×
1547
                        return err
×
1548
                }
×
1549

1550
                return nil
5✔
1551
        }
1552

1553
        p.activeChannels.ForEach(maybeSendUpd)
5✔
1554
}
1555

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

1573
        select {
3✔
1574
        case <-ready:
3✔
1575
        case <-p.cg.Done():
3✔
1576
        }
1577

1578
        p.cg.WgWait()
3✔
1579
}
1580

1581
// Disconnect terminates the connection with the remote peer. Additionally, a
1582
// signal is sent to the server and htlcSwitch indicating the resources
1583
// allocated to the peer can now be cleaned up.
1584
func (p *Brontide) Disconnect(reason error) {
3✔
1585
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
6✔
1586
                return
3✔
1587
        }
3✔
1588

1589
        // Make sure initialization has completed before we try to tear things
1590
        // down.
1591
        //
1592
        // NOTE: We only read the `startReady` chan if the peer has been
1593
        // started, otherwise we will skip reading it as this chan won't be
1594
        // closed, hence blocks forever.
1595
        if atomic.LoadInt32(&p.started) == 1 {
6✔
1596
                p.log.Debugf("Started, waiting on startReady signal")
3✔
1597

3✔
1598
                select {
3✔
1599
                case <-p.startReady:
3✔
1600
                case <-p.cg.Done():
×
1601
                        return
×
1602
                }
1603
        }
1604

1605
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
3✔
1606
        p.storeError(err)
3✔
1607

3✔
1608
        p.log.Infof(err.Error())
3✔
1609

3✔
1610
        // Stop PingManager before closing TCP connection.
3✔
1611
        p.pingManager.Stop()
3✔
1612

3✔
1613
        // Ensure that the TCP connection is properly closed before continuing.
3✔
1614
        p.cfg.Conn.Close()
3✔
1615

3✔
1616
        p.cg.Quit()
3✔
1617

3✔
1618
        // If our msg router isn't global (local to this instance), then we'll
3✔
1619
        // stop it. Otherwise, we'll leave it running.
3✔
1620
        if !p.globalMsgRouter {
6✔
1621
                p.msgRouter.WhenSome(func(router msgmux.Router) {
6✔
1622
                        router.Stop()
3✔
1623
                })
3✔
1624
        }
1625
}
1626

1627
// String returns the string representation of this peer.
1628
func (p *Brontide) String() string {
3✔
1629
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
3✔
1630
}
3✔
1631

1632
// readNextMessage reads, and returns the next message on the wire along with
1633
// any additional raw payload.
1634
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
10✔
1635
        noiseConn := p.cfg.Conn
10✔
1636
        err := noiseConn.SetReadDeadline(time.Time{})
10✔
1637
        if err != nil {
10✔
1638
                return nil, err
×
1639
        }
×
1640

1641
        pktLen, err := noiseConn.ReadNextHeader()
10✔
1642
        if err != nil {
13✔
1643
                return nil, fmt.Errorf("read next header: %w", err)
3✔
1644
        }
3✔
1645

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

1668
                // The ReadNextBody method will actually end up re-using the
1669
                // buffer, so within this closure, we can continue to use
1670
                // rawMsg as it's just a slice into the buf from the buffer
1671
                // pool.
1672
                rawMsg, readErr := noiseConn.ReadNextBody(buf[:pktLen])
7✔
1673
                if readErr != nil {
7✔
1674
                        return fmt.Errorf("read next body: %w", readErr)
×
1675
                }
×
1676
                msgLen = uint64(len(rawMsg))
7✔
1677

7✔
1678
                // Next, create a new io.Reader implementation from the raw
7✔
1679
                // message, and use this to decode the message directly from.
7✔
1680
                msgReader := bytes.NewReader(rawMsg)
7✔
1681
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
7✔
1682
                if err != nil {
10✔
1683
                        return err
3✔
1684
                }
3✔
1685

1686
                // At this point, rawMsg and buf will be returned back to the
1687
                // buffer pool for re-use.
1688
                return nil
7✔
1689
        })
1690
        atomic.AddUint64(&p.bytesReceived, msgLen)
7✔
1691
        if err != nil {
10✔
1692
                return nil, err
3✔
1693
        }
3✔
1694

1695
        p.logWireMessage(nextMsg, true)
7✔
1696

7✔
1697
        return nextMsg, nil
7✔
1698
}
1699

1700
// msgStream implements a goroutine-safe, in-order stream of messages to be
1701
// delivered via closure to a receiver. These messages MUST be in order due to
1702
// the nature of the lightning channel commitment and gossiper state machines.
1703
// TODO(conner): use stream handler interface to abstract out stream
1704
// state/logging.
1705
type msgStream struct {
1706
        streamShutdown int32 // To be used atomically.
1707

1708
        peer *Brontide
1709

1710
        apply func(lnwire.Message)
1711

1712
        startMsg string
1713
        stopMsg  string
1714

1715
        msgCond *sync.Cond
1716
        msgs    []lnwire.Message
1717

1718
        mtx sync.Mutex
1719

1720
        producerSema chan struct{}
1721

1722
        wg   sync.WaitGroup
1723
        quit chan struct{}
1724
}
1725

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

6✔
1734
        stream := &msgStream{
6✔
1735
                peer:         p,
6✔
1736
                apply:        apply,
6✔
1737
                startMsg:     startMsg,
6✔
1738
                stopMsg:      stopMsg,
6✔
1739
                producerSema: make(chan struct{}, bufSize),
6✔
1740
                quit:         make(chan struct{}),
6✔
1741
        }
6✔
1742
        stream.msgCond = sync.NewCond(&stream.mtx)
6✔
1743

6✔
1744
        // Before we return the active stream, we'll populate the producer's
6✔
1745
        // semaphore channel. We'll use this to ensure that the producer won't
6✔
1746
        // attempt to allocate memory in the queue for an item until it has
6✔
1747
        // sufficient extra space.
6✔
1748
        for i := uint32(0); i < bufSize; i++ {
24✔
1749
                stream.producerSema <- struct{}{}
18✔
1750
        }
18✔
1751

1752
        return stream
6✔
1753
}
1754

1755
// Start starts the chanMsgStream.
1756
func (ms *msgStream) Start() {
6✔
1757
        ms.wg.Add(1)
6✔
1758
        go ms.msgConsumer()
6✔
1759
}
6✔
1760

1761
// Stop stops the chanMsgStream.
1762
func (ms *msgStream) Stop() {
3✔
1763
        // TODO(roasbeef): signal too?
3✔
1764

3✔
1765
        close(ms.quit)
3✔
1766

3✔
1767
        // Now that we've closed the channel, we'll repeatedly signal the msg
3✔
1768
        // consumer until we've detected that it has exited.
3✔
1769
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
6✔
1770
                ms.msgCond.Signal()
3✔
1771
                time.Sleep(time.Millisecond * 100)
3✔
1772
        }
3✔
1773

1774
        ms.wg.Wait()
3✔
1775
}
1776

1777
// msgConsumer is the main goroutine that streams messages from the peer's
1778
// readHandler directly to the target channel.
1779
func (ms *msgStream) msgConsumer() {
6✔
1780
        defer ms.wg.Done()
6✔
1781
        defer peerLog.Tracef(ms.stopMsg)
6✔
1782
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
6✔
1783

6✔
1784
        peerLog.Tracef(ms.startMsg)
6✔
1785

6✔
1786
        for {
12✔
1787
                // First, we'll check our condition. If the queue of messages
6✔
1788
                // is empty, then we'll wait until a new item is added.
6✔
1789
                ms.msgCond.L.Lock()
6✔
1790
                for len(ms.msgs) == 0 {
12✔
1791
                        ms.msgCond.Wait()
6✔
1792

6✔
1793
                        // If we woke up in order to exit, then we'll do so.
6✔
1794
                        // Otherwise, we'll check the message queue for any new
6✔
1795
                        // items.
6✔
1796
                        select {
6✔
1797
                        case <-ms.peer.cg.Done():
3✔
1798
                                ms.msgCond.L.Unlock()
3✔
1799
                                return
3✔
1800
                        case <-ms.quit:
3✔
1801
                                ms.msgCond.L.Unlock()
3✔
1802
                                return
3✔
1803
                        default:
3✔
1804
                        }
1805
                }
1806

1807
                // Grab the message off the front of the queue, shifting the
1808
                // slice's reference down one in order to remove the message
1809
                // from the queue.
1810
                msg := ms.msgs[0]
3✔
1811
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
3✔
1812
                ms.msgs = ms.msgs[1:]
3✔
1813

3✔
1814
                ms.msgCond.L.Unlock()
3✔
1815

3✔
1816
                ms.apply(msg)
3✔
1817

3✔
1818
                // We've just successfully processed an item, so we'll signal
3✔
1819
                // to the producer that a new slot in the buffer. We'll use
3✔
1820
                // this to bound the size of the buffer to avoid allowing it to
3✔
1821
                // grow indefinitely.
3✔
1822
                select {
3✔
1823
                case ms.producerSema <- struct{}{}:
3✔
1824
                case <-ms.peer.cg.Done():
3✔
1825
                        return
3✔
1826
                case <-ms.quit:
3✔
1827
                        return
3✔
1828
                }
1829
        }
1830
}
1831

1832
// AddMsg adds a new message to the msgStream. This function is safe for
1833
// concurrent access.
1834
func (ms *msgStream) AddMsg(msg lnwire.Message) {
3✔
1835
        // First, we'll attempt to receive from the producerSema struct. This
3✔
1836
        // acts as a semaphore to prevent us from indefinitely buffering
3✔
1837
        // incoming items from the wire. Either the msg queue isn't full, and
3✔
1838
        // we'll not block, or the queue is full, and we'll block until either
3✔
1839
        // we're signalled to quit, or a slot is freed up.
3✔
1840
        select {
3✔
1841
        case <-ms.producerSema:
3✔
1842
        case <-ms.peer.cg.Done():
×
1843
                return
×
1844
        case <-ms.quit:
×
1845
                return
×
1846
        }
1847

1848
        // Next, we'll lock the condition, and add the message to the end of
1849
        // the message queue.
1850
        ms.msgCond.L.Lock()
3✔
1851
        ms.msgs = append(ms.msgs, msg)
3✔
1852
        ms.msgCond.L.Unlock()
3✔
1853

3✔
1854
        // With the message added, we signal to the msgConsumer that there are
3✔
1855
        // additional messages to consume.
3✔
1856
        ms.msgCond.Signal()
3✔
1857
}
1858

1859
// waitUntilLinkActive waits until the target link is active and returns a
1860
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1861
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1862
func waitUntilLinkActive(p *Brontide,
1863
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
3✔
1864

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

3✔
1867
        // Subscribe to receive channel events.
3✔
1868
        //
3✔
1869
        // NOTE: If the link is already active by SubscribeChannelEvents, then
3✔
1870
        // GetLink will retrieve the link and we can send messages. If the link
3✔
1871
        // becomes active between SubscribeChannelEvents and GetLink, then GetLink
3✔
1872
        // will retrieve the link. If the link becomes active after GetLink, then
3✔
1873
        // we will get an ActiveLinkEvent notification and retrieve the link. If
3✔
1874
        // the call to GetLink is before SubscribeChannelEvents, however, there
3✔
1875
        // will be a race condition.
3✔
1876
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
3✔
1877
        if err != nil {
6✔
1878
                // If we have a non-nil error, then the server is shutting down and we
3✔
1879
                // can exit here and return nil. This means no message will be delivered
3✔
1880
                // to the link.
3✔
1881
                return nil
3✔
1882
        }
3✔
1883
        defer sub.Cancel()
3✔
1884

3✔
1885
        // The link may already be active by this point, and we may have missed the
3✔
1886
        // ActiveLinkEvent. Check if the link exists.
3✔
1887
        link := p.fetchLinkFromKeyAndCid(cid)
3✔
1888
        if link != nil {
6✔
1889
                return link
3✔
1890
        }
3✔
1891

1892
        // If the link is nil, we must wait for it to be active.
1893
        for {
6✔
1894
                select {
3✔
1895
                // A new event has been sent by the ChannelNotifier. We first check
1896
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1897
                // that the event is for this channel. Otherwise, we discard the
1898
                // message.
1899
                case e := <-sub.Updates():
3✔
1900
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
3✔
1901
                        if !ok {
6✔
1902
                                // Ignore this notification.
3✔
1903
                                continue
3✔
1904
                        }
1905

1906
                        chanPoint := event.ChannelPoint
3✔
1907

3✔
1908
                        // Check whether the retrieved chanPoint matches the target
3✔
1909
                        // channel id.
3✔
1910
                        if !cid.IsChanPoint(chanPoint) {
3✔
1911
                                continue
×
1912
                        }
1913

1914
                        // The link shouldn't be nil as we received an
1915
                        // ActiveLinkEvent. If it is nil, we return nil and the
1916
                        // calling function should catch it.
1917
                        return p.fetchLinkFromKeyAndCid(cid)
3✔
1918

1919
                case <-p.cg.Done():
3✔
1920
                        return nil
3✔
1921
                }
1922
        }
1923
}
1924

1925
// newChanMsgStream is used to create a msgStream between the peer and
1926
// particular channel link in the htlcswitch. We utilize additional
1927
// synchronization with the fundingManager to ensure we don't attempt to
1928
// dispatch a message to a channel before it is fully active. A reference to the
1929
// channel this stream forwards to is held in scope to prevent unnecessary
1930
// lookups.
1931
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
3✔
1932
        var chanLink htlcswitch.ChannelUpdateHandler
3✔
1933

3✔
1934
        apply := func(msg lnwire.Message) {
6✔
1935
                // This check is fine because if the link no longer exists, it will
3✔
1936
                // be removed from the activeChannels map and subsequent messages
3✔
1937
                // shouldn't reach the chan msg stream.
3✔
1938
                if chanLink == nil {
6✔
1939
                        chanLink = waitUntilLinkActive(p, cid)
3✔
1940

3✔
1941
                        // If the link is still not active and the calling function
3✔
1942
                        // errored out, just return.
3✔
1943
                        if chanLink == nil {
6✔
1944
                                p.log.Warnf("Link=%v is not active", cid)
3✔
1945
                                return
3✔
1946
                        }
3✔
1947
                }
1948

1949
                // In order to avoid unnecessarily delivering message
1950
                // as the peer is exiting, we'll check quickly to see
1951
                // if we need to exit.
1952
                select {
3✔
1953
                case <-p.cg.Done():
×
1954
                        return
×
1955
                default:
3✔
1956
                }
1957

1958
                chanLink.HandleChannelUpdate(msg)
3✔
1959
        }
1960

1961
        return newMsgStream(p,
3✔
1962
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
3✔
1963
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
3✔
1964
                msgStreamSize,
3✔
1965
                apply,
3✔
1966
        )
3✔
1967
}
1968

1969
// newDiscMsgStream is used to setup a msgStream between the peer and the
1970
// authenticated gossiper. This stream should be used to forward all remote
1971
// channel announcements.
1972
func newDiscMsgStream(p *Brontide) *msgStream {
6✔
1973
        apply := func(msg lnwire.Message) {
9✔
1974
                // TODO(yy): `ProcessRemoteAnnouncement` returns an error chan
3✔
1975
                // and we need to process it.
3✔
1976
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(msg, p)
3✔
1977
        }
3✔
1978

1979
        return newMsgStream(
6✔
1980
                p,
6✔
1981
                "Update stream for gossiper created",
6✔
1982
                "Update stream for gossiper exited",
6✔
1983
                msgStreamSize,
6✔
1984
                apply,
6✔
1985
        )
6✔
1986
}
1987

1988
// readHandler is responsible for reading messages off the wire in series, then
1989
// properly dispatching the handling of the message to the proper subsystem.
1990
//
1991
// NOTE: This method MUST be run as a goroutine.
1992
func (p *Brontide) readHandler() {
6✔
1993
        defer p.cg.WgDone()
6✔
1994

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

6✔
2003
        discStream := newDiscMsgStream(p)
6✔
2004
        discStream.Start()
6✔
2005
        defer discStream.Stop()
6✔
2006

6✔
2007
out:
6✔
2008
        for atomic.LoadInt32(&p.disconnect) == 0 {
13✔
2009
                nextMsg, err := p.readNextMessage()
7✔
2010
                if err != nil {
10✔
2011
                        p.log.Infof("unable to read message from peer: %v", err)
3✔
2012

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

2026
                        // If they sent us an address type that we don't yet
2027
                        // know of, then this isn't a wire error, so we'll
2028
                        // simply continue parsing the remainder of their
2029
                        // messages.
2030
                        case *lnwire.ErrUnknownAddrType:
×
2031
                                p.storeError(e)
×
2032
                                continue
×
2033

2034
                        // If the NodeAnnouncement has an invalid alias, then
2035
                        // we'll log that error above and continue so we can
2036
                        // continue to read messages from the peer. We do not
2037
                        // store this error because it is of little debugging
2038
                        // value.
2039
                        case *lnwire.ErrInvalidNodeAlias:
×
2040
                                continue
×
2041

2042
                        // If the error we encountered wasn't just a message we
2043
                        // didn't recognize, then we'll stop all processing as
2044
                        // this is a fatal error.
2045
                        default:
3✔
2046
                                p.log.Errorf("read next msg err: %v", err)
3✔
2047

3✔
2048
                                break out
3✔
2049
                        }
2050
                }
2051

2052
                // Reset the ticker to delay sending the Ping. As long as we are
2053
                // receiving a message here, we know for sure the connection is
2054
                // alive, thus we can delay firing pings to check for the
2055
                // liveness.
2056
                p.pingManager.ResetPingTicker()
4✔
2057

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

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

2074
                var (
4✔
2075
                        targetChan   lnwire.ChannelID
4✔
2076
                        isLinkUpdate bool
4✔
2077
                )
4✔
2078

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

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

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

2095
                case *lnwire.OpenChannel,
2096
                        *lnwire.AcceptChannel,
2097
                        *lnwire.FundingCreated,
2098
                        *lnwire.FundingSigned,
2099
                        *lnwire.ChannelReady:
3✔
2100

3✔
2101
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2102

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

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

2120
                case *lnwire.Error:
3✔
2121
                        targetChan = msg.ChanID
3✔
2122
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
3✔
2123

2124
                case *lnwire.ChannelReestablish:
3✔
2125
                        targetChan = msg.ChanID
3✔
2126
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2127

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

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

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

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

3✔
2170
                        discStream.AddMsg(msg)
3✔
2171

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

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

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

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

2196
        p.Disconnect(errors.New("read handler closed"))
3✔
2197
}
2198

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

2207
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
4✔
2208
}
2209

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

2221
        // Return false if the channel is unknown.
2222
        channel, ok := p.activeChannels.Load(chanID)
3✔
2223
        if !ok {
3✔
2224
                return false
×
2225
        }
×
2226

2227
        // During startup, we will use a nil value to mark a pending channel
2228
        // that's loaded from disk.
2229
        return channel == nil
3✔
2230
}
2231

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

11✔
2241
        return channel != nil
11✔
2242
}
11✔
2243

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

2253
        return channel == nil
6✔
2254
}
2255

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

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

3✔
2270
        p.activeChannels.Range(func(_ lnwire.ChannelID,
3✔
2271
                channel *lnwallet.LightningChannel) bool {
6✔
2272

3✔
2273
                // Pending channels will be nil in the activeChannels map.
3✔
2274
                if channel == nil {
6✔
2275
                        // Return true to continue the iteration.
3✔
2276
                        return true
3✔
2277
                }
3✔
2278

2279
                haveChannels = true
3✔
2280

3✔
2281
                // Return false to break the iteration.
3✔
2282
                return false
3✔
2283
        })
2284

2285
        // If we do not have any active channels with the peer, we do not store
2286
        // errors as a dos mitigation.
2287
        if !haveChannels {
6✔
2288
                p.log.Trace("no channels with peer, not storing err")
3✔
2289
                return
3✔
2290
        }
3✔
2291

2292
        p.cfg.ErrorBuffer.Add(
3✔
2293
                &TimestampedError{Timestamp: time.Now(), Error: err},
3✔
2294
        )
3✔
2295
}
2296

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

3✔
2306
        if errMsg, ok := msg.(*lnwire.Error); ok {
6✔
2307
                p.storeError(errMsg)
3✔
2308
        }
3✔
2309

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

2318
                return false
×
2319

2320
        // If the channel ID for the message corresponds to a pending channel,
2321
        // then the funding manager will handle it.
2322
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
3✔
2323
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2324
                return false
3✔
2325

2326
        // If not we hand the message to the channel link for this channel.
2327
        case p.isActiveChannel(chanID):
3✔
2328
                return true
3✔
2329

2330
        default:
3✔
2331
                return false
3✔
2332
        }
2333
}
2334

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

2344
        case *lnwire.OpenChannel:
3✔
2345
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
3✔
2346
                        "push_amt=%v, reserve=%v, flags=%v",
3✔
2347
                        msg.PendingChannelID[:], msg.ChainHash,
3✔
2348
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
3✔
2349
                        msg.ChannelReserve, msg.ChannelFlags)
3✔
2350

2351
        case *lnwire.AcceptChannel:
3✔
2352
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
3✔
2353
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
3✔
2354
                        msg.MinAcceptDepth)
3✔
2355

2356
        case *lnwire.FundingCreated:
3✔
2357
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
3✔
2358
                        msg.PendingChannelID[:], msg.FundingPoint)
3✔
2359

2360
        case *lnwire.FundingSigned:
3✔
2361
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
3✔
2362

2363
        case *lnwire.ChannelReady:
3✔
2364
                return fmt.Sprintf("chan_id=%v, next_point=%x",
3✔
2365
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
3✔
2366

2367
        case *lnwire.Shutdown:
3✔
2368
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
3✔
2369
                        msg.Address[:])
3✔
2370

2371
        case *lnwire.ClosingComplete:
3✔
2372
                return fmt.Sprintf("chan_id=%v, fee_sat=%v, locktime=%v",
3✔
2373
                        msg.ChannelID, msg.FeeSatoshis, msg.LockTime)
3✔
2374

2375
        case *lnwire.ClosingSig:
3✔
2376
                return fmt.Sprintf("chan_id=%v", msg.ChannelID)
3✔
2377

2378
        case *lnwire.ClosingSigned:
3✔
2379
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
3✔
2380
                        msg.FeeSatoshis)
3✔
2381

2382
        case *lnwire.UpdateAddHTLC:
3✔
2383
                var blindingPoint []byte
3✔
2384
                msg.BlindingPoint.WhenSome(
3✔
2385
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
3✔
2386
                                *btcec.PublicKey]) {
6✔
2387

3✔
2388
                                blindingPoint = b.Val.SerializeCompressed()
3✔
2389
                        },
3✔
2390
                )
2391

2392
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
3✔
2393
                        "hash=%x, blinding_point=%x, custom_records=%v",
3✔
2394
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
3✔
2395
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
3✔
2396

2397
        case *lnwire.UpdateFailHTLC:
3✔
2398
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
3✔
2399
                        msg.ID, msg.Reason)
3✔
2400

2401
        case *lnwire.UpdateFulfillHTLC:
3✔
2402
                return fmt.Sprintf("chan_id=%v, id=%v, preimage=%x, "+
3✔
2403
                        "custom_records=%v", msg.ChanID, msg.ID,
3✔
2404
                        msg.PaymentPreimage[:], msg.CustomRecords)
3✔
2405

2406
        case *lnwire.CommitSig:
3✔
2407
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
3✔
2408
                        len(msg.HtlcSigs))
3✔
2409

2410
        case *lnwire.RevokeAndAck:
3✔
2411
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
3✔
2412
                        msg.ChanID, msg.Revocation[:],
3✔
2413
                        msg.NextRevocationKey.SerializeCompressed())
3✔
2414

2415
        case *lnwire.UpdateFailMalformedHTLC:
3✔
2416
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
3✔
2417
                        msg.ChanID, msg.ID, msg.FailureCode)
3✔
2418

2419
        case *lnwire.Warning:
×
2420
                return fmt.Sprintf("%v", msg.Warning())
×
2421

2422
        case *lnwire.Error:
3✔
2423
                return fmt.Sprintf("%v", msg.Error())
3✔
2424

2425
        case *lnwire.AnnounceSignatures1:
3✔
2426
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
3✔
2427
                        msg.ShortChannelID.ToUint64())
3✔
2428

2429
        case *lnwire.ChannelAnnouncement1:
3✔
2430
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
3✔
2431
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
3✔
2432

2433
        case *lnwire.ChannelUpdate1:
3✔
2434
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
3✔
2435
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
3✔
2436
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
3✔
2437
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
3✔
2438

2439
        case *lnwire.NodeAnnouncement:
3✔
2440
                return fmt.Sprintf("node=%x, update_time=%v",
3✔
2441
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
3✔
2442

2443
        case *lnwire.Ping:
×
2444
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
2445

2446
        case *lnwire.Pong:
×
2447
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
×
2448

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

2453
        case *lnwire.ChannelReestablish:
3✔
2454
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
3✔
2455
                        "remote_tail_height=%v", msg.ChanID,
3✔
2456
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
3✔
2457

2458
        case *lnwire.ReplyShortChanIDsEnd:
3✔
2459
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
3✔
2460
                        msg.Complete)
3✔
2461

2462
        case *lnwire.ReplyChannelRange:
3✔
2463
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
3✔
2464
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
3✔
2465
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
3✔
2466
                        msg.EncodingType)
3✔
2467

2468
        case *lnwire.QueryShortChanIDs:
3✔
2469
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
3✔
2470
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
3✔
2471

2472
        case *lnwire.QueryChannelRange:
3✔
2473
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
3✔
2474
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
3✔
2475
                        msg.LastBlockHeight())
3✔
2476

2477
        case *lnwire.GossipTimestampRange:
3✔
2478
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
3✔
2479
                        "stamp_range=%v", msg.ChainHash,
3✔
2480
                        time.Unix(int64(msg.FirstTimestamp), 0),
3✔
2481
                        msg.TimestampRange)
3✔
2482

2483
        case *lnwire.Stfu:
3✔
2484
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
3✔
2485
                        msg.Initiator)
3✔
2486

2487
        case *lnwire.Custom:
3✔
2488
                return fmt.Sprintf("type=%d", msg.Type)
3✔
2489
        }
2490

2491
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2492
}
2493

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

2505
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
23✔
2506
                // Debug summary of message.
3✔
2507
                summary := messageSummary(msg)
3✔
2508
                if len(summary) > 0 {
6✔
2509
                        summary = "(" + summary + ")"
3✔
2510
                }
3✔
2511

2512
                preposition := "to"
3✔
2513
                if read {
6✔
2514
                        preposition = "from"
3✔
2515
                }
3✔
2516

2517
                var msgType string
3✔
2518
                if msg.MsgType() < lnwire.CustomTypeStart {
6✔
2519
                        msgType = msg.MsgType().String()
3✔
2520
                } else {
6✔
2521
                        msgType = "custom"
3✔
2522
                }
3✔
2523

2524
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
3✔
2525
                        msgType, summary, preposition, p)
3✔
2526
        }))
2527

2528
        prefix := "readMessage from peer"
20✔
2529
        if !read {
36✔
2530
                prefix = "writeMessage to peer"
16✔
2531
        }
16✔
2532

2533
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
20✔
2534
}
2535

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

2553
        noiseConn := p.cfg.Conn
16✔
2554

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

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

16✔
2571
                // Record the number of bytes written on the wire, if any.
16✔
2572
                if n > 0 {
19✔
2573
                        atomic.AddUint64(&p.bytesSent, uint64(n))
3✔
2574
                }
3✔
2575

2576
                return err
16✔
2577
        }
2578

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

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

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

2606
        return flushMsg()
16✔
2607
}
2608

2609
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2610
// queue, and writing them out to the wire. This goroutine coordinates with the
2611
// queueHandler in order to ensure the incoming message queue is quickly
2612
// drained.
2613
//
2614
// NOTE: This method MUST be run as a goroutine.
2615
func (p *Brontide) writeHandler() {
6✔
2616
        var exitErr error
6✔
2617

6✔
2618
        // Create a timer to time out the write. We create it here to avoid
6✔
2619
        // allocations in the loop below.
6✔
2620
        flushTimer := time.NewTimer(writeFlushTimeout)
6✔
2621

6✔
2622
out:
6✔
2623
        for {
16✔
2624
                select {
10✔
2625
                case outMsg := <-p.sendQueue:
7✔
2626
                        // Reset the timeout.
7✔
2627
                        flushTimer.Reset(writeFlushTimeout)
7✔
2628

7✔
2629
                        // Record the time at which we first attempt to send the
7✔
2630
                        // message.
7✔
2631
                        startTime := time.Now()
7✔
2632

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

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

×
NEW
2654
                                // Check whether the flushing has already timed
×
NEW
2655
                                // out. If so, we will exit and disconnect the
×
NEW
2656
                                // peer with a timeout error.
×
2657
                                select {
×
NEW
2658
                                case <-flushTimer.C:
×
NEW
2659
                                        exitErr = errors.New("write timeout")
×
NEW
2660

×
NEW
2661
                                        break out
×
2662

UNCOV
2663
                                default:
×
2664
                                }
2665

NEW
2666
                                goto retry
×
2667
                        }
2668

2669
                        // Reset the ticker to delay sending the Ping. Since
2670
                        // we've successfully wriiten a msg to the connection,
2671
                        // we know for sure the connection is alive, thus we can
2672
                        // delay firing pings to check for the liveness.
2673
                        //
2674
                        // NOTE: This means if the connection is idle, the
2675
                        // interval of pings is not strictly one minute as we
2676
                        // will reset it here after a successful write. This
2677
                        // offset should be negligible if the connection is
2678
                        // healthy.
2679
                        p.pingManager.ResetPingTicker()
7✔
2680

7✔
2681
                        // If the peer requested a synchronous write, respond
7✔
2682
                        // with the error.
7✔
2683
                        if outMsg.errChan != nil {
11✔
2684
                                outMsg.errChan <- err
4✔
2685
                        }
4✔
2686

2687
                        if err != nil {
7✔
2688
                                exitErr = fmt.Errorf("unable to write "+
×
2689
                                        "message: %v", err)
×
2690
                                break out
×
2691
                        }
2692

2693
                case <-p.cg.Done():
3✔
2694
                        exitErr = lnpeer.ErrPeerExiting
3✔
2695
                        break out
3✔
2696
                }
2697
        }
2698

2699
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2700
        // disconnect.
2701
        p.cg.WgDone()
3✔
2702

3✔
2703
        p.Disconnect(exitErr)
3✔
2704

3✔
2705
        p.log.Trace("writeHandler for peer done")
3✔
2706
}
2707

2708
// queueHandler is responsible for accepting messages from outside subsystems
2709
// to be eventually sent out on the wire by the writeHandler.
2710
//
2711
// NOTE: This method MUST be run as a goroutine.
2712
func (p *Brontide) queueHandler() {
6✔
2713
        defer p.cg.WgDone()
6✔
2714

6✔
2715
        // priorityMsgs holds an in order list of messages deemed high-priority
6✔
2716
        // to be added to the sendQueue. This predominately includes messages
6✔
2717
        // from the funding manager and htlcswitch.
6✔
2718
        priorityMsgs := list.New()
6✔
2719

6✔
2720
        // lazyMsgs holds an in order list of messages deemed low-priority to be
6✔
2721
        // added to the sendQueue only after all high-priority messages have
6✔
2722
        // been queued. This predominately includes messages from the gossiper.
6✔
2723
        lazyMsgs := list.New()
6✔
2724

6✔
2725
        for {
20✔
2726
                // Examine the front of the priority queue, if it is empty check
14✔
2727
                // the low priority queue.
14✔
2728
                elem := priorityMsgs.Front()
14✔
2729
                if elem == nil {
25✔
2730
                        elem = lazyMsgs.Front()
11✔
2731
                }
11✔
2732

2733
                if elem != nil {
21✔
2734
                        front := elem.Value.(outgoingMsg)
7✔
2735

7✔
2736
                        // There's an element on the queue, try adding
7✔
2737
                        // it to the sendQueue. We also watch for
7✔
2738
                        // messages on the outgoingQueue, in case the
7✔
2739
                        // writeHandler cannot accept messages on the
7✔
2740
                        // sendQueue.
7✔
2741
                        select {
7✔
2742
                        case p.sendQueue <- front:
7✔
2743
                                if front.priority {
13✔
2744
                                        priorityMsgs.Remove(elem)
6✔
2745
                                } else {
10✔
2746
                                        lazyMsgs.Remove(elem)
4✔
2747
                                }
4✔
2748
                        case msg := <-p.outgoingQueue:
3✔
2749
                                if msg.priority {
6✔
2750
                                        priorityMsgs.PushBack(msg)
3✔
2751
                                } else {
6✔
2752
                                        lazyMsgs.PushBack(msg)
3✔
2753
                                }
3✔
2754
                        case <-p.cg.Done():
×
2755
                                return
×
2756
                        }
2757
                } else {
10✔
2758
                        // If there weren't any messages to send to the
10✔
2759
                        // writeHandler, then we'll accept a new message
10✔
2760
                        // into the queue from outside sub-systems.
10✔
2761
                        select {
10✔
2762
                        case msg := <-p.outgoingQueue:
7✔
2763
                                if msg.priority {
13✔
2764
                                        priorityMsgs.PushBack(msg)
6✔
2765
                                } else {
10✔
2766
                                        lazyMsgs.PushBack(msg)
4✔
2767
                                }
4✔
2768
                        case <-p.cg.Done():
3✔
2769
                                return
3✔
2770
                        }
2771
                }
2772
        }
2773
}
2774

2775
// PingTime returns the estimated ping time to the peer in microseconds.
2776
func (p *Brontide) PingTime() int64 {
3✔
2777
        return p.pingManager.GetPingTimeMicroSeconds()
3✔
2778
}
3✔
2779

2780
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2781
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2782
// or failed to write, and nil otherwise.
2783
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
28✔
2784
        p.queue(true, msg, errChan)
28✔
2785
}
28✔
2786

2787
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2788
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2789
// queue or failed to write, and nil otherwise.
2790
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
4✔
2791
        p.queue(false, msg, errChan)
4✔
2792
}
4✔
2793

2794
// queue sends a given message to the queueHandler using the passed priority. If
2795
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2796
// failed to write, and nil otherwise.
2797
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2798
        errChan chan error) {
29✔
2799

29✔
2800
        select {
29✔
2801
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
28✔
2802
        case <-p.cg.Done():
×
2803
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
×
2804
                        spew.Sdump(msg))
×
2805
                if errChan != nil {
×
2806
                        errChan <- lnpeer.ErrPeerExiting
×
2807
                }
×
2808
        }
2809
}
2810

2811
// ChannelSnapshots returns a slice of channel snapshots detailing all
2812
// currently active channels maintained with the remote peer.
2813
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
3✔
2814
        snapshots := make(
3✔
2815
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
3✔
2816
        )
3✔
2817

3✔
2818
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2819
                activeChan *lnwallet.LightningChannel) error {
6✔
2820

3✔
2821
                // If the activeChan is nil, then we skip it as the channel is
3✔
2822
                // pending.
3✔
2823
                if activeChan == nil {
6✔
2824
                        return nil
3✔
2825
                }
3✔
2826

2827
                // We'll only return a snapshot for channels that are
2828
                // *immediately* available for routing payments over.
2829
                if activeChan.RemoteNextRevocation() == nil {
6✔
2830
                        return nil
3✔
2831
                }
3✔
2832

2833
                snapshot := activeChan.StateSnapshot()
3✔
2834
                snapshots = append(snapshots, snapshot)
3✔
2835

3✔
2836
                return nil
3✔
2837
        })
2838

2839
        return snapshots
3✔
2840
}
2841

2842
// genDeliveryScript returns a new script to be used to send our funds to in
2843
// the case of a cooperative channel close negotiation.
2844
func (p *Brontide) genDeliveryScript() ([]byte, error) {
9✔
2845
        // We'll send a normal p2wkh address unless we've negotiated the
9✔
2846
        // shutdown-any-segwit feature.
9✔
2847
        addrType := lnwallet.WitnessPubKey
9✔
2848
        if p.taprootShutdownAllowed() {
12✔
2849
                addrType = lnwallet.TaprootPubkey
3✔
2850
        }
3✔
2851

2852
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
9✔
2853
                addrType, false, lnwallet.DefaultAccountName,
9✔
2854
        )
9✔
2855
        if err != nil {
9✔
2856
                return nil, err
×
2857
        }
×
2858
        p.log.Infof("Delivery addr for channel close: %v",
9✔
2859
                deliveryAddr)
9✔
2860

9✔
2861
        return txscript.PayToAddrScript(deliveryAddr)
9✔
2862
}
2863

2864
// channelManager is goroutine dedicated to handling all requests/signals
2865
// pertaining to the opening, cooperative closing, and force closing of all
2866
// channels maintained with the remote peer.
2867
//
2868
// NOTE: This method MUST be run as a goroutine.
2869
func (p *Brontide) channelManager() {
20✔
2870
        defer p.cg.WgDone()
20✔
2871

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

20✔
2877
out:
20✔
2878
        for {
61✔
2879
                select {
41✔
2880
                // A new pending channel has arrived which means we are about
2881
                // to complete a funding workflow and is waiting for the final
2882
                // `ChannelReady` messages to be exchanged. We will add this
2883
                // channel to the `activeChannels` with a nil value to indicate
2884
                // this is a pending channel.
2885
                case req := <-p.newPendingChannel:
4✔
2886
                        p.handleNewPendingChannel(req)
4✔
2887

2888
                // A new channel has arrived which means we've just completed a
2889
                // funding workflow. We'll initialize the necessary local
2890
                // state, and notify the htlc switch of a new link.
2891
                case req := <-p.newActiveChannel:
3✔
2892
                        p.handleNewActiveChannel(req)
3✔
2893

2894
                // The funding flow for a pending channel is failed, we will
2895
                // remove it from Brontide.
2896
                case req := <-p.removePendingChannel:
4✔
2897
                        p.handleRemovePendingChannel(req)
4✔
2898

2899
                // We've just received a local request to close an active
2900
                // channel. It will either kick of a cooperative channel
2901
                // closure negotiation, or be a notification of a breached
2902
                // contract that should be abandoned.
2903
                case req := <-p.localCloseChanReqs:
10✔
2904
                        p.handleLocalCloseReq(req)
10✔
2905

2906
                // We've received a link failure from a link that was added to
2907
                // the switch. This will initiate the teardown of the link, and
2908
                // initiate any on-chain closures if necessary.
2909
                case failure := <-p.linkFailures:
3✔
2910
                        p.handleLinkFailure(failure)
3✔
2911

2912
                // We've received a new cooperative channel closure related
2913
                // message from the remote peer, we'll use this message to
2914
                // advance the chan closer state machine.
2915
                case closeMsg := <-p.chanCloseMsgs:
16✔
2916
                        p.handleCloseMsg(closeMsg)
16✔
2917

2918
                // The channel reannounce delay has elapsed, broadcast the
2919
                // reenabled channel updates to the network. This should only
2920
                // fire once, so we set the reenableTimeout channel to nil to
2921
                // mark it for garbage collection. If the peer is torn down
2922
                // before firing, reenabling will not be attempted.
2923
                // TODO(conner): consolidate reenables timers inside chan status
2924
                // manager
2925
                case <-reenableTimeout:
3✔
2926
                        p.reenableActiveChannels()
3✔
2927

3✔
2928
                        // Since this channel will never fire again during the
3✔
2929
                        // lifecycle of the peer, we nil the channel to mark it
3✔
2930
                        // eligible for garbage collection, and make this
3✔
2931
                        // explicitly ineligible to receive in future calls to
3✔
2932
                        // select. This also shaves a few CPU cycles since the
3✔
2933
                        // select will ignore this case entirely.
3✔
2934
                        reenableTimeout = nil
3✔
2935

3✔
2936
                        // Once the reenabling is attempted, we also cancel the
3✔
2937
                        // channel event subscription to free up the overflow
3✔
2938
                        // queue used in channel notifier.
3✔
2939
                        //
3✔
2940
                        // NOTE: channelEventClient will be nil if the
3✔
2941
                        // reenableTimeout is greater than 1 minute.
3✔
2942
                        if p.channelEventClient != nil {
6✔
2943
                                p.channelEventClient.Cancel()
3✔
2944
                        }
3✔
2945

2946
                case <-p.cg.Done():
3✔
2947
                        // As, we've been signalled to exit, we'll reset all
3✔
2948
                        // our active channel back to their default state.
3✔
2949
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2950
                                lc *lnwallet.LightningChannel) error {
6✔
2951

3✔
2952
                                // Exit if the channel is nil as it's a pending
3✔
2953
                                // channel.
3✔
2954
                                if lc == nil {
6✔
2955
                                        return nil
3✔
2956
                                }
3✔
2957

2958
                                lc.ResetState()
3✔
2959

3✔
2960
                                return nil
3✔
2961
                        })
2962

2963
                        break out
3✔
2964
                }
2965
        }
2966
}
2967

2968
// reenableActiveChannels searches the index of channels maintained with this
2969
// peer, and reenables each public, non-pending channel. This is done at the
2970
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
2971
// No message will be sent if the channel is already enabled.
2972
func (p *Brontide) reenableActiveChannels() {
3✔
2973
        // First, filter all known channels with this peer for ones that are
3✔
2974
        // both public and not pending.
3✔
2975
        activePublicChans := p.filterChannelsToEnable()
3✔
2976

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

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

3✔
2986
                switch {
3✔
2987
                // No error occurred, continue to request the next channel.
2988
                case err == nil:
3✔
2989
                        continue
3✔
2990

2991
                // Cannot auto enable a manually disabled channel so we do
2992
                // nothing but proceed to the next channel.
2993
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
3✔
2994
                        p.log.Debugf("Channel(%v) was manually disabled, "+
3✔
2995
                                "ignoring automatic enable request", chanPoint)
3✔
2996

3✔
2997
                        continue
3✔
2998

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

×
3016
                                continue
×
3017
                        }
3018

3019
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
3020
                                "ChanStatusManager reported inactive, retrying")
×
3021

×
3022
                        // Add the channel to the retry map.
×
3023
                        retryChans[chanPoint] = struct{}{}
×
3024
                }
3025
        }
3026

3027
        // Retry the channels if we have any.
3028
        if len(retryChans) != 0 {
3✔
3029
                p.retryRequestEnable(retryChans)
×
3030
        }
×
3031
}
3032

3033
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
3034
// for the target channel ID. If the channel isn't active an error is returned.
3035
// Otherwise, either an existing state machine will be returned, or a new one
3036
// will be created.
3037
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
3038
        *chanCloserFsm, error) {
16✔
3039

16✔
3040
        chanCloser, found := p.activeChanCloses.Load(chanID)
16✔
3041
        if found {
29✔
3042
                // An entry will only be found if the closer has already been
13✔
3043
                // created for a non-pending channel or for a channel that had
13✔
3044
                // previously started the shutdown process but the connection
13✔
3045
                // was restarted.
13✔
3046
                return &chanCloser, nil
13✔
3047
        }
13✔
3048

3049
        // First, we'll ensure that we actually know of the target channel. If
3050
        // not, we'll ignore this message.
3051
        channel, ok := p.activeChannels.Load(chanID)
6✔
3052

6✔
3053
        // If the channel isn't in the map or the channel is nil, return
6✔
3054
        // ErrChannelNotFound as the channel is pending.
6✔
3055
        if !ok || channel == nil {
9✔
3056
                return nil, ErrChannelNotFound
3✔
3057
        }
3✔
3058

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

3078
        // In order to begin fee negotiations, we'll first compute our target
3079
        // ideal fee-per-kw.
3080
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
6✔
3081
                p.cfg.CoopCloseTargetConfs,
6✔
3082
        )
6✔
3083
        if err != nil {
6✔
3084
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3085
                return nil, fmt.Errorf("unable to estimate fee")
×
3086
        }
×
3087

3088
        addr, err := p.addrWithInternalKey(deliveryScript)
6✔
3089
        if err != nil {
6✔
3090
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3091
        }
×
3092
        negotiateChanCloser, err := p.createChanCloser(
6✔
3093
                channel, addr, feePerKw, nil, lntypes.Remote,
6✔
3094
        )
6✔
3095
        if err != nil {
6✔
3096
                p.log.Errorf("unable to create chan closer: %v", err)
×
3097
                return nil, fmt.Errorf("unable to create chan closer")
×
3098
        }
×
3099

3100
        chanCloser = makeNegotiateCloser(negotiateChanCloser)
6✔
3101

6✔
3102
        p.activeChanCloses.Store(chanID, chanCloser)
6✔
3103

6✔
3104
        return &chanCloser, nil
6✔
3105
}
3106

3107
// filterChannelsToEnable filters a list of channels to be enabled upon start.
3108
// The filtered channels are active channels that's neither private nor
3109
// pending.
3110
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
3✔
3111
        var activePublicChans []wire.OutPoint
3✔
3112

3✔
3113
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
3✔
3114
                lnChan *lnwallet.LightningChannel) bool {
6✔
3115

3✔
3116
                // If the lnChan is nil, continue as this is a pending channel.
3✔
3117
                if lnChan == nil {
5✔
3118
                        return true
2✔
3119
                }
2✔
3120

3121
                dbChan := lnChan.State()
3✔
3122
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
3123
                if !isPublic || dbChan.IsPending {
3✔
3124
                        return true
×
3125
                }
×
3126

3127
                // We'll also skip any channels added during this peer's
3128
                // lifecycle since they haven't waited out the timeout. Their
3129
                // first announcement will be enabled, and the chan status
3130
                // manager will begin monitoring them passively since they exist
3131
                // in the database.
3132
                if _, ok := p.addedChannels.Load(chanID); ok {
3✔
3133
                        return true
×
3134
                }
×
3135

3136
                activePublicChans = append(
3✔
3137
                        activePublicChans, dbChan.FundingOutpoint,
3✔
3138
                )
3✔
3139

3✔
3140
                return true
3✔
3141
        })
3142

3143
        return activePublicChans
3✔
3144
}
3145

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

×
3153
        // retryEnable is a helper closure that sends an enable request and
×
3154
        // removes the channel from the map if it's matched.
×
3155
        retryEnable := func(chanPoint wire.OutPoint) error {
×
3156
                // If this is an active channel event, check whether it's in
×
3157
                // our targeted channels map.
×
3158
                _, found := activeChans[chanPoint]
×
3159

×
3160
                // If this channel is irrelevant, return nil so the loop can
×
3161
                // jump to next iteration.
×
3162
                if !found {
×
3163
                        return nil
×
3164
                }
×
3165

3166
                // Otherwise we've just received an active signal for a channel
3167
                // that's previously failed to be enabled, we send the request
3168
                // again.
3169
                //
3170
                // We only give the channel one more shot, so we delete it from
3171
                // our map first to keep it from being attempted again.
3172
                delete(activeChans, chanPoint)
×
3173

×
3174
                // Send the request.
×
3175
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3176
                if err != nil {
×
3177
                        return fmt.Errorf("request enabling channel %v "+
×
3178
                                "failed: %w", chanPoint, err)
×
3179
                }
×
3180

3181
                return nil
×
3182
        }
3183

3184
        for {
×
3185
                // If activeChans is empty, we've done processing all the
×
3186
                // channels.
×
3187
                if len(activeChans) == 0 {
×
3188
                        p.log.Debug("Finished retry enabling channels")
×
3189
                        return
×
3190
                }
×
3191

3192
                select {
×
3193
                // A new event has been sent by the ChannelNotifier. We now
3194
                // check whether it's an active or inactive channel event.
3195
                case e := <-p.channelEventClient.Updates():
×
3196
                        // If this is an active channel event, try enable the
×
3197
                        // channel then jump to the next iteration.
×
3198
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
3199
                        if ok {
×
3200
                                chanPoint := *active.ChannelPoint
×
3201

×
3202
                                // If we received an error for this particular
×
3203
                                // channel, we log an error and won't quit as
×
3204
                                // we still want to retry other channels.
×
3205
                                if err := retryEnable(chanPoint); err != nil {
×
3206
                                        p.log.Errorf("Retry failed: %v", err)
×
3207
                                }
×
3208

3209
                                continue
×
3210
                        }
3211

3212
                        // Otherwise check for inactive link event, and jump to
3213
                        // next iteration if it's not.
3214
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3215
                        if !ok {
×
3216
                                continue
×
3217
                        }
3218

3219
                        // Found an inactive link event, if this is our
3220
                        // targeted channel, remove it from our map.
3221
                        chanPoint := *inactive.ChannelPoint
×
3222
                        _, found := activeChans[chanPoint]
×
3223
                        if !found {
×
3224
                                continue
×
3225
                        }
3226

3227
                        delete(activeChans, chanPoint)
×
3228
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3229
                                "inactive link event", chanPoint)
×
3230

3231
                case <-p.cg.Done():
×
3232
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3233
                        return
×
3234
                }
3235
        }
3236
}
3237

3238
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3239
// a suitable script to close out to. This may be nil if neither script is
3240
// set. If both scripts are set, this function will error if they do not match.
3241
func chooseDeliveryScript(upfront, requested lnwire.DeliveryAddress,
3242
        genDeliveryScript func() ([]byte, error),
3243
) (lnwire.DeliveryAddress, error) {
15✔
3244

15✔
3245
        switch {
15✔
3246
        // If no script was provided, then we'll generate a new delivery script.
3247
        case len(upfront) == 0 && len(requested) == 0:
7✔
3248
                return genDeliveryScript()
7✔
3249

3250
        // If no upfront shutdown script was provided, return the user
3251
        // requested address (which may be nil).
3252
        case len(upfront) == 0:
5✔
3253
                return requested, nil
5✔
3254

3255
        // If an upfront shutdown script was provided, and the user did not
3256
        // request a custom shutdown script, return the upfront address.
3257
        case len(requested) == 0:
5✔
3258
                return upfront, nil
5✔
3259

3260
        // If both an upfront shutdown script and a custom close script were
3261
        // provided, error if the user provided shutdown script does not match
3262
        // the upfront shutdown script (because closing out to a different
3263
        // script would violate upfront shutdown).
3264
        case !bytes.Equal(upfront, requested):
2✔
3265
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
3266

3267
        // The user requested script matches the upfront shutdown script, so we
3268
        // can return it without error.
3269
        default:
2✔
3270
                return upfront, nil
2✔
3271
        }
3272
}
3273

3274
// restartCoopClose checks whether we need to restart the cooperative close
3275
// process for a given channel.
3276
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3277
        *lnwire.Shutdown, error) {
3✔
3278

3✔
3279
        isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
3280

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

3300
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
3✔
3301

3✔
3302
        var deliveryScript []byte
3✔
3303

3✔
3304
        shutdownInfo, err := c.ShutdownInfo()
3✔
3305
        switch {
3✔
3306
        // We have previously stored the delivery script that we need to use
3307
        // in the shutdown message. Re-use this script.
3308
        case err == nil:
3✔
3309
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
6✔
3310
                        deliveryScript = info.DeliveryScript.Val
3✔
3311
                })
3✔
3312

3313
        // An error other than ErrNoShutdownInfo was returned
3314
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3315
                return nil, err
×
3316

3317
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3318
                deliveryScript = c.LocalShutdownScript
×
3319
                if len(deliveryScript) == 0 {
×
3320
                        var err error
×
3321
                        deliveryScript, err = p.genDeliveryScript()
×
3322
                        if err != nil {
×
3323
                                p.log.Errorf("unable to gen delivery script: "+
×
3324
                                        "%v", err)
×
3325

×
3326
                                return nil, fmt.Errorf("close addr unavailable")
×
3327
                        }
×
3328
                }
3329
        }
3330

3331
        // If the new RBF co-op close is negotiated, then we'll init and start
3332
        // that state machine, skipping the steps for the negotiate machine
3333
        // below. We don't support this close type for taproot channels though.
3334
        if p.rbfCoopCloseAllowed() && !isTaprootChan {
6✔
3335
                _, err := p.initRbfChanCloser(lnChan)
3✔
3336
                if err != nil {
3✔
3337
                        return nil, fmt.Errorf("unable to init rbf chan "+
×
3338
                                "closer during restart: %w", err)
×
3339
                }
×
3340

3341
                shutdownDesc := fn.MapOption(
3✔
3342
                        newRestartShutdownInit,
3✔
3343
                )(shutdownInfo)
3✔
3344

3✔
3345
                err = p.startRbfChanCloser(
3✔
3346
                        fn.FlattenOption(shutdownDesc), lnChan.ChannelPoint(),
3✔
3347
                )
3✔
3348

3✔
3349
                return nil, err
3✔
3350
        }
3351

3352
        // Compute an ideal fee.
3353
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
3354
                p.cfg.CoopCloseTargetConfs,
×
3355
        )
×
3356
        if err != nil {
×
3357
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3358
                return nil, fmt.Errorf("unable to estimate fee")
×
3359
        }
×
3360

3361
        // Determine whether we or the peer are the initiator of the coop
3362
        // close attempt by looking at the channel's status.
3363
        closingParty := lntypes.Remote
×
3364
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3365
                closingParty = lntypes.Local
×
3366
        }
×
3367

3368
        addr, err := p.addrWithInternalKey(deliveryScript)
×
3369
        if err != nil {
×
3370
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3371
        }
×
3372
        chanCloser, err := p.createChanCloser(
×
3373
                lnChan, addr, feePerKw, nil, closingParty,
×
3374
        )
×
3375
        if err != nil {
×
3376
                p.log.Errorf("unable to create chan closer: %v", err)
×
3377
                return nil, fmt.Errorf("unable to create chan closer")
×
3378
        }
×
3379

3380
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
×
3381

×
3382
        // Create the Shutdown message.
×
3383
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3384
        if err != nil {
×
3385
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3386
                p.activeChanCloses.Delete(chanID)
×
3387
                return nil, err
×
3388
        }
×
3389

3390
        return shutdownMsg, nil
×
3391
}
3392

3393
// createChanCloser constructs a ChanCloser from the passed parameters and is
3394
// used to de-duplicate code.
3395
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3396
        deliveryScript *chancloser.DeliveryAddrWithKey,
3397
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3398
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
12✔
3399

12✔
3400
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
12✔
3401
        if err != nil {
12✔
3402
                p.log.Errorf("unable to obtain best block: %v", err)
×
3403
                return nil, fmt.Errorf("cannot obtain best block")
×
3404
        }
×
3405

3406
        // The req will only be set if we initiated the co-op closing flow.
3407
        var maxFee chainfee.SatPerKWeight
12✔
3408
        if req != nil {
21✔
3409
                maxFee = req.MaxFee
9✔
3410
        }
9✔
3411

3412
        chanCloser := chancloser.NewChanCloser(
12✔
3413
                chancloser.ChanCloseCfg{
12✔
3414
                        Channel:      channel,
12✔
3415
                        MusigSession: NewMusigChanCloser(channel),
12✔
3416
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
12✔
3417
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
12✔
3418
                        AuxCloser:    p.cfg.AuxChanCloser,
12✔
3419
                        DisableChannel: func(op wire.OutPoint) error {
24✔
3420
                                return p.cfg.ChanStatusMgr.RequestDisable(
12✔
3421
                                        op, false,
12✔
3422
                                )
12✔
3423
                        },
12✔
3424
                        MaxFee: maxFee,
3425
                        Disconnect: func() error {
×
3426
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
3427
                        },
×
3428
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3429
                },
3430
                *deliveryScript,
3431
                fee,
3432
                uint32(startingHeight),
3433
                req,
3434
                closer,
3435
        )
3436

3437
        return chanCloser, nil
12✔
3438
}
3439

3440
// initNegotiateChanCloser initializes the channel closer for a channel that is
3441
// using the original "negotiation" based protocol. This path is used when
3442
// we're the one initiating the channel close.
3443
//
3444
// TODO(roasbeef): can make a MsgEndpoint for existing handling logic to
3445
// further abstract.
3446
func (p *Brontide) initNegotiateChanCloser(req *htlcswitch.ChanClose,
3447
        channel *lnwallet.LightningChannel) error {
10✔
3448

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

10✔
3452
        // An upfront shutdown and user provided script are both optional, but
10✔
3453
        // must be equal if both set  (because we cannot serve a request to
10✔
3454
        // close out to a script which violates upfront shutdown). Get the
10✔
3455
        // appropriate address to close out to (which may be nil if neither are
10✔
3456
        // set) and error if they are both set and do not match.
10✔
3457
        deliveryScript, err := chooseDeliveryScript(
10✔
3458
                channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
10✔
3459
                p.genDeliveryScript,
10✔
3460
        )
10✔
3461
        if err != nil {
11✔
3462
                return fmt.Errorf("cannot close channel %v: %w",
1✔
3463
                        req.ChanPoint, err)
1✔
3464
        }
1✔
3465

3466
        addr, err := p.addrWithInternalKey(deliveryScript)
9✔
3467
        if err != nil {
9✔
3468
                return fmt.Errorf("unable to parse addr for channel "+
×
3469
                        "%v: %w", req.ChanPoint, err)
×
3470
        }
×
3471

3472
        chanCloser, err := p.createChanCloser(
9✔
3473
                channel, addr, req.TargetFeePerKw, req, lntypes.Local,
9✔
3474
        )
9✔
3475
        if err != nil {
9✔
3476
                return fmt.Errorf("unable to make chan closer: %w", err)
×
3477
        }
×
3478

3479
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
9✔
3480
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
9✔
3481

9✔
3482
        // Finally, we'll initiate the channel shutdown within the
9✔
3483
        // chanCloser, and send the shutdown message to the remote
9✔
3484
        // party to kick things off.
9✔
3485
        shutdownMsg, err := chanCloser.ShutdownChan()
9✔
3486
        if err != nil {
9✔
3487
                // As we were unable to shutdown the channel, we'll return it
×
3488
                // back to its normal state.
×
3489
                defer channel.ResetState()
×
3490

×
3491
                p.activeChanCloses.Delete(chanID)
×
3492

×
3493
                return fmt.Errorf("unable to shutdown channel: %w", err)
×
3494
        }
×
3495

3496
        link := p.fetchLinkFromKeyAndCid(chanID)
9✔
3497
        if link == nil {
9✔
3498
                // If the link is nil then it means it was already removed from
×
3499
                // the switch or it never existed in the first place. The
×
3500
                // latter case is handled at the beginning of this function, so
×
3501
                // in the case where it has already been removed, we can skip
×
3502
                // adding the commit hook to queue a Shutdown message.
×
3503
                p.log.Warnf("link not found during attempted closure: "+
×
3504
                        "%v", chanID)
×
3505
                return nil
×
3506
        }
×
3507

3508
        if !link.DisableAdds(htlcswitch.Outgoing) {
9✔
3509
                p.log.Warnf("Outgoing link adds already "+
×
3510
                        "disabled: %v", link.ChanID())
×
3511
        }
×
3512

3513
        link.OnCommitOnce(htlcswitch.Outgoing, func() {
18✔
3514
                p.queueMsg(shutdownMsg, nil)
9✔
3515
        })
9✔
3516

3517
        return nil
9✔
3518
}
3519

3520
// chooseAddr returns the provided address if it is non-zero length, otherwise
3521
// None.
3522
func chooseAddr(addr lnwire.DeliveryAddress) fn.Option[lnwire.DeliveryAddress] {
3✔
3523
        if len(addr) == 0 {
6✔
3524
                return fn.None[lnwire.DeliveryAddress]()
3✔
3525
        }
3✔
3526

3527
        return fn.Some(addr)
×
3528
}
3529

3530
// observeRbfCloseUpdates observes the channel for any updates that may
3531
// indicate that a new txid has been broadcasted, or the channel fully closed
3532
// on chain.
3533
func (p *Brontide) observeRbfCloseUpdates(chanCloser *chancloser.RbfChanCloser,
3534
        closeReq *htlcswitch.ChanClose,
3535
        coopCloseStates chancloser.RbfStateSub) {
3✔
3536

3✔
3537
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3538
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3539

3✔
3540
        var (
3✔
3541
                lastTxids    lntypes.Dual[chainhash.Hash]
3✔
3542
                lastFeeRates lntypes.Dual[chainfee.SatPerVByte]
3✔
3543
        )
3✔
3544

3✔
3545
        maybeNotifyTxBroadcast := func(state chancloser.AsymmetricPeerState,
3✔
3546
                party lntypes.ChannelParty) {
6✔
3547

3✔
3548
                // First, check to see if we have an error to report to the
3✔
3549
                // caller. If so, then we''ll return that error and exit, as the
3✔
3550
                // stream will exit as well.
3✔
3551
                if closeErr, ok := state.(*chancloser.CloseErr); ok {
6✔
3552
                        // We hit an error during the last state transition, so
3✔
3553
                        // we'll extract the error then send it to the
3✔
3554
                        // user.
3✔
3555
                        err := closeErr.Err()
3✔
3556

3✔
3557
                        peerLog.Warnf("ChannelPoint(%v): encountered close "+
3✔
3558
                                "err: %v", closeReq.ChanPoint, err)
3✔
3559

3✔
3560
                        select {
3✔
3561
                        case closeReq.Err <- err:
3✔
3562
                        case <-closeReq.Ctx.Done():
×
3563
                        case <-p.cg.Done():
×
3564
                        }
3565

3566
                        return
3✔
3567
                }
3568

3569
                closePending, ok := state.(*chancloser.ClosePending)
3✔
3570

3✔
3571
                // If this isn't the close pending state, we aren't at the
3✔
3572
                // terminal state yet.
3✔
3573
                if !ok {
6✔
3574
                        return
3✔
3575
                }
3✔
3576

3577
                // Only notify if the fee rate is greater.
3578
                newFeeRate := closePending.FeeRate
3✔
3579
                lastFeeRate := lastFeeRates.GetForParty(party)
3✔
3580
                if newFeeRate <= lastFeeRate {
6✔
3581
                        peerLog.Debugf("ChannelPoint(%v): remote party made "+
3✔
3582
                                "update for fee rate %v, but we already have "+
3✔
3583
                                "a higher fee rate of %v", closeReq.ChanPoint,
3✔
3584
                                newFeeRate, lastFeeRate)
3✔
3585

3✔
3586
                        return
3✔
3587
                }
3✔
3588

3589
                feeRate := closePending.FeeRate
3✔
3590
                lastFeeRates.SetForParty(party, feeRate)
3✔
3591

3✔
3592
                // At this point, we'll have a txid that we can use to notify
3✔
3593
                // the client, but only if it's different from the last one we
3✔
3594
                // sent. If the user attempted to bump, but was rejected due to
3✔
3595
                // RBF, then we'll send a redundant update.
3✔
3596
                closingTxid := closePending.CloseTx.TxHash()
3✔
3597
                lastTxid := lastTxids.GetForParty(party)
3✔
3598
                if closeReq != nil && closingTxid != lastTxid {
6✔
3599
                        select {
3✔
3600
                        case closeReq.Updates <- &PendingUpdate{
3601
                                Txid:        closingTxid[:],
3602
                                FeePerVbyte: fn.Some(closePending.FeeRate),
3603
                                IsLocalCloseTx: fn.Some(
3604
                                        party == lntypes.Local,
3605
                                ),
3606
                        }:
3✔
3607

3608
                        case <-closeReq.Ctx.Done():
×
3609
                                return
×
3610

3611
                        case <-p.cg.Done():
×
3612
                                return
×
3613
                        }
3614
                }
3615

3616
                lastTxids.SetForParty(party, closingTxid)
3✔
3617
        }
3618

3619
        peerLog.Infof("Observing RBF close updates for channel %v",
3✔
3620
                closeReq.ChanPoint)
3✔
3621

3✔
3622
        // We'll consume each new incoming state to send out the appropriate
3✔
3623
        // RPC update.
3✔
3624
        for {
6✔
3625
                select {
3✔
3626
                case newState := <-newStateChan:
3✔
3627

3✔
3628
                        switch closeState := newState.(type) {
3✔
3629
                        // Once we've reached the state of pending close, we
3630
                        // have a txid that we broadcasted.
3631
                        case *chancloser.ClosingNegotiation:
3✔
3632
                                peerState := closeState.PeerState
3✔
3633

3✔
3634
                                // Each side may have gained a new co-op close
3✔
3635
                                // tx, so we'll examine both to see if they've
3✔
3636
                                // changed.
3✔
3637
                                maybeNotifyTxBroadcast(
3✔
3638
                                        peerState.GetForParty(lntypes.Local),
3✔
3639
                                        lntypes.Local,
3✔
3640
                                )
3✔
3641
                                maybeNotifyTxBroadcast(
3✔
3642
                                        peerState.GetForParty(lntypes.Remote),
3✔
3643
                                        lntypes.Remote,
3✔
3644
                                )
3✔
3645

3646
                        // Otherwise, if we're transition to CloseFin, then we
3647
                        // know that we're done.
3648
                        case *chancloser.CloseFin:
3✔
3649
                                // To clean up, we'll remove the chan closer
3✔
3650
                                // from the active map, and send the final
3✔
3651
                                // update to the client.
3✔
3652
                                closingTxid := closeState.ConfirmedTx.TxHash()
3✔
3653
                                if closeReq != nil {
6✔
3654
                                        closeReq.Updates <- &ChannelCloseUpdate{
3✔
3655
                                                ClosingTxid: closingTxid[:],
3✔
3656
                                                Success:     true,
3✔
3657
                                        }
3✔
3658
                                }
3✔
3659
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
3660
                                        *closeReq.ChanPoint,
3✔
3661
                                )
3✔
3662
                                p.activeChanCloses.Delete(chanID)
3✔
3663

3✔
3664
                                return
3✔
3665
                        }
3666

3667
                case <-closeReq.Ctx.Done():
3✔
3668
                        return
3✔
3669

3670
                case <-p.cg.Done():
3✔
3671
                        return
3✔
3672
                }
3673
        }
3674
}
3675

3676
// chanErrorReporter is a simple implementation of the
3677
// chancloser.ErrorReporter. This is bound to a single channel by the channel
3678
// ID.
3679
type chanErrorReporter struct {
3680
        chanID lnwire.ChannelID
3681
        peer   *Brontide
3682
}
3683

3684
// newChanErrorReporter creates a new instance of the chanErrorReporter.
3685
func newChanErrorReporter(chanID lnwire.ChannelID,
3686
        peer *Brontide) *chanErrorReporter {
3✔
3687

3✔
3688
        return &chanErrorReporter{
3✔
3689
                chanID: chanID,
3✔
3690
                peer:   peer,
3✔
3691
        }
3✔
3692
}
3✔
3693

3694
// ReportError is a method that's used to report an error that occurred during
3695
// state machine execution. This is used by the RBF close state machine to
3696
// terminate the state machine and send an error to the remote peer.
3697
//
3698
// This is a part of the chancloser.ErrorReporter interface.
3699
func (c *chanErrorReporter) ReportError(chanErr error) {
×
3700
        c.peer.log.Errorf("coop close error for channel %v: %v",
×
3701
                c.chanID, chanErr)
×
3702

×
3703
        var errMsg []byte
×
3704
        if errors.Is(chanErr, chancloser.ErrInvalidStateTransition) {
×
3705
                errMsg = []byte("unexpected protocol message")
×
3706
        } else {
×
3707
                errMsg = []byte(chanErr.Error())
×
3708
        }
×
3709

3710
        err := c.peer.SendMessageLazy(false, &lnwire.Error{
×
3711
                ChanID: c.chanID,
×
3712
                Data:   errMsg,
×
3713
        })
×
3714
        if err != nil {
×
3715
                c.peer.log.Warnf("unable to send error message to peer: %v",
×
3716
                        err)
×
3717
        }
×
3718

3719
        // After we send the error message to the peer, we'll re-initialize the
3720
        // coop close state machine as they may send a shutdown message to
3721
        // retry the coop close.
3722
        lnChan, ok := c.peer.activeChannels.Load(c.chanID)
×
3723
        if !ok {
×
3724
                return
×
3725
        }
×
3726

3727
        if lnChan == nil {
×
3728
                c.peer.log.Debugf("channel %v is pending, not "+
×
3729
                        "re-initializing coop close state machine",
×
3730
                        c.chanID)
×
3731

×
3732
                return
×
3733
        }
×
3734

3735
        if _, err := c.peer.initRbfChanCloser(lnChan); err != nil {
×
3736
                c.peer.activeChanCloses.Delete(c.chanID)
×
3737

×
3738
                c.peer.log.Errorf("unable to init RBF chan closer after "+
×
3739
                        "error case: %v", err)
×
3740
        }
×
3741
}
3742

3743
// chanFlushEventSentinel is used to send the RBF coop close state machine the
3744
// channel flushed event. We'll wait until the state machine enters the
3745
// ChannelFlushing state, then request the link to send the event once flushed.
3746
//
3747
// NOTE: This MUST be run as a goroutine.
3748
func (p *Brontide) chanFlushEventSentinel(chanCloser *chancloser.RbfChanCloser,
3749
        link htlcswitch.ChannelUpdateHandler,
3750
        channel *lnwallet.LightningChannel) {
3✔
3751

3✔
3752
        defer p.cg.WgDone()
3✔
3753

3✔
3754
        // If there's no link, then the channel has already been flushed, so we
3✔
3755
        // don't need to continue.
3✔
3756
        if link == nil {
6✔
3757
                return
3✔
3758
        }
3✔
3759

3760
        coopCloseStates := chanCloser.RegisterStateEvents()
3✔
3761
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3762

3✔
3763
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3764

3✔
3765
        sendChanFlushed := func() {
6✔
3766
                chanState := channel.StateSnapshot()
3✔
3767

3✔
3768
                peerLog.Infof("ChannelPoint(%v) has been flushed for co-op "+
3✔
3769
                        "close, sending event to chan closer",
3✔
3770
                        channel.ChannelPoint())
3✔
3771

3✔
3772
                chanBalances := chancloser.ShutdownBalances{
3✔
3773
                        LocalBalance:  chanState.LocalBalance,
3✔
3774
                        RemoteBalance: chanState.RemoteBalance,
3✔
3775
                }
3✔
3776
                ctx := context.Background()
3✔
3777
                chanCloser.SendEvent(ctx, &chancloser.ChannelFlushed{
3✔
3778
                        ShutdownBalances: chanBalances,
3✔
3779
                        FreshFlush:       true,
3✔
3780
                })
3✔
3781
        }
3✔
3782

3783
        // We'll wait until the channel enters the ChannelFlushing state. We
3784
        // exit after a success loop. As after the first RBF iteration, the
3785
        // channel will always be flushed.
3786
        for newState := range newStateChan {
6✔
3787
                if _, ok := newState.(*chancloser.ChannelFlushing); ok {
6✔
3788
                        peerLog.Infof("ChannelPoint(%v): rbf coop "+
3✔
3789
                                "close is awaiting a flushed state, "+
3✔
3790
                                "registering with link..., ",
3✔
3791
                                channel.ChannelPoint())
3✔
3792

3✔
3793
                        // Request the link to send the event once the channel
3✔
3794
                        // is flushed. We only need this event sent once, so we
3✔
3795
                        // can exit now.
3✔
3796
                        link.OnFlushedOnce(sendChanFlushed)
3✔
3797

3✔
3798
                        return
3✔
3799
                }
3✔
3800
        }
3801
}
3802

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

3✔
3809
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
3✔
3810

3✔
3811
        link := p.fetchLinkFromKeyAndCid(chanID)
3✔
3812

3✔
3813
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
3✔
3814
        if err != nil {
3✔
3815
                return nil, fmt.Errorf("cannot obtain best block: %w", err)
×
3816
        }
×
3817

3818
        defaultFeePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
3819
                p.cfg.CoopCloseTargetConfs,
3✔
3820
        )
3✔
3821
        if err != nil {
3✔
3822
                return nil, fmt.Errorf("unable to estimate fee: %w", err)
×
3823
        }
×
3824

3825
        thawHeight, err := channel.AbsoluteThawHeight()
3✔
3826
        if err != nil {
3✔
3827
                return nil, fmt.Errorf("unable to get thaw height: %w", err)
×
3828
        }
×
3829

3830
        peerPub := *p.IdentityKey()
3✔
3831

3✔
3832
        msgMapper := chancloser.NewRbfMsgMapper(
3✔
3833
                uint32(startingHeight), chanID, peerPub,
3✔
3834
        )
3✔
3835

3✔
3836
        initialState := chancloser.ChannelActive{}
3✔
3837

3✔
3838
        scid := channel.ZeroConfRealScid().UnwrapOr(
3✔
3839
                channel.ShortChanID(),
3✔
3840
        )
3✔
3841

3✔
3842
        env := chancloser.Environment{
3✔
3843
                ChainParams:    p.cfg.Wallet.Cfg.NetParams,
3✔
3844
                ChanPeer:       peerPub,
3✔
3845
                ChanPoint:      channel.ChannelPoint(),
3✔
3846
                ChanID:         chanID,
3✔
3847
                Scid:           scid,
3✔
3848
                ChanType:       channel.ChanType(),
3✔
3849
                DefaultFeeRate: defaultFeePerKw.FeePerVByte(),
3✔
3850
                ThawHeight:     fn.Some(thawHeight),
3✔
3851
                RemoteUpfrontShutdown: chooseAddr(
3✔
3852
                        channel.RemoteUpfrontShutdownScript(),
3✔
3853
                ),
3✔
3854
                LocalUpfrontShutdown: chooseAddr(
3✔
3855
                        channel.LocalUpfrontShutdownScript(),
3✔
3856
                ),
3✔
3857
                NewDeliveryScript: func() (lnwire.DeliveryAddress, error) {
6✔
3858
                        return p.genDeliveryScript()
3✔
3859
                },
3✔
3860
                FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
3861
                CloseSigner:  channel,
3862
                ChanObserver: newChanObserver(
3863
                        channel, link, p.cfg.ChanStatusMgr,
3864
                ),
3865
        }
3866

3867
        spendEvent := protofsm.RegisterSpend[chancloser.ProtocolEvent]{
3✔
3868
                OutPoint:   channel.ChannelPoint(),
3✔
3869
                PkScript:   channel.FundingTxOut().PkScript,
3✔
3870
                HeightHint: channel.DeriveHeightHint(),
3✔
3871
                PostSpendEvent: fn.Some[chancloser.RbfSpendMapper](
3✔
3872
                        chancloser.SpendMapper,
3✔
3873
                ),
3✔
3874
        }
3✔
3875

3✔
3876
        daemonAdapters := NewLndDaemonAdapters(LndAdapterCfg{
3✔
3877
                MsgSender:     newPeerMsgSender(peerPub, p),
3✔
3878
                TxBroadcaster: p.cfg.Wallet,
3✔
3879
                ChainNotifier: p.cfg.ChainNotifier,
3✔
3880
        })
3✔
3881

3✔
3882
        protoCfg := chancloser.RbfChanCloserCfg{
3✔
3883
                Daemon:        daemonAdapters,
3✔
3884
                InitialState:  &initialState,
3✔
3885
                Env:           &env,
3✔
3886
                InitEvent:     fn.Some[protofsm.DaemonEvent](&spendEvent),
3✔
3887
                ErrorReporter: newChanErrorReporter(chanID, p),
3✔
3888
                MsgMapper: fn.Some[protofsm.MsgMapper[chancloser.ProtocolEvent]]( //nolint:ll
3✔
3889
                        msgMapper,
3✔
3890
                ),
3✔
3891
        }
3✔
3892

3✔
3893
        ctx := context.Background()
3✔
3894
        chanCloser := protofsm.NewStateMachine(protoCfg)
3✔
3895
        chanCloser.Start(ctx)
3✔
3896

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

3✔
3902
                return r.RegisterEndpoint(&chanCloser)
3✔
3903
        })
3✔
3904
        if err != nil {
3✔
3905
                chanCloser.Stop()
×
3906

×
3907
                return nil, fmt.Errorf("unable to register endpoint for co-op "+
×
3908
                        "close: %w", err)
×
3909
        }
×
3910

3911
        p.activeChanCloses.Store(chanID, makeRbfCloser(&chanCloser))
3✔
3912

3✔
3913
        // Now that we've created the rbf closer state machine, we'll launch a
3✔
3914
        // new goroutine to eventually send in the ChannelFlushed event once
3✔
3915
        // needed.
3✔
3916
        p.cg.WgAdd(1)
3✔
3917
        go p.chanFlushEventSentinel(&chanCloser, link, channel)
3✔
3918

3✔
3919
        return &chanCloser, nil
3✔
3920
}
3921

3922
// shutdownInit describes the two ways we can initiate a new shutdown. Either we
3923
// got an RPC request to do so (left), or we sent a shutdown message to the
3924
// party (for w/e reason), but crashed before the close was complete.
3925
//
3926
//nolint:ll
3927
type shutdownInit = fn.Option[fn.Either[*htlcswitch.ChanClose, channeldb.ShutdownInfo]]
3928

3929
// shutdownStartFeeRate returns the fee rate that should be used for the
3930
// shutdown.  This returns a doubly wrapped option as the shutdown info might
3931
// be none, and the fee rate is only defined for the user initiated shutdown.
3932
func shutdownStartFeeRate(s shutdownInit) fn.Option[chainfee.SatPerKWeight] {
3✔
3933
        feeRateOpt := fn.MapOption(func(init fn.Either[*htlcswitch.ChanClose,
3✔
3934
                channeldb.ShutdownInfo]) fn.Option[chainfee.SatPerKWeight] {
6✔
3935

3✔
3936
                var feeRate fn.Option[chainfee.SatPerKWeight]
3✔
3937
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
6✔
3938
                        feeRate = fn.Some(req.TargetFeePerKw)
3✔
3939
                })
3✔
3940

3941
                return feeRate
3✔
3942
        })(s)
3943

3944
        return fn.FlattenOption(feeRateOpt)
3✔
3945
}
3946

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

3✔
3954
                var addr fn.Option[lnwire.DeliveryAddress]
3✔
3955
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
6✔
3956
                        if len(req.DeliveryScript) != 0 {
6✔
3957
                                addr = fn.Some(req.DeliveryScript)
3✔
3958
                        }
3✔
3959
                })
3960
                init.WhenRight(func(info channeldb.ShutdownInfo) {
6✔
3961
                        addr = fn.Some(info.DeliveryScript.Val)
3✔
3962
                })
3✔
3963

3964
                return addr
3✔
3965
        })(s)
3966

3967
        return fn.FlattenOption(addrOpt)
3✔
3968
}
3969

3970
// whenRPCShutdown registers a callback to be executed when the shutdown init
3971
// type is and RPC request.
3972
func whenRPCShutdown(s shutdownInit, f func(r *htlcswitch.ChanClose)) {
3✔
3973
        s.WhenSome(func(init fn.Either[*htlcswitch.ChanClose,
3✔
3974
                channeldb.ShutdownInfo]) {
6✔
3975

3✔
3976
                init.WhenLeft(f)
3✔
3977
        })
3✔
3978
}
3979

3980
// newRestartShutdownInit creates a new shutdownInit for the case where we need
3981
// to restart the shutdown flow after a restart.
3982
func newRestartShutdownInit(info channeldb.ShutdownInfo) shutdownInit {
3✔
3983
        return fn.Some(fn.NewRight[*htlcswitch.ChanClose](info))
3✔
3984
}
3✔
3985

3986
// newRPCShutdownInit creates a new shutdownInit for the case where we
3987
// initiated the shutdown via an RPC client.
3988
func newRPCShutdownInit(req *htlcswitch.ChanClose) shutdownInit {
3✔
3989
        return fn.Some(
3✔
3990
                fn.NewLeft[*htlcswitch.ChanClose, channeldb.ShutdownInfo](req),
3✔
3991
        )
3✔
3992
}
3✔
3993

3994
// waitUntilRbfCoastClear waits until the RBF co-op close state machine has
3995
// advanced to a terminal state before attempting another fee bump.
3996
func waitUntilRbfCoastClear(ctx context.Context,
3997
        rbfCloser *chancloser.RbfChanCloser) error {
3✔
3998

3✔
3999
        coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4000
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
4001
        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4002

3✔
4003
        isTerminalState := func(newState chancloser.RbfState) bool {
6✔
4004
                // If we're not in the negotiation sub-state, then we aren't at
3✔
4005
                // the terminal state yet.
3✔
4006
                state, ok := newState.(*chancloser.ClosingNegotiation)
3✔
4007
                if !ok {
3✔
4008
                        return false
×
4009
                }
×
4010

4011
                localState := state.PeerState.GetForParty(lntypes.Local)
3✔
4012

3✔
4013
                // If this isn't the close pending state, we aren't at the
3✔
4014
                // terminal state yet.
3✔
4015
                _, ok = localState.(*chancloser.ClosePending)
3✔
4016

3✔
4017
                return ok
3✔
4018
        }
4019

4020
        // Before we enter the subscription loop below, check to see if we're
4021
        // already in the terminal state.
4022
        rbfState, err := rbfCloser.CurrentState()
3✔
4023
        if err != nil {
3✔
4024
                return err
×
4025
        }
×
4026
        if isTerminalState(rbfState) {
6✔
4027
                return nil
3✔
4028
        }
3✔
4029

4030
        peerLog.Debugf("Waiting for RBF iteration to complete...")
×
4031

×
4032
        for {
×
4033
                select {
×
4034
                case newState := <-newStateChan:
×
4035
                        if isTerminalState(newState) {
×
4036
                                return nil
×
4037
                        }
×
4038

4039
                case <-ctx.Done():
×
4040
                        return fmt.Errorf("context canceled")
×
4041
                }
4042
        }
4043
}
4044

4045
// startRbfChanCloser kicks off the co-op close process using the new RBF based
4046
// co-op close protocol. This is called when we're the one that's initiating
4047
// the cooperative channel close.
4048
//
4049
// TODO(roasbeef): just accept the two shutdown pointer params instead??
4050
func (p *Brontide) startRbfChanCloser(shutdown shutdownInit,
4051
        chanPoint wire.OutPoint) error {
3✔
4052

3✔
4053
        // Unlike the old negotiate chan closer, we'll always create the RBF
3✔
4054
        // chan closer on startup, so we can skip init here.
3✔
4055
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4056
        chanCloser, found := p.activeChanCloses.Load(chanID)
3✔
4057
        if !found {
3✔
4058
                return fmt.Errorf("rbf chan closer not found for channel %v",
×
4059
                        chanPoint)
×
4060
        }
×
4061

4062
        defaultFeePerKw, err := shutdownStartFeeRate(
3✔
4063
                shutdown,
3✔
4064
        ).UnwrapOrFuncErr(func() (chainfee.SatPerKWeight, error) {
6✔
4065
                return p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
4066
                        p.cfg.CoopCloseTargetConfs,
3✔
4067
                )
3✔
4068
        })
3✔
4069
        if err != nil {
3✔
4070
                return fmt.Errorf("unable to estimate fee: %w", err)
×
4071
        }
×
4072

4073
        chanCloser.WhenRight(func(rbfCloser *chancloser.RbfChanCloser) {
6✔
4074
                peerLog.Infof("ChannelPoint(%v): rbf-coop close requested, "+
3✔
4075
                        "sending shutdown", chanPoint)
3✔
4076

3✔
4077
                rbfState, err := rbfCloser.CurrentState()
3✔
4078
                if err != nil {
3✔
4079
                        peerLog.Warnf("ChannelPoint(%v): unable to get "+
×
4080
                                "current state for rbf-coop close: %v",
×
4081
                                chanPoint, err)
×
4082

×
4083
                        return
×
4084
                }
×
4085

4086
                coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4087

3✔
4088
                // Before we send our event below, we'll launch a goroutine to
3✔
4089
                // watch for the final terminal state to send updates to the RPC
3✔
4090
                // client. We only need to do this if there's an RPC caller.
3✔
4091
                var rpcShutdown bool
3✔
4092
                whenRPCShutdown(shutdown, func(req *htlcswitch.ChanClose) {
6✔
4093
                        rpcShutdown = true
3✔
4094

3✔
4095
                        p.cg.WgAdd(1)
3✔
4096
                        go func() {
6✔
4097
                                defer p.cg.WgDone()
3✔
4098

3✔
4099
                                p.observeRbfCloseUpdates(
3✔
4100
                                        rbfCloser, req, coopCloseStates,
3✔
4101
                                )
3✔
4102
                        }()
3✔
4103
                })
4104

4105
                if !rpcShutdown {
6✔
4106
                        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4107
                }
3✔
4108

4109
                ctx, _ := p.cg.Create(context.Background())
3✔
4110
                feeRate := defaultFeePerKw.FeePerVByte()
3✔
4111

3✔
4112
                // Depending on the state of the state machine, we'll either
3✔
4113
                // kick things off by sending shutdown, or attempt to send a new
3✔
4114
                // offer to the remote party.
3✔
4115
                switch rbfState.(type) {
3✔
4116
                // The channel is still active, so we'll now kick off the co-op
4117
                // close process by instructing it to send a shutdown message to
4118
                // the remote party.
4119
                case *chancloser.ChannelActive:
3✔
4120
                        rbfCloser.SendEvent(
3✔
4121
                                context.Background(),
3✔
4122
                                &chancloser.SendShutdown{
3✔
4123
                                        IdealFeeRate: feeRate,
3✔
4124
                                        DeliveryAddr: shutdownStartAddr(
3✔
4125
                                                shutdown,
3✔
4126
                                        ),
3✔
4127
                                },
3✔
4128
                        )
3✔
4129

4130
                // If we haven't yet sent an offer (didn't have enough funds at
4131
                // the prior fee rate), or we've sent an offer, then we'll
4132
                // trigger a new offer event.
4133
                case *chancloser.ClosingNegotiation:
3✔
4134
                        // Before we send the event below, we'll wait until
3✔
4135
                        // we're in a semi-terminal state.
3✔
4136
                        err := waitUntilRbfCoastClear(ctx, rbfCloser)
3✔
4137
                        if err != nil {
3✔
4138
                                peerLog.Warnf("ChannelPoint(%v): unable to "+
×
4139
                                        "wait for coast to clear: %v",
×
4140
                                        chanPoint, err)
×
4141

×
4142
                                return
×
4143
                        }
×
4144

4145
                        event := chancloser.ProtocolEvent(
3✔
4146
                                &chancloser.SendOfferEvent{
3✔
4147
                                        TargetFeeRate: feeRate,
3✔
4148
                                },
3✔
4149
                        )
3✔
4150
                        rbfCloser.SendEvent(ctx, event)
3✔
4151

4152
                default:
×
4153
                        peerLog.Warnf("ChannelPoint(%v): unexpected state "+
×
4154
                                "for rbf-coop close: %T", chanPoint, rbfState)
×
4155
                }
4156
        })
4157

4158
        return nil
3✔
4159
}
4160

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

10✔
4166
        channel, ok := p.activeChannels.Load(chanID)
10✔
4167

10✔
4168
        // Though this function can't be called for pending channels, we still
10✔
4169
        // check whether channel is nil for safety.
10✔
4170
        if !ok || channel == nil {
10✔
4171
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
×
4172
                        "unknown", chanID)
×
4173
                p.log.Errorf(err.Error())
×
4174
                req.Err <- err
×
4175
                return
×
4176
        }
×
4177

4178
        isTaprootChan := channel.ChanType().IsTaproot()
10✔
4179

10✔
4180
        switch req.CloseType {
10✔
4181
        // A type of CloseRegular indicates that the user has opted to close
4182
        // out this channel on-chain, so we execute the cooperative channel
4183
        // closure workflow.
4184
        case contractcourt.CloseRegular:
10✔
4185
                var err error
10✔
4186
                switch {
10✔
4187
                // If this is the RBF coop state machine, then we'll instruct
4188
                // it to send the shutdown message. This also might be an RBF
4189
                // iteration, in which case we'll be obtaining a new
4190
                // transaction w/ a higher fee rate.
4191
                //
4192
                // We don't support this close type for taproot channels yet
4193
                // however.
4194
                case !isTaprootChan && p.rbfCoopCloseAllowed():
3✔
4195
                        err = p.startRbfChanCloser(
3✔
4196
                                newRPCShutdownInit(req), channel.ChannelPoint(),
3✔
4197
                        )
3✔
4198
                default:
10✔
4199
                        err = p.initNegotiateChanCloser(req, channel)
10✔
4200
                }
4201

4202
                if err != nil {
11✔
4203
                        p.log.Errorf(err.Error())
1✔
4204
                        req.Err <- err
1✔
4205
                }
1✔
4206

4207
        // A type of CloseBreach indicates that the counterparty has breached
4208
        // the channel therefore we need to clean up our local state.
4209
        case contractcourt.CloseBreach:
×
4210
                // TODO(roasbeef): no longer need with newer beach logic?
×
4211
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
×
4212
                        "channel", req.ChanPoint)
×
4213
                p.WipeChannel(req.ChanPoint)
×
4214
        }
4215
}
4216

4217
// linkFailureReport is sent to the channelManager whenever a link reports a
4218
// link failure, and is forced to exit. The report houses the necessary
4219
// information to clean up the channel state, send back the error message, and
4220
// force close if necessary.
4221
type linkFailureReport struct {
4222
        chanPoint   wire.OutPoint
4223
        chanID      lnwire.ChannelID
4224
        shortChanID lnwire.ShortChannelID
4225
        linkErr     htlcswitch.LinkFailureError
4226
}
4227

4228
// handleLinkFailure processes a link failure report when a link in the switch
4229
// fails. It facilitates the removal of all channel state within the peer,
4230
// force closing the channel depending on severity, and sending the error
4231
// message back to the remote party.
4232
func (p *Brontide) handleLinkFailure(failure linkFailureReport) {
3✔
4233
        // Retrieve the channel from the map of active channels. We do this to
3✔
4234
        // have access to it even after WipeChannel remove it from the map.
3✔
4235
        chanID := lnwire.NewChanIDFromOutPoint(failure.chanPoint)
3✔
4236
        lnChan, _ := p.activeChannels.Load(chanID)
3✔
4237

3✔
4238
        // We begin by wiping the link, which will remove it from the switch,
3✔
4239
        // such that it won't be attempted used for any more updates.
3✔
4240
        //
3✔
4241
        // TODO(halseth): should introduce a way to atomically stop/pause the
3✔
4242
        // link and cancel back any adds in its mailboxes such that we can
3✔
4243
        // safely force close without the link being added again and updates
3✔
4244
        // being applied.
3✔
4245
        p.WipeChannel(&failure.chanPoint)
3✔
4246

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

3✔
4252
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
3✔
4253
                        failure.chanPoint,
3✔
4254
                )
3✔
4255
                if err != nil {
6✔
4256
                        p.log.Errorf("unable to force close "+
3✔
4257
                                "link(%v): %v", failure.shortChanID, err)
3✔
4258
                } else {
6✔
4259
                        p.log.Infof("channel(%v) force "+
3✔
4260
                                "closed with txid %v",
3✔
4261
                                failure.shortChanID, closeTx.TxHash())
3✔
4262
                }
3✔
4263
        }
4264

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

×
4270
                if err := lnChan.State().MarkBorked(); err != nil {
×
4271
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
4272
                                failure.shortChanID, err)
×
4273
                }
×
4274
        }
4275

4276
        // Send an error to the peer, why we failed the channel.
4277
        if failure.linkErr.ShouldSendToPeer() {
6✔
4278
                // If SendData is set, send it to the peer. If not, we'll use
3✔
4279
                // the standard error messages in the payload. We only include
3✔
4280
                // sendData in the cases where the error data does not contain
3✔
4281
                // sensitive information.
3✔
4282
                data := []byte(failure.linkErr.Error())
3✔
4283
                if failure.linkErr.SendData != nil {
3✔
4284
                        data = failure.linkErr.SendData
×
4285
                }
×
4286

4287
                var networkMsg lnwire.Message
3✔
4288
                if failure.linkErr.Warning {
3✔
4289
                        networkMsg = &lnwire.Warning{
×
4290
                                ChanID: failure.chanID,
×
4291
                                Data:   data,
×
4292
                        }
×
4293
                } else {
3✔
4294
                        networkMsg = &lnwire.Error{
3✔
4295
                                ChanID: failure.chanID,
3✔
4296
                                Data:   data,
3✔
4297
                        }
3✔
4298
                }
3✔
4299

4300
                err := p.SendMessage(true, networkMsg)
3✔
4301
                if err != nil {
3✔
4302
                        p.log.Errorf("unable to send msg to "+
×
4303
                                "remote peer: %v", err)
×
4304
                }
×
4305
        }
4306

4307
        // If the failure action is disconnect, then we'll execute that now. If
4308
        // we had to send an error above, it was a sync call, so we expect the
4309
        // message to be flushed on the wire by now.
4310
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
3✔
4311
                p.Disconnect(fmt.Errorf("link requested disconnect"))
×
4312
        }
×
4313
}
4314

4315
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
4316
// public key and the channel id.
4317
func (p *Brontide) fetchLinkFromKeyAndCid(
4318
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
22✔
4319

22✔
4320
        var chanLink htlcswitch.ChannelUpdateHandler
22✔
4321

22✔
4322
        // We don't need to check the error here, and can instead just loop
22✔
4323
        // over the slice and return nil.
22✔
4324
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
22✔
4325
        for _, link := range links {
43✔
4326
                if link.ChanID() == cid {
42✔
4327
                        chanLink = link
21✔
4328
                        break
21✔
4329
                }
4330
        }
4331

4332
        return chanLink
22✔
4333
}
4334

4335
// finalizeChanClosure performs the final clean up steps once the cooperative
4336
// closure transaction has been fully broadcast. The finalized closing state
4337
// machine should be passed in. Once the transaction has been sufficiently
4338
// confirmed, the channel will be marked as fully closed within the database,
4339
// and any clients will be notified of updates to the closing state.
4340
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
7✔
4341
        closeReq := chanCloser.CloseRequest()
7✔
4342

7✔
4343
        // First, we'll clear all indexes related to the channel in question.
7✔
4344
        chanPoint := chanCloser.Channel().ChannelPoint()
7✔
4345
        p.WipeChannel(&chanPoint)
7✔
4346

7✔
4347
        // Also clear the activeChanCloses map of this channel.
7✔
4348
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
7✔
4349
        p.activeChanCloses.Delete(cid) // TODO(roasbeef): existing race
7✔
4350

7✔
4351
        // Next, we'll launch a goroutine which will request to be notified by
7✔
4352
        // the ChainNotifier once the closure transaction obtains a single
7✔
4353
        // confirmation.
7✔
4354
        notifier := p.cfg.ChainNotifier
7✔
4355

7✔
4356
        // If any error happens during waitForChanToClose, forward it to
7✔
4357
        // closeReq. If this channel closure is not locally initiated, closeReq
7✔
4358
        // will be nil, so just ignore the error.
7✔
4359
        errChan := make(chan error, 1)
7✔
4360
        if closeReq != nil {
12✔
4361
                errChan = closeReq.Err
5✔
4362
        }
5✔
4363

4364
        closingTx, err := chanCloser.ClosingTx()
7✔
4365
        if err != nil {
7✔
4366
                if closeReq != nil {
×
4367
                        p.log.Error(err)
×
4368
                        closeReq.Err <- err
×
4369
                }
×
4370
        }
4371

4372
        closingTxid := closingTx.TxHash()
7✔
4373

7✔
4374
        // If this is a locally requested shutdown, update the caller with a
7✔
4375
        // new event detailing the current pending state of this request.
7✔
4376
        if closeReq != nil {
12✔
4377
                closeReq.Updates <- &PendingUpdate{
5✔
4378
                        Txid: closingTxid[:],
5✔
4379
                }
5✔
4380
        }
5✔
4381

4382
        localOut := chanCloser.LocalCloseOutput()
7✔
4383
        remoteOut := chanCloser.RemoteCloseOutput()
7✔
4384
        auxOut := chanCloser.AuxOutputs()
7✔
4385
        go WaitForChanToClose(
7✔
4386
                chanCloser.NegotiationHeight(), notifier, errChan,
7✔
4387
                &chanPoint, &closingTxid, closingTx.TxOut[0].PkScript, func() {
14✔
4388
                        // Respond to the local subsystem which requested the
7✔
4389
                        // channel closure.
7✔
4390
                        if closeReq != nil {
12✔
4391
                                closeReq.Updates <- &ChannelCloseUpdate{
5✔
4392
                                        ClosingTxid:       closingTxid[:],
5✔
4393
                                        Success:           true,
5✔
4394
                                        LocalCloseOutput:  localOut,
5✔
4395
                                        RemoteCloseOutput: remoteOut,
5✔
4396
                                        AuxOutputs:        auxOut,
5✔
4397
                                }
5✔
4398
                        }
5✔
4399
                },
4400
        )
4401
}
4402

4403
// WaitForChanToClose uses the passed notifier to wait until the channel has
4404
// been detected as closed on chain and then concludes by executing the
4405
// following actions: the channel point will be sent over the settleChan, and
4406
// finally the callback will be executed. If any error is encountered within
4407
// the function, then it will be sent over the errChan.
4408
func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
4409
        errChan chan error, chanPoint *wire.OutPoint,
4410
        closingTxID *chainhash.Hash, closeScript []byte, cb func()) {
7✔
4411

7✔
4412
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
7✔
4413
                "with txid: %v", chanPoint, closingTxID)
7✔
4414

7✔
4415
        // TODO(roasbeef): add param for num needed confs
7✔
4416
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
7✔
4417
                closingTxID, closeScript, 1, bestHeight,
7✔
4418
        )
7✔
4419
        if err != nil {
7✔
4420
                if errChan != nil {
×
4421
                        errChan <- err
×
4422
                }
×
4423
                return
×
4424
        }
4425

4426
        // In the case that the ChainNotifier is shutting down, all subscriber
4427
        // notification channels will be closed, generating a nil receive.
4428
        height, ok := <-confNtfn.Confirmed
7✔
4429
        if !ok {
10✔
4430
                return
3✔
4431
        }
3✔
4432

4433
        // The channel has been closed, remove it from any active indexes, and
4434
        // the database state.
4435
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
7✔
4436
                "height %v", chanPoint, height.BlockHeight)
7✔
4437

7✔
4438
        // Finally, execute the closure call back to mark the confirmation of
7✔
4439
        // the transaction closing the contract.
7✔
4440
        cb()
7✔
4441
}
4442

4443
// WipeChannel removes the passed channel point from all indexes associated with
4444
// the peer and the switch.
4445
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
7✔
4446
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
7✔
4447

7✔
4448
        p.activeChannels.Delete(chanID)
7✔
4449

7✔
4450
        // Instruct the HtlcSwitch to close this link as the channel is no
7✔
4451
        // longer active.
7✔
4452
        p.cfg.Switch.RemoveLink(chanID)
7✔
4453
}
7✔
4454

4455
// handleInitMsg handles the incoming init message which contains global and
4456
// local feature vectors. If feature vectors are incompatible then disconnect.
4457
func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
6✔
4458
        // First, merge any features from the legacy global features field into
6✔
4459
        // those presented in the local features fields.
6✔
4460
        err := msg.Features.Merge(msg.GlobalFeatures)
6✔
4461
        if err != nil {
6✔
4462
                return fmt.Errorf("unable to merge legacy global features: %w",
×
4463
                        err)
×
4464
        }
×
4465

4466
        // Then, finalize the remote feature vector providing the flattened
4467
        // feature bit namespace.
4468
        p.remoteFeatures = lnwire.NewFeatureVector(
6✔
4469
                msg.Features, lnwire.Features,
6✔
4470
        )
6✔
4471

6✔
4472
        // Now that we have their features loaded, we'll ensure that they
6✔
4473
        // didn't set any required bits that we don't know of.
6✔
4474
        err = feature.ValidateRequired(p.remoteFeatures)
6✔
4475
        if err != nil {
6✔
4476
                return fmt.Errorf("invalid remote features: %w", err)
×
4477
        }
×
4478

4479
        // Ensure the remote party's feature vector contains all transitive
4480
        // dependencies. We know ours are correct since they are validated
4481
        // during the feature manager's instantiation.
4482
        err = feature.ValidateDeps(p.remoteFeatures)
6✔
4483
        if err != nil {
6✔
4484
                return fmt.Errorf("invalid remote features: %w", err)
×
4485
        }
×
4486

4487
        // Now that we know we understand their requirements, we'll check to
4488
        // see if they don't support anything that we deem to be mandatory.
4489
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
6✔
4490
                return fmt.Errorf("data loss protection required")
×
4491
        }
×
4492

4493
        return nil
6✔
4494
}
4495

4496
// LocalFeatures returns the set of global features that has been advertised by
4497
// the local node. This allows sub-systems that use this interface to gate their
4498
// behavior off the set of negotiated feature bits.
4499
//
4500
// NOTE: Part of the lnpeer.Peer interface.
4501
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
3✔
4502
        return p.cfg.Features
3✔
4503
}
3✔
4504

4505
// RemoteFeatures returns the set of global features that has been advertised by
4506
// the remote node. This allows sub-systems that use this interface to gate
4507
// their behavior off the set of negotiated feature bits.
4508
//
4509
// NOTE: Part of the lnpeer.Peer interface.
4510
func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector {
16✔
4511
        return p.remoteFeatures
16✔
4512
}
16✔
4513

4514
// hasNegotiatedScidAlias returns true if we've negotiated the
4515
// option-scid-alias feature bit with the peer.
4516
func (p *Brontide) hasNegotiatedScidAlias() bool {
6✔
4517
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
6✔
4518
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
6✔
4519
        return peerHas && localHas
6✔
4520
}
6✔
4521

4522
// sendInitMsg sends the Init message to the remote peer. This message contains
4523
// our currently supported local and global features.
4524
func (p *Brontide) sendInitMsg(legacyChan bool) error {
10✔
4525
        features := p.cfg.Features.Clone()
10✔
4526
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
10✔
4527

10✔
4528
        // If we have a legacy channel open with a peer, we downgrade static
10✔
4529
        // remote required to optional in case the peer does not understand the
10✔
4530
        // required feature bit. If we do not do this, the peer will reject our
10✔
4531
        // connection because it does not understand a required feature bit, and
10✔
4532
        // our channel will be unusable.
10✔
4533
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
11✔
4534
                p.log.Infof("Legacy channel open with peer, " +
1✔
4535
                        "downgrading static remote required feature bit to " +
1✔
4536
                        "optional")
1✔
4537

1✔
4538
                // Unset and set in both the local and global features to
1✔
4539
                // ensure both sets are consistent and merge able by old and
1✔
4540
                // new nodes.
1✔
4541
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4542
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4543

1✔
4544
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
4545
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
4546
        }
1✔
4547

4548
        msg := lnwire.NewInitMessage(
10✔
4549
                legacyFeatures.RawFeatureVector,
10✔
4550
                features.RawFeatureVector,
10✔
4551
        )
10✔
4552

10✔
4553
        return p.writeMessage(msg)
10✔
4554
}
4555

4556
// resendChanSyncMsg will attempt to find a channel sync message for the closed
4557
// channel and resend it to our peer.
4558
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
3✔
4559
        // If we already re-sent the mssage for this channel, we won't do it
3✔
4560
        // again.
3✔
4561
        if _, ok := p.resentChanSyncMsg[cid]; ok {
3✔
UNCOV
4562
                return nil
×
UNCOV
4563
        }
×
4564

4565
        // Check if we have any channel sync messages stored for this channel.
4566
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
3✔
4567
        if err != nil {
6✔
4568
                return fmt.Errorf("unable to fetch channel sync messages for "+
3✔
4569
                        "peer %v: %v", p, err)
3✔
4570
        }
3✔
4571

4572
        if c.LastChanSyncMsg == nil {
3✔
4573
                return fmt.Errorf("no chan sync message stored for channel %v",
×
4574
                        cid)
×
4575
        }
×
4576

4577
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
3✔
4578
                return fmt.Errorf("ignoring channel reestablish from "+
×
4579
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
4580
        }
×
4581

4582
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
3✔
4583
                "peer", cid)
3✔
4584

3✔
4585
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
3✔
4586
                return fmt.Errorf("failed resending channel sync "+
×
4587
                        "message to peer %v: %v", p, err)
×
4588
        }
×
4589

4590
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
3✔
4591
                cid)
3✔
4592

3✔
4593
        // Note down that we sent the message, so we won't resend it again for
3✔
4594
        // this connection.
3✔
4595
        p.resentChanSyncMsg[cid] = struct{}{}
3✔
4596

3✔
4597
        return nil
3✔
4598
}
4599

4600
// SendMessage sends a variadic number of high-priority messages to the remote
4601
// peer. The first argument denotes if the method should block until the
4602
// messages have been sent to the remote peer or an error is returned,
4603
// otherwise it returns immediately after queuing.
4604
//
4605
// NOTE: Part of the lnpeer.Peer interface.
4606
func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error {
6✔
4607
        return p.sendMessage(sync, true, msgs...)
6✔
4608
}
6✔
4609

4610
// SendMessageLazy sends a variadic number of low-priority messages to the
4611
// remote peer. The first argument denotes if the method should block until
4612
// the messages have been sent to the remote peer or an error is returned,
4613
// otherwise it returns immediately after queueing.
4614
//
4615
// NOTE: Part of the lnpeer.Peer interface.
4616
func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
4✔
4617
        return p.sendMessage(sync, false, msgs...)
4✔
4618
}
4✔
4619

4620
// sendMessage queues a variadic number of messages using the passed priority
4621
// to the remote peer. If sync is true, this method will block until the
4622
// messages have been sent to the remote peer or an error is returned, otherwise
4623
// it returns immediately after queueing.
4624
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
7✔
4625
        // Add all incoming messages to the outgoing queue. A list of error
7✔
4626
        // chans is populated for each message if the caller requested a sync
7✔
4627
        // send.
7✔
4628
        var errChans []chan error
7✔
4629
        if sync {
11✔
4630
                errChans = make([]chan error, 0, len(msgs))
4✔
4631
        }
4✔
4632
        for _, msg := range msgs {
14✔
4633
                // If a sync send was requested, create an error chan to listen
7✔
4634
                // for an ack from the writeHandler.
7✔
4635
                var errChan chan error
7✔
4636
                if sync {
11✔
4637
                        errChan = make(chan error, 1)
4✔
4638
                        errChans = append(errChans, errChan)
4✔
4639
                }
4✔
4640

4641
                if priority {
13✔
4642
                        p.queueMsg(msg, errChan)
6✔
4643
                } else {
10✔
4644
                        p.queueMsgLazy(msg, errChan)
4✔
4645
                }
4✔
4646
        }
4647

4648
        // Wait for all replies from the writeHandler. For async sends, this
4649
        // will be a NOP as the list of error chans is nil.
4650
        for _, errChan := range errChans {
11✔
4651
                select {
4✔
4652
                case err := <-errChan:
4✔
4653
                        return err
4✔
4654
                case <-p.cg.Done():
×
4655
                        return lnpeer.ErrPeerExiting
×
4656
                case <-p.cfg.Quit:
×
4657
                        return lnpeer.ErrPeerExiting
×
4658
                }
4659
        }
4660

4661
        return nil
6✔
4662
}
4663

4664
// PubKey returns the pubkey of the peer in compressed serialized format.
4665
//
4666
// NOTE: Part of the lnpeer.Peer interface.
4667
func (p *Brontide) PubKey() [33]byte {
5✔
4668
        return p.cfg.PubKeyBytes
5✔
4669
}
5✔
4670

4671
// IdentityKey returns the public key of the remote peer.
4672
//
4673
// NOTE: Part of the lnpeer.Peer interface.
4674
func (p *Brontide) IdentityKey() *btcec.PublicKey {
18✔
4675
        return p.cfg.Addr.IdentityKey
18✔
4676
}
18✔
4677

4678
// Address returns the network address of the remote peer.
4679
//
4680
// NOTE: Part of the lnpeer.Peer interface.
4681
func (p *Brontide) Address() net.Addr {
3✔
4682
        return p.cfg.Addr.Address
3✔
4683
}
3✔
4684

4685
// AddNewChannel adds a new channel to the peer. The channel should fail to be
4686
// added if the cancel channel is closed.
4687
//
4688
// NOTE: Part of the lnpeer.Peer interface.
4689
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
4690
        cancel <-chan struct{}) error {
3✔
4691

3✔
4692
        errChan := make(chan error, 1)
3✔
4693
        newChanMsg := &newChannelMsg{
3✔
4694
                channel: newChan,
3✔
4695
                err:     errChan,
3✔
4696
        }
3✔
4697

3✔
4698
        select {
3✔
4699
        case p.newActiveChannel <- newChanMsg:
3✔
4700
        case <-cancel:
×
4701
                return errors.New("canceled adding new channel")
×
4702
        case <-p.cg.Done():
×
4703
                return lnpeer.ErrPeerExiting
×
4704
        }
4705

4706
        // We pause here to wait for the peer to recognize the new channel
4707
        // before we close the channel barrier corresponding to the channel.
4708
        select {
3✔
4709
        case err := <-errChan:
3✔
4710
                return err
3✔
4711
        case <-p.cg.Done():
×
4712
                return lnpeer.ErrPeerExiting
×
4713
        }
4714
}
4715

4716
// AddPendingChannel adds a pending open channel to the peer. The channel
4717
// should fail to be added if the cancel channel is closed.
4718
//
4719
// NOTE: Part of the lnpeer.Peer interface.
4720
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
4721
        cancel <-chan struct{}) error {
3✔
4722

3✔
4723
        errChan := make(chan error, 1)
3✔
4724
        newChanMsg := &newChannelMsg{
3✔
4725
                channelID: cid,
3✔
4726
                err:       errChan,
3✔
4727
        }
3✔
4728

3✔
4729
        select {
3✔
4730
        case p.newPendingChannel <- newChanMsg:
3✔
4731

4732
        case <-cancel:
×
4733
                return errors.New("canceled adding pending channel")
×
4734

4735
        case <-p.cg.Done():
×
4736
                return lnpeer.ErrPeerExiting
×
4737
        }
4738

4739
        // We pause here to wait for the peer to recognize the new pending
4740
        // channel before we close the channel barrier corresponding to the
4741
        // channel.
4742
        select {
3✔
4743
        case err := <-errChan:
3✔
4744
                return err
3✔
4745

4746
        case <-cancel:
×
4747
                return errors.New("canceled adding pending channel")
×
4748

4749
        case <-p.cg.Done():
×
4750
                return lnpeer.ErrPeerExiting
×
4751
        }
4752
}
4753

4754
// RemovePendingChannel removes a pending open channel from the peer.
4755
//
4756
// NOTE: Part of the lnpeer.Peer interface.
4757
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
3✔
4758
        errChan := make(chan error, 1)
3✔
4759
        newChanMsg := &newChannelMsg{
3✔
4760
                channelID: cid,
3✔
4761
                err:       errChan,
3✔
4762
        }
3✔
4763

3✔
4764
        select {
3✔
4765
        case p.removePendingChannel <- newChanMsg:
3✔
4766
        case <-p.cg.Done():
×
4767
                return lnpeer.ErrPeerExiting
×
4768
        }
4769

4770
        // We pause here to wait for the peer to respond to the cancellation of
4771
        // the pending channel before we close the channel barrier
4772
        // corresponding to the channel.
4773
        select {
3✔
4774
        case err := <-errChan:
3✔
4775
                return err
3✔
4776

4777
        case <-p.cg.Done():
×
4778
                return lnpeer.ErrPeerExiting
×
4779
        }
4780
}
4781

4782
// StartTime returns the time at which the connection was established if the
4783
// peer started successfully, and zero otherwise.
4784
func (p *Brontide) StartTime() time.Time {
3✔
4785
        return p.startTime
3✔
4786
}
3✔
4787

4788
// handleCloseMsg is called when a new cooperative channel closure related
4789
// message is received from the remote peer. We'll use this message to advance
4790
// the chan closer state machine.
4791
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
16✔
4792
        link := p.fetchLinkFromKeyAndCid(msg.cid)
16✔
4793

16✔
4794
        // We'll now fetch the matching closing state machine in order to
16✔
4795
        // continue, or finalize the channel closure process.
16✔
4796
        chanCloserE, err := p.fetchActiveChanCloser(msg.cid)
16✔
4797
        if err != nil {
19✔
4798
                // If the channel is not known to us, we'll simply ignore this
3✔
4799
                // message.
3✔
4800
                if err == ErrChannelNotFound {
6✔
4801
                        return
3✔
4802
                }
3✔
4803

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

×
4806
                errMsg := &lnwire.Error{
×
4807
                        ChanID: msg.cid,
×
4808
                        Data:   lnwire.ErrorData(err.Error()),
×
4809
                }
×
4810
                p.queueMsg(errMsg, nil)
×
4811
                return
×
4812
        }
4813

4814
        if chanCloserE.IsRight() {
16✔
4815
                // TODO(roasbeef): assert?
×
4816
                return
×
4817
        }
×
4818

4819
        // At this point, we'll only enter this call path if a negotiate chan
4820
        // closer was used. So we'll extract that from the either now.
4821
        //
4822
        // TODO(roabeef): need extra helper func for either to make cleaner
4823
        var chanCloser *chancloser.ChanCloser
16✔
4824
        chanCloserE.WhenLeft(func(c *chancloser.ChanCloser) {
32✔
4825
                chanCloser = c
16✔
4826
        })
16✔
4827

4828
        handleErr := func(err error) {
17✔
4829
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
4830
                p.log.Error(err)
1✔
4831

1✔
4832
                // As the negotiations failed, we'll reset the channel state
1✔
4833
                // machine to ensure we act to on-chain events as normal.
1✔
4834
                chanCloser.Channel().ResetState()
1✔
4835
                if chanCloser.CloseRequest() != nil {
1✔
4836
                        chanCloser.CloseRequest().Err <- err
×
4837
                }
×
4838

4839
                p.activeChanCloses.Delete(msg.cid)
1✔
4840

1✔
4841
                p.Disconnect(err)
1✔
4842
        }
4843

4844
        // Next, we'll process the next message using the target state machine.
4845
        // We'll either continue negotiation, or halt.
4846
        switch typed := msg.msg.(type) {
16✔
4847
        case *lnwire.Shutdown:
8✔
4848
                // Disable incoming adds immediately.
8✔
4849
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
8✔
4850
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
4851
                                link.ChanID())
×
4852
                }
×
4853

4854
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
8✔
4855
                if err != nil {
8✔
4856
                        handleErr(err)
×
4857
                        return
×
4858
                }
×
4859

4860
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
14✔
4861
                        // If the link is nil it means we can immediately queue
6✔
4862
                        // the Shutdown message since we don't have to wait for
6✔
4863
                        // commitment transaction synchronization.
6✔
4864
                        if link == nil {
7✔
4865
                                p.queueMsg(&msg, nil)
1✔
4866
                                return
1✔
4867
                        }
1✔
4868

4869
                        // Immediately disallow any new HTLC's from being added
4870
                        // in the outgoing direction.
4871
                        if !link.DisableAdds(htlcswitch.Outgoing) {
5✔
4872
                                p.log.Warnf("Outgoing link adds already "+
×
4873
                                        "disabled: %v", link.ChanID())
×
4874
                        }
×
4875

4876
                        // When we have a Shutdown to send, we defer it till the
4877
                        // next time we send a CommitSig to remain spec
4878
                        // compliant.
4879
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
10✔
4880
                                p.queueMsg(&msg, nil)
5✔
4881
                        })
5✔
4882
                })
4883

4884
                beginNegotiation := func() {
16✔
4885
                        oClosingSigned, err := chanCloser.BeginNegotiation()
8✔
4886
                        if err != nil {
8✔
4887
                                handleErr(err)
×
4888
                                return
×
4889
                        }
×
4890

4891
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
16✔
4892
                                p.queueMsg(&msg, nil)
8✔
4893
                        })
8✔
4894
                }
4895

4896
                if link == nil {
9✔
4897
                        beginNegotiation()
1✔
4898
                } else {
8✔
4899
                        // Now we register a flush hook to advance the
7✔
4900
                        // ChanCloser and possibly send out a ClosingSigned
7✔
4901
                        // when the link finishes draining.
7✔
4902
                        link.OnFlushedOnce(func() {
14✔
4903
                                // Remove link in goroutine to prevent deadlock.
7✔
4904
                                go p.cfg.Switch.RemoveLink(msg.cid)
7✔
4905
                                beginNegotiation()
7✔
4906
                        })
7✔
4907
                }
4908

4909
        case *lnwire.ClosingSigned:
11✔
4910
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
11✔
4911
                if err != nil {
12✔
4912
                        handleErr(err)
1✔
4913
                        return
1✔
4914
                }
1✔
4915

4916
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
22✔
4917
                        p.queueMsg(&msg, nil)
11✔
4918
                })
11✔
4919

4920
        default:
×
4921
                panic("impossible closeMsg type")
×
4922
        }
4923

4924
        // If we haven't finished close negotiations, then we'll continue as we
4925
        // can't yet finalize the closure.
4926
        if _, err := chanCloser.ClosingTx(); err != nil {
26✔
4927
                return
11✔
4928
        }
11✔
4929

4930
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
4931
        // the channel closure by notifying relevant sub-systems and launching a
4932
        // goroutine to wait for close tx conf.
4933
        p.finalizeChanClosure(chanCloser)
7✔
4934
}
4935

4936
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
4937
// the channelManager goroutine, which will shut down the link and possibly
4938
// close the channel.
4939
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
3✔
4940
        select {
3✔
4941
        case p.localCloseChanReqs <- req:
3✔
4942
                p.log.Info("Local close channel request is going to be " +
3✔
4943
                        "delivered to the peer")
3✔
4944
        case <-p.cg.Done():
×
4945
                p.log.Info("Unable to deliver local close channel request " +
×
4946
                        "to peer")
×
4947
        }
4948
}
4949

4950
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
4951
func (p *Brontide) NetAddress() *lnwire.NetAddress {
3✔
4952
        return p.cfg.Addr
3✔
4953
}
3✔
4954

4955
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
4956
func (p *Brontide) Inbound() bool {
3✔
4957
        return p.cfg.Inbound
3✔
4958
}
3✔
4959

4960
// ConnReq is a getter for the Brontide's connReq in cfg.
4961
func (p *Brontide) ConnReq() *connmgr.ConnReq {
3✔
4962
        return p.cfg.ConnReq
3✔
4963
}
3✔
4964

4965
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
4966
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
3✔
4967
        return p.cfg.ErrorBuffer
3✔
4968
}
3✔
4969

4970
// SetAddress sets the remote peer's address given an address.
4971
func (p *Brontide) SetAddress(address net.Addr) {
×
4972
        p.cfg.Addr.Address = address
×
4973
}
×
4974

4975
// ActiveSignal returns the peer's active signal.
4976
func (p *Brontide) ActiveSignal() chan struct{} {
3✔
4977
        return p.activeSignal
3✔
4978
}
3✔
4979

4980
// Conn returns a pointer to the peer's connection struct.
4981
func (p *Brontide) Conn() net.Conn {
3✔
4982
        return p.cfg.Conn
3✔
4983
}
3✔
4984

4985
// BytesReceived returns the number of bytes received from the peer.
4986
func (p *Brontide) BytesReceived() uint64 {
3✔
4987
        return atomic.LoadUint64(&p.bytesReceived)
3✔
4988
}
3✔
4989

4990
// BytesSent returns the number of bytes sent to the peer.
4991
func (p *Brontide) BytesSent() uint64 {
3✔
4992
        return atomic.LoadUint64(&p.bytesSent)
3✔
4993
}
3✔
4994

4995
// LastRemotePingPayload returns the last payload the remote party sent as part
4996
// of their ping.
4997
func (p *Brontide) LastRemotePingPayload() []byte {
3✔
4998
        pingPayload := p.lastPingPayload.Load()
3✔
4999
        if pingPayload == nil {
6✔
5000
                return []byte{}
3✔
5001
        }
3✔
5002

5003
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
5004
        if !ok {
×
5005
                return nil
×
5006
        }
×
5007

5008
        return pingBytes
×
5009
}
5010

5011
// attachChannelEventSubscription creates a channel event subscription and
5012
// attaches to client to Brontide if the reenableTimeout is no greater than 1
5013
// minute.
5014
func (p *Brontide) attachChannelEventSubscription() error {
6✔
5015
        // If the timeout is greater than 1 minute, it's unlikely that the link
6✔
5016
        // hasn't yet finished its reestablishment. Return a nil without
6✔
5017
        // creating the client to specify that we don't want to retry.
6✔
5018
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
9✔
5019
                return nil
3✔
5020
        }
3✔
5021

5022
        // When the reenable timeout is less than 1 minute, it's likely the
5023
        // channel link hasn't finished its reestablishment yet. In that case,
5024
        // we'll give it a second chance by subscribing to the channel update
5025
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
5026
        // enabling the channel again.
5027
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
6✔
5028
        if err != nil {
6✔
5029
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
5030
        }
×
5031

5032
        p.channelEventClient = sub
6✔
5033

6✔
5034
        return nil
6✔
5035
}
5036

5037
// updateNextRevocation updates the existing channel's next revocation if it's
5038
// nil.
5039
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
6✔
5040
        chanPoint := c.FundingOutpoint
6✔
5041
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
6✔
5042

6✔
5043
        // Read the current channel.
6✔
5044
        currentChan, loaded := p.activeChannels.Load(chanID)
6✔
5045

6✔
5046
        // currentChan should exist, but we perform a check anyway to avoid nil
6✔
5047
        // pointer dereference.
6✔
5048
        if !loaded {
7✔
5049
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
5050
                        chanID)
1✔
5051
        }
1✔
5052

5053
        // currentChan should not be nil, but we perform a check anyway to
5054
        // avoid nil pointer dereference.
5055
        if currentChan == nil {
6✔
5056
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
5057
                        chanID)
1✔
5058
        }
1✔
5059

5060
        // If we're being sent a new channel, and our existing channel doesn't
5061
        // have the next revocation, then we need to update the current
5062
        // existing channel.
5063
        if currentChan.RemoteNextRevocation() != nil {
4✔
5064
                return nil
×
5065
        }
×
5066

5067
        p.log.Infof("Processing retransmitted ChannelReady for "+
4✔
5068
                "ChannelPoint(%v)", chanPoint)
4✔
5069

4✔
5070
        nextRevoke := c.RemoteNextRevocation
4✔
5071

4✔
5072
        err := currentChan.InitNextRevocation(nextRevoke)
4✔
5073
        if err != nil {
4✔
5074
                return fmt.Errorf("unable to init next revocation: %w", err)
×
5075
        }
×
5076

5077
        return nil
4✔
5078
}
5079

5080
// addActiveChannel adds a new active channel to the `activeChannels` map. It
5081
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
5082
// it and assembles it with a channel link.
5083
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
3✔
5084
        chanPoint := c.FundingOutpoint
3✔
5085
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5086

3✔
5087
        // If we've reached this point, there are two possible scenarios.  If
3✔
5088
        // the channel was in the active channels map as nil, then it was
3✔
5089
        // loaded from disk and we need to send reestablish. Else, it was not
3✔
5090
        // loaded from disk and we don't need to send reestablish as this is a
3✔
5091
        // fresh channel.
3✔
5092
        shouldReestablish := p.isLoadedFromDisk(chanID)
3✔
5093

3✔
5094
        chanOpts := c.ChanOpts
3✔
5095
        if shouldReestablish {
6✔
5096
                // If we have to do the reestablish dance for this channel,
3✔
5097
                // ensure that we don't try to call InitRemoteMusigNonces twice
3✔
5098
                // by calling SkipNonceInit.
3✔
5099
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
3✔
5100
        }
3✔
5101

5102
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
3✔
5103
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
5104
        })
×
5105
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
3✔
5106
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
5107
        })
×
5108
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
3✔
5109
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
5110
        })
×
5111

5112
        // If not already active, we'll add this channel to the set of active
5113
        // channels, so we can look it up later easily according to its channel
5114
        // ID.
5115
        lnChan, err := lnwallet.NewLightningChannel(
3✔
5116
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
3✔
5117
        )
3✔
5118
        if err != nil {
3✔
5119
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
5120
        }
×
5121

5122
        // Store the channel in the activeChannels map.
5123
        p.activeChannels.Store(chanID, lnChan)
3✔
5124

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

3✔
5127
        // Next, we'll assemble a ChannelLink along with the necessary items it
3✔
5128
        // needs to function.
3✔
5129
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
3✔
5130
        if err != nil {
3✔
5131
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
5132
                        err)
×
5133
        }
×
5134

5135
        // We'll query the channel DB for the new channel's initial forwarding
5136
        // policies to determine the policy we start out with.
5137
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
3✔
5138
        if err != nil {
3✔
5139
                return fmt.Errorf("unable to query for initial forwarding "+
×
5140
                        "policy: %v", err)
×
5141
        }
×
5142

5143
        // Create the link and add it to the switch.
5144
        err = p.addLink(
3✔
5145
                &chanPoint, lnChan, initialPolicy, chainEvents,
3✔
5146
                shouldReestablish, fn.None[lnwire.Shutdown](),
3✔
5147
        )
3✔
5148
        if err != nil {
3✔
5149
                return fmt.Errorf("can't register new channel link(%v) with "+
×
5150
                        "peer", chanPoint)
×
5151
        }
×
5152

5153
        isTaprootChan := c.ChanType.IsTaproot()
3✔
5154

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

5162
        // Now that the link has been added above, we'll also init an RBF chan
5163
        // closer for this channel, but only if the new close feature is
5164
        // negotiated.
5165
        //
5166
        // Creating this here ensures that any shutdown messages sent will be
5167
        // automatically routed by the msg router.
5168
        if _, err := p.initRbfChanCloser(lnChan); err != nil {
3✔
5169
                p.activeChanCloses.Delete(chanID)
×
5170

×
5171
                return fmt.Errorf("unable to init RBF chan closer for new "+
×
5172
                        "chan: %w", err)
×
5173
        }
×
5174

5175
        return nil
3✔
5176
}
5177

5178
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
5179
// know this channel ID or not, we'll either add it to the `activeChannels` map
5180
// or init the next revocation for it.
5181
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
3✔
5182
        newChan := req.channel
3✔
5183
        chanPoint := newChan.FundingOutpoint
3✔
5184
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5185

3✔
5186
        // Only update RemoteNextRevocation if the channel is in the
3✔
5187
        // activeChannels map and if we added the link to the switch. Only
3✔
5188
        // active channels will be added to the switch.
3✔
5189
        if p.isActiveChannel(chanID) {
6✔
5190
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
3✔
5191
                        chanPoint)
3✔
5192

3✔
5193
                // Handle it and close the err chan on the request.
3✔
5194
                close(req.err)
3✔
5195

3✔
5196
                // Update the next revocation point.
3✔
5197
                err := p.updateNextRevocation(newChan.OpenChannel)
3✔
5198
                if err != nil {
3✔
5199
                        p.log.Errorf(err.Error())
×
5200
                }
×
5201

5202
                return
3✔
5203
        }
5204

5205
        // This is a new channel, we now add it to the map.
5206
        if err := p.addActiveChannel(req.channel); err != nil {
3✔
5207
                // Log and send back the error to the request.
×
5208
                p.log.Errorf(err.Error())
×
5209
                req.err <- err
×
5210

×
5211
                return
×
5212
        }
×
5213

5214
        // Close the err chan if everything went fine.
5215
        close(req.err)
3✔
5216
}
5217

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

7✔
5225
        chanID := req.channelID
7✔
5226

7✔
5227
        // If we already have this channel, something is wrong with the funding
7✔
5228
        // flow as it will only be marked as active after `ChannelReady` is
7✔
5229
        // handled. In this case, we will do nothing but log an error, just in
7✔
5230
        // case this is a legit channel.
7✔
5231
        if p.isActiveChannel(chanID) {
8✔
5232
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
5233
                        "pending channel request", chanID)
1✔
5234

1✔
5235
                return
1✔
5236
        }
1✔
5237

5238
        // The channel has already been added, we will do nothing and return.
5239
        if p.isPendingChannel(chanID) {
7✔
5240
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
5241
                        "pending channel request", chanID)
1✔
5242

1✔
5243
                return
1✔
5244
        }
1✔
5245

5246
        // This is a new channel, we now add it to the map `activeChannels`
5247
        // with nil value and mark it as a newly added channel in
5248
        // `addedChannels`.
5249
        p.activeChannels.Store(chanID, nil)
5✔
5250
        p.addedChannels.Store(chanID, struct{}{})
5✔
5251
}
5252

5253
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
5254
// from `activeChannels` map. The request will be ignored if the channel is
5255
// considered active by Brontide. Noop if the channel ID cannot be found.
5256
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
7✔
5257
        defer close(req.err)
7✔
5258

7✔
5259
        chanID := req.channelID
7✔
5260

7✔
5261
        // If we already have this channel, something is wrong with the funding
7✔
5262
        // flow as it will only be marked as active after `ChannelReady` is
7✔
5263
        // handled. In this case, we will log an error and exit.
7✔
5264
        if p.isActiveChannel(chanID) {
8✔
5265
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
5266
                        chanID)
1✔
5267
                return
1✔
5268
        }
1✔
5269

5270
        // The channel has not been added yet, we will log a warning as there
5271
        // is an unexpected call from funding manager.
5272
        if !p.isPendingChannel(chanID) {
10✔
5273
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
4✔
5274
        }
4✔
5275

5276
        // Remove the record of this pending channel.
5277
        p.activeChannels.Delete(chanID)
6✔
5278
        p.addedChannels.Delete(chanID)
6✔
5279
}
5280

5281
// sendLinkUpdateMsg sends a message that updates the channel to the
5282
// channel's message stream.
5283
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
3✔
5284
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
3✔
5285

3✔
5286
        chanStream, ok := p.activeMsgStreams[cid]
3✔
5287
        if !ok {
6✔
5288
                // If a stream hasn't yet been created, then we'll do so, add
3✔
5289
                // it to the map, and finally start it.
3✔
5290
                chanStream = newChanMsgStream(p, cid)
3✔
5291
                p.activeMsgStreams[cid] = chanStream
3✔
5292
                chanStream.Start()
3✔
5293

3✔
5294
                // Stop the stream when quit.
3✔
5295
                go func() {
6✔
5296
                        <-p.cg.Done()
3✔
5297
                        chanStream.Stop()
3✔
5298
                }()
3✔
5299
        }
5300

5301
        // With the stream obtained, add the message to the stream so we can
5302
        // continue processing message.
5303
        chanStream.AddMsg(msg)
3✔
5304
}
5305

5306
// scaleTimeout multiplies the argument duration by a constant factor depending
5307
// on variious heuristics. Currently this is only used to check whether our peer
5308
// appears to be connected over Tor and relaxes the timout deadline. However,
5309
// this is subject to change and should be treated as opaque.
5310
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
70✔
5311
        if p.isTorConnection {
73✔
5312
                return timeout * time.Duration(torTimeoutMultiplier)
3✔
5313
        }
3✔
5314

5315
        return timeout
67✔
5316
}
5317

5318
// CoopCloseUpdates is a struct used to communicate updates for an active close
5319
// to the caller.
5320
type CoopCloseUpdates struct {
5321
        UpdateChan chan interface{}
5322

5323
        ErrChan chan error
5324
}
5325

5326
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5327
// point has an active RBF chan closer.
5328
func (p *Brontide) ChanHasRbfCoopCloser(chanPoint wire.OutPoint) bool {
3✔
5329
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5330
        chanCloser, found := p.activeChanCloses.Load(chanID)
3✔
5331
        if !found {
6✔
5332
                return false
3✔
5333
        }
3✔
5334

5335
        return chanCloser.IsRight()
3✔
5336
}
5337

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

3✔
5346
        // If RBF coop close isn't permitted, then we'll an error.
3✔
5347
        if !p.rbfCoopCloseAllowed() {
3✔
5348
                return nil, fmt.Errorf("rbf coop close not enabled for " +
×
5349
                        "channel")
×
5350
        }
×
5351

5352
        closeUpdates := &CoopCloseUpdates{
3✔
5353
                UpdateChan: make(chan interface{}, 1),
3✔
5354
                ErrChan:    make(chan error, 1),
3✔
5355
        }
3✔
5356

3✔
5357
        // We'll re-use the existing switch struct here, even though we're
3✔
5358
        // bypassing the switch entirely.
3✔
5359
        closeReq := htlcswitch.ChanClose{
3✔
5360
                CloseType:      contractcourt.CloseRegular,
3✔
5361
                ChanPoint:      &chanPoint,
3✔
5362
                TargetFeePerKw: feeRate,
3✔
5363
                DeliveryScript: deliveryScript,
3✔
5364
                Updates:        closeUpdates.UpdateChan,
3✔
5365
                Err:            closeUpdates.ErrChan,
3✔
5366
                Ctx:            ctx,
3✔
5367
        }
3✔
5368

3✔
5369
        err := p.startRbfChanCloser(newRPCShutdownInit(&closeReq), chanPoint)
3✔
5370
        if err != nil {
3✔
5371
                return nil, err
×
5372
        }
×
5373

5374
        return closeUpdates, nil
3✔
5375
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc