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

lightningnetwork / lnd / 13558005087

27 Feb 2025 03:04AM UTC coverage: 58.834% (-0.001%) from 58.835%
13558005087

Pull #8453

github

Roasbeef
lnwallet/chancloser: increase test coverage of state machine
Pull Request #8453: [4/4] - multi: integrate new rbf coop close FSM into the existing peer flow

1079 of 1370 new or added lines in 23 files covered. (78.76%)

578 existing lines in 40 files now uncovered.

137063 of 232965 relevant lines covered (58.83%)

19205.84 hits per line

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

78.59
/peer/brontide.go
1
package peer
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

123
        err chan error
124
}
125

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

511
        pingManager *PingManager
512

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

520
        cfg Config
521

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

620
        startReady chan struct{}
621

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

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

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

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

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

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

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

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

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

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

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

711
                return lastSerializedBlockHeader[:]
×
712
        }
713

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

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

743
        return p
26✔
744
}
745

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

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

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

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

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

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

784
                haveLegacyChan = true
1✔
785
                break
1✔
786
        }
787

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4✔
915
        return nil
4✔
916
}
917

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1041
                                chanID := lnwire.NewChanIDFromOutPoint(
1✔
1042
                                        dbChan.FundingOutpoint,
1✔
1043
                                )
1✔
1044

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

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

1✔
1057
                                msgs = append(msgs, channelReadyMsg)
1✔
1058
                        }
1059

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

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

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

1094
                chanPoint := dbChan.FundingOutpoint
3✔
1095

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

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

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

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

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

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

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

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

1140
                                if shutdownMsg == nil {
2✔
1141
                                        continue
1✔
1142
                                }
1143

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

1149
                        continue
3✔
1150
                }
1151

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

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

1✔
1174
                        selfPolicy = p1
1✔
1175
                } else {
2✔
1176
                        selfPolicy = p2
1✔
1177
                }
1✔
1178

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

1192
                        inboundFee := models.NewInboundFeeFromWire(
1✔
1193
                                inboundWireFee,
1✔
1194
                        )
1✔
1195

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

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

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

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

1✔
1224
                        continue
1✔
1225
                }
1226

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

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

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

×
1251
                                return
×
1252
                        }
×
1253

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

×
1270
                                return
×
1271
                        }
×
1272

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

1✔
1277
                        p.activeChanCloses.Store(chanID, makeNegotiateCloser(
1✔
1278
                                negotiateChanCloser,
1✔
1279
                        ))
1✔
1280

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

×
1287
                                return
×
1288
                        }
×
1289

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

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

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

1313
                p.activeChannels.Store(chanID, lnChan)
1✔
1314

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

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

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

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

1350
        return msgs, nil
4✔
1351
}
1352

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

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

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

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

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

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

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

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

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

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

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

1463
                hasConfirmedPublicChan = true
1✔
1464
                break
1✔
1465
        }
1466
        if !hasConfirmedPublicChan {
8✔
1467
                return
4✔
1468
        }
4✔
1469

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

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

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

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

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

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

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

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

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

1✔
1523
                        return nil
1✔
1524
                }
1✔
1525

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

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

×
1538
                        return err
×
1539
                }
×
1540

1541
                return nil
3✔
1542
        }
1543

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

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

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

1569
        p.cg.WgWait()
1✔
1570
}
1571

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

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

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

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

2✔
1599
        p.log.Infof(err.Error())
2✔
1600

2✔
1601
        // Stop PingManager before closing TCP connection.
2✔
1602
        p.pingManager.Stop()
2✔
1603

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

2✔
1607
        p.cg.Quit()
2✔
1608

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

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

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

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

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

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

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

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

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

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

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

1699
        peer *Brontide
1700

1701
        apply func(lnwire.Message)
1702

1703
        startMsg string
1704
        stopMsg  string
1705

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

1709
        mtx sync.Mutex
1710

1711
        producerSema chan struct{}
1712

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

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

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

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

1743
        return stream
4✔
1744
}
1745

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

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

1✔
1756
        close(ms.quit)
1✔
1757

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

1765
        ms.wg.Wait()
1✔
1766
}
1767

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

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

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

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

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

1✔
1805
                ms.msgCond.L.Unlock()
1✔
1806

1✔
1807
                ms.apply(msg)
1✔
1808

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

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

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

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

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

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

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

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

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

1897
                        chanPoint := event.ChannelPoint
1✔
1898

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

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

1910
                case <-p.cg.Done():
1✔
1911
                        return nil
1✔
1912
                }
1913
        }
1914
}
1915

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

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

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

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

1949
                chanLink.HandleChannelUpdate(msg)
