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

lightningnetwork / lnd / 14913967390

08 May 2025 06:56PM UTC coverage: 68.973% (-0.04%) from 69.014%
14913967390

Pull #9797

github

web-flow
Merge cf81e1aa2 into 43e822c3b
Pull Request #9797: peer: introduce super priority send queue for pings+pongs

30 of 114 new or added lines in 1 file covered. (26.32%)

101 existing lines in 26 files now uncovered.

133909 of 194147 relevant lines covered (68.97%)

22076.95 hits per line

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

77.63
/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
        // msgStreamSize is the size of the message streams.
97
        msgStreamSize = 5
98
)
99

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

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

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

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

126
        err chan error
127
}
128

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

493
        // MUST be used atomically.
494
        bytesReceived uint64
495
        bytesSent     uint64
496

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

514
        pingManager *PingManager
515

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

523
        cfg Config
524

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

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

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

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

541
        // superPrioSendQueue is a channel for messages that must bypass the
542
        // regular sendQueue, such as pings.
543
        superPrioSendQueue chan outgoingMsg
544

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

627
        startReady chan struct{}
628

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

634
        // log is a peer-specific logging instance.
635
        log btclog.Logger
636
}
637

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

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

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

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

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

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

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

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

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

719
                return lastSerializedBlockHeader[:]
×
720
        }
721

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

735
        p.pingManager = NewPingManager(&PingManagerConfig{
28✔
736
                NewPingPayload:   newPingPayload,
28✔
737
                NewPongSize:      randPongSize,
28✔
738
                IntervalDuration: p.scaleTimeout(pingInterval),
28✔
739
                TimeoutDuration:  p.scaleTimeout(pingTimeout),
28✔
740
                SendPing: func(ping *lnwire.Ping) {
28✔
NEW
741
                        // Pings are fire-and-forget, so sync=false,
×
NEW
742
                        // errChan=nil. These messages are sent via the super
×
NEW
743
                        // priority queue to avoid delays from other messages.
×
NEW
744
                        err := p.SendSuperPriorityMessage(false, ping)
×
NEW
745
                        if err != nil &&
×
NEW
746
                                !errors.Is(err, lnpeer.ErrPeerExiting) {
×
NEW
747
                                p.log.Warnf("Failed to send ping "+
×
NEW
748
                                        "via super priority queue: %v", err)
×
NEW
749
                        }
×
750
                },
751
                OnPongFailure: func(err error) {
×
752
                        eStr := "pong response failure for %s: %v " +
×
753
                                "-- disconnecting"
×
754
                        p.log.Warnf(eStr, p, err)
×
755
                        go p.Disconnect(fmt.Errorf(eStr, p, err))
×
756
                },
×
757
        })
758

759
        return p
28✔
760
}
761

762
// Start starts all helper goroutines the peer needs for normal operations.  In
763
// the case this peer has already been started, then this function is a noop.
764
func (p *Brontide) Start() error {
6✔
765
        if atomic.AddInt32(&p.started, 1) != 1 {
6✔
766
                return nil
×
767
        }
×
768

769
        // Once we've finished starting up the peer, we'll signal to other
770
        // goroutines that the they can move forward to tear down the peer, or
771
        // carry out other relevant changes.
772
        defer close(p.startReady)
6✔
773

6✔
774
        p.log.Tracef("starting with conn[%v->%v]",
6✔
775
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
6✔
776

6✔
777
        // Fetch and then load all the active channels we have with this remote
6✔
778
        // peer from the database.
6✔
779
        activeChans, err := p.cfg.ChannelDB.FetchOpenChannels(
6✔
780
                p.cfg.Addr.IdentityKey,
6✔
781
        )
6✔
782
        if err != nil {
6✔
783
                p.log.Errorf("Unable to fetch active chans "+
×
784
                        "for peer: %v", err)
×
785
                return err
×
786
        }
×
787

788
        if len(activeChans) == 0 {
10✔
789
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
4✔
790
        }
4✔
791

792
        // Quickly check if we have any existing legacy channels with this
793
        // peer.
794
        haveLegacyChan := false
6✔
795
        for _, c := range activeChans {
11✔
796
                if c.ChanType.IsTweakless() {
10✔
797
                        continue
5✔
798
                }
799

800
                haveLegacyChan = true
3✔
801
                break
3✔
802
        }
803

804
        // Exchange local and global features, the init message should be very
805
        // first between two nodes.
806
        if err := p.sendInitMsg(haveLegacyChan); err != nil {
9✔
807
                return fmt.Errorf("unable to send init msg: %w", err)
3✔
808
        }
3✔
809

810
        // Before we launch any of the helper goroutines off the peer struct,
811
        // we'll first ensure proper adherence to the p2p protocol. The init
812
        // message MUST be sent before any other message.
813
        readErr := make(chan error, 1)
6✔
814
        msgChan := make(chan lnwire.Message, 1)
6✔
815
        p.cg.WgAdd(1)
6✔
816
        go func() {
12✔
817
                defer p.cg.WgDone()
6✔
818

6✔
819
                msg, err := p.readNextMessage()
6✔
820
                if err != nil {
6✔
821
                        readErr <- err
×
822
                        msgChan <- nil
×
823
                        return
×
824
                }
×
825
                readErr <- nil
6✔
826
                msgChan <- msg
6✔
827
        }()
828

829
        select {
6✔
830
        // In order to avoid blocking indefinitely, we'll give the other peer
831
        // an upper timeout to respond before we bail out early.
832
        case <-time.After(handshakeTimeout):
×
833
                return fmt.Errorf("peer did not complete handshake within %v",
×
834
                        handshakeTimeout)
×
835
        case err := <-readErr:
6✔
836
                if err != nil {
6✔
837
                        return fmt.Errorf("unable to read init msg: %w", err)
×
838
                }
×
839
        }
840

841
        // Once the init message arrives, we can parse it so we can figure out
842
        // the negotiation of features for this session.
843
        msg := <-msgChan
6✔
844
        if msg, ok := msg.(*lnwire.Init); ok {
12✔
845
                if err := p.handleInitMsg(msg); err != nil {
6✔
846
                        p.storeError(err)
×
847
                        return err
×
848
                }
×
849
        } else {
×
850
                return errors.New("very first message between nodes " +
×
851
                        "must be init message")
×
852
        }
×
853

854
        // Next, load all the active channels we have with this peer,
855
        // registering them with the switch and launching the necessary
856
        // goroutines required to operate them.
857
        p.log.Debugf("Loaded %v active channels from database",
6✔
858
                len(activeChans))
6✔
859

6✔
860
        // Conditionally subscribe to channel events before loading channels so
6✔
861
        // we won't miss events. This subscription is used to listen to active
6✔
862
        // channel event when reenabling channels. Once the reenabling process
6✔
863
        // is finished, this subscription will be canceled.
6✔
864
        //
6✔
865
        // NOTE: ChannelNotifier must be started before subscribing events
6✔
866
        // otherwise we'd panic here.
6✔
867
        if err := p.attachChannelEventSubscription(); err != nil {
6✔
868
                return err
×
869
        }
×
870

871
        // Register the message router now as we may need to register some
872
        // endpoints while loading the channels below.
873
        p.msgRouter.WhenSome(func(router msgmux.Router) {
12✔
874
                router.Start(context.Background())
6✔
875
        })
6✔
876

877
        msgs, err := p.loadActiveChannels(activeChans)
6✔
878
        if err != nil {
6✔
879
                return fmt.Errorf("unable to load channels: %w", err)
×
880
        }
×
881

882
        p.startTime = time.Now()
6✔
883

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

5✔
891
                // Send the messages directly via writeMessage and bypass the
5✔
892
                // writeHandler goroutine.
5✔
893
                for _, msg := range msgs {
10✔
894
                        if err := p.writeMessage(msg); err != nil {
5✔
895
                                return fmt.Errorf("unable to send "+
×
896
                                        "reestablish msg: %v", err)
×
897
                        }
×
898
                }
899
        }
900

901
        err = p.pingManager.Start()
6✔
902
        if err != nil {
6✔
903
                return fmt.Errorf("could not start ping manager %w", err)
×
904
        }
×
905

906
        p.cg.WgAdd(4)
6✔
907
        go p.queueHandler()
6✔
908
        go p.writeHandler()
6✔
909
        go p.channelManager()
6✔
910
        go p.readHandler()
6✔
911

6✔
912
        // Signal to any external processes that the peer is now active.
6✔
913
        close(p.activeSignal)
6✔
914

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

6✔
930
        return nil
6✔
931
}
932

933
// initGossipSync initializes either a gossip syncer or an initial routing
934
// dump, depending on the negotiated synchronization method.
935
func (p *Brontide) initGossipSync() {
6✔
936
        // If the remote peer knows of the new gossip queries feature, then
6✔
937
        // we'll create a new gossipSyncer in the AuthenticatedGossiper for it.
6✔
938
        if p.remoteFeatures.HasFeature(lnwire.GossipQueriesOptional) {
12✔
939
                p.log.Info("Negotiated chan series queries")
6✔
940

6✔
941
                if p.cfg.AuthGossiper == nil {
9✔
942
                        // This should only ever be hit in the unit tests.
3✔
943
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
3✔
944
                                "gossip sync.")
3✔
945
                        return
3✔
946
                }
3✔
947

948
                // Register the peer's gossip syncer with the gossiper.
949
                // This blocks synchronously to ensure the gossip syncer is
950
                // registered with the gossiper before attempting to read
951
                // messages from the remote peer.
952
                //
953
                // TODO(wilmer): Only sync updates from non-channel peers. This
954
                // requires an improved version of the current network
955
                // bootstrapper to ensure we can find and connect to non-channel
956
                // peers.
957
                p.cfg.AuthGossiper.InitSyncState(p)
3✔
958
        }
959
}
960

961
// taprootShutdownAllowed returns true if both parties have negotiated the
962
// shutdown-any-segwit feature.
963
func (p *Brontide) taprootShutdownAllowed() bool {
9✔
964
        return p.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
9✔
965
                p.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
9✔
966
}
9✔
967

968
// rbfCoopCloseAllowed returns true if both parties have negotiated the new RBF
969
// coop close feature.
970
func (p *Brontide) rbfCoopCloseAllowed() bool {
10✔
971
        return p.RemoteFeatures().HasFeature(
10✔
972
                lnwire.RbfCoopCloseOptionalStaging,
10✔
973
        ) && p.LocalFeatures().HasFeature(
10✔
974
                lnwire.RbfCoopCloseOptionalStaging,
10✔
975
        )
10✔
976
}
10✔
977

978
// QuitSignal is a method that should return a channel which will be sent upon
979
// or closed once the backing peer exits. This allows callers using the
980
// interface to cancel any processing in the event the backing implementation
981
// exits.
982
//
983
// NOTE: Part of the lnpeer.Peer interface.
984
func (p *Brontide) QuitSignal() <-chan struct{} {
3✔
985
        return p.cg.Done()
3✔
986
}
3✔
987

988
// addrWithInternalKey takes a delivery script, then attempts to supplement it
989
// with information related to the internal key for the addr, but only if it's
990
// a taproot addr.
991
func (p *Brontide) addrWithInternalKey(
992
        deliveryScript []byte) (*chancloser.DeliveryAddrWithKey, error) {
12✔
993

12✔
994
        // Currently, custom channels cannot be created with external upfront
12✔
995
        // shutdown addresses, so this shouldn't be an issue. We only require
12✔
996
        // the internal key for taproot addresses to be able to provide a non
12✔
997
        // inclusion proof of any scripts.
12✔
998
        internalKeyDesc, err := lnwallet.InternalKeyForAddr(
12✔
999
                p.cfg.Wallet, &p.cfg.Wallet.Cfg.NetParams, deliveryScript,
12✔
1000
        )
12✔
1001
        if err != nil {
12✔
1002
                return nil, fmt.Errorf("unable to fetch internal key: %w", err)
×
1003
        }
×
1004

1005
        return &chancloser.DeliveryAddrWithKey{
12✔
1006
                DeliveryAddress: deliveryScript,
12✔
1007
                InternalKey: fn.MapOption(
12✔
1008
                        func(desc keychain.KeyDescriptor) btcec.PublicKey {
15✔
1009
                                return *desc.PubKey
3✔
1010
                        },
3✔
1011
                )(internalKeyDesc),
1012
        }, nil
1013
}
1014

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

6✔
1022
        // Return a slice of messages to send to the peers in case the channel
6✔
1023
        // cannot be loaded normally.
6✔
1024
        var msgs []lnwire.Message
6✔
1025

6✔
1026
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
6✔
1027

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

1048
                                err = p.cfg.AddLocalAlias(
3✔
1049
                                        aliasScid, dbChan.ShortChanID(), false,
3✔
1050
                                        false,
3✔
1051
                                )
3✔
1052
                                if err != nil {
3✔
1053
                                        return nil, err
×
1054
                                }
×
1055

1056
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
1057
                                        dbChan.FundingOutpoint,
3✔
1058
                                )
3✔
1059

3✔
1060
                                // Fetch the second commitment point to send in
3✔
1061
                                // the channel_ready message.
3✔
1062
                                second, err := dbChan.SecondCommitmentPoint()
3✔
1063
                                if err != nil {
3✔
1064
                                        return nil, err
×
1065
                                }
×
1066

1067
                                channelReadyMsg := lnwire.NewChannelReady(
3✔
1068
                                        chanID, second,
3✔
1069
                                )
3✔
1070
                                channelReadyMsg.AliasScid = &aliasScid
3✔
1071

3✔
1072
                                msgs = append(msgs, channelReadyMsg)
3✔
1073
                        }
1074

1075
                        // If we've negotiated the option-scid-alias feature
1076
                        // and this channel does not have ScidAliasFeature set
1077
                        // to true due to an upgrade where the feature bit was
1078
                        // turned on, we'll update the channel's database
1079
                        // state.
1080
                        err := dbChan.MarkScidAliasNegotiated()
3✔
1081
                        if err != nil {
3✔
1082
                                return nil, err
×
1083
                        }
×
1084
                }
1085

1086
                var chanOpts []lnwallet.ChannelOpt
5✔
1087
                p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
5✔
1088
                        chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
1089
                })
×
1090
                p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
5✔
1091
                        chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
1092
                })
×
1093
                p.cfg.AuxResolver.WhenSome(
5✔
1094
                        func(s lnwallet.AuxContractResolver) {
5✔
1095
                                chanOpts = append(
×
1096
                                        chanOpts, lnwallet.WithAuxResolver(s),
×
1097
                                )
×
1098
                        },
×
1099
                )
1100

1101
                lnChan, err := lnwallet.NewLightningChannel(
5✔
1102
                        p.cfg.Signer, dbChan, p.cfg.SigPool, chanOpts...,
5✔
1103
                )
5✔
1104
                if err != nil {
5✔
1105
                        return nil, fmt.Errorf("unable to create channel "+
×
1106
                                "state machine: %w", err)
×
1107
                }
×
1108

1109
                chanPoint := dbChan.FundingOutpoint
5✔
1110

5✔
1111
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
5✔
1112

5✔
1113
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
5✔
1114
                        chanPoint, lnChan.IsPending())
5✔
1115

5✔
1116
                // Skip adding any permanently irreconcilable channels to the
5✔
1117
                // htlcswitch.
5✔
1118
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
5✔
1119
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
10✔
1120

5✔
1121
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
5✔
1122
                                "start.", chanPoint, dbChan.ChanStatus())
5✔
1123

5✔
1124
                        // To help our peer recover from a potential data loss,
5✔
1125
                        // we resend our channel reestablish message if the
5✔
1126
                        // channel is in a borked state. We won't process any
5✔
1127
                        // channel reestablish message sent from the peer, but
5✔
1128
                        // that's okay since the assumption is that we did when
5✔
1129
                        // marking the channel borked.
5✔
1130
                        chanSync, err := dbChan.ChanSyncMsg()
5✔
1131
                        if err != nil {
5✔
1132
                                p.log.Errorf("Unable to create channel "+
×
1133
                                        "reestablish message for channel %v: "+
×
1134
                                        "%v", chanPoint, err)
×
1135
                                continue
×
1136
                        }
1137

1138
                        msgs = append(msgs, chanSync)
5✔
1139

5✔
1140
                        // Check if this channel needs to have the cooperative
5✔
1141
                        // close process restarted. If so, we'll need to send
5✔
1142
                        // the Shutdown message that is returned.
5✔
1143
                        if dbChan.HasChanStatus(
5✔
1144
                                channeldb.ChanStatusCoopBroadcasted,
5✔
1145
                        ) {
8✔
1146

3✔
1147
                                shutdownMsg, err := p.restartCoopClose(lnChan)
3✔
1148
                                if err != nil {
3✔
1149
                                        p.log.Errorf("Unable to restart "+
×
1150
                                                "coop close for channel: %v",
×
1151
                                                err)
×
1152
                                        continue
×
1153
                                }
1154

1155
                                if shutdownMsg == nil {
6✔
1156
                                        continue
3✔
1157
                                }
1158

1159
                                // Append the message to the set of messages to
1160
                                // send.
1161
                                msgs = append(msgs, shutdownMsg)
×
1162
                        }
1163

1164
                        continue
5✔
1165
                }
1166

1167
                // Before we register this new link with the HTLC Switch, we'll
1168
                // need to fetch its current link-layer forwarding policy from
1169
                // the database.
1170
                graph := p.cfg.ChannelGraph
3✔
1171
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
3✔
1172
                        &chanPoint,
3✔
1173
                )
3✔
1174
                if err != nil && !errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1175
                        return nil, err
×
1176
                }
×
1177

1178
                // We'll filter out our policy from the directional channel
1179
                // edges based whom the edge connects to. If it doesn't connect
1180
                // to us, then we know that we were the one that advertised the
1181
                // policy.
1182
                //
1183
                // TODO(roasbeef): can add helper method to get policy for
1184
                // particular channel.
1185
                var selfPolicy *models.ChannelEdgePolicy
3✔
1186
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
3✔
1187
                        p.cfg.ServerPubKey[:]) {
6✔
1188

3✔
1189
                        selfPolicy = p1
3✔
1190
                } else {
6✔
1191
                        selfPolicy = p2
3✔
1192
                }
3✔
1193

1194
                // If we don't yet have an advertised routing policy, then
1195
                // we'll use the current default, otherwise we'll translate the
1196
                // routing policy into a forwarding policy.
1197
                var forwardingPolicy *models.ForwardingPolicy
3✔
1198
                if selfPolicy != nil {
6✔
1199
                        var inboundWireFee lnwire.Fee
3✔
1200
                        _, err := selfPolicy.ExtraOpaqueData.ExtractRecords(
3✔
1201
                                &inboundWireFee,
3✔
1202
                        )
3✔
1203
                        if err != nil {
3✔
1204
                                return nil, err
×
1205
                        }
×
1206

1207
                        inboundFee := models.NewInboundFeeFromWire(
3✔
1208
                                inboundWireFee,
3✔
1209
                        )
3✔
1210

3✔
1211
                        forwardingPolicy = &models.ForwardingPolicy{
3✔
1212
                                MinHTLCOut:    selfPolicy.MinHTLC,
3✔
1213
                                MaxHTLC:       selfPolicy.MaxHTLC,
3✔
1214
                                BaseFee:       selfPolicy.FeeBaseMSat,
3✔
1215
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
3✔
1216
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
3✔
1217

3✔
1218
                                InboundFee: inboundFee,
3✔
1219
                        }
3✔
1220
                } else {
3✔
1221
                        p.log.Warnf("Unable to find our forwarding policy "+
3✔
1222
                                "for channel %v, using default values",
3✔
1223
                                chanPoint)
3✔
1224
                        forwardingPolicy = &p.cfg.RoutingPolicy
3✔
1225
                }
3✔
1226

1227
                p.log.Tracef("Using link policy of: %v",
3✔
1228
                        spew.Sdump(forwardingPolicy))
3✔
1229

3✔
1230
                // If the channel is pending, set the value to nil in the
3✔
1231
                // activeChannels map. This is done to signify that the channel
3✔
1232
                // is pending. We don't add the link to the switch here - it's
3✔
1233
                // the funding manager's responsibility to spin up pending
3✔
1234
                // channels. Adding them here would just be extra work as we'll
3✔
1235
                // tear them down when creating + adding the final link.
3✔
1236
                if lnChan.IsPending() {
6✔
1237
                        p.activeChannels.Store(chanID, nil)
3✔
1238

3✔
1239
                        continue
3✔
1240
                }
1241

1242
                shutdownInfo, err := lnChan.State().ShutdownInfo()
3✔
1243
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
3✔
1244
                        return nil, err
×
1245
                }
×
1246

1247
                isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
1248

3✔
1249
                var (
3✔
1250
                        shutdownMsg     fn.Option[lnwire.Shutdown]
3✔
1251
                        shutdownInfoErr error
3✔
1252
                )
3✔
1253
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
6✔
1254
                        // If we can use the new RBF close feature, we don't
3✔
1255
                        // need to create the legacy closer. However for taproot
3✔
1256
                        // channels, we'll continue to use the legacy closer.
3✔
1257
                        if p.rbfCoopCloseAllowed() && !isTaprootChan {
6✔
1258
                                return
3✔
1259
                        }
3✔
1260

1261
                        // Compute an ideal fee.
1262
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
1263
                                p.cfg.CoopCloseTargetConfs,
3✔
1264
                        )
3✔
1265
                        if err != nil {
3✔
1266
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1267
                                        "estimate fee: %w", err)
×
1268

×
1269
                                return
×
1270
                        }
×
1271

1272
                        addr, err := p.addrWithInternalKey(
3✔
1273
                                info.DeliveryScript.Val,
3✔
1274
                        )
3✔
1275
                        if err != nil {
3✔
1276
                                shutdownInfoErr = fmt.Errorf("unable to make "+
×
1277
                                        "delivery addr: %w", err)
×
1278
                                return
×
1279
                        }
×
1280
                        negotiateChanCloser, err := p.createChanCloser(
3✔
1281
                                lnChan, addr, feePerKw, nil,
3✔
1282
                                info.Closer(),
3✔
1283
                        )
3✔
1284
                        if err != nil {
3✔
1285
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1286
                                        "create chan closer: %w", err)
×
1287

×
1288
                                return
×
1289
                        }
×
1290

1291
                        chanID := lnwire.NewChanIDFromOutPoint(
3✔
1292
                                lnChan.State().FundingOutpoint,
3✔
1293
                        )
3✔
1294

3✔
1295
                        p.activeChanCloses.Store(chanID, makeNegotiateCloser(
3✔
1296
                                negotiateChanCloser,
3✔
1297
                        ))
3✔
1298

3✔
1299
                        // Create the Shutdown message.
3✔
1300
                        shutdown, err := negotiateChanCloser.ShutdownChan()
3✔
1301
                        if err != nil {
3✔
1302
                                p.activeChanCloses.Delete(chanID)
×
1303
                                shutdownInfoErr = err
×
1304

×
1305
                                return
×
1306
                        }
×
1307

1308
                        shutdownMsg = fn.Some(*shutdown)
3✔
1309
                })
1310
                if shutdownInfoErr != nil {
3✔
1311
                        return nil, shutdownInfoErr
×
1312
                }
×
1313

1314
                // Subscribe to the set of on-chain events for this channel.
1315
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
3✔
1316
                        chanPoint,
3✔
1317
                )
3✔
1318
                if err != nil {
3✔
1319
                        return nil, err
×
1320
                }
×
1321

1322
                err = p.addLink(
3✔
1323
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
3✔
1324
                        true, shutdownMsg,
3✔
1325
                )
3✔
1326
                if err != nil {
3✔
1327
                        return nil, fmt.Errorf("unable to add link %v to "+
×
1328
                                "switch: %v", chanPoint, err)
×
1329
                }
×
1330

1331
                p.activeChannels.Store(chanID, lnChan)
3✔
1332

3✔
1333
                // We're using the old co-op close, so we don't need to init
3✔
1334
                // the new RBF chan closer. If we have a taproot chan, then
3✔
1335
                // we'll also use the legacy type, so we don't need to make the
3✔
1336
                // new closer.
3✔
1337
                if !p.rbfCoopCloseAllowed() || isTaprootChan {
6✔
1338
                        continue
3✔
1339
                }
1340

1341
                // Now that the link has been added above, we'll also init an
1342
                // RBF chan closer for this channel, but only if the new close
1343
                // feature is negotiated.
1344
                //
1345
                // Creating this here ensures that any shutdown messages sent
1346
                // will be automatically routed by the msg router.
1347
                if _, err := p.initRbfChanCloser(lnChan); err != nil {
3✔
1348
                        p.activeChanCloses.Delete(chanID)
×
1349

×
1350
                        return nil, fmt.Errorf("unable to init RBF chan "+
×
1351
                                "closer during peer connect: %w", err)
×
1352
                }
×
1353

1354
                // If the shutdown info isn't blank, then we should kick things
1355
                // off by sending a shutdown message to the remote party to
1356
                // continue the old shutdown flow.
1357
                restartShutdown := func(s channeldb.ShutdownInfo) error {
6✔
1358
                        return p.startRbfChanCloser(
3✔
1359
                                newRestartShutdownInit(s),
3✔
1360
                                lnChan.ChannelPoint(),
3✔
1361
                        )
3✔
1362
                }
3✔
1363
                err = fn.MapOptionZ(shutdownInfo, restartShutdown)
3✔
1364
                if err != nil {
3✔
1365
                        return nil, fmt.Errorf("unable to start RBF "+
×
1366
                                "chan closer: %w", err)
×
1367
                }
×
1368
        }
1369

1370
        return msgs, nil
6✔
1371
}
1372

1373
// addLink creates and adds a new ChannelLink from the specified channel.
1374
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1375
        lnChan *lnwallet.LightningChannel,
1376
        forwardingPolicy *models.ForwardingPolicy,
1377
        chainEvents *contractcourt.ChainEventSubscription,
1378
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
3✔
1379

3✔
1380
        // onChannelFailure will be called by the link in case the channel
3✔
1381
        // fails for some reason.
3✔
1382
        onChannelFailure := func(chanID lnwire.ChannelID,
3✔
1383
                shortChanID lnwire.ShortChannelID,
3✔
1384
                linkErr htlcswitch.LinkFailureError) {
6✔
1385

3✔
1386
                failure := linkFailureReport{
3✔
1387
                        chanPoint:   *chanPoint,
3✔
1388
                        chanID:      chanID,
3✔
1389
                        shortChanID: shortChanID,
3✔
1390
                        linkErr:     linkErr,
3✔
1391
                }
3✔
1392

3✔
1393
                select {
3✔
1394
                case p.linkFailures <- failure:
3✔
1395
                case <-p.cg.Done():
×
1396
                case <-p.cfg.Quit:
1✔
1397
                }
1398
        }
1399

1400
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
6✔
1401
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
3✔
1402
        }
3✔
1403

1404
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
6✔
1405
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
3✔
1406
        }
3✔
1407

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

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

3✔
1463
        // With the channel link created, we'll now notify the htlc switch so
3✔
1464
        // this channel can be used to dispatch local payments and also
3✔
1465
        // passively forward payments.
3✔
1466
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
3✔
1467
}
1468

1469
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1470
// one confirmed public channel exists with them.
1471
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
6✔
1472
        defer p.cg.WgDone()
6✔
1473

6✔
1474
        hasConfirmedPublicChan := false
6✔
1475
        for _, channel := range channels {
11✔
1476
                if channel.IsPending {
8✔
1477
                        continue
3✔
1478
                }
1479
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
10✔
1480
                        continue
5✔
1481
                }
1482

1483
                hasConfirmedPublicChan = true
3✔
1484
                break
3✔
1485
        }
1486
        if !hasConfirmedPublicChan {
12✔
1487
                return
6✔
1488
        }
6✔
1489

1490
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
3✔
1491
        if err != nil {
3✔
1492
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1493
                return
×
1494
        }
×
1495

1496
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
3✔
1497
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1498
        }
×
1499
}
1500

1501
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1502
// have any active channels with them.
1503
func (p *Brontide) maybeSendChannelUpdates() {
6✔
1504
        defer p.cg.WgDone()
6✔
1505

6✔
1506
        // If we don't have any active channels, then we can exit early.
6✔
1507
        if p.activeChannels.Len() == 0 {
10✔
1508
                return
4✔
1509
        }
4✔
1510

1511
        maybeSendUpd := func(cid lnwire.ChannelID,
5✔
1512
                lnChan *lnwallet.LightningChannel) error {
10✔
1513

5✔
1514
                // Nil channels are pending, so we'll skip them.
5✔
1515
                if lnChan == nil {
8✔
1516
                        return nil
3✔
1517
                }
3✔
1518

1519
                dbChan := lnChan.State()
5✔
1520
                scid := func() lnwire.ShortChannelID {
10✔
1521
                        switch {
5✔
1522
                        // Otherwise if it's a zero conf channel and confirmed,
1523
                        // then we need to use the "real" scid.
1524
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
3✔
1525
                                return dbChan.ZeroConfRealScid()
3✔
1526

1527
                        // Otherwise, we can use the normal scid.
1528
                        default:
5✔
1529
                                return dbChan.ShortChanID()
5✔
1530
                        }
1531
                }()
1532

1533
                // Now that we know the channel is in a good state, we'll try
1534
                // to fetch the update to send to the remote peer. If the
1535
                // channel is pending, and not a zero conf channel, we'll get
1536
                // an error here which we'll ignore.
1537
                chanUpd, err := p.cfg.FetchLastChanUpdate(scid)
5✔
1538
                if err != nil {
8✔
1539
                        p.log.Debugf("Unable to fetch channel update for "+
3✔
1540
                                "ChannelPoint(%v), scid=%v: %v",
3✔
1541
                                dbChan.FundingOutpoint, dbChan.ShortChanID, err)
3✔
1542

3✔
1543
                        return nil
3✔
1544
                }
3✔
1545

1546
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
5✔
1547
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
5✔
1548

5✔
1549
                // We'll send it as a normal message instead of using the lazy
5✔
1550
                // queue to prioritize transmission of the fresh update.
5✔
1551
                if err := p.SendMessage(false, chanUpd); err != nil {
5✔
1552
                        err := fmt.Errorf("unable to send channel update for "+
×
1553
                                "ChannelPoint(%v), scid=%v: %w",
×
1554
                                dbChan.FundingOutpoint, dbChan.ShortChanID(),
×
1555
                                err)
×
1556
                        p.log.Errorf(err.Error())
×
1557

×
1558
                        return err
×
1559
                }
×
1560

1561
                return nil
5✔
1562
        }
1563

1564
        p.activeChannels.ForEach(maybeSendUpd)
5✔
1565
}
1566

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

1584
        select {
3✔
1585
        case <-ready:
3✔
1586
        case <-p.cg.Done():
3✔
1587
        }
1588

1589
        p.cg.WgWait()
3✔
1590
}
1591

1592
// Disconnect terminates the connection with the remote peer. Additionally, a
1593
// signal is sent to the server and htlcSwitch indicating the resources
1594
// allocated to the peer can now be cleaned up.
1595
func (p *Brontide) Disconnect(reason error) {
4✔
1596
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
7✔
1597
                return
3✔
1598
        }
3✔
1599

1600
        // Make sure initialization has completed before we try to tear things
1601
        // down.
1602
        //
1603
        // NOTE: We only read the `startReady` chan if the peer has been
1604
        // started, otherwise we will skip reading it as this chan won't be
1605
        // closed, hence blocks forever.
1606
        if atomic.LoadInt32(&p.started) == 1 {
7✔
1607
                p.log.Debugf("Started, waiting on startReady signal")
3✔
1608

3✔
1609
                select {
3✔
1610
                case <-p.startReady:
3✔
1611
                case <-p.cg.Done():
×
1612
                        return
×
1613
                }
1614
        }
1615

1616
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
4✔
1617
        p.storeError(err)
4✔
1618

4✔
1619
        p.log.Infof(err.Error())
4✔
1620

4✔
1621
        // Stop PingManager before closing TCP connection.
4✔
1622
        p.pingManager.Stop()
4✔
1623

4✔
1624
        // Ensure that the TCP connection is properly closed before continuing.
4✔
1625
        p.cfg.Conn.Close()
4✔
1626

4✔
1627
        p.cg.Quit()
4✔
1628

4✔
1629
        // If our msg router isn't global (local to this instance), then we'll
4✔
1630
        // stop it. Otherwise, we'll leave it running.
4✔
1631
        if !p.globalMsgRouter {
8✔
1632
                p.msgRouter.WhenSome(func(router msgmux.Router) {
8✔
1633
                        router.Stop()
4✔
1634
                })
4✔
1635
        }
1636
}
1637

1638
// String returns the string representation of this peer.
1639
func (p *Brontide) String() string {
4✔
1640
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
4✔
1641
}
4✔
1642

1643
// readNextMessage reads, and returns the next message on the wire along with
1644
// any additional raw payload.
1645
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
10✔
1646
        noiseConn := p.cfg.Conn
10✔
1647
        err := noiseConn.SetReadDeadline(time.Time{})
10✔
1648
        if err != nil {
10✔
1649
                return nil, err
×
1650
        }
×
1651

1652
        pktLen, err := noiseConn.ReadNextHeader()
10✔
1653
        if err != nil {
13✔
1654
                return nil, fmt.Errorf("read next header: %w", err)
3✔
1655
        }
3✔
1656

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

1679
                // The ReadNextBody method will actually end up re-using the
1680
                // buffer, so within this closure, we can continue to use
1681
                // rawMsg as it's just a slice into the buf from the buffer
1682
                // pool.
1683
                rawMsg, readErr := noiseConn.ReadNextBody(buf[:pktLen])
7✔
1684
                if readErr != nil {
7✔
1685
                        return fmt.Errorf("read next body: %w", readErr)
×
1686
                }
×
1687
                msgLen = uint64(len(rawMsg))
7✔
1688

7✔
1689
                // Next, create a new io.Reader implementation from the raw
7✔
1690
                // message, and use this to decode the message directly from.
7✔
1691
                msgReader := bytes.NewReader(rawMsg)
7✔
1692
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
7✔
1693
                if err != nil {
10✔
1694
                        return err
3✔
1695
                }
3✔
1696

1697
                // At this point, rawMsg and buf will be returned back to the
1698
                // buffer pool for re-use.
1699
                return nil
7✔
1700
        })
1701
        atomic.AddUint64(&p.bytesReceived, msgLen)
7✔
1702
        if err != nil {
10✔
1703
                return nil, err
3✔
1704
        }
3✔
1705

1706
        p.logWireMessage(nextMsg, true)
7✔
1707

7✔
1708
        return nextMsg, nil
7✔
1709
}
1710

1711
// msgStream implements a goroutine-safe, in-order stream of messages to be
1712
// delivered via closure to a receiver. These messages MUST be in order due to
1713
// the nature of the lightning channel commitment and gossiper state machines.
1714
// TODO(conner): use stream handler interface to abstract out stream
1715
// state/logging.
1716
type msgStream struct {
1717
        streamShutdown int32 // To be used atomically.
1718

1719
        peer *Brontide
1720

1721
        apply func(lnwire.Message)
1722

1723
        startMsg string
1724
        stopMsg  string
1725

1726
        msgCond *sync.Cond
1727
        msgs    []lnwire.Message
1728

1729
        mtx sync.Mutex
1730

1731
        producerSema chan struct{}
1732

1733
        wg   sync.WaitGroup
1734
        quit chan struct{}
1735
}
1736

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

6✔
1745
        stream := &msgStream{
6✔
1746
                peer:         p,
6✔
1747
                apply:        apply,
6✔
1748
                startMsg:     startMsg,
6✔
1749
                stopMsg:      stopMsg,
6✔
1750
                producerSema: make(chan struct{}, bufSize),
6✔
1751
                quit:         make(chan struct{}),
6✔
1752
        }
6✔
1753
        stream.msgCond = sync.NewCond(&stream.mtx)
6✔
1754

6✔
1755
        // Before we return the active stream, we'll populate the producer's
6✔
1756
        // semaphore channel. We'll use this to ensure that the producer won't
6✔
1757
        // attempt to allocate memory in the queue for an item until it has
6✔
1758
        // sufficient extra space.
6✔
1759
        for i := uint32(0); i < bufSize; i++ {
24✔
1760
                stream.producerSema <- struct{}{}
18✔
1761
        }
18✔
1762

1763
        return stream
6✔
1764
}
1765

1766
// Start starts the chanMsgStream.
1767
func (ms *msgStream) Start() {
6✔
1768
        ms.wg.Add(1)
6✔
1769
        go ms.msgConsumer()
6✔
1770
}
6✔
1771

1772
// Stop stops the chanMsgStream.
1773
func (ms *msgStream) Stop() {
3✔
1774
        // TODO(roasbeef): signal too?
3✔
1775

3✔
1776
        close(ms.quit)
3✔
1777

3✔
1778
        // Now that we've closed the channel, we'll repeatedly signal the msg
3✔
1779
        // consumer until we've detected that it has exited.
3✔
1780
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
6✔
1781
                ms.msgCond.Signal()
3✔
1782
                time.Sleep(time.Millisecond * 100)
3✔
1783
        }
3✔
1784

1785
        ms.wg.Wait()
3✔
1786
}
1787

1788
// msgConsumer is the main goroutine that streams messages from the peer's
1789
// readHandler directly to the target channel.
1790
func (ms *msgStream) msgConsumer() {
6✔
1791
        defer ms.wg.Done()
6✔
1792
        defer peerLog.Tracef(ms.stopMsg)
6✔
1793
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
6✔
1794

6✔
1795
        peerLog.Tracef(ms.startMsg)
6✔
1796

6✔
1797
        for {
12✔
1798
                // First, we'll check our condition. If the queue of messages
6✔
1799
                // is empty, then we'll wait until a new item is added.
6✔
1800
                ms.msgCond.L.Lock()
6✔
1801
                for len(ms.msgs) == 0 {
12✔
1802
                        ms.msgCond.Wait()
6✔
1803

6✔
1804
                        // If we woke up in order to exit, then we'll do so.
6✔
1805
                        // Otherwise, we'll check the message queue for any new
6✔
1806
                        // items.
6✔
1807
                        select {
6✔
1808
                        case <-ms.peer.cg.Done():
3✔
1809
                                ms.msgCond.L.Unlock()
3✔
1810
                                return
3✔
1811
                        case <-ms.quit:
3✔
1812
                                ms.msgCond.L.Unlock()
3✔
1813
                                return
3✔
1814
                        default:
3✔
1815
                        }
1816
                }
1817

1818
                // Grab the message off the front of the queue, shifting the
1819
                // slice's reference down one in order to remove the message
1820
                // from the queue.
1821
                msg := ms.msgs[0]
3✔
1822
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
3✔
1823
                ms.msgs = ms.msgs[1:]
3✔
1824

3✔
1825
                ms.msgCond.L.Unlock()
3✔
1826

3✔
1827
                ms.apply(msg)
3✔
1828

3✔
1829
                // We've just successfully processed an item, so we'll signal
3✔
1830
                // to the producer that a new slot in the buffer. We'll use
3✔
1831
                // this to bound the size of the buffer to avoid allowing it to
3✔
1832
                // grow indefinitely.
3✔
1833
                select {
3✔
1834
                case ms.producerSema <- struct{}{}:
3✔
1835
                case <-ms.peer.cg.Done():
3✔
1836
                        return
3✔
1837
                case <-ms.quit:
3✔
1838
                        return
3✔
1839
                }
1840
        }
1841
}
1842

1843
// AddMsg adds a new message to the msgStream. This function is safe for
1844
// concurrent access.
1845
func (ms *msgStream) AddMsg(msg lnwire.Message) {
3✔
1846
        // First, we'll attempt to receive from the producerSema struct. This
3✔
1847
        // acts as a semaphore to prevent us from indefinitely buffering
3✔
1848
        // incoming items from the wire. Either the msg queue isn't full, and
3✔
1849
        // we'll not block, or the queue is full, and we'll block until either
3✔
1850
        // we're signalled to quit, or a slot is freed up.
3✔
1851
        select {
3✔
1852
        case <-ms.producerSema:
3✔
1853
        case <-ms.peer.cg.Done():
×
1854
                return
×
1855
        case <-ms.quit:
×
1856
                return
×
1857
        }
1858

1859
        // Next, we'll lock the condition, and add the message to the end of
1860
        // the message queue.
1861
        ms.msgCond.L.Lock()
3✔
1862
        ms.msgs = append(ms.msgs, msg)
3✔
1863
        ms.msgCond.L.Unlock()
3✔
1864

3✔
1865
        // With the message added, we signal to the msgConsumer that there are
3✔
1866
        // additional messages to consume.
3✔
1867
        ms.msgCond.Signal()
3✔
1868
}
1869

1870
// waitUntilLinkActive waits until the target link is active and returns a
1871
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1872
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1873
func waitUntilLinkActive(p *Brontide,
1874
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
3✔
1875

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

3✔
1878
        // Subscribe to receive channel events.
3✔
1879
        //
3✔
1880
        // NOTE: If the link is already active by SubscribeChannelEvents, then
3✔
1881
        // GetLink will retrieve the link and we can send messages. If the link
3✔
1882
        // becomes active between SubscribeChannelEvents and GetLink, then GetLink
3✔
1883
        // will retrieve the link. If the link becomes active after GetLink, then
3✔
1884
        // we will get an ActiveLinkEvent notification and retrieve the link. If
3✔
1885
        // the call to GetLink is before SubscribeChannelEvents, however, there
3✔
1886
        // will be a race condition.
3✔
1887
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
3✔
1888
        if err != nil {
6✔
1889
                // If we have a non-nil error, then the server is shutting down and we
3✔
1890
                // can exit here and return nil. This means no message will be delivered
3✔
1891
                // to the link.
3✔
1892
                return nil
3✔
1893
        }
3✔
1894
        defer sub.Cancel()
3✔
1895

3✔
1896
        // The link may already be active by this point, and we may have missed the
3✔
1897
        // ActiveLinkEvent. Check if the link exists.
3✔
1898
        link := p.fetchLinkFromKeyAndCid(cid)
3✔
1899
        if link != nil {
6✔
1900
                return link
3✔
1901
        }
3✔
1902

1903
        // If the link is nil, we must wait for it to be active.
1904
        for {
6✔
1905
                select {
3✔
1906
                // A new event has been sent by the ChannelNotifier. We first check
1907
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1908
                // that the event is for this channel. Otherwise, we discard the
1909
                // message.
1910
                case e := <-sub.Updates():
3✔
1911
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
3✔
1912
                        if !ok {
6✔
1913
                                // Ignore this notification.
3✔
1914
                                continue
3✔
1915
                        }
1916

1917
                        chanPoint := event.ChannelPoint
3✔
1918

3✔
1919
                        // Check whether the retrieved chanPoint matches the target
3✔
1920
                        // channel id.
3✔
1921
                        if !cid.IsChanPoint(chanPoint) {
3✔
1922
                                continue
×
1923
                        }
1924

1925
                        // The link shouldn't be nil as we received an
1926
                        // ActiveLinkEvent. If it is nil, we return nil and the
1927
                        // calling function should catch it.
1928
                        return p.fetchLinkFromKeyAndCid(cid)
3✔
1929

1930
                case <-p.cg.Done():
3✔
1931
                        return nil
3✔
1932
                }
1933
        }
1934
}
1935

1936
// newChanMsgStream is used to create a msgStream between the peer and
1937
// particular channel link in the htlcswitch. We utilize additional
1938
// synchronization with the fundingManager to ensure we don't attempt to
1939
// dispatch a message to a channel before it is fully active. A reference to the
1940
// channel this stream forwards to is held in scope to prevent unnecessary
1941
// lookups.
1942
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
3✔
1943
        var chanLink htlcswitch.ChannelUpdateHandler
3✔
1944

3✔
1945
        apply := func(msg lnwire.Message) {
6✔
1946
                // This check is fine because if the link no longer exists, it will
3✔
1947
                // be removed from the activeChannels map and subsequent messages
3✔
1948
                // shouldn't reach the chan msg stream.
3✔
1949
                if chanLink == nil {
6✔
1950
                        chanLink = waitUntilLinkActive(p, cid)
3✔
1951

3✔
1952
                        // If the link is still not active and the calling function
3✔
1953
                        // errored out, just return.
3✔
1954
                        if chanLink == nil {
6✔
1955
                                p.log.Warnf("Link=%v is not active", cid)
3✔
1956
                                return
3✔
1957
                        }
3✔
1958
                }
1959

1960
                // In order to avoid unnecessarily delivering message
1961
                // as the peer is exiting, we'll check quickly to see
1962
                // if we need to exit.
1963
                select {
3✔
1964
                case <-p.cg.Done():
×
1965
                        return
×
1966
                default:
3✔
1967
                }
1968

1969
                chanLink.HandleChannelUpdate(msg)
3✔
1970
        }
1971

1972
        return newMsgStream(p,
3✔
1973
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
3✔
1974
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
3✔
1975
                msgStreamSize,
3✔
1976
                apply,
3✔
1977
        )
3✔
1978
}
1979

1980
// newDiscMsgStream is used to setup a msgStream between the peer and the
1981
// authenticated gossiper. This stream should be used to forward all remote
1982
// channel announcements.
1983
func newDiscMsgStream(p *Brontide) *msgStream {
6✔
1984
        apply := func(msg lnwire.Message) {
9✔
1985
                // TODO(yy): `ProcessRemoteAnnouncement` returns an error chan
3✔
1986
                // and we need to process it.
3✔
1987
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(msg, p)
3✔
1988
        }
3✔
1989

1990
        return newMsgStream(
6✔
1991
                p,
6✔
1992
                "Update stream for gossiper created",
6✔
1993
                "Update stream for gossiper exited",
6✔
1994
                msgStreamSize,
6✔
1995
                apply,
6✔
1996
        )
6✔
1997
}
1998

1999
// readHandler is responsible for reading messages off the wire in series, then
2000
// properly dispatching the handling of the message to the proper subsystem.
2001
//
2002
// NOTE: This method MUST be run as a goroutine.
2003
func (p *Brontide) readHandler() {
6✔
2004
        defer p.cg.WgDone()
6✔
2005

6✔
2006
        // We'll stop the timer after a new messages is received, and also
6✔
2007
        // reset it after we process the next message.
6✔
2008
        idleTimer := time.AfterFunc(idleTimeout, func() {
6✔
2009
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
2010
                        p, idleTimeout)
×
2011
                p.Disconnect(err)
×
2012
        })
×
2013

2014
        // Initialize our negotiated gossip sync method before reading messages
2015
        // off the wire. When using gossip queries, this ensures a gossip
2016
        // syncer is active by the time query messages arrive.
2017
        //
2018
        // TODO(conner): have peer store gossip syncer directly and bypass
2019
        // gossiper?
2020
        p.initGossipSync()
6✔
2021

6✔
2022
        discStream := newDiscMsgStream(p)
6✔
2023
        discStream.Start()
6✔
2024
        defer discStream.Stop()
6✔
2025
out:
6✔
2026
        for atomic.LoadInt32(&p.disconnect) == 0 {
13✔
2027
                nextMsg, err := p.readNextMessage()
7✔
2028
                if !idleTimer.Stop() {
10✔
2029
                        select {
3✔
2030
                        case <-idleTimer.C:
×
2031
                        default:
3✔
2032
                        }
2033
                }
2034
                if err != nil {
7✔
2035
                        p.log.Infof("unable to read message from peer: %v", err)
3✔
2036

3✔
2037
                        // If we could not read our peer's message due to an
3✔
2038
                        // unknown type or invalid alias, we continue processing
3✔
2039
                        // as normal. We store unknown message and address
3✔
2040
                        // types, as they may provide debugging insight.
3✔
2041
                        switch e := err.(type) {
3✔
2042
                        // If this is just a message we don't yet recognize,
2043
                        // we'll continue processing as normal as this allows
2044
                        // us to introduce new messages in a forwards
2045
                        // compatible manner.
2046
                        case *lnwire.UnknownMessage:
3✔
2047
                                p.storeError(e)
3✔
2048
                                idleTimer.Reset(idleTimeout)
3✔
2049
                                continue
3✔
2050

2051
                        // If they sent us an address type that we don't yet
2052
                        // know of, then this isn't a wire error, so we'll
2053
                        // simply continue parsing the remainder of their
2054
                        // messages.
2055
                        case *lnwire.ErrUnknownAddrType:
×
2056
                                p.storeError(e)
×
2057
                                idleTimer.Reset(idleTimeout)
×
2058
                                continue
×
2059

2060
                        // If the NodeAnnouncement has an invalid alias, then
2061
                        // we'll log that error above and continue so we can
2062
                        // continue to read messages from the peer. We do not
2063
                        // store this error because it is of little debugging
2064
                        // value.
2065
                        case *lnwire.ErrInvalidNodeAlias:
×
2066
                                idleTimer.Reset(idleTimeout)
×
2067
                                continue
×
2068

2069
                        // If the error we encountered wasn't just a message we
2070
                        // didn't recognize, then we'll stop all processing as
2071
                        // this is a fatal error.
2072
                        default:
3✔
2073
                                break out
3✔
2074
                        }
2075
                }
2076

2077
                // If a message router is active, then we'll try to have it
2078
                // handle this message. If it can, then we're able to skip the
2079
                // rest of the message handling logic.
2080
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
8✔
2081
                        return r.RouteMsg(msgmux.PeerMsg{
4✔
2082
                                PeerPub: *p.IdentityKey(),
4✔
2083
                                Message: nextMsg,
4✔
2084
                        })
4✔
2085
                })
4✔
2086

2087
                // No error occurred, and the message was handled by the
2088
                // router.
2089
                if err == nil {
7✔
2090
                        continue
3✔
2091
                }
2092

2093
                var (
4✔
2094
                        targetChan   lnwire.ChannelID
4✔
2095
                        isLinkUpdate bool
4✔
2096
                )
4✔
2097

4✔
2098
                switch msg := nextMsg.(type) {
4✔
2099
                case *lnwire.Pong:
×
2100
                        // When we receive a Pong message in response to our
×
2101
                        // last ping message, we send it to the pingManager
×
2102
                        p.pingManager.ReceivedPong(msg)
×
2103

2104
                case *lnwire.Ping:
×
2105
                        // First, we'll store their latest ping payload within
×
2106
                        // the relevant atomic variable.
×
2107
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
2108

×
2109
                        // Next, we'll send over the amount of specified pong
×
NEW
2110
                        // bytes. Pong responses are sent via the super priority
×
NEW
2111
                        // queue to ensure timely response to pings. These are
×
NEW
2112
                        // fire-and-forget.
×
NEW
2113
                        pong := lnwire.NewPong(
×
NEW
2114
                                p.cfg.PongBuf[0:msg.NumPongBytes],
×
NEW
2115
                        )
×
NEW
2116
                        p.SendSuperPriorityMessage(false, pong)
×
2117

2118
                case *lnwire.OpenChannel,
2119
                        *lnwire.AcceptChannel,
2120
                        *lnwire.FundingCreated,
2121
                        *lnwire.FundingSigned,
2122
                        *lnwire.ChannelReady:
3✔
2123

3✔
2124
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2125

2126
                case *lnwire.Shutdown:
3✔
2127
                        select {
3✔
2128
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
2129
                        case <-p.cg.Done():
×
2130
                                break out
×
2131
                        }
2132
                case *lnwire.ClosingSigned:
3✔
2133
                        select {
3✔
2134
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
2135
                        case <-p.cg.Done():
×
2136
                                break out
×
2137
                        }
2138

2139
                case *lnwire.Warning:
×
2140
                        targetChan = msg.ChanID
×
2141
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2142

2143
                case *lnwire.Error:
3✔
2144
                        targetChan = msg.ChanID
3✔
2145
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
3✔
2146

2147
                case *lnwire.ChannelReestablish:
3✔
2148
                        targetChan = msg.ChanID
3✔
2149
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2150

3✔
2151
                        // If we failed to find the link in question, and the
3✔
2152
                        // message received was a channel sync message, then
3✔
2153
                        // this might be a peer trying to resync closed channel.
3✔
2154
                        // In this case we'll try to resend our last channel
3✔
2155
                        // sync message, such that the peer can recover funds
3✔
2156
                        // from the closed channel.
3✔
2157
                        if !isLinkUpdate {
6✔
2158
                                err := p.resendChanSyncMsg(targetChan)
3✔
2159
                                if err != nil {
6✔
2160
                                        // TODO(halseth): send error to peer?
3✔
2161
                                        p.log.Errorf("resend failed: %v",
3✔
2162
                                                err)
3✔
2163
                                }
3✔
2164
                        }
2165

2166
                // For messages that implement the LinkUpdater interface, we
2167
                // will consider them as link updates and send them to
2168
                // chanStream. These messages will be queued inside chanStream
2169
                // if the channel is not active yet.
2170
                case lnwire.LinkUpdater:
3✔
2171
                        targetChan = msg.TargetChanID()
3✔
2172
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2173

3✔
2174
                        // Log an error if we don't have this channel. This
3✔
2175
                        // means the peer has sent us a message with unknown
3✔
2176
                        // channel ID.
3✔
2177
                        if !isLinkUpdate {
6✔
2178
                                p.log.Errorf("Unknown channel ID: %v found "+
3✔
2179
                                        "in received msg=%s", targetChan,
3✔
2180
                                        nextMsg.MsgType())
3✔
2181
                        }
3✔
2182

2183
                case *lnwire.ChannelUpdate1,
2184
                        *lnwire.ChannelAnnouncement1,
2185
                        *lnwire.NodeAnnouncement,
2186
                        *lnwire.AnnounceSignatures1,
2187
                        *lnwire.GossipTimestampRange,
2188
                        *lnwire.QueryShortChanIDs,
2189
                        *lnwire.QueryChannelRange,
2190
                        *lnwire.ReplyChannelRange,
2191
                        *lnwire.ReplyShortChanIDsEnd:
3✔
2192

3✔
2193
                        discStream.AddMsg(msg)
3✔
2194

2195
                case *lnwire.Custom:
4✔
2196
                        err := p.handleCustomMessage(msg)
4✔
2197
                        if err != nil {
4✔
2198
                                p.storeError(err)
×
2199
                                p.log.Errorf("%v", err)
×
2200
                        }
×
2201

2202
                default:
×
2203
                        // If the message we received is unknown to us, store
×
2204
                        // the type to track the failure.
×
2205
                        err := fmt.Errorf("unknown message type %v received",
×
2206
                                uint16(msg.MsgType()))
×
2207
                        p.storeError(err)
×
2208

×
2209
                        p.log.Errorf("%v", err)
×
2210
                }
2211

2212
                if isLinkUpdate {
7✔
2213
                        // If this is a channel update, then we need to feed it
3✔
2214
                        // into the channel's in-order message stream.
3✔
2215
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
3✔
2216
                }
3✔
2217

2218
                idleTimer.Reset(idleTimeout)
4✔
2219
        }
2220

2221
        p.Disconnect(errors.New("read handler closed"))
3✔
2222

3✔
2223
        p.log.Trace("readHandler for peer done")
3✔
2224
}
2225

2226
// handleCustomMessage handles the given custom message if a handler is
2227
// registered.
2228
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
4✔
2229
        if p.cfg.HandleCustomMessage == nil {
4✔
2230
                return fmt.Errorf("no custom message handler for "+
×
2231
                        "message type %v", uint16(msg.MsgType()))
×
2232
        }
×
2233

2234
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
4✔
2235
}
2236

2237
// isLoadedFromDisk returns true if the provided channel ID is loaded from
2238
// disk.
2239
//
2240
// NOTE: only returns true for pending channels.
2241
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
3✔
2242
        // If this is a newly added channel, no need to reestablish.
3✔
2243
        _, added := p.addedChannels.Load(chanID)
3✔
2244
        if added {
6✔
2245
                return false
3✔
2246
        }
3✔
2247

2248
        // Return false if the channel is unknown.
2249
        channel, ok := p.activeChannels.Load(chanID)
3✔
2250
        if !ok {
3✔
2251
                return false
×
2252
        }
×
2253

2254
        // During startup, we will use a nil value to mark a pending channel
2255
        // that's loaded from disk.
2256
        return channel == nil
3✔
2257
}
2258

2259
// isActiveChannel returns true if the provided channel id is active, otherwise
2260
// returns false.
2261
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
11✔
2262
        // The channel would be nil if,
11✔
2263
        // - the channel doesn't exist, or,
11✔
2264
        // - the channel exists, but is pending. In this case, we don't
11✔
2265
        //   consider this channel active.
11✔
2266
        channel, _ := p.activeChannels.Load(chanID)
11✔
2267

11✔
2268
        return channel != nil
11✔
2269
}
11✔
2270

2271
// isPendingChannel returns true if the provided channel ID is pending, and
2272
// returns false if the channel is active or unknown.
2273
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
9✔
2274
        // Return false if the channel is unknown.
9✔
2275
        channel, ok := p.activeChannels.Load(chanID)
9✔
2276
        if !ok {
15✔
2277
                return false
6✔
2278
        }
6✔
2279

2280
        return channel == nil
6✔
2281
}
2282

2283
// hasChannel returns true if the peer has a pending/active channel specified
2284
// by the channel ID.
2285
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
3✔
2286
        _, ok := p.activeChannels.Load(chanID)
3✔
2287
        return ok
3✔
2288
}
3✔
2289

2290
// storeError stores an error in our peer's buffer of recent errors with the
2291
// current timestamp. Errors are only stored if we have at least one active
2292
// channel with the peer to mitigate a dos vector where a peer costlessly
2293
// connects to us and spams us with errors.
2294
func (p *Brontide) storeError(err error) {
4✔
2295
        var haveChannels bool
4✔
2296

4✔
2297
        p.activeChannels.Range(func(_ lnwire.ChannelID,
4✔
2298
                channel *lnwallet.LightningChannel) bool {
8✔
2299

4✔
2300
                // Pending channels will be nil in the activeChannels map.
4✔
2301
                if channel == nil {
7✔
2302
                        // Return true to continue the iteration.
3✔
2303
                        return true
3✔
2304
                }
3✔
2305

2306
                haveChannels = true
4✔
2307

4✔
2308
                // Return false to break the iteration.
4✔
2309
                return false
4✔
2310
        })
2311

2312
        // If we do not have any active channels with the peer, we do not store
2313
        // errors as a dos mitigation.
2314
        if !haveChannels {
7✔
2315
                p.log.Trace("no channels with peer, not storing err")
3✔
2316
                return
3✔
2317
        }
3✔
2318

2319
        p.cfg.ErrorBuffer.Add(
4✔
2320
                &TimestampedError{Timestamp: time.Now(), Error: err},
4✔
2321
        )
4✔
2322
}
2323

2324
// handleWarningOrError processes a warning or error msg and returns true if
2325
// msg should be forwarded to the associated channel link. False is returned if
2326
// any necessary forwarding of msg was already handled by this method. If msg is
2327
// an error from a peer with an active channel, we'll store it in memory.
2328
//
2329
// NOTE: This method should only be called from within the readHandler.
2330
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
2331
        msg lnwire.Message) bool {
3✔
2332

3✔
2333
        if errMsg, ok := msg.(*lnwire.Error); ok {
6✔
2334
                p.storeError(errMsg)
3✔
2335
        }
3✔
2336

2337
        switch {
3✔
2338
        // Connection wide messages should be forwarded to all channel links
2339
        // with this peer.
2340
        case chanID == lnwire.ConnectionWideID:
×
2341
                for _, chanStream := range p.activeMsgStreams {
×
2342
                        chanStream.AddMsg(msg)
×
2343
                }
×
2344

2345
                return false
×
2346

2347
        // If the channel ID for the message corresponds to a pending channel,
2348
        // then the funding manager will handle it.
2349
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
3✔
2350
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2351
                return false
3✔
2352

2353
        // If not we hand the message to the channel link for this channel.
2354
        case p.isActiveChannel(chanID):
3✔
2355
                return true
3✔
2356

2357
        default:
3✔
2358
                return false
3✔
2359
        }
2360
}
2361

2362
// messageSummary returns a human-readable string that summarizes a
2363
// incoming/outgoing message. Not all messages will have a summary, only those
2364
// which have additional data that can be informative at a glance.
2365
func messageSummary(msg lnwire.Message) string {
3✔
2366
        switch msg := msg.(type) {
3✔
2367
        case *lnwire.Init:
3✔
2368
                // No summary.
3✔
2369
                return ""
3✔
2370

2371
        case *lnwire.OpenChannel:
3✔
2372
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
3✔
2373
                        "push_amt=%v, reserve=%v, flags=%v",
3✔
2374
                        msg.PendingChannelID[:], msg.ChainHash,
3✔
2375
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
3✔
2376
                        msg.ChannelReserve, msg.ChannelFlags)
3✔
2377

2378
        case *lnwire.AcceptChannel:
3✔
2379
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
3✔
2380
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
3✔
2381
                        msg.MinAcceptDepth)
3✔
2382

2383
        case *lnwire.FundingCreated:
3✔
2384
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
3✔
2385
                        msg.PendingChannelID[:], msg.FundingPoint)
3✔
2386

2387
        case *lnwire.FundingSigned:
3✔
2388
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
3✔
2389

2390
        case *lnwire.ChannelReady:
3✔
2391
                return fmt.Sprintf("chan_id=%v, next_point=%x",
3✔
2392
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
3✔
2393

2394
        case *lnwire.Shutdown:
3✔
2395
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
3✔
2396
                        msg.Address[:])
3✔
2397

2398
        case *lnwire.ClosingComplete:
3✔
2399
                return fmt.Sprintf("chan_id=%v, fee_sat=%v, locktime=%v",
3✔
2400
                        msg.ChannelID, msg.FeeSatoshis, msg.LockTime)
3✔
2401

2402
        case *lnwire.ClosingSig:
3✔
2403
                return fmt.Sprintf("chan_id=%v", msg.ChannelID)
3✔
2404

2405
        case *lnwire.ClosingSigned:
3✔
2406
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
3✔
2407
                        msg.FeeSatoshis)
3✔
2408

2409
        case *lnwire.UpdateAddHTLC:
3✔
2410
                var blindingPoint []byte
3✔
2411
                msg.BlindingPoint.WhenSome(
3✔
2412
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
3✔
2413
                                *btcec.PublicKey]) {
6✔
2414

3✔
2415
                                blindingPoint = b.Val.SerializeCompressed()
3✔
2416
                        },
3✔
2417
                )
2418

2419
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
3✔
2420
                        "hash=%x, blinding_point=%x, custom_records=%v",
3✔
2421
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
3✔
2422
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
3✔
2423

2424
        case *lnwire.UpdateFailHTLC:
3✔
2425
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
3✔
2426
                        msg.ID, msg.Reason)
3✔
2427

2428
        case *lnwire.UpdateFulfillHTLC:
3✔
2429
                return fmt.Sprintf("chan_id=%v, id=%v, preimage=%x, "+
3✔
2430
                        "custom_records=%v", msg.ChanID, msg.ID,
3✔
2431
                        msg.PaymentPreimage[:], msg.CustomRecords)
3✔
2432

2433
        case *lnwire.CommitSig:
3✔
2434
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
3✔
2435
                        len(msg.HtlcSigs))
3✔
2436

2437
        case *lnwire.RevokeAndAck:
3✔
2438
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
3✔
2439
                        msg.ChanID, msg.Revocation[:],
3✔
2440
                        msg.NextRevocationKey.SerializeCompressed())
3✔
2441

2442
        case *lnwire.UpdateFailMalformedHTLC:
3✔
2443
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
3✔
2444
                        msg.ChanID, msg.ID, msg.FailureCode)
3✔
2445

2446
        case *lnwire.Warning:
×
2447
                return fmt.Sprintf("%v", msg.Warning())
×
2448

2449
        case *lnwire.Error:
3✔
2450
                return fmt.Sprintf("%v", msg.Error())
3✔
2451

2452
        case *lnwire.AnnounceSignatures1:
3✔
2453
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
3✔
2454
                        msg.ShortChannelID.ToUint64())
3✔
2455

2456
        case *lnwire.ChannelAnnouncement1:
3✔
2457
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
3✔
2458
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
3✔
2459

2460
        case *lnwire.ChannelUpdate1:
3✔
2461
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
3✔
2462
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
3✔
2463
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
3✔
2464
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
3✔
2465

2466
        case *lnwire.NodeAnnouncement:
3✔
2467
                return fmt.Sprintf("node=%x, update_time=%v",
3✔
2468
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
3✔
2469

2470
        case *lnwire.Ping:
×
2471
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
2472

2473
        case *lnwire.Pong:
×
2474
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
×
2475

2476
        case *lnwire.UpdateFee:
×
2477
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2478
                        msg.ChanID, int64(msg.FeePerKw))
×
2479

2480
        case *lnwire.ChannelReestablish:
3✔
2481
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
3✔
2482
                        "remote_tail_height=%v", msg.ChanID,
3✔
2483
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
3✔
2484

2485
        case *lnwire.ReplyShortChanIDsEnd:
3✔
2486
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
3✔
2487
                        msg.Complete)
3✔
2488

2489
        case *lnwire.ReplyChannelRange:
3✔
2490
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
3✔
2491
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
3✔
2492
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
3✔
2493
                        msg.EncodingType)
3✔
2494

2495
        case *lnwire.QueryShortChanIDs:
3✔
2496
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
3✔
2497
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
3✔
2498

2499
        case *lnwire.QueryChannelRange:
3✔
2500
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
3✔
2501
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
3✔
2502
                        msg.LastBlockHeight())
3✔
2503

2504
        case *lnwire.GossipTimestampRange:
3✔
2505
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
3✔
2506
                        "stamp_range=%v", msg.ChainHash,
3✔
2507
                        time.Unix(int64(msg.FirstTimestamp), 0),
3✔
2508
                        msg.TimestampRange)
3✔
2509

2510
        case *lnwire.Stfu:
3✔
2511
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
3✔
2512
                        msg.Initiator)
3✔
2513

2514
        case *lnwire.Custom:
3✔
2515
                return fmt.Sprintf("type=%d", msg.Type)
3✔
2516
        }
2517

2518
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2519
}
2520

2521
// logWireMessage logs the receipt or sending of particular wire message. This
2522
// function is used rather than just logging the message in order to produce
2523
// less spammy log messages in trace mode by setting the 'Curve" parameter to
2524
// nil. Doing this avoids printing out each of the field elements in the curve
2525
// parameters for secp256k1.
2526
func (p *Brontide) logWireMessage(msg lnwire.Message, read bool) {
20✔
2527
        summaryPrefix := "Received"
20✔
2528
        if !read {
36✔
2529
                summaryPrefix = "Sending"
16✔
2530
        }
16✔
2531

2532
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
23✔
2533
                // Debug summary of message.
3✔
2534
                summary := messageSummary(msg)
3✔
2535
                if len(summary) > 0 {
6✔
2536
                        summary = "(" + summary + ")"
3✔
2537
                }
3✔
2538

2539
                preposition := "to"
3✔
2540
                if read {
6✔
2541
                        preposition = "from"
3✔
2542
                }
3✔
2543

2544
                var msgType string
3✔
2545
                if msg.MsgType() < lnwire.CustomTypeStart {
6✔
2546
                        msgType = msg.MsgType().String()
3✔
2547
                } else {
6✔
2548
                        msgType = "custom"
3✔
2549
                }
3✔
2550

2551
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
3✔
2552
                        msgType, summary, preposition, p)
3✔
2553
        }))
2554

2555
        prefix := "readMessage from peer"
20✔
2556
        if !read {
36✔
2557
                prefix = "writeMessage to peer"
16✔
2558
        }
16✔
2559

2560
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
20✔
2561
}
2562

2563
// writeMessage writes and flushes the target lnwire.Message to the remote peer.
2564
// If the passed message is nil, this method will only try to flush an existing
2565
// message buffered on the connection. It is safe to call this method again
2566
// with a nil message iff a timeout error is returned. This will continue to
2567
// flush the pending message to the wire.
2568
//
2569
// NOTE:
2570
// Besides its usage in Start, this function should not be used elsewhere
2571
// except in writeHandler. If multiple goroutines call writeMessage at the same
2572
// time, panics can occur because WriteMessage and Flush don't use any locking
2573
// internally.
2574
func (p *Brontide) writeMessage(msg lnwire.Message) error {
16✔
2575
        // Only log the message on the first attempt.
16✔
2576
        if msg != nil {
32✔
2577
                p.logWireMessage(msg, false)
16✔
2578
        }
16✔
2579

2580
        noiseConn := p.cfg.Conn
16✔
2581

16✔
2582
        flushMsg := func() error {
32✔
2583
                // Ensure the write deadline is set before we attempt to send
16✔
2584
                // the message.
16✔
2585
                writeDeadline := time.Now().Add(
16✔
2586
                        p.scaleTimeout(writeMessageTimeout),
16✔
2587
                )
16✔
2588
                err := noiseConn.SetWriteDeadline(writeDeadline)
16✔
2589
                if err != nil {
16✔
2590
                        return err
×
2591
                }
×
2592

2593
                // Flush the pending message to the wire. If an error is
2594
                // encountered, e.g. write timeout, the number of bytes written
2595
                // so far will be returned.
2596
                n, err := noiseConn.Flush()
16✔
2597

16✔
2598
                // Record the number of bytes written on the wire, if any.
16✔
2599
                if n > 0 {
19✔
2600
                        atomic.AddUint64(&p.bytesSent, uint64(n))
3✔
2601
                }
3✔
2602

2603
                return err
16✔
2604
        }
2605

2606
        // If the current message has already been serialized, encrypted, and
2607
        // buffered on the underlying connection we will skip straight to
2608
        // flushing it to the wire.
2609
        if msg == nil {
16✔
2610
                return flushMsg()
×
2611
        }
×
2612

2613
        // Otherwise, this is a new message. We'll acquire a write buffer to
2614
        // serialize the message and buffer the ciphertext on the connection.
2615
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
32✔
2616
                // Using a buffer allocated by the write pool, encode the
16✔
2617
                // message directly into the buffer.
16✔
2618
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
16✔
2619
                if writeErr != nil {
16✔
2620
                        return writeErr
×
2621
                }
×
2622

2623
                // Finally, write the message itself in a single swoop. This
2624
                // will buffer the ciphertext on the underlying connection. We
2625
                // will defer flushing the message until the write pool has been
2626
                // released.
2627
                return noiseConn.WriteMessage(buf.Bytes())
16✔
2628
        })
2629
        if err != nil {
16✔
2630
                return err
×
2631
        }
×
2632

2633
        return flushMsg()
16✔
2634
}
2635

2636
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2637
// queue, and writing them out to the wire. This goroutine coordinates with the
2638
// queueHandler in order to ensure the incoming message queue is quickly
2639
// drained.
2640
//
2641
// NOTE: This method MUST be run as a goroutine.
2642
func (p *Brontide) writeHandler() {
6✔
2643
        // We'll stop the timer after a new messages is sent, and also reset it
6✔
2644
        // after we process the next message.
6✔
2645
        idleTimer := time.AfterFunc(idleTimeout, func() {
6✔
2646
                err := fmt.Errorf("peer %s no write for %s -- disconnecting",
×
2647
                        p, idleTimeout)
×
2648
                p.Disconnect(err)
×
2649
        })
×
2650

2651
        var exitErr error
6✔
2652

6✔
2653
out:
6✔
2654
        for {
16✔
2655
                var msgToWrite outgoingMsg
10✔
2656

10✔
2657
                // Prioritize superPrioSendQueue, only falling into the default
10✔
2658
                // to check the normal queue if we don't have anything to send.
10✔
2659
                select {
10✔
NEW
2660
                case msgToWrite = <-p.superPrioSendQueue:
×
2661
                default:
10✔
2662
                        // No superPrio msg, check normal sendQueue or quit.
10✔
2663
                        select {
10✔
NEW
2664
                        case msgToWrite = <-p.superPrioSendQueue:
×
2665

2666
                        case msgToWrite = <-p.sendQueue:
7✔
2667

2668
                        case <-p.cg.Done():
3✔
2669
                                exitErr = lnpeer.ErrPeerExiting
3✔
2670
                                break out
3✔
2671
                        }
2672
                }
2673

2674
                // Record the time at which we first attempt to send the
2675
                // message.
2676
                startTime := time.Now()
7✔
2677

7✔
2678
        retryWrite:
7✔
2679
                // Write out the message to the socket. If a timeout
2680
                // error is encountered, we will catch this and retry
2681
                // after backing off in case the remote peer is just
2682
                // slow to process messages from the wire.
2683
                err := p.writeMessage(msgToWrite.msg)
7✔
2684
                if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
7✔
NEW
2685
                        logPrefix := "Write timeout detected for peer"
×
NEW
2686
                        p.log.Debugf("%s, first write for message "+
×
NEW
2687
                                "attempted %v ago",
×
NEW
2688
                                logPrefix, time.Since(startTime))
×
NEW
2689

×
NEW
2690
                        // If we received a timeout error, this implies
×
NEW
2691
                        // that the message was buffered on the
×
NEW
2692
                        // connection successfully and that a flush was
×
NEW
2693
                        // attempted. We'll set the message to nil so
×
NEW
2694
                        // that on a subsequent pass we only try to
×
NEW
2695
                        // flush the buffered message, and forgo
×
NEW
2696
                        // reserializing or reencrypting it.
×
NEW
2697
                        msgToWrite.msg = nil
×
NEW
2698

×
NEW
2699
                        goto retryWrite
×
2700
                }
2701

2702
                // The write succeeded or failed with a non-timeout error.
2703
                // Reset the idle timer.
2704
                if !idleTimer.Stop() {
7✔
NEW
2705
                        select {
×
NEW
2706
                        case <-idleTimer.C:
×
NEW
2707
                        default:
×
2708
                        }
2709
                }
2710
                idleTimer.Reset(idleTimeout)
7✔
2711

7✔
2712
                // If the peer requested a synchronous write, respond
7✔
2713
                // with the error.
7✔
2714
                if msgToWrite.errChan != nil {
11✔
2715
                        msgToWrite.errChan <- err
4✔
2716
                }
4✔
2717

2718
                if err != nil {
7✔
NEW
2719
                        errMsgPrefix := "unable to write message"
×
NEW
2720
                        exitErr = fmt.Errorf("%s: %v", errMsgPrefix, err)
×
UNCOV
2721
                        break out
×
2722
                }
2723

2724
        }
2725

2726
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2727
        // disconnect.
2728
        p.cg.WgDone()
3✔
2729

3✔
2730
        p.Disconnect(exitErr)
3✔
2731

3✔
2732
        p.log.Trace("writeHandler for peer done")
3✔
2733
}
2734

2735
// queueHandler is responsible for accepting messages from outside subsystems
2736
// to be eventually sent out on the wire by the writeHandler.
2737
//
2738
// NOTE: This method MUST be run as a goroutine.
2739
func (p *Brontide) queueHandler() {
6✔
2740
        defer p.cg.WgDone()
6✔
2741

6✔
2742
        // priorityMsgs holds an in order list of messages deemed high-priority
6✔
2743
        // to be added to the sendQueue. This predominately includes messages
6✔
2744
        // from the funding manager and htlcswitch.
6✔
2745
        priorityMsgs := list.New()
6✔
2746

6✔
2747
        // lazyMsgs holds an in order list of messages deemed low-priority to be
6✔
2748
        // added to the sendQueue only after all high-priority messages have
6✔
2749
        // been queued. This predominately includes messages from the gossiper.
6✔
2750
        lazyMsgs := list.New()
6✔
2751

6✔
2752
        for {
20✔
2753
                // Examine the front of the priority queue, if it is empty check
14✔
2754
                // the low priority queue.
14✔
2755
                elem := priorityMsgs.Front()
14✔
2756
                if elem == nil {
25✔
2757
                        elem = lazyMsgs.Front()
11✔
2758
                }
11✔
2759

2760
                if elem != nil {
21✔
2761
                        front := elem.Value.(outgoingMsg)
7✔
2762

7✔
2763
                        // There's an element on the queue, try adding
7✔
2764
                        // it to the sendQueue. We also watch for
7✔
2765
                        // messages on the outgoingQueue, in case the
7✔
2766
                        // writeHandler cannot accept messages on the
7✔
2767
                        // sendQueue.
7✔
2768
                        select {
7✔
2769
                        case p.sendQueue <- front:
7✔
2770
                                if front.priority {
13✔
2771
                                        priorityMsgs.Remove(elem)
6✔
2772
                                } else {
10✔
2773
                                        lazyMsgs.Remove(elem)
4✔
2774
                                }
4✔
2775
                        case msg := <-p.outgoingQueue:
3✔
2776
                                if msg.priority {
6✔
2777
                                        priorityMsgs.PushBack(msg)
3✔
2778
                                } else {
6✔
2779
                                        lazyMsgs.PushBack(msg)
3✔
2780
                                }
3✔
2781
                        case <-p.cg.Done():
×
2782
                                return
×
2783
                        }
2784
                } else {
10✔
2785
                        // If there weren't any messages to send to the
10✔
2786
                        // writeHandler, then we'll accept a new message
10✔
2787
                        // into the queue from outside sub-systems.
10✔
2788
                        select {
10✔
2789
                        case msg := <-p.outgoingQueue:
7✔
2790
                                if msg.priority {
13✔
2791
                                        priorityMsgs.PushBack(msg)
6✔
2792
                                } else {
10✔
2793
                                        lazyMsgs.PushBack(msg)
4✔
2794
                                }
4✔
2795
                        case <-p.cg.Done():
3✔
2796
                                return
3✔
2797
                        }
2798
                }
2799
        }
2800
}
2801

2802
// queueSuperPriorityMsg adds the lnwire.Message to the super priority send
2803
// queue. If the errChan is non-nil, an error is sent back if the msg failed
2804
// to queue or failed to write, and nil otherwise.
NEW
2805
func (p *Brontide) queueSuperPriorityMsg(msg lnwire.Message, errChan chan error) {
×
NEW
2806
        outMsg := outgoingMsg{
×
NEW
2807
                priority: true,
×
NEW
2808
                msg:      msg,
×
NEW
2809
                errChan:  errChan,
×
NEW
2810
        }
×
NEW
2811

×
NEW
2812
        select {
×
NEW
2813
        case p.superPrioSendQueue <- outMsg:
×
2814

NEW
2815
        case <-p.cg.Done():
×
NEW
2816
                p.log.Tracef("Peer shutting down, could not enqueue "+
×
NEW
2817
                        "super priority msg: %v.", spew.Sdump(msg))
×
NEW
2818

×
NEW
2819
                if errChan != nil {
×
NEW
2820
                        errChan <- lnpeer.ErrPeerExiting
×
NEW
2821
                }
×
2822

NEW
2823
        case <-p.cfg.Quit:
×
NEW
2824
                p.log.Tracef("Server shutting down, could not enqueue "+
×
NEW
2825
                        "super priority msg: %v.", spew.Sdump(msg))
×
NEW
2826

×
NEW
2827
                if errChan != nil {
×
NEW
2828
                        errChan <- lnpeer.ErrPeerExiting
×
NEW
2829
                }
×
2830
        }
2831
}
2832

2833
// PingTime returns the estimated ping time to the peer in microseconds.
2834
func (p *Brontide) PingTime() int64 {
3✔
2835
        return p.pingManager.GetPingTimeMicroSeconds()
3✔
2836
}
3✔
2837

2838
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2839
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2840
// or failed to write, and nil otherwise.
2841
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
27✔
2842
        p.queue(true, msg, errChan)
27✔
2843
}
27✔
2844

2845
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2846
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2847
// queue or failed to write, and nil otherwise.
2848
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
4✔
2849
        p.queue(false, msg, errChan)
4✔
2850
}
4✔
2851

2852
// queue sends a given message to the queueHandler using the passed priority. If
2853
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2854
// failed to write, and nil otherwise.
2855
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2856
        errChan chan error) {
28✔
2857

28✔
2858
        select {
28✔
2859
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
28✔
UNCOV
2860
        case <-p.cg.Done():
×
UNCOV
2861
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
×
UNCOV
2862
                        spew.Sdump(msg))
×
UNCOV
2863
                if errChan != nil {
×
2864
                        errChan <- lnpeer.ErrPeerExiting
×
2865
                }
×
2866
        }
2867
}
2868

2869
// ChannelSnapshots returns a slice of channel snapshots detailing all
2870
// currently active channels maintained with the remote peer.
2871
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
3✔
2872
        snapshots := make(
3✔
2873
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
3✔
2874
        )
3✔
2875

3✔
2876
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2877
                activeChan *lnwallet.LightningChannel) error {
6✔
2878

3✔
2879
                // If the activeChan is nil, then we skip it as the channel is
3✔
2880
                // pending.
3✔
2881
                if activeChan == nil {
6✔
2882
                        return nil
3✔
2883
                }
3✔
2884

2885
                // We'll only return a snapshot for channels that are
2886
                // *immediately* available for routing payments over.
2887
                if activeChan.RemoteNextRevocation() == nil {
6✔
2888
                        return nil
3✔
2889
                }
3✔
2890

2891
                snapshot := activeChan.StateSnapshot()
3✔
2892
                snapshots = append(snapshots, snapshot)
3✔
2893

3✔
2894
                return nil
3✔
2895
        })
2896

2897
        return snapshots
3✔
2898
}
2899

2900
// genDeliveryScript returns a new script to be used to send our funds to in
2901
// the case of a cooperative channel close negotiation.
2902
func (p *Brontide) genDeliveryScript() ([]byte, error) {
9✔
2903
        // We'll send a normal p2wkh address unless we've negotiated the
9✔
2904
        // shutdown-any-segwit feature.
9✔
2905
        addrType := lnwallet.WitnessPubKey
9✔
2906
        if p.taprootShutdownAllowed() {
12✔
2907
                addrType = lnwallet.TaprootPubkey
3✔
2908
        }
3✔
2909

2910
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
9✔
2911
                addrType, false, lnwallet.DefaultAccountName,
9✔
2912
        )
9✔
2913
        if err != nil {
9✔
2914
                return nil, err
×
2915
        }
×
2916
        p.log.Infof("Delivery addr for channel close: %v",
9✔
2917
                deliveryAddr)
9✔
2918

9✔
2919
        return txscript.PayToAddrScript(deliveryAddr)
9✔
2920
}
2921

2922
// channelManager is goroutine dedicated to handling all requests/signals
2923
// pertaining to the opening, cooperative closing, and force closing of all
2924
// channels maintained with the remote peer.
2925
//
2926
// NOTE: This method MUST be run as a goroutine.
2927
func (p *Brontide) channelManager() {
20✔
2928
        defer p.cg.WgDone()
20✔
2929

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

20✔
2935
out:
20✔
2936
        for {
62✔
2937
                select {
42✔
2938
                // A new pending channel has arrived which means we are about
2939
                // to complete a funding workflow and is waiting for the final
2940
                // `ChannelReady` messages to be exchanged. We will add this
2941
                // channel to the `activeChannels` with a nil value to indicate
2942
                // this is a pending channel.
2943
                case req := <-p.newPendingChannel:
4✔
2944
                        p.handleNewPendingChannel(req)
4✔
2945

2946
                // A new channel has arrived which means we've just completed a
2947
                // funding workflow. We'll initialize the necessary local
2948
                // state, and notify the htlc switch of a new link.
2949
                case req := <-p.newActiveChannel:
3✔
2950
                        p.handleNewActiveChannel(req)
3✔
2951

2952
                // The funding flow for a pending channel is failed, we will
2953
                // remove it from Brontide.
2954
                case req := <-p.removePendingChannel:
4✔
2955
                        p.handleRemovePendingChannel(req)
4✔
2956

2957
                // We've just received a local request to close an active
2958
                // channel. It will either kick of a cooperative channel
2959
                // closure negotiation, or be a notification of a breached
2960
                // contract that should be abandoned.
2961
                case req := <-p.localCloseChanReqs:
10✔
2962
                        p.handleLocalCloseReq(req)
10✔
2963

2964
                // We've received a link failure from a link that was added to
2965
                // the switch. This will initiate the teardown of the link, and
2966
                // initiate any on-chain closures if necessary.
2967
                case failure := <-p.linkFailures:
3✔
2968
                        p.handleLinkFailure(failure)
3✔
2969

2970
                // We've received a new cooperative channel closure related
2971
                // message from the remote peer, we'll use this message to
2972
                // advance the chan closer state machine.
2973
                case closeMsg := <-p.chanCloseMsgs:
16✔
2974
                        p.handleCloseMsg(closeMsg)
16✔
2975

2976
                // The channel reannounce delay has elapsed, broadcast the
2977
                // reenabled channel updates to the network. This should only
2978
                // fire once, so we set the reenableTimeout channel to nil to
2979
                // mark it for garbage collection. If the peer is torn down
2980
                // before firing, reenabling will not be attempted.
2981
                // TODO(conner): consolidate reenables timers inside chan status
2982
                // manager
2983
                case <-reenableTimeout:
3✔
2984
                        p.reenableActiveChannels()
3✔
2985

3✔
2986
                        // Since this channel will never fire again during the
3✔
2987
                        // lifecycle of the peer, we nil the channel to mark it
3✔
2988
                        // eligible for garbage collection, and make this
3✔
2989
                        // explicitly ineligible to receive in future calls to
3✔
2990
                        // select. This also shaves a few CPU cycles since the
3✔
2991
                        // select will ignore this case entirely.
3✔
2992
                        reenableTimeout = nil
3✔
2993

3✔
2994
                        // Once the reenabling is attempted, we also cancel the
3✔
2995
                        // channel event subscription to free up the overflow
3✔
2996
                        // queue used in channel notifier.
3✔
2997
                        //
3✔
2998
                        // NOTE: channelEventClient will be nil if the
3✔
2999
                        // reenableTimeout is greater than 1 minute.
3✔
3000
                        if p.channelEventClient != nil {
6✔
3001
                                p.channelEventClient.Cancel()
3✔
3002
                        }
3✔
3003

3004
                case <-p.cg.Done():
4✔
3005
                        // As, we've been signalled to exit, we'll reset all
4✔
3006
                        // our active channel back to their default state.
4✔
3007
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
4✔
3008
                                lc *lnwallet.LightningChannel) error {
8✔
3009

4✔
3010
                                // Exit if the channel is nil as it's a pending
4✔
3011
                                // channel.
4✔
3012
                                if lc == nil {
7✔
3013
                                        return nil
3✔
3014
                                }
3✔
3015

3016
                                lc.ResetState()
4✔
3017

4✔
3018
                                return nil
4✔
3019
                        })
3020

3021
                        break out
4✔
3022
                }
3023
        }
3024
}
3025

3026
// reenableActiveChannels searches the index of channels maintained with this
3027
// peer, and reenables each public, non-pending channel. This is done at the
3028
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
3029
// No message will be sent if the channel is already enabled.
3030
func (p *Brontide) reenableActiveChannels() {
3✔
3031
        // First, filter all known channels with this peer for ones that are
3✔
3032
        // both public and not pending.
3✔
3033
        activePublicChans := p.filterChannelsToEnable()
3✔
3034

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

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

3✔
3044
                switch {
3✔
3045
                // No error occurred, continue to request the next channel.
3046
                case err == nil:
3✔
3047
                        continue
3✔
3048

3049
                // Cannot auto enable a manually disabled channel so we do
3050
                // nothing but proceed to the next channel.
3051
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
3✔
3052
                        p.log.Debugf("Channel(%v) was manually disabled, "+
3✔
3053
                                "ignoring automatic enable request", chanPoint)
3✔
3054

3✔
3055
                        continue
3✔
3056

3057
                // If the channel is reported as inactive, we will give it
3058
                // another chance. When handling the request, ChanStatusManager
3059
                // will check whether the link is active or not. One of the
3060
                // conditions is whether the link has been marked as
3061
                // reestablished, which happens inside a goroutine(htlcManager)
3062
                // after the link is started. And we may get a false negative
3063
                // saying the link is not active because that goroutine hasn't
3064
                // reached the line to mark the reestablishment. Thus we give
3065
                // it a second chance to send the request.
3066
                case errors.Is(err, netann.ErrEnableInactiveChan):
×
3067
                        // If we don't have a client created, it means we
×
3068
                        // shouldn't retry enabling the channel.
×
3069
                        if p.channelEventClient == nil {
×
3070
                                p.log.Errorf("Channel(%v) request enabling "+
×
3071
                                        "failed due to inactive link",
×
3072
                                        chanPoint)
×
3073

×
3074
                                continue
×
3075
                        }
3076

3077
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
3078
                                "ChanStatusManager reported inactive, retrying")
×
3079

×
3080
                        // Add the channel to the retry map.
×
3081
                        retryChans[chanPoint] = struct{}{}
×
3082
                }
3083
        }
3084

3085
        // Retry the channels if we have any.
3086
        if len(retryChans) != 0 {
3✔
3087
                p.retryRequestEnable(retryChans)
×
3088
        }
×
3089
}
3090

3091
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
3092
// for the target channel ID. If the channel isn't active an error is returned.
3093
// Otherwise, either an existing state machine will be returned, or a new one
3094
// will be created.
3095
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
3096
        *chanCloserFsm, error) {
16✔
3097

16✔
3098
        chanCloser, found := p.activeChanCloses.Load(chanID)
16✔
3099
        if found {
29✔
3100
                // An entry will only be found if the closer has already been
13✔
3101
                // created for a non-pending channel or for a channel that had
13✔
3102
                // previously started the shutdown process but the connection
13✔
3103
                // was restarted.
13✔
3104
                return &chanCloser, nil
13✔
3105
        }
13✔
3106

3107
        // First, we'll ensure that we actually know of the target channel. If
3108
        // not, we'll ignore this message.
3109
        channel, ok := p.activeChannels.Load(chanID)
6✔
3110

6✔
3111
        // If the channel isn't in the map or the channel is nil, return
6✔
3112
        // ErrChannelNotFound as the channel is pending.
6✔
3113
        if !ok || channel == nil {
9✔
3114
                return nil, ErrChannelNotFound
3✔
3115
        }
3✔
3116

3117
        // We'll create a valid closing state machine in order to respond to
3118
        // the initiated cooperative channel closure. First, we set the
3119
        // delivery script that our funds will be paid out to. If an upfront
3120
        // shutdown script was set, we will use it. Otherwise, we get a fresh
3121
        // delivery script.
3122
        //
3123
        // TODO: Expose option to allow upfront shutdown script from watch-only
3124
        // accounts.
3125
        deliveryScript := channel.LocalUpfrontShutdownScript()
6✔
3126
        if len(deliveryScript) == 0 {
12✔
3127
                var err error
6✔
3128
                deliveryScript, err = p.genDeliveryScript()
6✔
3129
                if err != nil {
6✔
3130
                        p.log.Errorf("unable to gen delivery script: %v",
×
3131
                                err)
×
3132
                        return nil, fmt.Errorf("close addr unavailable")
×
3133
                }
×
3134
        }
3135

3136
        // In order to begin fee negotiations, we'll first compute our target
3137
        // ideal fee-per-kw.
3138
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
6✔
3139
                p.cfg.CoopCloseTargetConfs,
6✔
3140
        )
6✔
3141
        if err != nil {
6✔
3142
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3143
                return nil, fmt.Errorf("unable to estimate fee")
×
3144
        }
×
3145

3146
        addr, err := p.addrWithInternalKey(deliveryScript)
6✔
3147
        if err != nil {
6✔
3148
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3149
        }
×
3150
        negotiateChanCloser, err := p.createChanCloser(
6✔
3151
                channel, addr, feePerKw, nil, lntypes.Remote,
6✔
3152
        )
6✔
3153
        if err != nil {
6✔
3154
                p.log.Errorf("unable to create chan closer: %v", err)
×
3155
                return nil, fmt.Errorf("unable to create chan closer")
×
3156
        }
×
3157

3158
        chanCloser = makeNegotiateCloser(negotiateChanCloser)
6✔
3159

6✔
3160
        p.activeChanCloses.Store(chanID, chanCloser)
6✔
3161

6✔
3162
        return &chanCloser, nil
6✔
3163
}
3164

3165
// filterChannelsToEnable filters a list of channels to be enabled upon start.
3166
// The filtered channels are active channels that's neither private nor
3167
// pending.
3168
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
3✔
3169
        var activePublicChans []wire.OutPoint
3✔
3170

3✔
3171
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
3✔
3172
                lnChan *lnwallet.LightningChannel) bool {
6✔
3173

3✔
3174
                // If the lnChan is nil, continue as this is a pending channel.
3✔
3175
                if lnChan == nil {
5✔
3176
                        return true
2✔
3177
                }
2✔
3178

3179
                dbChan := lnChan.State()
3✔
3180
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
3181
                if !isPublic || dbChan.IsPending {
3✔
3182
                        return true
×
3183
                }
×
3184

3185
                // We'll also skip any channels added during this peer's
3186
                // lifecycle since they haven't waited out the timeout. Their
3187
                // first announcement will be enabled, and the chan status
3188
                // manager will begin monitoring them passively since they exist
3189
                // in the database.
3190
                if _, ok := p.addedChannels.Load(chanID); ok {
4✔
3191
                        return true
1✔
3192
                }
1✔
3193

3194
                activePublicChans = append(
3✔
3195
                        activePublicChans, dbChan.FundingOutpoint,
3✔
3196
                )
3✔
3197

3✔
3198
                return true
3✔
3199
        })
3200

3201
        return activePublicChans
3✔
3202
}
3203

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

×
3211
        // retryEnable is a helper closure that sends an enable request and
×
3212
        // removes the channel from the map if it's matched.
×
3213
        retryEnable := func(chanPoint wire.OutPoint) error {
×
3214
                // If this is an active channel event, check whether it's in
×
3215
                // our targeted channels map.
×
3216
                _, found := activeChans[chanPoint]
×
3217

×
3218
                // If this channel is irrelevant, return nil so the loop can
×
3219
                // jump to next iteration.
×
3220
                if !found {
×
3221
                        return nil
×
3222
                }
×
3223

3224
                // Otherwise we've just received an active signal for a channel
3225
                // that's previously failed to be enabled, we send the request
3226
                // again.
3227
                //
3228
                // We only give the channel one more shot, so we delete it from
3229
                // our map first to keep it from being attempted again.
3230
                delete(activeChans, chanPoint)
×
3231

×
3232
                // Send the request.
×
3233
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3234
                if err != nil {
×
3235
                        return fmt.Errorf("request enabling channel %v "+
×
3236
                                "failed: %w", chanPoint, err)
×
3237
                }
×
3238

3239
                return nil
×
3240
        }
3241

3242
        for {
×
3243
                // If activeChans is empty, we've done processing all the
×
3244
                // channels.
×
3245
                if len(activeChans) == 0 {
×
3246
                        p.log.Debug("Finished retry enabling channels")
×
3247
                        return
×
3248
                }
×
3249

3250
                select {
×
3251
                // A new event has been sent by the ChannelNotifier. We now
3252
                // check whether it's an active or inactive channel event.
3253
                case e := <-p.channelEventClient.Updates():
×
3254
                        // If this is an active channel event, try enable the
×
3255
                        // channel then jump to the next iteration.
×
3256
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
3257
                        if ok {
×
3258
                                chanPoint := *active.ChannelPoint
×
3259

×
3260
                                // If we received an error for this particular
×
3261
                                // channel, we log an error and won't quit as
×
3262
                                // we still want to retry other channels.
×
3263
                                if err := retryEnable(chanPoint); err != nil {
×
3264
                                        p.log.Errorf("Retry failed: %v", err)
×
3265
                                }
×
3266

3267
                                continue
×
3268
                        }
3269

3270
                        // Otherwise check for inactive link event, and jump to
3271
                        // next iteration if it's not.
3272
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3273
                        if !ok {
×
3274
                                continue
×
3275
                        }
3276

3277
                        // Found an inactive link event, if this is our
3278
                        // targeted channel, remove it from our map.
3279
                        chanPoint := *inactive.ChannelPoint
×
3280
                        _, found := activeChans[chanPoint]
×
3281
                        if !found {
×
3282
                                continue
×
3283
                        }
3284

3285
                        delete(activeChans, chanPoint)
×
3286
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3287
                                "inactive link event", chanPoint)
×
3288

3289
                case <-p.cg.Done():
×
3290
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3291
                        return
×
3292
                }
3293
        }
3294
}
3295

3296
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3297
// a suitable script to close out to. This may be nil if neither script is
3298
// set. If both scripts are set, this function will error if they do not match.
3299
func chooseDeliveryScript(upfront, requested lnwire.DeliveryAddress,
3300
        genDeliveryScript func() ([]byte, error),
3301
) (lnwire.DeliveryAddress, error) {
15✔
3302

15✔
3303
        switch {
15✔
3304
        // If no script was provided, then we'll generate a new delivery script.
3305
        case len(upfront) == 0 && len(requested) == 0:
7✔
3306
                return genDeliveryScript()
7✔
3307

3308
        // If no upfront shutdown script was provided, return the user
3309
        // requested address (which may be nil).
3310
        case len(upfront) == 0:
5✔
3311
                return requested, nil
5✔
3312

3313
        // If an upfront shutdown script was provided, and the user did not
3314
        // request a custom shutdown script, return the upfront address.
3315
        case len(requested) == 0:
5✔
3316
                return upfront, nil
5✔
3317

3318
        // If both an upfront shutdown script and a custom close script were
3319
        // provided, error if the user provided shutdown script does not match
3320
        // the upfront shutdown script (because closing out to a different
3321
        // script would violate upfront shutdown).
3322
        case !bytes.Equal(upfront, requested):
2✔
3323
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
3324

3325
        // The user requested script matches the upfront shutdown script, so we
3326
        // can return it without error.
3327
        default:
2✔
3328
                return upfront, nil
2✔
3329
        }
3330
}
3331

3332
// restartCoopClose checks whether we need to restart the cooperative close
3333
// process for a given channel.
3334
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3335
        *lnwire.Shutdown, error) {
3✔
3336

3✔
3337
        isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
3338

3✔
3339
        // If this channel has status ChanStatusCoopBroadcasted and does not
3✔
3340
        // have a closing transaction, then the cooperative close process was
3✔
3341
        // started but never finished. We'll re-create the chanCloser state
3✔
3342
        // machine and resend Shutdown. BOLT#2 requires that we retransmit
3✔
3343
        // Shutdown exactly, but doing so would mean persisting the RPC
3✔
3344
        // provided close script. Instead use the LocalUpfrontShutdownScript
3✔
3345
        // or generate a script.
3✔
3346
        c := lnChan.State()
3✔
3347
        _, err := c.BroadcastedCooperative()
3✔
3348
        if err != nil && err != channeldb.ErrNoCloseTx {
3✔
3349
                // An error other than ErrNoCloseTx was encountered.
×
3350
                return nil, err
×
3351
        } else if err == nil && !p.rbfCoopCloseAllowed() {
3✔
3352
                // This is a channel that doesn't support RBF coop close, and it
×
3353
                // already had a coop close txn broadcast. As a result, we can
×
3354
                // just exit here as all we can do is wait for it to confirm.
×
3355
                return nil, nil
×
3356
        }
×
3357

3358
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
3✔
3359

3✔
3360
        var deliveryScript []byte
3✔
3361

3✔
3362
        shutdownInfo, err := c.ShutdownInfo()
3✔
3363
        switch {
3✔
3364
        // We have previously stored the delivery script that we need to use
3365
        // in the shutdown message. Re-use this script.
3366
        case err == nil:
3✔
3367
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
6✔
3368
                        deliveryScript = info.DeliveryScript.Val
3✔
3369
                })
3✔
3370

3371
        // An error other than ErrNoShutdownInfo was returned
3372
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3373
                return nil, err
×
3374

3375
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3376
                deliveryScript = c.LocalShutdownScript
×
3377
                if len(deliveryScript) == 0 {
×
3378
                        var err error
×
3379
                        deliveryScript, err = p.genDeliveryScript()
×
3380
                        if err != nil {
×
3381
                                p.log.Errorf("unable to gen delivery script: "+
×
3382
                                        "%v", err)
×
3383

×
3384
                                return nil, fmt.Errorf("close addr unavailable")
×
3385
                        }
×
3386
                }
3387
        }
3388

3389
        // If the new RBF co-op close is negotiated, then we'll init and start
3390
        // that state machine, skipping the steps for the negotiate machine
3391
        // below. We don't support this close type for taproot channels though.
3392
        if p.rbfCoopCloseAllowed() && !isTaprootChan {
6✔
3393
                _, err := p.initRbfChanCloser(lnChan)
3✔
3394
                if err != nil {
3✔
3395
                        return nil, fmt.Errorf("unable to init rbf chan "+
×
3396
                                "closer during restart: %w", err)
×
3397
                }
×
3398

3399
                shutdownDesc := fn.MapOption(
3✔
3400
                        newRestartShutdownInit,
3✔
3401
                )(shutdownInfo)
3✔
3402

3✔
3403
                err = p.startRbfChanCloser(
3✔
3404
                        fn.FlattenOption(shutdownDesc), lnChan.ChannelPoint(),
3✔
3405
                )
3✔
3406

3✔
3407
                return nil, err
3✔
3408
        }
3409

3410
        // Compute an ideal fee.
3411
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
3412
                p.cfg.CoopCloseTargetConfs,
×
3413
        )
×
3414
        if err != nil {
×
3415
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3416
                return nil, fmt.Errorf("unable to estimate fee")
×
3417
        }
×
3418

3419
        // Determine whether we or the peer are the initiator of the coop
3420
        // close attempt by looking at the channel's status.
3421
        closingParty := lntypes.Remote
×
3422
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3423
                closingParty = lntypes.Local
×
3424
        }
×
3425

3426
        addr, err := p.addrWithInternalKey(deliveryScript)
×
3427
        if err != nil {
×
3428
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3429
        }
×
3430
        chanCloser, err := p.createChanCloser(
×
3431
                lnChan, addr, feePerKw, nil, closingParty,
×
3432
        )
×
3433
        if err != nil {
×
3434
                p.log.Errorf("unable to create chan closer: %v", err)
×
3435
                return nil, fmt.Errorf("unable to create chan closer")
×
3436
        }
×
3437

3438
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
×
3439

×
3440
        // Create the Shutdown message.
×
3441
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3442
        if err != nil {
×
3443
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3444
                p.activeChanCloses.Delete(chanID)
×
3445
                return nil, err
×
3446
        }
×
3447

3448
        return shutdownMsg, nil
×
3449
}
3450

3451
// createChanCloser constructs a ChanCloser from the passed parameters and is
3452
// used to de-duplicate code.
3453
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3454
        deliveryScript *chancloser.DeliveryAddrWithKey,
3455
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3456
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
12✔
3457

12✔
3458
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
12✔
3459
        if err != nil {
12✔
3460
                p.log.Errorf("unable to obtain best block: %v", err)
×
3461
                return nil, fmt.Errorf("cannot obtain best block")
×
3462
        }
×
3463

3464
        // The req will only be set if we initiated the co-op closing flow.
3465
        var maxFee chainfee.SatPerKWeight
12✔
3466
        if req != nil {
21✔
3467
                maxFee = req.MaxFee
9✔
3468
        }
9✔
3469

3470
        chanCloser := chancloser.NewChanCloser(
12✔
3471
                chancloser.ChanCloseCfg{
12✔
3472
                        Channel:      channel,
12✔
3473
                        MusigSession: NewMusigChanCloser(channel),
12✔
3474
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
12✔
3475
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
12✔
3476
                        AuxCloser:    p.cfg.AuxChanCloser,
12✔
3477
                        DisableChannel: func(op wire.OutPoint) error {
24✔
3478
                                return p.cfg.ChanStatusMgr.RequestDisable(
12✔
3479
                                        op, false,
12✔
3480
                                )
12✔
3481
                        },
12✔
3482
                        MaxFee: maxFee,
3483
                        Disconnect: func() error {
×
3484
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
3485
                        },
×
3486
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3487
                },
3488
                *deliveryScript,
3489
                fee,
3490
                uint32(startingHeight),
3491
                req,
3492
                closer,
3493
        )
3494

3495
        return chanCloser, nil
12✔
3496
}
3497

3498
// initNegotiateChanCloser initializes the channel closer for a channel that is
3499
// using the original "negotiation" based protocol. This path is used when
3500
// we're the one initiating the channel close.
3501
//
3502
// TODO(roasbeef): can make a MsgEndpoint for existing handling logic to
3503
// further abstract.
3504
func (p *Brontide) initNegotiateChanCloser(req *htlcswitch.ChanClose,
3505
        channel *lnwallet.LightningChannel) error {
10✔
3506

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

10✔
3510
        // An upfront shutdown and user provided script are both optional, but
10✔
3511
        // must be equal if both set  (because we cannot serve a request to
10✔
3512
        // close out to a script which violates upfront shutdown). Get the
10✔
3513
        // appropriate address to close out to (which may be nil if neither are
10✔
3514
        // set) and error if they are both set and do not match.
10✔
3515
        deliveryScript, err := chooseDeliveryScript(
10✔
3516
                channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
10✔
3517
                p.genDeliveryScript,
10✔
3518
        )
10✔
3519
        if err != nil {
11✔
3520
                return fmt.Errorf("cannot close channel %v: %w",
1✔
3521
                        req.ChanPoint, err)
1✔
3522
        }
1✔
3523

3524
        addr, err := p.addrWithInternalKey(deliveryScript)
9✔
3525
        if err != nil {
9✔
3526
                return fmt.Errorf("unable to parse addr for channel "+
×
3527
                        "%v: %w", req.ChanPoint, err)
×
3528
        }
×
3529

3530
        chanCloser, err := p.createChanCloser(
9✔
3531
                channel, addr, req.TargetFeePerKw, req, lntypes.Local,
9✔
3532
        )
9✔
3533
        if err != nil {
9✔
3534
                return fmt.Errorf("unable to make chan closer: %w", err)
×
3535
        }
×
3536

3537
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
9✔
3538
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
9✔
3539

9✔
3540
        // Finally, we'll initiate the channel shutdown within the
9✔
3541
        // chanCloser, and send the shutdown message to the remote
9✔
3542
        // party to kick things off.
9✔
3543
        shutdownMsg, err := chanCloser.ShutdownChan()
9✔
3544
        if err != nil {
9✔
3545
                // As we were unable to shutdown the channel, we'll return it
×
3546
                // back to its normal state.
×
3547
                defer channel.ResetState()
×
3548

×
3549
                p.activeChanCloses.Delete(chanID)
×
3550

×
3551
                return fmt.Errorf("unable to shutdown channel: %w", err)
×
3552
        }
×
3553

3554
        link := p.fetchLinkFromKeyAndCid(chanID)
9✔
3555
        if link == nil {
9✔
3556
                // If the link is nil then it means it was already removed from
×
3557
                // the switch or it never existed in the first place. The
×
3558
                // latter case is handled at the beginning of this function, so
×
3559
                // in the case where it has already been removed, we can skip
×
3560
                // adding the commit hook to queue a Shutdown message.
×
3561
                p.log.Warnf("link not found during attempted closure: "+
×
3562
                        "%v", chanID)
×
3563
                return nil
×
3564
        }
×
3565

3566
        if !link.DisableAdds(htlcswitch.Outgoing) {
9✔
3567
                p.log.Warnf("Outgoing link adds already "+
×
3568
                        "disabled: %v", link.ChanID())
×
3569
        }
×
3570

3571
        link.OnCommitOnce(htlcswitch.Outgoing, func() {
18✔
3572
                p.queueMsg(shutdownMsg, nil)
9✔
3573
        })
9✔
3574

3575
        return nil
9✔
3576
}
3577

3578
// chooseAddr returns the provided address if it is non-zero length, otherwise
3579
// None.
3580
func chooseAddr(addr lnwire.DeliveryAddress) fn.Option[lnwire.DeliveryAddress] {
3✔
3581
        if len(addr) == 0 {
6✔
3582
                return fn.None[lnwire.DeliveryAddress]()
3✔
3583
        }
3✔
3584

3585
        return fn.Some(addr)
×
3586
}
3587

3588
// observeRbfCloseUpdates observes the channel for any updates that may
3589
// indicate that a new txid has been broadcasted, or the channel fully closed
3590
// on chain.
3591
func (p *Brontide) observeRbfCloseUpdates(chanCloser *chancloser.RbfChanCloser,
3592
        closeReq *htlcswitch.ChanClose,
3593
        coopCloseStates chancloser.RbfStateSub) {
3✔
3594

3✔
3595
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3596
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3597

3✔
3598
        var (
3✔
3599
                lastTxids    lntypes.Dual[chainhash.Hash]
3✔
3600
                lastFeeRates lntypes.Dual[chainfee.SatPerVByte]
3✔
3601
        )
3✔
3602

3✔
3603
        maybeNotifyTxBroadcast := func(state chancloser.AsymmetricPeerState,
3✔
3604
                party lntypes.ChannelParty) {
6✔
3605

3✔
3606
                // First, check to see if we have an error to report to the
3✔
3607
                // caller. If so, then we''ll return that error and exit, as the
3✔
3608
                // stream will exit as well.
3✔
3609
                if closeErr, ok := state.(*chancloser.CloseErr); ok {
6✔
3610
                        // We hit an error during the last state transition, so
3✔
3611
                        // we'll extract the error then send it to the
3✔
3612
                        // user.
3✔
3613
                        err := closeErr.Err()
3✔
3614

3✔
3615
                        peerLog.Warnf("ChannelPoint(%v): encountered close "+
3✔
3616
                                "err: %v", closeReq.ChanPoint, err)
3✔
3617

3✔
3618
                        select {
3✔
3619
                        case closeReq.Err <- err:
3✔
3620
                        case <-closeReq.Ctx.Done():
×
3621
                        case <-p.cg.Done():
×
3622
                        }
3623

3624
                        return
3✔
3625
                }
3626

3627
                closePending, ok := state.(*chancloser.ClosePending)
3✔
3628

3✔
3629
                // If this isn't the close pending state, we aren't at the
3✔
3630
                // terminal state yet.
3✔
3631
                if !ok {
6✔
3632
                        return
3✔
3633
                }
3✔
3634

3635
                // Only notify if the fee rate is greater.
3636
                newFeeRate := closePending.FeeRate
3✔
3637
                lastFeeRate := lastFeeRates.GetForParty(party)
3✔
3638
                if newFeeRate <= lastFeeRate {
6✔
3639
                        peerLog.Debugf("ChannelPoint(%v): remote party made "+
3✔
3640
                                "update for fee rate %v, but we already have "+
3✔
3641
                                "a higher fee rate of %v", closeReq.ChanPoint,
3✔
3642
                                newFeeRate, lastFeeRate)
3✔
3643

3✔
3644
                        return
3✔
3645
                }
3✔
3646

3647
                feeRate := closePending.FeeRate
3✔
3648
                lastFeeRates.SetForParty(party, feeRate)
3✔
3649

3✔
3650
                // At this point, we'll have a txid that we can use to notify
3✔
3651
                // the client, but only if it's different from the last one we
3✔
3652
                // sent. If the user attempted to bump, but was rejected due to
3✔
3653
                // RBF, then we'll send a redundant update.
3✔
3654
                closingTxid := closePending.CloseTx.TxHash()
3✔
3655
                lastTxid := lastTxids.GetForParty(party)
3✔
3656
                if closeReq != nil && closingTxid != lastTxid {
6✔
3657
                        select {
3✔
3658
                        case closeReq.Updates <- &PendingUpdate{
3659
                                Txid:        closingTxid[:],
3660
                                FeePerVbyte: fn.Some(closePending.FeeRate),
3661
                                IsLocalCloseTx: fn.Some(
3662
                                        party == lntypes.Local,
3663
                                ),
3664
                        }:
3✔
3665

3666
                        case <-closeReq.Ctx.Done():
×
3667
                                return
×
3668

3669
                        case <-p.cg.Done():
×
3670
                                return
×
3671
                        }
3672
                }
3673

3674
                lastTxids.SetForParty(party, closingTxid)
3✔
3675
        }
3676

3677
        peerLog.Infof("Observing RBF close updates for channel %v",
3✔
3678
                closeReq.ChanPoint)
3✔
3679

3✔
3680
        // We'll consume each new incoming state to send out the appropriate
3✔
3681
        // RPC update.
3✔
3682
        for {
6✔
3683
                select {
3✔
3684
                case newState := <-newStateChan:
3✔
3685

3✔
3686
                        switch closeState := newState.(type) {
3✔
3687
                        // Once we've reached the state of pending close, we
3688
                        // have a txid that we broadcasted.
3689
                        case *chancloser.ClosingNegotiation:
3✔
3690
                                peerState := closeState.PeerState
3✔
3691

3✔
3692
                                // Each side may have gained a new co-op close
3✔
3693
                                // tx, so we'll examine both to see if they've
3✔
3694
                                // changed.
3✔
3695
                                maybeNotifyTxBroadcast(
3✔
3696
                                        peerState.GetForParty(lntypes.Local),
3✔
3697
                                        lntypes.Local,
3✔
3698
                                )
3✔
3699
                                maybeNotifyTxBroadcast(
3✔
3700
                                        peerState.GetForParty(lntypes.Remote),
3✔
3701
                                        lntypes.Remote,
3✔
3702
                                )
3✔
3703

3704
                        // Otherwise, if we're transition to CloseFin, then we
3705
                        // know that we're done.
3706
                        case *chancloser.CloseFin:
3✔
3707
                                // To clean up, we'll remove the chan closer
3✔
3708
                                // from the active map, and send the final
3✔
3709
                                // update to the client.
3✔
3710
                                closingTxid := closeState.ConfirmedTx.TxHash()
3✔
3711
                                if closeReq != nil {
6✔
3712
                                        closeReq.Updates <- &ChannelCloseUpdate{
3✔
3713
                                                ClosingTxid: closingTxid[:],
3✔
3714
                                                Success:     true,
3✔
3715
                                        }
3✔
3716
                                }
3✔
3717
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
3718
                                        *closeReq.ChanPoint,
3✔
3719
                                )
3✔
3720
                                p.activeChanCloses.Delete(chanID)
3✔
3721

3✔
3722
                                return
3✔
3723
                        }
3724

3725
                case <-closeReq.Ctx.Done():
3✔
3726
                        return
3✔
3727

3728
                case <-p.cg.Done():
3✔
3729
                        return
3✔
3730
                }
3731
        }
3732
}
3733

3734
// chanErrorReporter is a simple implementation of the
3735
// chancloser.ErrorReporter. This is bound to a single channel by the channel
3736
// ID.
3737
type chanErrorReporter struct {
3738
        chanID lnwire.ChannelID
3739
        peer   *Brontide
3740
}
3741

3742
// newChanErrorReporter creates a new instance of the chanErrorReporter.
3743
func newChanErrorReporter(chanID lnwire.ChannelID,
3744
        peer *Brontide) *chanErrorReporter {
3✔
3745

3✔
3746
        return &chanErrorReporter{
3✔
3747
                chanID: chanID,
3✔
3748
                peer:   peer,
3✔
3749
        }
3✔
3750
}
3✔
3751

3752
// ReportError is a method that's used to report an error that occurred during
3753
// state machine execution. This is used by the RBF close state machine to
3754
// terminate the state machine and send an error to the remote peer.
3755
//
3756
// This is a part of the chancloser.ErrorReporter interface.
3757
func (c *chanErrorReporter) ReportError(chanErr error) {
×
3758
        c.peer.log.Errorf("coop close error for channel %v: %v",
×
3759
                c.chanID, chanErr)
×
3760

×
3761
        var errMsg []byte
×
3762
        if errors.Is(chanErr, chancloser.ErrInvalidStateTransition) {
×
3763
                errMsg = []byte("unexpected protocol message")
×
3764
        } else {
×
3765
                errMsg = []byte(chanErr.Error())
×
3766
        }
×
3767

3768
        err := c.peer.SendMessageLazy(false, &lnwire.Error{
×
3769
                ChanID: c.chanID,
×
3770
                Data:   errMsg,
×
3771
        })
×
3772
        if err != nil {
×
3773
                c.peer.log.Warnf("unable to send error message to peer: %v",
×
3774
                        err)
×
3775
        }
×
3776

3777
        // After we send the error message to the peer, we'll re-initialize the
3778
        // coop close state machine as they may send a shutdown message to
3779
        // retry the coop close.
3780
        lnChan, ok := c.peer.activeChannels.Load(c.chanID)
×
3781
        if !ok {
×
3782
                return
×
3783
        }
×
3784

3785
        if lnChan == nil {
×
3786
                c.peer.log.Debugf("channel %v is pending, not "+
×
3787
                        "re-initializing coop close state machine",
×
3788
                        c.chanID)
×
3789

×
3790
                return
×
3791
        }
×
3792

3793
        if _, err := c.peer.initRbfChanCloser(lnChan); err != nil {
×
3794
                c.peer.activeChanCloses.Delete(c.chanID)
×
3795

×
3796
                c.peer.log.Errorf("unable to init RBF chan closer after "+
×
3797
                        "error case: %v", err)
×
3798
        }
×
3799
}
3800

3801
// chanFlushEventSentinel is used to send the RBF coop close state machine the
3802
// channel flushed event. We'll wait until the state machine enters the
3803
// ChannelFlushing state, then request the link to send the event once flushed.
3804
//
3805
// NOTE: This MUST be run as a goroutine.
3806
func (p *Brontide) chanFlushEventSentinel(chanCloser *chancloser.RbfChanCloser,
3807
        link htlcswitch.ChannelUpdateHandler,
3808
        channel *lnwallet.LightningChannel) {
3✔
3809

3✔
3810
        defer p.cg.WgDone()
3✔
3811

3✔
3812
        // If there's no link, then the channel has already been flushed, so we
3✔
3813
        // don't need to continue.
3✔
3814
        if link == nil {
6✔
3815
                return
3✔
3816
        }
3✔
3817

3818
        coopCloseStates := chanCloser.RegisterStateEvents()
3✔
3819
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3820

3✔
3821
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3822

3✔
3823
        sendChanFlushed := func() {
6✔
3824
                chanState := channel.StateSnapshot()
3✔
3825

3✔
3826
                peerLog.Infof("ChannelPoint(%v) has been flushed for co-op "+
3✔
3827
                        "close, sending event to chan closer",
3✔
3828
                        channel.ChannelPoint())
3✔
3829

3✔
3830
                chanBalances := chancloser.ShutdownBalances{
3✔
3831
                        LocalBalance:  chanState.LocalBalance,
3✔
3832
                        RemoteBalance: chanState.RemoteBalance,
3✔
3833
                }
3✔
3834
                ctx := context.Background()
3✔
3835
                chanCloser.SendEvent(ctx, &chancloser.ChannelFlushed{
3✔
3836
                        ShutdownBalances: chanBalances,
3✔
3837
                        FreshFlush:       true,
3✔
3838
                })
3✔
3839
        }
3✔
3840

3841
        // We'll wait until the channel enters the ChannelFlushing state. We
3842
        // exit after a success loop. As after the first RBF iteration, the
3843
        // channel will always be flushed.
3844
        for newState := range newStateChan {
6✔
3845
                if _, ok := newState.(*chancloser.ChannelFlushing); ok {
6✔
3846
                        peerLog.Infof("ChannelPoint(%v): rbf coop "+
3✔
3847
                                "close is awaiting a flushed state, "+
3✔
3848
                                "registering with link..., ",
3✔
3849
                                channel.ChannelPoint())
3✔
3850

3✔
3851
                        // Request the link to send the event once the channel
3✔
3852
                        // is flushed. We only need this event sent once, so we
3✔
3853
                        // can exit now.
3✔
3854
                        link.OnFlushedOnce(sendChanFlushed)
3✔
3855

3✔
3856
                        return
3✔
3857
                }
3✔
3858
        }
3859
}
3860

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

3✔
3867
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
3✔
3868

3✔
3869
        link := p.fetchLinkFromKeyAndCid(chanID)
3✔
3870

3✔
3871
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
3✔
3872
        if err != nil {
3✔
3873
                return nil, fmt.Errorf("cannot obtain best block: %w", err)
×
3874
        }
×
3875

3876
        defaultFeePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
3877
                p.cfg.CoopCloseTargetConfs,
3✔
3878
        )
3✔
3879
        if err != nil {
3✔
3880
                return nil, fmt.Errorf("unable to estimate fee: %w", err)
×
3881
        }
×
3882

3883
        thawHeight, err := channel.AbsoluteThawHeight()
3✔
3884
        if err != nil {
3✔
3885
                return nil, fmt.Errorf("unable to get thaw height: %w", err)
×
3886
        }
×
3887

3888
        peerPub := *p.IdentityKey()
3✔
3889

3✔
3890
        msgMapper := chancloser.NewRbfMsgMapper(
3✔
3891
                uint32(startingHeight), chanID, peerPub,
3✔
3892
        )
3✔
3893

3✔
3894
        initialState := chancloser.ChannelActive{}
3✔
3895

3✔
3896
        scid := channel.ZeroConfRealScid().UnwrapOr(
3✔
3897
                channel.ShortChanID(),
3✔
3898
        )
3✔
3899

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

3925
        spendEvent := protofsm.RegisterSpend[chancloser.ProtocolEvent]{
3✔
3926
                OutPoint:   channel.ChannelPoint(),
3✔
3927
                PkScript:   channel.FundingTxOut().PkScript,
3✔
3928
                HeightHint: channel.DeriveHeightHint(),
3✔
3929
                PostSpendEvent: fn.Some[chancloser.RbfSpendMapper](
3✔
3930
                        chancloser.SpendMapper,
3✔
3931
                ),
3✔
3932
        }
3✔
3933

3✔
3934
        daemonAdapters := NewLndDaemonAdapters(LndAdapterCfg{
3✔
3935
                MsgSender:     newPeerMsgSender(peerPub, p),
3✔
3936
                TxBroadcaster: p.cfg.Wallet,
3✔
3937
                ChainNotifier: p.cfg.ChainNotifier,
3✔
3938
        })
3✔
3939

3✔
3940
        protoCfg := chancloser.RbfChanCloserCfg{
3✔
3941
                Daemon:        daemonAdapters,
3✔
3942
                InitialState:  &initialState,
3✔
3943
                Env:           &env,
3✔
3944
                InitEvent:     fn.Some[protofsm.DaemonEvent](&spendEvent),
3✔
3945
                ErrorReporter: newChanErrorReporter(chanID, p),
3✔
3946
                MsgMapper: fn.Some[protofsm.MsgMapper[chancloser.ProtocolEvent]]( //nolint:ll
3✔
3947
                        msgMapper,
3✔
3948
                ),
3✔
3949
        }
3✔
3950

3✔
3951
        ctx := context.Background()
3✔
3952
        chanCloser := protofsm.NewStateMachine(protoCfg)
3✔
3953
        chanCloser.Start(ctx)
3✔
3954

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

3✔
3960
                return r.RegisterEndpoint(&chanCloser)
3✔
3961
        })
3✔
3962
        if err != nil {
3✔
3963
                chanCloser.Stop()
×
3964

×
3965
                return nil, fmt.Errorf("unable to register endpoint for co-op "+
×
3966
                        "close: %w", err)
×
3967
        }
×
3968

3969
        p.activeChanCloses.Store(chanID, makeRbfCloser(&chanCloser))
3✔
3970

3✔
3971
        // Now that we've created the rbf closer state machine, we'll launch a
3✔
3972
        // new goroutine to eventually send in the ChannelFlushed event once
3✔
3973
        // needed.
3✔
3974
        p.cg.WgAdd(1)
3✔
3975
        go p.chanFlushEventSentinel(&chanCloser, link, channel)
3✔
3976

3✔
3977
        return &chanCloser, nil
3✔
3978
}
3979

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

3987
// shutdownStartFeeRate returns the fee rate that should be used for the
3988
// shutdown.  This returns a doubly wrapped option as the shutdown info might
3989
// be none, and the fee rate is only defined for the user initiated shutdown.
3990
func shutdownStartFeeRate(s shutdownInit) fn.Option[chainfee.SatPerKWeight] {
3✔
3991
        feeRateOpt := fn.MapOption(func(init fn.Either[*htlcswitch.ChanClose,
3✔
3992
                channeldb.ShutdownInfo]) fn.Option[chainfee.SatPerKWeight] {
6✔
3993

3✔
3994
                var feeRate fn.Option[chainfee.SatPerKWeight]
3✔
3995
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
6✔
3996
                        feeRate = fn.Some(req.TargetFeePerKw)
3✔
3997
                })
3✔
3998

3999
                return feeRate
3✔
4000
        })(s)
4001

4002
        return fn.FlattenOption(feeRateOpt)
3✔
4003
}
4004

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

3✔
4012
                var addr fn.Option[lnwire.DeliveryAddress]
3✔
4013
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
6✔
4014
                        if len(req.DeliveryScript) != 0 {
6✔
4015
                                addr = fn.Some(req.DeliveryScript)
3✔
4016
                        }
3✔
4017
                })
4018
                init.WhenRight(func(info channeldb.ShutdownInfo) {
6✔
4019
                        addr = fn.Some(info.DeliveryScript.Val)
3✔
4020
                })
3✔
4021

4022
                return addr
3✔
4023
        })(s)
4024

4025
        return fn.FlattenOption(addrOpt)
3✔
4026
}
4027

4028
// whenRPCShutdown registers a callback to be executed when the shutdown init
4029
// type is and RPC request.
4030
func whenRPCShutdown(s shutdownInit, f func(r *htlcswitch.ChanClose)) {
3✔
4031
        s.WhenSome(func(init fn.Either[*htlcswitch.ChanClose,
3✔
4032
                channeldb.ShutdownInfo]) {
6✔
4033

3✔
4034
                init.WhenLeft(f)
3✔
4035
        })
3✔
4036
}
4037

4038
// newRestartShutdownInit creates a new shutdownInit for the case where we need
4039
// to restart the shutdown flow after a restart.
4040
func newRestartShutdownInit(info channeldb.ShutdownInfo) shutdownInit {
3✔
4041
        return fn.Some(fn.NewRight[*htlcswitch.ChanClose](info))
3✔
4042
}
3✔
4043

4044
// newRPCShutdownInit creates a new shutdownInit for the case where we
4045
// initiated the shutdown via an RPC client.
4046
func newRPCShutdownInit(req *htlcswitch.ChanClose) shutdownInit {
3✔
4047
        return fn.Some(
3✔
4048
                fn.NewLeft[*htlcswitch.ChanClose, channeldb.ShutdownInfo](req),
3✔
4049
        )
3✔
4050
}
3✔
4051

4052
// waitUntilRbfCoastClear waits until the RBF co-op close state machine has
4053
// advanced to a terminal state before attempting another fee bump.
4054
func waitUntilRbfCoastClear(ctx context.Context,
4055
        rbfCloser *chancloser.RbfChanCloser) error {
3✔
4056

3✔
4057
        coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4058
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
4059
        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4060

3✔
4061
        isTerminalState := func(newState chancloser.RbfState) bool {
6✔
4062
                // If we're not in the negotiation sub-state, then we aren't at
3✔
4063
                // the terminal state yet.
3✔
4064
                state, ok := newState.(*chancloser.ClosingNegotiation)
3✔
4065
                if !ok {
3✔
4066
                        return false
×
4067
                }
×
4068

4069
                localState := state.PeerState.GetForParty(lntypes.Local)
3✔
4070

3✔
4071
                // If this isn't the close pending state, we aren't at the
3✔
4072
                // terminal state yet.
3✔
4073
                _, ok = localState.(*chancloser.ClosePending)
3✔
4074

3✔
4075
                return ok
3✔
4076
        }
4077

4078
        // Before we enter the subscription loop below, check to see if we're
4079
        // already in the terminal state.
4080
        rbfState, err := rbfCloser.CurrentState()
3✔
4081
        if err != nil {
3✔
4082
                return err
×
4083
        }
×
4084
        if isTerminalState(rbfState) {
6✔
4085
                return nil
3✔
4086
        }
3✔
4087

4088
        peerLog.Debugf("Waiting for RBF iteration to complete...")
×
4089

×
4090
        for {
×
4091
                select {
×
4092
                case newState := <-newStateChan:
×
4093
                        if isTerminalState(newState) {
×
4094
                                return nil
×
4095
                        }
×
4096

4097
                case <-ctx.Done():
×
4098
                        return fmt.Errorf("context canceled")
×
4099
                }
4100
        }
4101
}
4102

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

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

4120
        defaultFeePerKw, err := shutdownStartFeeRate(
3✔
4121
                shutdown,
3✔
4122
        ).UnwrapOrFuncErr(func() (chainfee.SatPerKWeight, error) {
6✔
4123
                return p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
4124
                        p.cfg.CoopCloseTargetConfs,
3✔
4125
                )
3✔
4126
        })
3✔
4127
        if err != nil {
3✔
4128
                return fmt.Errorf("unable to estimate fee: %w", err)
×
4129
        }
×
4130

4131
        chanCloser.WhenRight(func(rbfCloser *chancloser.RbfChanCloser) {
6✔
4132
                peerLog.Infof("ChannelPoint(%v): rbf-coop close requested, "+
3✔
4133
                        "sending shutdown", chanPoint)
3✔
4134

3✔
4135
                rbfState, err := rbfCloser.CurrentState()
3✔
4136
                if err != nil {
3✔
4137
                        peerLog.Warnf("ChannelPoint(%v): unable to get "+
×
4138
                                "current state for rbf-coop close: %v",
×
4139
                                chanPoint, err)
×
4140

×
4141
                        return
×
4142
                }
×
4143

4144
                coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4145

3✔
4146
                // Before we send our event below, we'll launch a goroutine to
3✔
4147
                // watch for the final terminal state to send updates to the RPC
3✔
4148
                // client. We only need to do this if there's an RPC caller.
3✔
4149
                var rpcShutdown bool
3✔
4150
                whenRPCShutdown(shutdown, func(req *htlcswitch.ChanClose) {
6✔
4151
                        rpcShutdown = true
3✔
4152

3✔
4153
                        p.cg.WgAdd(1)
3✔
4154
                        go func() {
6✔
4155
                                defer p.cg.WgDone()
3✔
4156

3✔
4157
                                p.observeRbfCloseUpdates(
3✔
4158
                                        rbfCloser, req, coopCloseStates,
3✔
4159
                                )
3✔
4160
                        }()
3✔
4161
                })
4162

4163
                if !rpcShutdown {
6✔
4164
                        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4165
                }
3✔
4166

4167
                ctx, _ := p.cg.Create(context.Background())
3✔
4168
                feeRate := defaultFeePerKw.FeePerVByte()
3✔
4169

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

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

×
4200
                                return
×
4201
                        }
×
4202

4203
                        event := chancloser.ProtocolEvent(
3✔
4204
                                &chancloser.SendOfferEvent{
3✔
4205
                                        TargetFeeRate: feeRate,
3✔
4206
                                },
3✔
4207
                        )
3✔
4208
                        rbfCloser.SendEvent(ctx, event)
3✔
4209

4210
                default:
×
4211
                        peerLog.Warnf("ChannelPoint(%v): unexpected state "+
×
4212
                                "for rbf-coop close: %T", chanPoint, rbfState)
×
4213
                }
4214
        })
4215

4216
        return nil
3✔
4217
}
4218

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

10✔
4224
        channel, ok := p.activeChannels.Load(chanID)
10✔
4225

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

4236
        isTaprootChan := channel.ChanType().IsTaproot()
10✔
4237

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

4260
                if err != nil {
11✔
4261
                        p.log.Errorf(err.Error())
1✔
4262
                        req.Err <- err
1✔
4263
                }
1✔
4264

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

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

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

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

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

3✔
4310
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
3✔
4311
                        failure.chanPoint,
3✔
4312
                )
3✔
4313
                if err != nil {
6✔
4314
                        p.log.Errorf("unable to force close "+
3✔
4315
                                "link(%v): %v", failure.shortChanID, err)
3✔
4316
                } else {
6✔
4317
                        p.log.Infof("channel(%v) force "+
3✔
4318
                                "closed with txid %v",
3✔
4319
                                failure.shortChanID, closeTx.TxHash())
3✔
4320
                }
3✔
4321
        }
4322

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

×
4328
                if err := lnChan.State().MarkBorked(); err != nil {
×
4329
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
4330
                                failure.shortChanID, err)
×
4331
                }
×
4332
        }
4333

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

4345
                var networkMsg lnwire.Message
3✔
4346
                if failure.linkErr.Warning {
3✔
4347
                        networkMsg = &lnwire.Warning{
×
4348
                                ChanID: failure.chanID,
×
4349
                                Data:   data,
×
4350
                        }
×
4351
                } else {
3✔
4352
                        networkMsg = &lnwire.Error{
3✔
4353
                                ChanID: failure.chanID,
3✔
4354
                                Data:   data,
3✔
4355
                        }
3✔
4356
                }
3✔
4357

4358
                err := p.SendMessage(true, networkMsg)
3✔
4359
                if err != nil {
3✔
4360
                        p.log.Errorf("unable to send msg to "+
×
4361
                                "remote peer: %v", err)
×
4362
                }
×
4363
        }
4364

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

4373
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
4374
// public key and the channel id.
4375
func (p *Brontide) fetchLinkFromKeyAndCid(
4376
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
22✔
4377

22✔
4378
        var chanLink htlcswitch.ChannelUpdateHandler
22✔
4379

22✔
4380
        // We don't need to check the error here, and can instead just loop
22✔
4381
        // over the slice and return nil.
22✔
4382
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
22✔
4383
        for _, link := range links {
43✔
4384
                if link.ChanID() == cid {
42✔
4385
                        chanLink = link
21✔
4386
                        break
21✔
4387
                }
4388
        }
4389

4390
        return chanLink
22✔
4391
}
4392

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

7✔
4401
        // First, we'll clear all indexes related to the channel in question.
7✔
4402
        chanPoint := chanCloser.Channel().ChannelPoint()
7✔
4403
        p.WipeChannel(&chanPoint)
7✔
4404

7✔
4405
        // Also clear the activeChanCloses map of this channel.
7✔
4406
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
7✔
4407
        p.activeChanCloses.Delete(cid) // TODO(roasbeef): existing race
7✔
4408

7✔
4409
        // Next, we'll launch a goroutine which will request to be notified by
7✔
4410
        // the ChainNotifier once the closure transaction obtains a single
7✔
4411
        // confirmation.
7✔
4412
        notifier := p.cfg.ChainNotifier
7✔
4413

7✔
4414
        // If any error happens during waitForChanToClose, forward it to
7✔
4415
        // closeReq. If this channel closure is not locally initiated, closeReq
7✔
4416
        // will be nil, so just ignore the error.
7✔
4417
        errChan := make(chan error, 1)
7✔
4418
        if closeReq != nil {
12✔
4419
                errChan = closeReq.Err
5✔
4420
        }
5✔
4421

4422
        closingTx, err := chanCloser.ClosingTx()
7✔
4423
        if err != nil {
7✔
4424
                if closeReq != nil {
×
4425
                        p.log.Error(err)
×
4426
                        closeReq.Err <- err
×
4427
                }
×
4428
        }
4429

4430
        closingTxid := closingTx.TxHash()
7✔
4431

7✔
4432
        // If this is a locally requested shutdown, update the caller with a
7✔
4433
        // new event detailing the current pending state of this request.
7✔
4434
        if closeReq != nil {
12✔
4435
                closeReq.Updates <- &PendingUpdate{
5✔
4436
                        Txid: closingTxid[:],
5✔
4437
                }
5✔
4438
        }
5✔
4439

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

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

7✔
4470
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
7✔
4471
                "with txid: %v", chanPoint, closingTxID)
7✔
4472

7✔
4473
        // TODO(roasbeef): add param for num needed confs
7✔
4474
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
7✔
4475
                closingTxID, closeScript, 1, bestHeight,
7✔
4476
        )
7✔
4477
        if err != nil {
7✔
4478
                if errChan != nil {
×
4479
                        errChan <- err
×
4480
                }
×
4481
                return
×
4482
        }
4483

4484
        // In the case that the ChainNotifier is shutting down, all subscriber
4485
        // notification channels will be closed, generating a nil receive.
4486
        height, ok := <-confNtfn.Confirmed
7✔
4487
        if !ok {
10✔
4488
                return
3✔
4489
        }
3✔
4490

4491
        // The channel has been closed, remove it from any active indexes, and
4492
        // the database state.
4493
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
7✔
4494
                "height %v", chanPoint, height.BlockHeight)
7✔
4495

7✔
4496
        // Finally, execute the closure call back to mark the confirmation of
7✔
4497
        // the transaction closing the contract.
7✔
4498
        cb()
7✔
4499
}
4500

4501
// WipeChannel removes the passed channel point from all indexes associated with
4502
// the peer and the switch.
4503
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
7✔
4504
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
7✔
4505

7✔
4506
        p.activeChannels.Delete(chanID)
7✔
4507

7✔
4508
        // Instruct the HtlcSwitch to close this link as the channel is no
7✔
4509
        // longer active.
7✔
4510
        p.cfg.Switch.RemoveLink(chanID)
7✔
4511
}
7✔
4512

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

4524
        // Then, finalize the remote feature vector providing the flattened
4525
        // feature bit namespace.
4526
        p.remoteFeatures = lnwire.NewFeatureVector(
6✔
4527
                msg.Features, lnwire.Features,
6✔
4528
        )
6✔
4529

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

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

4545
        // Now that we know we understand their requirements, we'll check to
4546
        // see if they don't support anything that we deem to be mandatory.
4547
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
6✔
4548
                return fmt.Errorf("data loss protection required")
×
4549
        }
×
4550

4551
        return nil
6✔
4552
}
4553

4554
// LocalFeatures returns the set of global features that has been advertised by
4555
// the local node. This allows sub-systems that use this interface to gate their
4556
// behavior off the set of negotiated feature bits.
4557
//
4558
// NOTE: Part of the lnpeer.Peer interface.
4559
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
3✔
4560
        return p.cfg.Features
3✔
4561
}
3✔
4562

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

4572
// hasNegotiatedScidAlias returns true if we've negotiated the
4573
// option-scid-alias feature bit with the peer.
4574
func (p *Brontide) hasNegotiatedScidAlias() bool {
6✔
4575
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
6✔
4576
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
6✔
4577
        return peerHas && localHas
6✔
4578
}
6✔
4579

4580
// sendInitMsg sends the Init message to the remote peer. This message contains
4581
// our currently supported local and global features.
4582
func (p *Brontide) sendInitMsg(legacyChan bool) error {
10✔
4583
        features := p.cfg.Features.Clone()
10✔
4584
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
10✔
4585

10✔
4586
        // If we have a legacy channel open with a peer, we downgrade static
10✔
4587
        // remote required to optional in case the peer does not understand the
10✔
4588
        // required feature bit. If we do not do this, the peer will reject our
10✔
4589
        // connection because it does not understand a required feature bit, and
10✔
4590
        // our channel will be unusable.
10✔
4591
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
11✔
4592
                p.log.Infof("Legacy channel open with peer, " +
1✔
4593
                        "downgrading static remote required feature bit to " +
1✔
4594
                        "optional")
1✔
4595

1✔
4596
                // Unset and set in both the local and global features to
1✔
4597
                // ensure both sets are consistent and merge able by old and
1✔
4598
                // new nodes.
1✔
4599
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4600
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4601

1✔
4602
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
4603
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
4604
        }
1✔
4605

4606
        msg := lnwire.NewInitMessage(
10✔
4607
                legacyFeatures.RawFeatureVector,
10✔
4608
                features.RawFeatureVector,
10✔
4609
        )
10✔
4610

10✔
4611
        return p.writeMessage(msg)
10✔
4612
}
4613

4614
// resendChanSyncMsg will attempt to find a channel sync message for the closed
4615
// channel and resend it to our peer.
4616
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
3✔
4617
        // If we already re-sent the mssage for this channel, we won't do it
3✔
4618
        // again.
3✔
4619
        if _, ok := p.resentChanSyncMsg[cid]; ok {
4✔
4620
                return nil
1✔
4621
        }
1✔
4622

4623
        // Check if we have any channel sync messages stored for this channel.
4624
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
3✔
4625
        if err != nil {
6✔
4626
                return fmt.Errorf("unable to fetch channel sync messages for "+
3✔
4627
                        "peer %v: %v", p, err)
3✔
4628
        }
3✔
4629

4630
        if c.LastChanSyncMsg == nil {
3✔
4631
                return fmt.Errorf("no chan sync message stored for channel %v",
×
4632
                        cid)
×
4633
        }
×
4634

4635
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
3✔
4636
                return fmt.Errorf("ignoring channel reestablish from "+
×
4637
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
4638
        }
×
4639

4640
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
3✔
4641
                "peer", cid)
3✔
4642

3✔
4643
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
3✔
4644
                return fmt.Errorf("failed resending channel sync "+
×
4645
                        "message to peer %v: %v", p, err)
×
4646
        }
×
4647

4648
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
3✔
4649
                cid)
3✔
4650

3✔
4651
        // Note down that we sent the message, so we won't resend it again for
3✔
4652
        // this connection.
3✔
4653
        p.resentChanSyncMsg[cid] = struct{}{}
3✔
4654

3✔
4655
        return nil
3✔
4656
}
4657

4658
// SendMessage sends a variadic number of high-priority messages to the remote
4659
// peer. The first argument denotes if the method should block until the
4660
// messages have been sent to the remote peer or an error is returned,
4661
// otherwise it returns immediately after queuing.
4662
//
4663
// NOTE: Part of the lnpeer.Peer interface.
4664
func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error {
6✔
4665
        return p.sendMessage(sync, true, msgs...)
6✔
4666
}
6✔
4667

4668
// SendMessageLazy sends a variadic number of low-priority messages to the
4669
// remote peer. The first argument denotes if the method should block until
4670
// the messages have been sent to the remote peer or an error is returned,
4671
// otherwise it returns immediately after queueing.
4672
//
4673
// NOTE: Part of the lnpeer.Peer interface.
4674
func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
4✔
4675
        return p.sendMessage(sync, false, msgs...)
4✔
4676
}
4✔
4677

4678
// SendSuperPriorityMessage sends a variadic number of super-priority messages
4679
// to the remote peer. If sync is true, this method will block until the
4680
// messages have been sent to the remote peer or an error is returned, otherwise
4681
// it returns immediately after queueing. These messages bypass the regular and
4682
// lazy send queues handled by the queueHandler.
4683
//
4684
// NOTE: Part of the lnpeer.Peer interface.
NEW
4685
func (p *Brontide) SendSuperPriorityMessage(sync bool, msgs ...lnwire.Message) error {
×
NEW
4686
        var errChans []chan error
×
NEW
4687
        if sync {
×
NEW
4688
                errChans = make([]chan error, 0, len(msgs))
×
NEW
4689
        }
×
4690

NEW
4691
        for _, msg := range msgs {
×
NEW
4692
                var errChan chan error
×
NEW
4693
                if sync {
×
NEW
4694
                        errChan = make(chan error, 1)
×
NEW
4695
                        errChans = append(errChans, errChan)
×
NEW
4696
                }
×
4697

NEW
4698
                p.queueSuperPriorityMsg(msg, errChan)
×
4699
        }
4700

4701
        // Wait for all replies from the writeHandler if a sync send was
4702
        // requested.
NEW
4703
        for _, errChan := range errChans {
×
NEW
4704
                select {
×
NEW
4705
                case err := <-errChan:
×
NEW
4706
                        if err != nil {
×
NEW
4707
                                return err
×
NEW
4708
                        }
×
4709

NEW
4710
                case <-p.cg.Done():
×
NEW
4711
                        return lnpeer.ErrPeerExiting
×
4712

NEW
4713
                case <-p.cfg.Quit:
×
NEW
4714
                        return lnpeer.ErrPeerExiting
×
4715
                }
4716
        }
4717

NEW
4718
        return nil
×
4719
}
4720

4721
// sendMessage queues a variadic number of messages using the passed priority
4722
// to the remote peer. If sync is true, this method will block until the
4723
// messages have been sent to the remote peer or an error is returned, otherwise
4724
// it returns immediately after queueing.
4725
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
7✔
4726
        // Add all incoming messages to the outgoing queue. A list of error
7✔
4727
        // chans is populated for each message if the caller requested a sync
7✔
4728
        // send.
7✔
4729
        var errChans []chan error
7✔
4730
        if sync {
11✔
4731
                errChans = make([]chan error, 0, len(msgs))
4✔
4732
        }
4✔
4733
        for _, msg := range msgs {
14✔
4734
                // If a sync send was requested, create an error chan to listen
7✔
4735
                // for an ack from the writeHandler.
7✔
4736
                var errChan chan error
7✔
4737
                if sync {
11✔
4738
                        errChan = make(chan error, 1)
4✔
4739
                        errChans = append(errChans, errChan)
4✔
4740
                }
4✔
4741

4742
                if priority {
13✔
4743
                        p.queueMsg(msg, errChan)
6✔
4744
                } else {
10✔
4745
                        p.queueMsgLazy(msg, errChan)
4✔
4746
                }
4✔
4747
        }
4748

4749
        // Wait for all replies from the writeHandler. For async sends, this
4750
        // will be a NOP as the list of error chans is nil.
4751
        for _, errChan := range errChans {
11✔
4752
                select {
4✔
4753
                case err := <-errChan:
4✔
4754
                        return err
4✔
4755
                case <-p.cg.Done():
×
4756
                        return lnpeer.ErrPeerExiting
×
4757
                case <-p.cfg.Quit:
×
4758
                        return lnpeer.ErrPeerExiting
×
4759
                }
4760
        }
4761

4762
        return nil
6✔
4763
}
4764

4765
// PubKey returns the pubkey of the peer in compressed serialized format.
4766
//
4767
// NOTE: Part of the lnpeer.Peer interface.
4768
func (p *Brontide) PubKey() [33]byte {
5✔
4769
        return p.cfg.PubKeyBytes
5✔
4770
}
5✔
4771

4772
// IdentityKey returns the public key of the remote peer.
4773
//
4774
// NOTE: Part of the lnpeer.Peer interface.
4775
func (p *Brontide) IdentityKey() *btcec.PublicKey {
18✔
4776
        return p.cfg.Addr.IdentityKey
18✔
4777
}
18✔
4778

4779
// Address returns the network address of the remote peer.
4780
//
4781
// NOTE: Part of the lnpeer.Peer interface.
4782
func (p *Brontide) Address() net.Addr {
3✔
4783
        return p.cfg.Addr.Address
3✔
4784
}
3✔
4785

4786
// AddNewChannel adds a new channel to the peer. The channel should fail to be
4787
// added if the cancel channel is closed.
4788
//
4789
// NOTE: Part of the lnpeer.Peer interface.
4790
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
4791
        cancel <-chan struct{}) error {
3✔
4792

3✔
4793
        errChan := make(chan error, 1)
3✔
4794
        newChanMsg := &newChannelMsg{
3✔
4795
                channel: newChan,
3✔
4796
                err:     errChan,
3✔
4797
        }
3✔
4798

3✔
4799
        select {
3✔
4800
        case p.newActiveChannel <- newChanMsg:
3✔
4801
        case <-cancel:
×
4802
                return errors.New("canceled adding new channel")
×
4803
        case <-p.cg.Done():
×
4804
                return lnpeer.ErrPeerExiting
×
4805
        }
4806

4807
        // We pause here to wait for the peer to recognize the new channel
4808
        // before we close the channel barrier corresponding to the channel.
4809
        select {
3✔
4810
        case err := <-errChan:
3✔
4811
                return err
3✔
4812
        case <-p.cg.Done():
×
4813
                return lnpeer.ErrPeerExiting
×
4814
        }
4815
}
4816

4817
// AddPendingChannel adds a pending open channel to the peer. The channel
4818
// should fail to be added if the cancel channel is closed.
4819
//
4820
// NOTE: Part of the lnpeer.Peer interface.
4821
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
4822
        cancel <-chan struct{}) error {
3✔
4823

3✔
4824
        errChan := make(chan error, 1)
3✔
4825
        newChanMsg := &newChannelMsg{
3✔
4826
                channelID: cid,
3✔
4827
                err:       errChan,
3✔
4828
        }
3✔
4829

3✔
4830
        select {
3✔
4831
        case p.newPendingChannel <- newChanMsg:
3✔
4832

4833
        case <-cancel:
×
4834
                return errors.New("canceled adding pending channel")
×
4835

4836
        case <-p.cg.Done():
×
4837
                return lnpeer.ErrPeerExiting
×
4838
        }
4839

4840
        // We pause here to wait for the peer to recognize the new pending
4841
        // channel before we close the channel barrier corresponding to the
4842
        // channel.
4843
        select {
3✔
4844
        case err := <-errChan:
3✔
4845
                return err
3✔
4846

4847
        case <-cancel:
×
4848
                return errors.New("canceled adding pending channel")
×
4849

4850
        case <-p.cg.Done():
×
4851
                return lnpeer.ErrPeerExiting
×
4852
        }
4853
}
4854

4855
// RemovePendingChannel removes a pending open channel from the peer.
4856
//
4857
// NOTE: Part of the lnpeer.Peer interface.
4858
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
3✔
4859
        errChan := make(chan error, 1)
3✔
4860
        newChanMsg := &newChannelMsg{
3✔
4861
                channelID: cid,
3✔
4862
                err:       errChan,
3✔
4863
        }
3✔
4864

3✔
4865
        select {
3✔
4866
        case p.removePendingChannel <- newChanMsg:
3✔
4867
        case <-p.cg.Done():
×
4868
                return lnpeer.ErrPeerExiting
×
4869
        }
4870

4871
        // We pause here to wait for the peer to respond to the cancellation of
4872
        // the pending channel before we close the channel barrier
4873
        // corresponding to the channel.
4874
        select {
3✔
4875
        case err := <-errChan:
3✔
4876
                return err
3✔
4877

4878
        case <-p.cg.Done():
×
4879
                return lnpeer.ErrPeerExiting
×
4880
        }
4881
}
4882

4883
// StartTime returns the time at which the connection was established if the
4884
// peer started successfully, and zero otherwise.
4885
func (p *Brontide) StartTime() time.Time {
3✔
4886
        return p.startTime
3✔
4887
}
3✔
4888

4889
// handleCloseMsg is called when a new cooperative channel closure related
4890
// message is received from the remote peer. We'll use this message to advance
4891
// the chan closer state machine.
4892
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
16✔
4893
        link := p.fetchLinkFromKeyAndCid(msg.cid)
16✔
4894

16✔
4895
        // We'll now fetch the matching closing state machine in order to
16✔
4896
        // continue, or finalize the channel closure process.
16✔
4897
        chanCloserE, err := p.fetchActiveChanCloser(msg.cid)
16✔
4898
        if err != nil {
19✔
4899
                // If the channel is not known to us, we'll simply ignore this
3✔
4900
                // message.
3✔
4901
                if err == ErrChannelNotFound {
6✔
4902
                        return
3✔
4903
                }
3✔
4904

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

×
4907
                errMsg := &lnwire.Error{
×
4908
                        ChanID: msg.cid,
×
4909
                        Data:   lnwire.ErrorData(err.Error()),
×
4910
                }
×
4911
                p.queueMsg(errMsg, nil)
×
4912
                return
×
4913
        }
4914

4915
        if chanCloserE.IsRight() {
16✔
4916
                // TODO(roasbeef): assert?
×
4917
                return
×
4918
        }
×
4919

4920
        // At this point, we'll only enter this call path if a negotiate chan
4921
        // closer was used. So we'll extract that from the either now.
4922
        //
4923
        // TODO(roabeef): need extra helper func for either to make cleaner
4924
        var chanCloser *chancloser.ChanCloser
16✔
4925
        chanCloserE.WhenLeft(func(c *chancloser.ChanCloser) {
32✔
4926
                chanCloser = c
16✔
4927
        })
16✔
4928

4929
        handleErr := func(err error) {
18✔
4930
                err = fmt.Errorf("unable to process close msg: %w", err)
2✔
4931
                p.log.Error(err)
2✔
4932

2✔
4933
                // As the negotiations failed, we'll reset the channel state
2✔
4934
                // machine to ensure we act to on-chain events as normal.
2✔
4935
                chanCloser.Channel().ResetState()
2✔
4936
                if chanCloser.CloseRequest() != nil {
2✔
4937
                        chanCloser.CloseRequest().Err <- err
×
4938
                }
×
4939

4940
                p.activeChanCloses.Delete(msg.cid)
2✔
4941

2✔
4942
                p.Disconnect(err)
2✔
4943
        }
4944

4945
        // Next, we'll process the next message using the target state machine.
4946
        // We'll either continue negotiation, or halt.
4947
        switch typed := msg.msg.(type) {
16✔
4948
        case *lnwire.Shutdown:
8✔
4949
                // Disable incoming adds immediately.
8✔
4950
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
8✔
4951
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
4952
                                link.ChanID())
×
4953
                }
×
4954

4955
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
8✔
4956
                if err != nil {
8✔
4957
                        handleErr(err)
×
4958
                        return
×
4959
                }
×
4960

4961
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
14✔
4962
                        // If the link is nil it means we can immediately queue
6✔
4963
                        // the Shutdown message since we don't have to wait for
6✔
4964
                        // commitment transaction synchronization.
6✔
4965
                        if link == nil {
7✔
4966
                                p.queueMsg(&msg, nil)
1✔
4967
                                return
1✔
4968
                        }
1✔
4969

4970
                        // Immediately disallow any new HTLC's from being added
4971
                        // in the outgoing direction.
4972
                        if !link.DisableAdds(htlcswitch.Outgoing) {
5✔
4973
                                p.log.Warnf("Outgoing link adds already "+
×
4974
                                        "disabled: %v", link.ChanID())
×
4975
                        }
×
4976

4977
                        // When we have a Shutdown to send, we defer it till the
4978
                        // next time we send a CommitSig to remain spec
4979
                        // compliant.
4980
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
10✔
4981
                                p.queueMsg(&msg, nil)
5✔
4982
                        })
5✔
4983
                })
4984

4985
                beginNegotiation := func() {
16✔
4986
                        oClosingSigned, err := chanCloser.BeginNegotiation()
8✔
4987
                        if err != nil {
9✔
4988
                                handleErr(err)
1✔
4989
                                return
1✔
4990
                        }
1✔
4991

4992
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
14✔
4993
                                p.queueMsg(&msg, nil)
7✔
4994
                        })
7✔
4995
                }
4996

4997
                if link == nil {
9✔
4998
                        beginNegotiation()
1✔
4999
                } else {
8✔
5000
                        // Now we register a flush hook to advance the
7✔
5001
                        // ChanCloser and possibly send out a ClosingSigned
7✔
5002
                        // when the link finishes draining.
7✔
5003
                        link.OnFlushedOnce(func() {
14✔
5004
                                // Remove link in goroutine to prevent deadlock.
7✔
5005
                                go p.cfg.Switch.RemoveLink(msg.cid)
7✔
5006
                                beginNegotiation()
7✔
5007
                        })
7✔
5008
                }
5009

5010
        case *lnwire.ClosingSigned:
11✔
5011
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
11✔
5012
                if err != nil {
12✔
5013
                        handleErr(err)
1✔
5014
                        return
1✔
5015
                }
1✔
5016

5017
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
22✔
5018
                        p.queueMsg(&msg, nil)
11✔
5019
                })
11✔
5020

5021
        default:
×
5022
                panic("impossible closeMsg type")
×
5023
        }
5024

5025
        // If we haven't finished close negotiations, then we'll continue as we
5026
        // can't yet finalize the closure.
5027
        if _, err := chanCloser.ClosingTx(); err != nil {
28✔
5028
                return
12✔
5029
        }
12✔
5030

5031
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
5032
        // the channel closure by notifying relevant sub-systems and launching a
5033
        // goroutine to wait for close tx conf.
5034
        p.finalizeChanClosure(chanCloser)
7✔
5035
}
5036

5037
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
5038
// the channelManager goroutine, which will shut down the link and possibly
5039
// close the channel.
5040
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
3✔
5041
        select {
3✔
5042
        case p.localCloseChanReqs <- req:
3✔
5043
                p.log.Info("Local close channel request is going to be " +
3✔
5044
                        "delivered to the peer")
3✔
5045
        case <-p.cg.Done():
×
5046
                p.log.Info("Unable to deliver local close channel request " +
×
5047
                        "to peer")
×
5048
        }
5049
}
5050

5051
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
5052
func (p *Brontide) NetAddress() *lnwire.NetAddress {
3✔
5053
        return p.cfg.Addr
3✔
5054
}
3✔
5055

5056
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
5057
func (p *Brontide) Inbound() bool {
3✔
5058
        return p.cfg.Inbound
3✔
5059
}
3✔
5060

5061
// ConnReq is a getter for the Brontide's connReq in cfg.
5062
func (p *Brontide) ConnReq() *connmgr.ConnReq {
3✔
5063
        return p.cfg.ConnReq
3✔
5064
}
3✔
5065

5066
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
5067
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
3✔
5068
        return p.cfg.ErrorBuffer
3✔
5069
}
3✔
5070

5071
// SetAddress sets the remote peer's address given an address.
5072
func (p *Brontide) SetAddress(address net.Addr) {
×
5073
        p.cfg.Addr.Address = address
×
5074
}
×
5075

5076
// ActiveSignal returns the peer's active signal.
5077
func (p *Brontide) ActiveSignal() chan struct{} {
3✔
5078
        return p.activeSignal
3✔
5079
}
3✔
5080

5081
// Conn returns a pointer to the peer's connection struct.
5082
func (p *Brontide) Conn() net.Conn {
3✔
5083
        return p.cfg.Conn
3✔
5084
}
3✔
5085

5086
// BytesReceived returns the number of bytes received from the peer.
5087
func (p *Brontide) BytesReceived() uint64 {
3✔
5088
        return atomic.LoadUint64(&p.bytesReceived)
3✔
5089
}
3✔
5090

5091
// BytesSent returns the number of bytes sent to the peer.
5092
func (p *Brontide) BytesSent() uint64 {
3✔
5093
        return atomic.LoadUint64(&p.bytesSent)
3✔
5094
}
3✔
5095

5096
// LastRemotePingPayload returns the last payload the remote party sent as part
5097
// of their ping.
5098
func (p *Brontide) LastRemotePingPayload() []byte {
3✔
5099
        pingPayload := p.lastPingPayload.Load()
3✔
5100
        if pingPayload == nil {
6✔
5101
                return []byte{}
3✔
5102
        }
3✔
5103

5104
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
5105
        if !ok {
×
5106
                return nil
×
5107
        }
×
5108

5109
        return pingBytes
×
5110
}
5111

5112
// attachChannelEventSubscription creates a channel event subscription and
5113
// attaches to client to Brontide if the reenableTimeout is no greater than 1
5114
// minute.
5115
func (p *Brontide) attachChannelEventSubscription() error {
6✔
5116
        // If the timeout is greater than 1 minute, it's unlikely that the link
6✔
5117
        // hasn't yet finished its reestablishment. Return a nil without
6✔
5118
        // creating the client to specify that we don't want to retry.
6✔
5119
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
9✔
5120
                return nil
3✔
5121
        }
3✔
5122

5123
        // When the reenable timeout is less than 1 minute, it's likely the
5124
        // channel link hasn't finished its reestablishment yet. In that case,
5125
        // we'll give it a second chance by subscribing to the channel update
5126
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
5127
        // enabling the channel again.
5128
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
6✔
5129
        if err != nil {
6✔
5130
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
5131
        }
×
5132

5133
        p.channelEventClient = sub
6✔
5134

6✔
5135
        return nil
6✔
5136
}
5137

5138
// updateNextRevocation updates the existing channel's next revocation if it's
5139
// nil.
5140
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
6✔
5141
        chanPoint := c.FundingOutpoint
6✔
5142
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
6✔
5143

6✔
5144
        // Read the current channel.
6✔
5145
        currentChan, loaded := p.activeChannels.Load(chanID)
6✔
5146

6✔
5147
        // currentChan should exist, but we perform a check anyway to avoid nil
6✔
5148
        // pointer dereference.
6✔
5149
        if !loaded {
7✔
5150
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
5151
                        chanID)
1✔
5152
        }
1✔
5153

5154
        // currentChan should not be nil, but we perform a check anyway to
5155
        // avoid nil pointer dereference.
5156
        if currentChan == nil {
6✔
5157
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
5158
                        chanID)
1✔
5159
        }
1✔
5160

5161
        // If we're being sent a new channel, and our existing channel doesn't
5162
        // have the next revocation, then we need to update the current
5163
        // existing channel.
5164
        if currentChan.RemoteNextRevocation() != nil {
4✔
5165
                return nil
×
5166
        }
×
5167

5168
        p.log.Infof("Processing retransmitted ChannelReady for "+
4✔
5169
                "ChannelPoint(%v)", chanPoint)
4✔
5170

4✔
5171
        nextRevoke := c.RemoteNextRevocation
4✔
5172

4✔
5173
        err := currentChan.InitNextRevocation(nextRevoke)
4✔
5174
        if err != nil {
4✔
5175
                return fmt.Errorf("unable to init next revocation: %w", err)
×
5176
        }
×
5177

5178
        return nil
4✔
5179
}
5180

5181
// addActiveChannel adds a new active channel to the `activeChannels` map. It
5182
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
5183
// it and assembles it with a channel link.
5184
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
3✔
5185
        chanPoint := c.FundingOutpoint
3✔
5186
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5187

3✔
5188
        // If we've reached this point, there are two possible scenarios.  If
3✔
5189
        // the channel was in the active channels map as nil, then it was
3✔
5190
        // loaded from disk and we need to send reestablish. Else, it was not
3✔
5191
        // loaded from disk and we don't need to send reestablish as this is a
3✔
5192
        // fresh channel.
3✔
5193
        shouldReestablish := p.isLoadedFromDisk(chanID)
3✔
5194

3✔
5195
        chanOpts := c.ChanOpts
3✔
5196
        if shouldReestablish {
6✔
5197
                // If we have to do the reestablish dance for this channel,
3✔
5198
                // ensure that we don't try to call InitRemoteMusigNonces twice
3✔
5199
                // by calling SkipNonceInit.
3✔
5200
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
3✔
5201
        }
3✔
5202

5203
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
3✔
5204
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
5205
        })
×
5206
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
3✔
5207
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
5208
        })
×
5209
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
3✔
5210
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
5211
        })
×
5212

5213
        // If not already active, we'll add this channel to the set of active
5214
        // channels, so we can look it up later easily according to its channel
5215
        // ID.
5216
        lnChan, err := lnwallet.NewLightningChannel(
3✔
5217
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
3✔
5218
        )
3✔
5219
        if err != nil {
3✔
5220
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
5221
        }
×
5222

5223
        // Store the channel in the activeChannels map.
5224
        p.activeChannels.Store(chanID, lnChan)
3✔
5225

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

3✔
5228
        // Next, we'll assemble a ChannelLink along with the necessary items it
3✔
5229
        // needs to function.
3✔
5230
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
3✔
5231
        if err != nil {
3✔
5232
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
5233
                        err)
×
5234
        }
×
5235

5236
        // We'll query the channel DB for the new channel's initial forwarding
5237
        // policies to determine the policy we start out with.
5238
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
3✔
5239
        if err != nil {
3✔
5240
                return fmt.Errorf("unable to query for initial forwarding "+
×
5241
                        "policy: %v", err)
×
5242
        }
×
5243

5244
        // Create the link and add it to the switch.
5245
        err = p.addLink(
3✔
5246
                &chanPoint, lnChan, initialPolicy, chainEvents,
3✔
5247
                shouldReestablish, fn.None[lnwire.Shutdown](),
3✔
5248
        )
3✔
5249
        if err != nil {
3✔
5250
                return fmt.Errorf("can't register new channel link(%v) with "+
×
5251
                        "peer", chanPoint)
×
5252
        }
×
5253

5254
        isTaprootChan := c.ChanType.IsTaproot()
3✔
5255

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

5263
        // Now that the link has been added above, we'll also init an RBF chan
5264
        // closer for this channel, but only if the new close feature is
5265
        // negotiated.
5266
        //
5267
        // Creating this here ensures that any shutdown messages sent will be
5268
        // automatically routed by the msg router.
5269
        if _, err := p.initRbfChanCloser(lnChan); err != nil {
3✔
5270
                p.activeChanCloses.Delete(chanID)
×
5271

×
5272
                return fmt.Errorf("unable to init RBF chan closer for new "+
×
5273
                        "chan: %w", err)
×
5274
        }
×
5275

5276
        return nil
3✔
5277
}
5278

5279
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
5280
// know this channel ID or not, we'll either add it to the `activeChannels` map
5281
// or init the next revocation for it.
5282
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
3✔
5283
        newChan := req.channel
3✔
5284
        chanPoint := newChan.FundingOutpoint
3✔
5285
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5286

3✔
5287
        // Only update RemoteNextRevocation if the channel is in the
3✔
5288
        // activeChannels map and if we added the link to the switch. Only
3✔
5289
        // active channels will be added to the switch.
3✔
5290
        if p.isActiveChannel(chanID) {
6✔
5291
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
3✔
5292
                        chanPoint)
3✔
5293

3✔
5294
                // Handle it and close the err chan on the request.
3✔
5295
                close(req.err)
3✔
5296

3✔
5297
                // Update the next revocation point.
3✔
5298
                err := p.updateNextRevocation(newChan.OpenChannel)
3✔
5299
                if err != nil {
3✔
5300
                        p.log.Errorf(err.Error())
×
5301
                }
×
5302

5303
                return
3✔
5304
        }
5305

5306
        // This is a new channel, we now add it to the map.
5307
        if err := p.addActiveChannel(req.channel); err != nil {
3✔
5308
                // Log and send back the error to the request.
×
5309
                p.log.Errorf(err.Error())
×
5310
                req.err <- err
×
5311

×
5312
                return
×
5313
        }
×
5314

5315
        // Close the err chan if everything went fine.
5316
        close(req.err)
3✔
5317
}
5318

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

7✔
5326
        chanID := req.channelID
7✔
5327

7✔
5328
        // If we already have this channel, something is wrong with the funding
7✔
5329
        // flow as it will only be marked as active after `ChannelReady` is
7✔
5330
        // handled. In this case, we will do nothing but log an error, just in
7✔
5331
        // case this is a legit channel.
7✔
5332
        if p.isActiveChannel(chanID) {
8✔
5333
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
5334
                        "pending channel request", chanID)
1✔
5335

1✔
5336
                return
1✔
5337
        }
1✔
5338

5339
        // The channel has already been added, we will do nothing and return.
5340
        if p.isPendingChannel(chanID) {
7✔
5341
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
5342
                        "pending channel request", chanID)
1✔
5343

1✔
5344
                return
1✔
5345
        }
1✔
5346

5347
        // This is a new channel, we now add it to the map `activeChannels`
5348
        // with nil value and mark it as a newly added channel in
5349
        // `addedChannels`.
5350
        p.activeChannels.Store(chanID, nil)
5✔
5351
        p.addedChannels.Store(chanID, struct{}{})
5✔
5352
}
5353

5354
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
5355
// from `activeChannels` map. The request will be ignored if the channel is
5356
// considered active by Brontide. Noop if the channel ID cannot be found.
5357
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
7✔
5358
        defer close(req.err)
7✔
5359

7✔
5360
        chanID := req.channelID
7✔
5361

7✔
5362
        // If we already have this channel, something is wrong with the funding
7✔
5363
        // flow as it will only be marked as active after `ChannelReady` is
7✔
5364
        // handled. In this case, we will log an error and exit.
7✔
5365
        if p.isActiveChannel(chanID) {
8✔
5366
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
5367
                        chanID)
1✔
5368
                return
1✔
5369
        }
1✔
5370

5371
        // The channel has not been added yet, we will log a warning as there
5372
        // is an unexpected call from funding manager.
5373
        if !p.isPendingChannel(chanID) {
10✔
5374
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
4✔
5375
        }
4✔
5376

5377
        // Remove the record of this pending channel.
5378
        p.activeChannels.Delete(chanID)
6✔
5379
        p.addedChannels.Delete(chanID)
6✔
5380
}
5381

5382
// sendLinkUpdateMsg sends a message that updates the channel to the
5383
// channel's message stream.
5384
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
3✔
5385
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
3✔
5386

3✔
5387
        chanStream, ok := p.activeMsgStreams[cid]
3✔
5388
        if !ok {
6✔
5389
                // If a stream hasn't yet been created, then we'll do so, add
3✔
5390
                // it to the map, and finally start it.
3✔
5391
                chanStream = newChanMsgStream(p, cid)
3✔
5392
                p.activeMsgStreams[cid] = chanStream
3✔
5393
                chanStream.Start()
3✔
5394

3✔
5395
                // Stop the stream when quit.
3✔
5396
                go func() {
6✔
5397
                        <-p.cg.Done()
3✔
5398
                        chanStream.Stop()
3✔
5399
                }()
3✔
5400
        }
5401

5402
        // With the stream obtained, add the message to the stream so we can
5403
        // continue processing message.
5404
        chanStream.AddMsg(msg)
3✔
5405
}
5406

5407
// scaleTimeout multiplies the argument duration by a constant factor depending
5408
// on variious heuristics. Currently this is only used to check whether our peer
5409
// appears to be connected over Tor and relaxes the timout deadline. However,
5410
// this is subject to change and should be treated as opaque.
5411
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
70✔
5412
        if p.isTorConnection {
73✔
5413
                return timeout * time.Duration(torTimeoutMultiplier)
3✔
5414
        }
3✔
5415

5416
        return timeout
67✔
5417
}
5418

5419
// CoopCloseUpdates is a struct used to communicate updates for an active close
5420
// to the caller.
5421
type CoopCloseUpdates struct {
5422
        UpdateChan chan interface{}
5423

5424
        ErrChan chan error
5425
}
5426

5427
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5428
// point has an active RBF chan closer.
5429
func (p *Brontide) ChanHasRbfCoopCloser(chanPoint wire.OutPoint) bool {
3✔
5430
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5431
        chanCloser, found := p.activeChanCloses.Load(chanID)
3✔
5432
        if !found {
6✔
5433
                return false
3✔
5434
        }
3✔
5435

5436
        return chanCloser.IsRight()
3✔
5437
}
5438

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

3✔
5447
        // If RBF coop close isn't permitted, then we'll an error.
3✔
5448
        if !p.rbfCoopCloseAllowed() {
3✔
5449
                return nil, fmt.Errorf("rbf coop close not enabled for " +
×
5450
                        "channel")
×
5451
        }
×
5452

5453
        closeUpdates := &CoopCloseUpdates{
3✔
5454
                UpdateChan: make(chan interface{}, 1),
3✔
5455
                ErrChan:    make(chan error, 1),
3✔
5456
        }
3✔
5457

3✔
5458
        // We'll re-use the existing switch struct here, even though we're
3✔
5459
        // bypassing the switch entirely.
3✔
5460
        closeReq := htlcswitch.ChanClose{
3✔
5461
                CloseType:      contractcourt.CloseRegular,
3✔
5462
                ChanPoint:      &chanPoint,
3✔
5463
                TargetFeePerKw: feeRate,
3✔
5464
                DeliveryScript: deliveryScript,
3✔
5465
                Updates:        closeUpdates.UpdateChan,
3✔
5466
                Err:            closeUpdates.ErrChan,
3✔
5467
                Ctx:            ctx,
3✔
5468
        }
3✔
5469

3✔
5470
        err := p.startRbfChanCloser(newRPCShutdownInit(&closeReq), chanPoint)
3✔
5471
        if err != nil {
3✔
5472
                return nil, err
×
5473
        }
×
5474

5475
        return closeUpdates, nil
3✔
5476
}
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