1✔
1950
        }
1951

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
2100
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
1✔
2101

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

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

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

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

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

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

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

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

1✔
2169
                        discStream.AddMsg(msg)
1✔
2170

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

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

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

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

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

2197
        p.Disconnect(errors.New("read handler closed"))
1✔
2198

1✔
2199
        p.log.Trace("readHandler for peer done")
1✔
2200
}
2201

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

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

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

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

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

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

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

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

2256
        return channel == nil
3✔
2257
}
2258

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

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

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

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

2282
                haveChannels = true
2✔
2283

2✔
2284
                // Return false to break the iteration.
2✔
2285
                return false
2✔
2286
        })
2287

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

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

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

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

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

2321
                return false
×
2322

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

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

2333
        default:
1✔
2334
                return false
1✔
2335
        }
2336
}
2337

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

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

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

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

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

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

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

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

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

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

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

1✔
2391
                                blindingPoint = b.Val.SerializeCompressed()
1✔
2392
                        },
1✔
2393
                )
2394

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2515
                preposition := "to"
1✔
2516
                if read {
2✔
2517
                        preposition = "from"
1✔
2518
                }
1✔
2519

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

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

2531
        prefix := "readMessage from peer"
18✔
2532
        if !read {
32✔
2533
                prefix = "writeMessage to peer"
14✔
2534
        }
14✔
2535

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

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

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

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

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

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

2579
                return err
14✔
2580
        }
2581

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

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

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

2609
        return flushMsg()
14✔
2610
}
2611

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

2627
        var exitErr error
4✔
2628

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

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

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

×
2658
                                goto retry
×
2659
                        }
2660

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

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

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

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

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

1✔
2693
        p.Disconnect(exitErr)
1✔
2694

1✔
2695
        p.log.Trace("writeHandler for peer done")
1✔
2696
}
2697

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2823
                snapshot := activeChan.StateSnapshot()
1✔
2824
                snapshots = append(snapshots, snapshot)
1✔
2825

1✔
2826
                return nil
1✔
2827
        })
2828

2829
        return snapshots
1✔
2830
}
2831

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2948
                                lc.ResetState()
2✔
2949

2✔
2950
                                return nil
2✔
2951
                        })
2952

2953
                        break out
2✔
2954
                }
2955
        }
2956
}
2957

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

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

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

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

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

1✔
2987
                        continue
1✔
2988

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

×
3006
                                continue
×
3007
                        }
3008

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

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

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

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

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

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

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

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

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

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

3090
        chanCloser = makeNegotiateCloser(negotiateChanCloser)
4✔
3091

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

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

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

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

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

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

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

3126
                activePublicChans = append(
1✔
3127
                        activePublicChans, dbChan.FundingOutpoint,
1✔
3128
                )
1✔
3129

1✔
3130
                return true
1✔
3131
        })
3132

3133
        return activePublicChans
1✔
3134
}
3135

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

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

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

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

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

3171
                return nil
×
3172
        }
3173

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

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

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

3199
                                continue
×
3200
                        }
3201

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

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

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

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

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

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

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

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

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

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

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

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

3288
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
1✔
3289

1✔
3290
        var deliveryScript []byte
1✔
3291

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

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

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

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

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

3329
                shutdownDesc := fn.MapOption(
1✔
3330
                        newRestartShutdownInit,
1✔
3331
                )(shutdownInfo)
1✔
3332

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

1✔
3337
                return nil, err
1✔
3338
        }
3339

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

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

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

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

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

3378
        return shutdownMsg, nil
×
3379
}
3380

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

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

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

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

3425
        return chanCloser, nil
10✔
3426
}
3427

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

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

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

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

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

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

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

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

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

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

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

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

3504
        return nil
7✔
3505
}
3506

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

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

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

1✔
3523
        coopCloseStates := chanCloser.RegisterStateEvents()
1✔
3524
        defer chanCloser.RemoveStateSub(coopCloseStates)
1✔
3525

1✔
3526
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
1✔
3527

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

1✔
3533
        maybeNotifyTxBroadcast := func(state chancloser.AsymmetricPeerState,
1✔
3534
                party lntypes.ChannelParty) {
2✔
3535

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

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

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

3554
                        return
1✔
3555
                }
3556

3557
                closePending, ok := state.(*chancloser.ClosePending)
1✔
3558

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

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

1✔
3574
                        return
1✔
3575
                }
1✔
3576

3577
                feeRate := closePending.FeeRate
1✔
3578
                lastFeeRates.SetForParty(party, feeRate)
1✔
3579

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

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

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

3604
                lastTxids.SetForParty(party, closingTxid)
1✔
3605
        }
3606

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

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

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

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

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

1✔
3656
                                return
1✔
3657
                        }
3658

3659
                case <-closeReq.Ctx.Done():
1✔
3660
                        return
1✔
3661

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

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

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

1✔
3680
        return &chanErrorReporter{
1✔
3681
                chanID: chanID,
1✔
3682
                peer:   peer,
1✔
3683
        }
1✔
3684
}
1✔
3685

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

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

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

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

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

×
NEW
3720
                return
×
NEW
3721
        }
×
3722

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

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

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

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

3744
        coopCloseStates := chanCloser.RegisterStateEvents()
1✔
3745
        defer chanCloser.RemoveStateSub(coopCloseStates)
1✔
3746

1✔
3747
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
1✔
3748

1✔
3749
        sendChanFlushed := func() {
2✔
3750
                chanState := channel.StateSnapshot()
1✔
3751

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

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

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

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

1✔
3782
                        return
1✔
3783
                }
1✔
3784
        }
3785
}
3786

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

1✔
3793
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
1✔
3794

1✔
3795
        link := p.fetchLinkFromKeyAndCid(chanID)
1✔
3796

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

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

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

3814
        peerPub := *p.IdentityKey()
1✔
3815

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

1✔
3820
        initialState := chancloser.ChannelActive{}
1✔
3821

1✔
3822
        scid := channel.ZeroConfRealScid().UnwrapOr(
1✔
3823
                channel.ShortChanID(),
1✔
3824
        )
1✔
3825

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

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

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

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

1✔
3878
        chanCloser := protofsm.NewStateMachine(protoCfg)
1✔
3879

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

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

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

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

3898
        p.activeChanCloses.Store(chanID, makeRbfCloser(&chanCloser))
1✔
3899

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

3909
        return &chanCloser, nil
1✔
3910
}
3911

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

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

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

3931
                return feeRate
1✔
3932
        })(s)
3933

3934
        return fn.FlattenOption(feeRateOpt)
1✔
3935
}
3936

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

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

3954
                return addr
1✔
3955
        })(s)
3956

3957
        return fn.FlattenOption(addrOpt)
1✔
3958
}
3959

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

1✔
3966
                init.WhenLeft(f)
1✔
3967
        })
1✔
3968
}
3969

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

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

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

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

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

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

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

×
NEW
4022
                        return
×
NEW
4023
                }
×
4024

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

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

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

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

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

4079
        return nil
1✔
4080
}
4081

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

20✔
4236
        var chanLink htlcswitch.ChannelUpdateHandler
20✔
4237

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

4248
        return chanLink
20✔
4249
}
4250

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4409
        return nil
4✔
4410
}
4411

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
4513
        return nil
1✔
4514
}
4515

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

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

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

4557
                if priority {
9✔
4558
                        p.queueMsg(msg, errChan)
4✔
4559
                } else {
6✔
4560
                        p.queueMsgLazy(msg, errChan)
2✔
4561
                }
2✔
4562
        }
4563

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

4577
        return nil
4✔
4578
}
4579

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

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

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

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

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

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

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

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

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

1✔
4645
        select {
1✔
4646
        case p.newPendingChannel <- newChanMsg:
1✔
4647

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4755
                p.activeChanCloses.Delete(msg.cid)
1✔
4756

1✔
4757
                p.Disconnect(err)
1✔
4758
        }
4759

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

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

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

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

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

4800
                beginNegotiation := func() {
12✔
4801
                        oClosingSigned, err := chanCloser.BeginNegotiation()
6✔
4802
                        if err != nil {
7✔
4803
                                handleErr(err)
1✔
4804
                                return
1✔
4805
                        }
1✔
4806

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4924
        return pingBytes
×
4925
}
4926

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

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

4948
        p.channelEventClient = sub
4✔
4949

4✔
4950
        return nil
4✔
4951
}
4952

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

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

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

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

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

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

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

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

4993
        return nil
2✔
4994
}
4995

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

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

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

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

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

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

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

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

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

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

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

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

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

5088
        return nil
1✔
5089
}
5090

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

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

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

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

5115
                return
1✔
5116
        }
5117

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

×
5124
                return
×
5125
        }
×
5126

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

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

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

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

1✔
5148
                return
1✔
5149
        }
1✔
5150

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

1✔
5156
                return
1✔
5157
        }
1✔
5158

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

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

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

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

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

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

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

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

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

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

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

5228
        return timeout
67✔
5229
}
5230

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

5236
        ErrChan chan error
5237
}
5238

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

5248
        return chanCloser.IsRight()
1✔
5249
}
5250

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

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

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

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

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

5287
        return closeUpdates, nil
1✔
5288
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc