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

lightningnetwork / lnd / 15155511119

21 May 2025 06:52AM UTC coverage: 57.389% (-11.6%) from 68.996%
15155511119

Pull #9844

github

web-flow
Merge 8658c8597 into c52a6ddeb
Pull Request #9844: Refactor Payment PR 3

346 of 493 new or added lines in 4 files covered. (70.18%)

30172 existing lines in 456 files now uncovered.

95441 of 166305 relevant lines covered (57.39%)

0.61 hits per line

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

76.47
/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 = 50
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
        // NoDisconnectOnPongFailure indicates whether the peer should *not* be
459
        // disconnected if a pong is not received in time or is mismatched.
460
        NoDisconnectOnPongFailure bool
461

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

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

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

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

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

497
        // MUST be used atomically.
498
        bytesReceived uint64
499
        bytesSent     uint64
500

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

518
        pingManager *PingManager
519

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

527
        cfg Config
528

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

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

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

541
        // outgoingQueue is a buffered channel which allows second/third party
542
        // objects to queue messages to be sent out on the wire.
543
        outgoingQueue 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 {
1✔
644
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
1✔
645

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

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

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

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

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

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

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

718
                return lastSerializedBlockHeader[:]
×
719
        }
720

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

734
        p.pingManager = NewPingManager(&PingManagerConfig{
1✔
735
                NewPingPayload:   newPingPayload,
1✔
736
                NewPongSize:      randPongSize,
1✔
737
                IntervalDuration: p.scaleTimeout(pingInterval),
1✔
738
                TimeoutDuration:  p.scaleTimeout(pingTimeout),
1✔
739
                SendPing: func(ping *lnwire.Ping) {
1✔
740
                        p.queueMsg(ping, nil)
×
741
                },
×
742
                OnPongFailure: func(reason error,
743
                        timeWaitedForPong time.Duration,
744
                        lastKnownRTT time.Duration) {
×
745

×
746
                        logMsg := fmt.Sprintf("pong response "+
×
747
                                "failure for %s: %v. Time waited for this "+
×
748
                                "pong: %v. Last successful RTT: %v.",
×
749
                                p, reason, timeWaitedForPong, lastKnownRTT)
×
750

×
751
                        // If NoDisconnectOnPongFailure is true, we don't
×
752
                        // disconnect. Otherwise (if it's false, the default),
×
753
                        // we disconnect.
×
754
                        if p.cfg.NoDisconnectOnPongFailure {
×
755
                                p.log.Warnf("%s -- not disconnecting "+
×
756
                                        "due to config", logMsg)
×
757
                                return
×
758
                        }
×
759

760
                        p.log.Warnf("%s -- disconnecting", logMsg)
×
761

×
762
                        go p.Disconnect(fmt.Errorf("pong failure: %w", reason))
×
763
                },
764
        })
765

766
        return p
1✔
767
}
768

769
// Start starts all helper goroutines the peer needs for normal operations.  In
770
// the case this peer has already been started, then this function is a noop.
771
func (p *Brontide) Start() error {
1✔
772
        if atomic.AddInt32(&p.started, 1) != 1 {
1✔
773
                return nil
×
774
        }
×
775

776
        // Once we've finished starting up the peer, we'll signal to other
777
        // goroutines that the they can move forward to tear down the peer, or
778
        // carry out other relevant changes.
779
        defer close(p.startReady)
1✔
780

1✔
781
        p.log.Tracef("starting with conn[%v->%v]",
1✔
782
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
1✔
783

1✔
784
        // Fetch and then load all the active channels we have with this remote
1✔
785
        // peer from the database.
1✔
786
        activeChans, err := p.cfg.ChannelDB.FetchOpenChannels(
1✔
787
                p.cfg.Addr.IdentityKey,
1✔
788
        )
1✔
789
        if err != nil {
1✔
790
                p.log.Errorf("Unable to fetch active chans "+
×
791
                        "for peer: %v", err)
×
792
                return err
×
793
        }
×
794

795
        if len(activeChans) == 0 {
2✔
796
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
1✔
797
        }
1✔
798

799
        // Quickly check if we have any existing legacy channels with this
800
        // peer.
801
        haveLegacyChan := false
1✔
802
        for _, c := range activeChans {
2✔
803
                if c.ChanType.IsTweakless() {
2✔
804
                        continue
1✔
805
                }
806

807
                haveLegacyChan = true
1✔
808
                break
1✔
809
        }
810

811
        // Exchange local and global features, the init message should be very
812
        // first between two nodes.
813
        if err := p.sendInitMsg(haveLegacyChan); err != nil {
1✔
UNCOV
814
                return fmt.Errorf("unable to send init msg: %w", err)
×
UNCOV
815
        }
×
816

817
        // Before we launch any of the helper goroutines off the peer struct,
818
        // we'll first ensure proper adherence to the p2p protocol. The init
819
        // message MUST be sent before any other message.
820
        readErr := make(chan error, 1)
1✔
821
        msgChan := make(chan lnwire.Message, 1)
1✔
822
        p.cg.WgAdd(1)
1✔
823
        go func() {
2✔
824
                defer p.cg.WgDone()
1✔
825

1✔
826
                msg, err := p.readNextMessage()
1✔
827
                if err != nil {
2✔
828
                        readErr <- err
1✔
829
                        msgChan <- nil
1✔
830
                        return
1✔
831
                }
1✔
832
                readErr <- nil
1✔
833
                msgChan <- msg
1✔
834
        }()
835

836
        select {
1✔
837
        // In order to avoid blocking indefinitely, we'll give the other peer
838
        // an upper timeout to respond before we bail out early.
839
        case <-time.After(handshakeTimeout):
×
840
                return fmt.Errorf("peer did not complete handshake within %v",
×
841
                        handshakeTimeout)
×
842
        case err := <-readErr:
1✔
843
                if err != nil {
2✔
844
                        return fmt.Errorf("unable to read init msg: %w", err)
1✔
845
                }
1✔
846
        }
847

848
        // Once the init message arrives, we can parse it so we can figure out
849
        // the negotiation of features for this session.
850
        msg := <-msgChan
1✔
851
        if msg, ok := msg.(*lnwire.Init); ok {
2✔
852
                if err := p.handleInitMsg(msg); err != nil {
1✔
853
                        p.storeError(err)
×
854
                        return err
×
855
                }
×
856
        } else {
×
857
                return errors.New("very first message between nodes " +
×
858
                        "must be init message")
×
859
        }
×
860

861
        // Next, load all the active channels we have with this peer,
862
        // registering them with the switch and launching the necessary
863
        // goroutines required to operate them.
864
        p.log.Debugf("Loaded %v active channels from database",
1✔
865
                len(activeChans))
1✔
866

1✔
867
        // Conditionally subscribe to channel events before loading channels so
1✔
868
        // we won't miss events. This subscription is used to listen to active
1✔
869
        // channel event when reenabling channels. Once the reenabling process
1✔
870
        // is finished, this subscription will be canceled.
1✔
871
        //
1✔
872
        // NOTE: ChannelNotifier must be started before subscribing events
1✔
873
        // otherwise we'd panic here.
1✔
874
        if err := p.attachChannelEventSubscription(); err != nil {
1✔
875
                return err
×
876
        }
×
877

878
        // Register the message router now as we may need to register some
879
        // endpoints while loading the channels below.
880
        p.msgRouter.WhenSome(func(router msgmux.Router) {
2✔
881
                router.Start(context.Background())
1✔
882
        })
1✔
883

884
        msgs, err := p.loadActiveChannels(activeChans)
1✔
885
        if err != nil {
1✔
886
                return fmt.Errorf("unable to load channels: %w", err)
×
887
        }
×
888

889
        p.startTime = time.Now()
1✔
890

1✔
891
        // Before launching the writeHandler goroutine, we send any channel
1✔
892
        // sync messages that must be resent for borked channels. We do this to
1✔
893
        // avoid data races with WriteMessage & Flush calls.
1✔
894
        if len(msgs) > 0 {
2✔
895
                p.log.Infof("Sending %d channel sync messages to peer after "+
1✔
896
                        "loading active channels", len(msgs))
1✔
897

1✔
898
                // Send the messages directly via writeMessage and bypass the
1✔
899
                // writeHandler goroutine.
1✔
900
                for _, msg := range msgs {
2✔
901
                        if err := p.writeMessage(msg); err != nil {
1✔
902
                                return fmt.Errorf("unable to send "+
×
903
                                        "reestablish msg: %v", err)
×
904
                        }
×
905
                }
906
        }
907

908
        err = p.pingManager.Start()
1✔
909
        if err != nil {
1✔
910
                return fmt.Errorf("could not start ping manager %w", err)
×
911
        }
×
912

913
        p.cg.WgAdd(4)
1✔
914
        go p.queueHandler()
1✔
915
        go p.writeHandler()
1✔
916
        go p.channelManager()
1✔
917
        go p.readHandler()
1✔
918

1✔
919
        // Signal to any external processes that the peer is now active.
1✔
920
        close(p.activeSignal)
1✔
921

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

1✔
937
        return nil
1✔
938
}
939

940
// initGossipSync initializes either a gossip syncer or an initial routing
941
// dump, depending on the negotiated synchronization method.
942
func (p *Brontide) initGossipSync() {
1✔
943
        // If the remote peer knows of the new gossip queries feature, then
1✔
944
        // we'll create a new gossipSyncer in the AuthenticatedGossiper for it.
1✔
945
        if p.remoteFeatures.HasFeature(lnwire.GossipQueriesOptional) {
2✔
946
                p.log.Info("Negotiated chan series queries")
1✔
947

1✔
948
                if p.cfg.AuthGossiper == nil {
1✔
UNCOV
949
                        // This should only ever be hit in the unit tests.
×
UNCOV
950
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
×
UNCOV
951
                                "gossip sync.")
×
UNCOV
952
                        return
×
UNCOV
953
                }
×
954

955
                // Register the peer's gossip syncer with the gossiper.
956
                // This blocks synchronously to ensure the gossip syncer is
957
                // registered with the gossiper before attempting to read
958
                // messages from the remote peer.
959
                //
960
                // TODO(wilmer): Only sync updates from non-channel peers. This
961
                // requires an improved version of the current network
962
                // bootstrapper to ensure we can find and connect to non-channel
963
                // peers.
964
                p.cfg.AuthGossiper.InitSyncState(p)
1✔
965
        }
966
}
967

968
// taprootShutdownAllowed returns true if both parties have negotiated the
969
// shutdown-any-segwit feature.
970
func (p *Brontide) taprootShutdownAllowed() bool {
1✔
971
        return p.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
1✔
972
                p.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
1✔
973
}
1✔
974

975
// rbfCoopCloseAllowed returns true if both parties have negotiated the new RBF
976
// coop close feature.
977
func (p *Brontide) rbfCoopCloseAllowed() bool {
1✔
978
        return p.RemoteFeatures().HasFeature(
1✔
979
                lnwire.RbfCoopCloseOptionalStaging,
1✔
980
        ) && p.LocalFeatures().HasFeature(
1✔
981
                lnwire.RbfCoopCloseOptionalStaging,
1✔
982
        )
1✔
983
}
1✔
984

985
// QuitSignal is a method that should return a channel which will be sent upon
986
// or closed once the backing peer exits. This allows callers using the
987
// interface to cancel any processing in the event the backing implementation
988
// exits.
989
//
990
// NOTE: Part of the lnpeer.Peer interface.
991
func (p *Brontide) QuitSignal() <-chan struct{} {
1✔
992
        return p.cg.Done()
1✔
993
}
1✔
994

995
// addrWithInternalKey takes a delivery script, then attempts to supplement it
996
// with information related to the internal key for the addr, but only if it's
997
// a taproot addr.
998
func (p *Brontide) addrWithInternalKey(
999
        deliveryScript []byte) (*chancloser.DeliveryAddrWithKey, error) {
1✔
1000

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

1012
        return &chancloser.DeliveryAddrWithKey{
1✔
1013
                DeliveryAddress: deliveryScript,
1✔
1014
                InternalKey: fn.MapOption(
1✔
1015
                        func(desc keychain.KeyDescriptor) btcec.PublicKey {
2✔
1016
                                return *desc.PubKey
1✔
1017
                        },
1✔
1018
                )(internalKeyDesc),
1019
        }, nil
1020
}
1021

1022
// loadActiveChannels creates indexes within the peer for tracking all active
1023
// channels returned by the database. It returns a slice of channel reestablish
1024
// messages that should be sent to the peer immediately, in case we have borked
1025
// channels that haven't been closed yet.
1026
func (p *Brontide) loadActiveChannels(chans []*channeldb.OpenChannel) (
1027
        []lnwire.Message, error) {
1✔
1028

1✔
1029
        // Return a slice of messages to send to the peers in case the channel
1✔
1030
        // cannot be loaded normally.
1✔
1031
        var msgs []lnwire.Message
1✔
1032

1✔
1033
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
1✔
1034

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

1055
                                err = p.cfg.AddLocalAlias(
1✔
1056
                                        aliasScid, dbChan.ShortChanID(), false,
1✔
1057
                                        false,
1✔
1058
                                )
1✔
1059
                                if err != nil {
1✔
1060
                                        return nil, err
×
1061
                                }
×
1062

1063
                                chanID := lnwire.NewChanIDFromOutPoint(
1✔
1064
                                        dbChan.FundingOutpoint,
1✔
1065
                                )
1✔
1066

1✔
1067
                                // Fetch the second commitment point to send in
1✔
1068
                                // the channel_ready message.
1✔
1069
                                second, err := dbChan.SecondCommitmentPoint()
1✔
1070
                                if err != nil {
1✔
1071
                                        return nil, err
×
1072
                                }
×
1073

1074
                                channelReadyMsg := lnwire.NewChannelReady(
1✔
1075
                                        chanID, second,
1✔
1076
                                )
1✔
1077
                                channelReadyMsg.AliasScid = &aliasScid
1✔
1078

1✔
1079
                                msgs = append(msgs, channelReadyMsg)
1✔
1080
                        }
1081

1082
                        // If we've negotiated the option-scid-alias feature
1083
                        // and this channel does not have ScidAliasFeature set
1084
                        // to true due to an upgrade where the feature bit was
1085
                        // turned on, we'll update the channel's database
1086
                        // state.
1087
                        err := dbChan.MarkScidAliasNegotiated()
1✔
1088
                        if err != nil {
1✔
1089
                                return nil, err
×
1090
                        }
×
1091
                }
1092

1093
                var chanOpts []lnwallet.ChannelOpt
1✔
1094
                p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
1✔
1095
                        chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
1096
                })
×
1097
                p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
1✔
1098
                        chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
1099
                })
×
1100
                p.cfg.AuxResolver.WhenSome(
1✔
1101
                        func(s lnwallet.AuxContractResolver) {
1✔
1102
                                chanOpts = append(
×
1103
                                        chanOpts, lnwallet.WithAuxResolver(s),
×
1104
                                )
×
1105
                        },
×
1106
                )
1107

1108
                lnChan, err := lnwallet.NewLightningChannel(
1✔
1109
                        p.cfg.Signer, dbChan, p.cfg.SigPool, chanOpts...,
1✔
1110
                )
1✔
1111
                if err != nil {
1✔
1112
                        return nil, fmt.Errorf("unable to create channel "+
×
1113
                                "state machine: %w", err)
×
1114
                }
×
1115

1116
                chanPoint := dbChan.FundingOutpoint
1✔
1117

1✔
1118
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
1✔
1119

1✔
1120
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
1✔
1121
                        chanPoint, lnChan.IsPending())
1✔
1122

1✔
1123
                // Skip adding any permanently irreconcilable channels to the
1✔
1124
                // htlcswitch.
1✔
1125
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
1✔
1126
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
2✔
1127

1✔
1128
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
1✔
1129
                                "start.", chanPoint, dbChan.ChanStatus())
1✔
1130

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

1145
                        msgs = append(msgs, chanSync)
1✔
1146

1✔
1147
                        // Check if this channel needs to have the cooperative
1✔
1148
                        // close process restarted. If so, we'll need to send
1✔
1149
                        // the Shutdown message that is returned.
1✔
1150
                        if dbChan.HasChanStatus(
1✔
1151
                                channeldb.ChanStatusCoopBroadcasted,
1✔
1152
                        ) {
2✔
1153

1✔
1154
                                shutdownMsg, err := p.restartCoopClose(lnChan)
1✔
1155
                                if err != nil {
1✔
1156
                                        p.log.Errorf("Unable to restart "+
×
1157
                                                "coop close for channel: %v",
×
1158
                                                err)
×
1159
                                        continue
×
1160
                                }
1161

1162
                                if shutdownMsg == nil {
2✔
1163
                                        continue
1✔
1164
                                }
1165

1166
                                // Append the message to the set of messages to
1167
                                // send.
1168
                                msgs = append(msgs, shutdownMsg)
×
1169
                        }
1170

1171
                        continue
1✔
1172
                }
1173

1174
                // Before we register this new link with the HTLC Switch, we'll
1175
                // need to fetch its current link-layer forwarding policy from
1176
                // the database.
1177
                graph := p.cfg.ChannelGraph
1✔
1178
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
1✔
1179
                        &chanPoint,
1✔
1180
                )
1✔
1181
                if err != nil && !errors.Is(err, graphdb.ErrEdgeNotFound) {
1✔
1182
                        return nil, err
×
1183
                }
×
1184

1185
                // We'll filter out our policy from the directional channel
1186
                // edges based whom the edge connects to. If it doesn't connect
1187
                // to us, then we know that we were the one that advertised the
1188
                // policy.
1189
                //
1190
                // TODO(roasbeef): can add helper method to get policy for
1191
                // particular channel.
1192
                var selfPolicy *models.ChannelEdgePolicy
1✔
1193
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
1✔
1194
                        p.cfg.ServerPubKey[:]) {
2✔
1195

1✔
1196
                        selfPolicy = p1
1✔
1197
                } else {
2✔
1198
                        selfPolicy = p2
1✔
1199
                }
1✔
1200

1201
                // If we don't yet have an advertised routing policy, then
1202
                // we'll use the current default, otherwise we'll translate the
1203
                // routing policy into a forwarding policy.
1204
                var forwardingPolicy *models.ForwardingPolicy
1✔
1205
                if selfPolicy != nil {
2✔
1206
                        var inboundWireFee lnwire.Fee
1✔
1207
                        _, err := selfPolicy.ExtraOpaqueData.ExtractRecords(
1✔
1208
                                &inboundWireFee,
1✔
1209
                        )
1✔
1210
                        if err != nil {
1✔
1211
                                return nil, err
×
1212
                        }
×
1213

1214
                        inboundFee := models.NewInboundFeeFromWire(
1✔
1215
                                inboundWireFee,
1✔
1216
                        )
1✔
1217

1✔
1218
                        forwardingPolicy = &models.ForwardingPolicy{
1✔
1219
                                MinHTLCOut:    selfPolicy.MinHTLC,
1✔
1220
                                MaxHTLC:       selfPolicy.MaxHTLC,
1✔
1221
                                BaseFee:       selfPolicy.FeeBaseMSat,
1✔
1222
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
1✔
1223
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
1✔
1224

1✔
1225
                                InboundFee: inboundFee,
1✔
1226
                        }
1✔
1227
                } else {
1✔
1228
                        p.log.Warnf("Unable to find our forwarding policy "+
1✔
1229
                                "for channel %v, using default values",
1✔
1230
                                chanPoint)
1✔
1231
                        forwardingPolicy = &p.cfg.RoutingPolicy
1✔
1232
                }
1✔
1233

1234
                p.log.Tracef("Using link policy of: %v",
1✔
1235
                        spew.Sdump(forwardingPolicy))
1✔
1236

1✔
1237
                // If the channel is pending, set the value to nil in the
1✔
1238
                // activeChannels map. This is done to signify that the channel
1✔
1239
                // is pending. We don't add the link to the switch here - it's
1✔
1240
                // the funding manager's responsibility to spin up pending
1✔
1241
                // channels. Adding them here would just be extra work as we'll
1✔
1242
                // tear them down when creating + adding the final link.
1✔
1243
                if lnChan.IsPending() {
2✔
1244
                        p.activeChannels.Store(chanID, nil)
1✔
1245

1✔
1246
                        continue
1✔
1247
                }
1248

1249
                shutdownInfo, err := lnChan.State().ShutdownInfo()
1✔
1250
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
1✔
1251
                        return nil, err
×
1252
                }
×
1253

1254
                isTaprootChan := lnChan.ChanType().IsTaproot()
1✔
1255

1✔
1256
                var (
1✔
1257
                        shutdownMsg     fn.Option[lnwire.Shutdown]
1✔
1258
                        shutdownInfoErr error
1✔
1259
                )
1✔
1260
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
2✔
1261
                        // If we can use the new RBF close feature, we don't
1✔
1262
                        // need to create the legacy closer. However for taproot
1✔
1263
                        // channels, we'll continue to use the legacy closer.
1✔
1264
                        if p.rbfCoopCloseAllowed() && !isTaprootChan {
2✔
1265
                                return
1✔
1266
                        }
1✔
1267

1268
                        // Compute an ideal fee.
1269
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
1✔
1270
                                p.cfg.CoopCloseTargetConfs,
1✔
1271
                        )
1✔
1272
                        if err != nil {
1✔
1273
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1274
                                        "estimate fee: %w", err)
×
1275

×
1276
                                return
×
1277
                        }
×
1278

1279
                        addr, err := p.addrWithInternalKey(
1✔
1280
                                info.DeliveryScript.Val,
1✔
1281
                        )
1✔
1282
                        if err != nil {
1✔
1283
                                shutdownInfoErr = fmt.Errorf("unable to make "+
×
1284
                                        "delivery addr: %w", err)
×
1285
                                return
×
1286
                        }
×
1287
                        negotiateChanCloser, err := p.createChanCloser(
1✔
1288
                                lnChan, addr, feePerKw, nil,
1✔
1289
                                info.Closer(),
1✔
1290
                        )
1✔
1291
                        if err != nil {
1✔
1292
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1293
                                        "create chan closer: %w", err)
×
1294

×
1295
                                return
×
1296
                        }
×
1297

1298
                        chanID := lnwire.NewChanIDFromOutPoint(
1✔
1299
                                lnChan.State().FundingOutpoint,
1✔
1300
                        )
1✔
1301

1✔
1302
                        p.activeChanCloses.Store(chanID, makeNegotiateCloser(
1✔
1303
                                negotiateChanCloser,
1✔
1304
                        ))
1✔
1305

1✔
1306
                        // Create the Shutdown message.
1✔
1307
                        shutdown, err := negotiateChanCloser.ShutdownChan()
1✔
1308
                        if err != nil {
1✔
1309
                                p.activeChanCloses.Delete(chanID)
×
1310
                                shutdownInfoErr = err
×
1311

×
1312
                                return
×
1313
                        }
×
1314

1315
                        shutdownMsg = fn.Some(*shutdown)
1✔
1316
                })
1317
                if shutdownInfoErr != nil {
1✔
1318
                        return nil, shutdownInfoErr
×
1319
                }
×
1320

1321
                // Subscribe to the set of on-chain events for this channel.
1322
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
1✔
1323
                        chanPoint,
1✔
1324
                )
1✔
1325
                if err != nil {
1✔
1326
                        return nil, err
×
1327
                }
×
1328

1329
                err = p.addLink(
1✔
1330
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
1✔
1331
                        true, shutdownMsg,
1✔
1332
                )
1✔
1333
                if err != nil {
1✔
1334
                        return nil, fmt.Errorf("unable to add link %v to "+
×
1335
                                "switch: %v", chanPoint, err)
×
1336
                }
×
1337

1338
                p.activeChannels.Store(chanID, lnChan)
1✔
1339

1✔
1340
                // We're using the old co-op close, so we don't need to init
1✔
1341
                // the new RBF chan closer. If we have a taproot chan, then
1✔
1342
                // we'll also use the legacy type, so we don't need to make the
1✔
1343
                // new closer.
1✔
1344
                if !p.rbfCoopCloseAllowed() || isTaprootChan {
2✔
1345
                        continue
1✔
1346
                }
1347

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

×
1357
                        return nil, fmt.Errorf("unable to init RBF chan "+
×
1358
                                "closer during peer connect: %w", err)
×
1359
                }
×
1360

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

1377
        return msgs, nil
1✔
1378
}
1379

1380
// addLink creates and adds a new ChannelLink from the specified channel.
1381
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1382
        lnChan *lnwallet.LightningChannel,
1383
        forwardingPolicy *models.ForwardingPolicy,
1384
        chainEvents *contractcourt.ChainEventSubscription,
1385
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
1✔
1386

1✔
1387
        // onChannelFailure will be called by the link in case the channel
1✔
1388
        // fails for some reason.
1✔
1389
        onChannelFailure := func(chanID lnwire.ChannelID,
1✔
1390
                shortChanID lnwire.ShortChannelID,
1✔
1391
                linkErr htlcswitch.LinkFailureError) {
2✔
1392

1✔
1393
                failure := linkFailureReport{
1✔
1394
                        chanPoint:   *chanPoint,
1✔
1395
                        chanID:      chanID,
1✔
1396
                        shortChanID: shortChanID,
1✔
1397
                        linkErr:     linkErr,
1✔
1398
                }
1✔
1399

1✔
1400
                select {
1✔
1401
                case p.linkFailures <- failure:
1✔
1402
                case <-p.cg.Done():
×
1403
                case <-p.cfg.Quit:
×
1404
                }
1405
        }
1406

1407
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
2✔
1408
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
1✔
1409
        }
1✔
1410

1411
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
2✔
1412
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
1✔
1413
        }
1✔
1414

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

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

1✔
1470
        // With the channel link created, we'll now notify the htlc switch so
1✔
1471
        // this channel can be used to dispatch local payments and also
1✔
1472
        // passively forward payments.
1✔
1473
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
1✔
1474
}
1475

1476
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1477
// one confirmed public channel exists with them.
1478
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
1✔
1479
        defer p.cg.WgDone()
1✔
1480

1✔
1481
        hasConfirmedPublicChan := false
1✔
1482
        for _, channel := range channels {
2✔
1483
                if channel.IsPending {
2✔
1484
                        continue
1✔
1485
                }
1486
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
2✔
1487
                        continue
1✔
1488
                }
1489

1490
                hasConfirmedPublicChan = true
1✔
1491
                break
1✔
1492
        }
1493
        if !hasConfirmedPublicChan {
2✔
1494
                return
1✔
1495
        }
1✔
1496

1497
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
1✔
1498
        if err != nil {
1✔
1499
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1500
                return
×
1501
        }
×
1502

1503
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
1✔
1504
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1505
        }
×
1506
}
1507

1508
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1509
// have any active channels with them.
1510
func (p *Brontide) maybeSendChannelUpdates() {
1✔
1511
        defer p.cg.WgDone()
1✔
1512

1✔
1513
        // If we don't have any active channels, then we can exit early.
1✔
1514
        if p.activeChannels.Len() == 0 {
2✔
1515
                return
1✔
1516
        }
1✔
1517

1518
        maybeSendUpd := func(cid lnwire.ChannelID,
1✔
1519
                lnChan *lnwallet.LightningChannel) error {
2✔
1520

1✔
1521
                // Nil channels are pending, so we'll skip them.
1✔
1522
                if lnChan == nil {
2✔
1523
                        return nil
1✔
1524
                }
1✔
1525

1526
                dbChan := lnChan.State()
1✔
1527
                scid := func() lnwire.ShortChannelID {
2✔
1528
                        switch {
1✔
1529
                        // Otherwise if it's a zero conf channel and confirmed,
1530
                        // then we need to use the "real" scid.
1531
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
1✔
1532
                                return dbChan.ZeroConfRealScid()
1✔
1533

1534
                        // Otherwise, we can use the normal scid.
1535
                        default:
1✔
1536
                                return dbChan.ShortChanID()
1✔
1537
                        }
1538
                }()
1539

1540
                // Now that we know the channel is in a good state, we'll try
1541
                // to fetch the update to send to the remote peer. If the
1542
                // channel is pending, and not a zero conf channel, we'll get
1543
                // an error here which we'll ignore.
1544
                chanUpd, err := p.cfg.FetchLastChanUpdate(scid)
1✔
1545
                if err != nil {
2✔
1546
                        p.log.Debugf("Unable to fetch channel update for "+
1✔
1547
                                "ChannelPoint(%v), scid=%v: %v",
1✔
1548
                                dbChan.FundingOutpoint, dbChan.ShortChanID, err)
1✔
1549

1✔
1550
                        return nil
1✔
1551
                }
1✔
1552

1553
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
1✔
1554
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
1✔
1555

1✔
1556
                // We'll send it as a normal message instead of using the lazy
1✔
1557
                // queue to prioritize transmission of the fresh update.
1✔
1558
                if err := p.SendMessage(false, chanUpd); err != nil {
1✔
1559
                        err := fmt.Errorf("unable to send channel update for "+
×
1560
                                "ChannelPoint(%v), scid=%v: %w",
×
1561
                                dbChan.FundingOutpoint, dbChan.ShortChanID(),
×
1562
                                err)
×
1563
                        p.log.Errorf(err.Error())
×
1564

×
1565
                        return err
×
1566
                }
×
1567

1568
                return nil
1✔
1569
        }
1570

1571
        p.activeChannels.ForEach(maybeSendUpd)
1✔
1572
}
1573

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

1591
        select {
1✔
1592
        case <-ready:
1✔
1593
        case <-p.cg.Done():
1✔
1594
        }
1595

1596
        p.cg.WgWait()
1✔
1597
}
1598

1599
// Disconnect terminates the connection with the remote peer. Additionally, a
1600
// signal is sent to the server and htlcSwitch indicating the resources
1601
// allocated to the peer can now be cleaned up.
1602
func (p *Brontide) Disconnect(reason error) {
1✔
1603
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
2✔
1604
                return
1✔
1605
        }
1✔
1606

1607
        // Make sure initialization has completed before we try to tear things
1608
        // down.
1609
        //
1610
        // NOTE: We only read the `startReady` chan if the peer has been
1611
        // started, otherwise we will skip reading it as this chan won't be
1612
        // closed, hence blocks forever.
1613
        if atomic.LoadInt32(&p.started) == 1 {
2✔
1614
                p.log.Debugf("Started, waiting on startReady signal")
1✔
1615

1✔
1616
                select {
1✔
1617
                case <-p.startReady:
1✔
1618
                case <-p.cg.Done():
×
1619
                        return
×
1620
                }
1621
        }
1622

1623
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
1✔
1624
        p.storeError(err)
1✔
1625

1✔
1626
        p.log.Infof(err.Error())
1✔
1627

1✔
1628
        // Stop PingManager before closing TCP connection.
1✔
1629
        p.pingManager.Stop()
1✔
1630

1✔
1631
        // Ensure that the TCP connection is properly closed before continuing.
1✔
1632
        p.cfg.Conn.Close()
1✔
1633

1✔
1634
        p.cg.Quit()
1✔
1635

1✔
1636
        // If our msg router isn't global (local to this instance), then we'll
1✔
1637
        // stop it. Otherwise, we'll leave it running.
1✔
1638
        if !p.globalMsgRouter {
2✔
1639
                p.msgRouter.WhenSome(func(router msgmux.Router) {
2✔
1640
                        router.Stop()
1✔
1641
                })
1✔
1642
        }
1643
}
1644

1645
// String returns the string representation of this peer.
1646
func (p *Brontide) String() string {
1✔
1647
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
1✔
1648
}
1✔
1649

1650
// readNextMessage reads, and returns the next message on the wire along with
1651
// any additional raw payload.
1652
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
1✔
1653
        noiseConn := p.cfg.Conn
1✔
1654
        err := noiseConn.SetReadDeadline(time.Time{})
1✔
1655
        if err != nil {
1✔
1656
                return nil, err
×
1657
        }
×
1658

1659
        pktLen, err := noiseConn.ReadNextHeader()
1✔
1660
        if err != nil {
2✔
1661
                return nil, fmt.Errorf("read next header: %w", err)
1✔
1662
        }
1✔
1663

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

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

1✔
1696
                // Next, create a new io.Reader implementation from the raw
1✔
1697
                // message, and use this to decode the message directly from.
1✔
1698
                msgReader := bytes.NewReader(rawMsg)
1✔
1699
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
1✔
1700
                if err != nil {
2✔
1701
                        return err
1✔
1702
                }
1✔
1703

1704
                // At this point, rawMsg and buf will be returned back to the
1705
                // buffer pool for re-use.
1706
                return nil
1✔
1707
        })
1708
        atomic.AddUint64(&p.bytesReceived, msgLen)
1✔
1709
        if err != nil {
2✔
1710
                return nil, err
1✔
1711
        }
1✔
1712

1713
        p.logWireMessage(nextMsg, true)
1✔
1714

1✔
1715
        return nextMsg, nil
1✔
1716
}
1717

1718
// msgStream implements a goroutine-safe, in-order stream of messages to be
1719
// delivered via closure to a receiver. These messages MUST be in order due to
1720
// the nature of the lightning channel commitment and gossiper state machines.
1721
// TODO(conner): use stream handler interface to abstract out stream
1722
// state/logging.
1723
type msgStream struct {
1724
        streamShutdown int32 // To be used atomically.
1725

1726
        peer *Brontide
1727

1728
        apply func(lnwire.Message)
1729

1730
        startMsg string
1731
        stopMsg  string
1732

1733
        msgCond *sync.Cond
1734
        msgs    []lnwire.Message
1735

1736
        mtx sync.Mutex
1737

1738
        producerSema chan struct{}
1739

1740
        wg   sync.WaitGroup
1741
        quit chan struct{}
1742
}
1743

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

1✔
1752
        stream := &msgStream{
1✔
1753
                peer:         p,
1✔
1754
                apply:        apply,
1✔
1755
                startMsg:     startMsg,
1✔
1756
                stopMsg:      stopMsg,
1✔
1757
                producerSema: make(chan struct{}, bufSize),
1✔
1758
                quit:         make(chan struct{}),
1✔
1759
        }
1✔
1760
        stream.msgCond = sync.NewCond(&stream.mtx)
1✔
1761

1✔
1762
        // Before we return the active stream, we'll populate the producer's
1✔
1763
        // semaphore channel. We'll use this to ensure that the producer won't
1✔
1764
        // attempt to allocate memory in the queue for an item until it has
1✔
1765
        // sufficient extra space.
1✔
1766
        for i := uint32(0); i < bufSize; i++ {
2✔
1767
                stream.producerSema <- struct{}{}
1✔
1768
        }
1✔
1769

1770
        return stream
1✔
1771
}
1772

1773
// Start starts the chanMsgStream.
1774
func (ms *msgStream) Start() {
1✔
1775
        ms.wg.Add(1)
1✔
1776
        go ms.msgConsumer()
1✔
1777
}
1✔
1778

1779
// Stop stops the chanMsgStream.
1780
func (ms *msgStream) Stop() {
1✔
1781
        // TODO(roasbeef): signal too?
1✔
1782

1✔
1783
        close(ms.quit)
1✔
1784

1✔
1785
        // Now that we've closed the channel, we'll repeatedly signal the msg
1✔
1786
        // consumer until we've detected that it has exited.
1✔
1787
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
2✔
1788
                ms.msgCond.Signal()
1✔
1789
                time.Sleep(time.Millisecond * 100)
1✔
1790
        }
1✔
1791

1792
        ms.wg.Wait()
1✔
1793
}
1794

1795
// msgConsumer is the main goroutine that streams messages from the peer's
1796
// readHandler directly to the target channel.
1797
func (ms *msgStream) msgConsumer() {
1✔
1798
        defer ms.wg.Done()
1✔
1799
        defer peerLog.Tracef(ms.stopMsg)
1✔
1800
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
1✔
1801

1✔
1802
        peerLog.Tracef(ms.startMsg)
1✔
1803

1✔
1804
        for {
2✔
1805
                // First, we'll check our condition. If the queue of messages
1✔
1806
                // is empty, then we'll wait until a new item is added.
1✔
1807
                ms.msgCond.L.Lock()
1✔
1808
                for len(ms.msgs) == 0 {
2✔
1809
                        ms.msgCond.Wait()
1✔
1810

1✔
1811
                        // If we woke up in order to exit, then we'll do so.
1✔
1812
                        // Otherwise, we'll check the message queue for any new
1✔
1813
                        // items.
1✔
1814
                        select {
1✔
1815
                        case <-ms.peer.cg.Done():
1✔
1816
                                ms.msgCond.L.Unlock()
1✔
1817
                                return
1✔
1818
                        case <-ms.quit:
1✔
1819
                                ms.msgCond.L.Unlock()
1✔
1820
                                return
1✔
1821
                        default:
1✔
1822
                        }
1823
                }
1824

1825
                // Grab the message off the front of the queue, shifting the
1826
                // slice's reference down one in order to remove the message
1827
                // from the queue.
1828
                msg := ms.msgs[0]
1✔
1829
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
1✔
1830
                ms.msgs = ms.msgs[1:]
1✔
1831

1✔
1832
                ms.msgCond.L.Unlock()
1✔
1833

1✔
1834
                ms.apply(msg)
1✔
1835

1✔
1836
                // We've just successfully processed an item, so we'll signal
1✔
1837
                // to the producer that a new slot in the buffer. We'll use
1✔
1838
                // this to bound the size of the buffer to avoid allowing it to
1✔
1839
                // grow indefinitely.
1✔
1840
                select {
1✔
1841
                case ms.producerSema <- struct{}{}:
1✔
1842
                case <-ms.peer.cg.Done():
1✔
1843
                        return
1✔
1844
                case <-ms.quit:
1✔
1845
                        return
1✔
1846
                }
1847
        }
1848
}
1849

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

1866
        // Next, we'll lock the condition, and add the message to the end of
1867
        // the message queue.
1868
        ms.msgCond.L.Lock()
1✔
1869
        ms.msgs = append(ms.msgs, msg)
1✔
1870
        ms.msgCond.L.Unlock()
1✔
1871

1✔
1872
        // With the message added, we signal to the msgConsumer that there are
1✔
1873
        // additional messages to consume.
1✔
1874
        ms.msgCond.Signal()
1✔
1875
}
1876

1877
// waitUntilLinkActive waits until the target link is active and returns a
1878
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1879
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1880
func waitUntilLinkActive(p *Brontide,
1881
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
1✔
1882

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

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

1✔
1903
        // The link may already be active by this point, and we may have missed the
1✔
1904
        // ActiveLinkEvent. Check if the link exists.
1✔
1905
        link := p.fetchLinkFromKeyAndCid(cid)
1✔
1906
        if link != nil {
2✔
1907
                return link
1✔
1908
        }
1✔
1909

1910
        // If the link is nil, we must wait for it to be active.
1911
        for {
2✔
1912
                select {
1✔
1913
                // A new event has been sent by the ChannelNotifier. We first check
1914
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1915
                // that the event is for this channel. Otherwise, we discard the
1916
                // message.
1917
                case e := <-sub.Updates():
1✔
1918
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
1✔
1919
                        if !ok {
2✔
1920
                                // Ignore this notification.
1✔
1921
                                continue
1✔
1922
                        }
1923

1924
                        chanPoint := event.ChannelPoint
1✔
1925

1✔
1926
                        // Check whether the retrieved chanPoint matches the target
1✔
1927
                        // channel id.
1✔
1928
                        if !cid.IsChanPoint(chanPoint) {
1✔
1929
                                continue
×
1930
                        }
1931

1932
                        // The link shouldn't be nil as we received an
1933
                        // ActiveLinkEvent. If it is nil, we return nil and the
1934
                        // calling function should catch it.
1935
                        return p.fetchLinkFromKeyAndCid(cid)
1✔
1936

1937
                case <-p.cg.Done():
1✔
1938
                        return nil
1✔
1939
                }
1940
        }
1941
}
1942

1943
// newChanMsgStream is used to create a msgStream between the peer and
1944
// particular channel link in the htlcswitch. We utilize additional
1945
// synchronization with the fundingManager to ensure we don't attempt to
1946
// dispatch a message to a channel before it is fully active. A reference to the
1947
// channel this stream forwards to is held in scope to prevent unnecessary
1948
// lookups.
1949
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
1✔
1950
        var chanLink htlcswitch.ChannelUpdateHandler
1✔
1951

1✔
1952
        apply := func(msg lnwire.Message) {
2✔
1953
                // This check is fine because if the link no longer exists, it will
1✔
1954
                // be removed from the activeChannels map and subsequent messages
1✔
1955
                // shouldn't reach the chan msg stream.
1✔
1956
                if chanLink == nil {
2✔
1957
                        chanLink = waitUntilLinkActive(p, cid)
1✔
1958

1✔
1959
                        // If the link is still not active and the calling function
1✔
1960
                        // errored out, just return.
1✔
1961
                        if chanLink == nil {
2✔
1962
                                p.log.Warnf("Link=%v is not active", cid)
1✔
1963
                                return
1✔
1964
                        }
1✔
1965
                }
1966

1967
                // In order to avoid unnecessarily delivering message
1968
                // as the peer is exiting, we'll check quickly to see
1969
                // if we need to exit.
1970
                select {
1✔
1971
                case <-p.cg.Done():
×
1972
                        return
×
1973
                default:
1✔
1974
                }
1975

1976
                chanLink.HandleChannelUpdate(msg)
1✔
1977
        }
1978

1979
        return newMsgStream(p,
1✔
1980
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
1✔
1981
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
1✔
1982
                msgStreamSize,
1✔
1983
                apply,
1✔
1984
        )
1✔
1985
}
1986

1987
// newDiscMsgStream is used to setup a msgStream between the peer and the
1988
// authenticated gossiper. This stream should be used to forward all remote
1989
// channel announcements.
1990
func newDiscMsgStream(p *Brontide) *msgStream {
1✔
1991
        apply := func(msg lnwire.Message) {
2✔
1992
                // TODO(yy): `ProcessRemoteAnnouncement` returns an error chan
1✔
1993
                // and we need to process it.
1✔
1994
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(msg, p)
1✔
1995
        }
1✔
1996

1997
        return newMsgStream(
1✔
1998
                p,
1✔
1999
                "Update stream for gossiper created",
1✔
2000
                "Update stream for gossiper exited",
1✔
2001
                msgStreamSize,
1✔
2002
                apply,
1✔
2003
        )
1✔
2004
}
2005

2006
// readHandler is responsible for reading messages off the wire in series, then
2007
// properly dispatching the handling of the message to the proper subsystem.
2008
//
2009
// NOTE: This method MUST be run as a goroutine.
2010
func (p *Brontide) readHandler() {
1✔
2011
        defer p.cg.WgDone()
1✔
2012

1✔
2013
        // We'll stop the timer after a new messages is received, and also
1✔
2014
        // reset it after we process the next message.
1✔
2015
        idleTimer := time.AfterFunc(idleTimeout, func() {
1✔
2016
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
2017
                        p, idleTimeout)
×
2018
                p.Disconnect(err)
×
2019
        })
×
2020

2021
        // Initialize our negotiated gossip sync method before reading messages
2022
        // off the wire. When using gossip queries, this ensures a gossip
2023
        // syncer is active by the time query messages arrive.
2024
        //
2025
        // TODO(conner): have peer store gossip syncer directly and bypass
2026
        // gossiper?
2027
        p.initGossipSync()
1✔
2028

1✔
2029
        discStream := newDiscMsgStream(p)
1✔
2030
        discStream.Start()
1✔
2031
        defer discStream.Stop()
1✔
2032
out:
1✔
2033
        for atomic.LoadInt32(&p.disconnect) == 0 {
2✔
2034
                nextMsg, err := p.readNextMessage()
1✔
2035
                if !idleTimer.Stop() {
2✔
2036
                        select {
1✔
2037
                        case <-idleTimer.C:
×
2038
                        default:
1✔
2039
                        }
2040
                }
2041
                if err != nil {
2✔
2042
                        p.log.Infof("unable to read message from peer: %v", err)
1✔
2043

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

2058
                        // If they sent us an address type that we don't yet
2059
                        // know of, then this isn't a wire error, so we'll
2060
                        // simply continue parsing the remainder of their
2061
                        // messages.
2062
                        case *lnwire.ErrUnknownAddrType:
×
2063
                                p.storeError(e)
×
2064
                                idleTimer.Reset(idleTimeout)
×
2065
                                continue
×
2066

2067
                        // If the NodeAnnouncement has an invalid alias, then
2068
                        // we'll log that error above and continue so we can
2069
                        // continue to read messages from the peer. We do not
2070
                        // store this error because it is of little debugging
2071
                        // value.
2072
                        case *lnwire.ErrInvalidNodeAlias:
×
2073
                                idleTimer.Reset(idleTimeout)
×
2074
                                continue
×
2075

2076
                        // If the error we encountered wasn't just a message we
2077
                        // didn't recognize, then we'll stop all processing as
2078
                        // this is a fatal error.
2079
                        default:
1✔
2080
                                break out
1✔
2081
                        }
2082
                }
2083

2084
                // If a message router is active, then we'll try to have it
2085
                // handle this message. If it can, then we're able to skip the
2086
                // rest of the message handling logic.
2087
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
2✔
2088
                        return r.RouteMsg(msgmux.PeerMsg{
1✔
2089
                                PeerPub: *p.IdentityKey(),
1✔
2090
                                Message: nextMsg,
1✔
2091
                        })
1✔
2092
                })
1✔
2093

2094
                // No error occurred, and the message was handled by the
2095
                // router.
2096
                if err == nil {
2✔
2097
                        continue
1✔
2098
                }
2099

2100
                var (
1✔
2101
                        targetChan   lnwire.ChannelID
1✔
2102
                        isLinkUpdate bool
1✔
2103
                )
1✔
2104

1✔
2105
                switch msg := nextMsg.(type) {
1✔
2106
                case *lnwire.Pong:
×
2107
                        // When we receive a Pong message in response to our
×
2108
                        // last ping message, we send it to the pingManager
×
2109
                        p.pingManager.ReceivedPong(msg)
×
2110

2111
                case *lnwire.Ping:
×
2112
                        // First, we'll store their latest ping payload within
×
2113
                        // the relevant atomic variable.
×
2114
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
2115

×
2116
                        // Next, we'll send over the amount of specified pong
×
2117
                        // bytes.
×
2118
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
×
2119
                        p.queueMsg(pong, nil)
×
2120

2121
                case *lnwire.OpenChannel,
2122
                        *lnwire.AcceptChannel,
2123
                        *lnwire.FundingCreated,
2124
                        *lnwire.FundingSigned,
2125
                        *lnwire.ChannelReady:
1✔
2126

1✔
2127
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
1✔
2128

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

2142
                case *lnwire.Warning:
×
2143
                        targetChan = msg.ChanID
×
2144
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2145

2146
                case *lnwire.Error:
1✔
2147
                        targetChan = msg.ChanID
1✔
2148
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
1✔
2149

2150
                case *lnwire.ChannelReestablish:
1✔
2151
                        targetChan = msg.ChanID
1✔
2152
                        isLinkUpdate = p.hasChannel(targetChan)
1✔
2153

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

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

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

2186
                case *lnwire.ChannelUpdate1,
2187
                        *lnwire.ChannelAnnouncement1,
2188
                        *lnwire.NodeAnnouncement,
2189
                        *lnwire.AnnounceSignatures1,
2190
                        *lnwire.GossipTimestampRange,
2191
                        *lnwire.QueryShortChanIDs,
2192
                        *lnwire.QueryChannelRange,
2193
                        *lnwire.ReplyChannelRange,
2194
                        *lnwire.ReplyShortChanIDsEnd:
1✔
2195

1✔
2196
                        discStream.AddMsg(msg)
1✔
2197

2198
                case *lnwire.Custom:
1✔
2199
                        err := p.handleCustomMessage(msg)
1✔
2200
                        if err != nil {
1✔
2201
                                p.storeError(err)
×
2202
                                p.log.Errorf("%v", err)
×
2203
                        }
×
2204

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

×
2212
                        p.log.Errorf("%v", err)
×
2213
                }
2214

2215
                if isLinkUpdate {
2✔
2216
                        // If this is a channel update, then we need to feed it
1✔
2217
                        // into the channel's in-order message stream.
1✔
2218
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
1✔
2219
                }
1✔
2220

2221
                idleTimer.Reset(idleTimeout)
1✔
2222
        }
2223

2224
        p.Disconnect(errors.New("read handler closed"))
1✔
2225

1✔
2226
        p.log.Trace("readHandler for peer done")
1✔
2227
}
2228

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

2237
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
1✔
2238
}
2239

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

2251
        // Return false if the channel is unknown.
2252
        channel, ok := p.activeChannels.Load(chanID)
1✔
2253
        if !ok {
1✔
2254
                return false
×
2255
        }
×
2256

2257
        // During startup, we will use a nil value to mark a pending channel
2258
        // that's loaded from disk.
2259
        return channel == nil
1✔
2260
}
2261

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

1✔
2271
        return channel != nil
1✔
2272
}
1✔
2273

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

2283
        return channel == nil
1✔
2284
}
2285

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

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

1✔
2300
        p.activeChannels.Range(func(_ lnwire.ChannelID,
1✔
2301
                channel *lnwallet.LightningChannel) bool {
2✔
2302

1✔
2303
                // Pending channels will be nil in the activeChannels map.
1✔
2304
                if channel == nil {
2✔
2305
                        // Return true to continue the iteration.
1✔
2306
                        return true
1✔
2307
                }
1✔
2308

2309
                haveChannels = true
1✔
2310

1✔
2311
                // Return false to break the iteration.
1✔
2312
                return false
1✔
2313
        })
2314

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

2322
        p.cfg.ErrorBuffer.Add(
1✔
2323
                &TimestampedError{Timestamp: time.Now(), Error: err},
1✔
2324
        )
1✔
2325
}
2326

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

1✔
2336
        if errMsg, ok := msg.(*lnwire.Error); ok {
2✔
2337
                p.storeError(errMsg)
1✔
2338
        }
1✔
2339

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

2348
                return false
×
2349

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

2356
        // If not we hand the message to the channel link for this channel.
2357
        case p.isActiveChannel(chanID):
1✔
2358
                return true
1✔
2359

2360
        default:
1✔
2361
                return false
1✔
2362
        }
2363
}
2364

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

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

2381
        case *lnwire.AcceptChannel:
1✔
2382
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
1✔
2383
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
1✔
2384
                        msg.MinAcceptDepth)
1✔
2385

2386
        case *lnwire.FundingCreated:
1✔
2387
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
1✔
2388
                        msg.PendingChannelID[:], msg.FundingPoint)
1✔
2389

2390
        case *lnwire.FundingSigned:
1✔
2391
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
1✔
2392

2393
        case *lnwire.ChannelReady:
1✔
2394
                return fmt.Sprintf("chan_id=%v, next_point=%x",
1✔
2395
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
1✔
2396

2397
        case *lnwire.Shutdown:
1✔
2398
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
1✔
2399
                        msg.Address[:])
1✔
2400

2401
        case *lnwire.ClosingComplete:
1✔
2402
                return fmt.Sprintf("chan_id=%v, fee_sat=%v, locktime=%v",
1✔
2403
                        msg.ChannelID, msg.FeeSatoshis, msg.LockTime)
1✔
2404

2405
        case *lnwire.ClosingSig:
1✔
2406
                return fmt.Sprintf("chan_id=%v", msg.ChannelID)
1✔
2407

2408
        case *lnwire.ClosingSigned:
1✔
2409
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
1✔
2410
                        msg.FeeSatoshis)
1✔
2411

2412
        case *lnwire.UpdateAddHTLC:
1✔
2413
                var blindingPoint []byte
1✔
2414
                msg.BlindingPoint.WhenSome(
1✔
2415
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
1✔
2416
                                *btcec.PublicKey]) {
2✔
2417

1✔
2418
                                blindingPoint = b.Val.SerializeCompressed()
1✔
2419
                        },
1✔
2420
                )
2421

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

2427
        case *lnwire.UpdateFailHTLC:
1✔
2428
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
1✔
2429
                        msg.ID, msg.Reason)
1✔
2430

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

2436
        case *lnwire.CommitSig:
1✔
2437
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
1✔
2438
                        len(msg.HtlcSigs))
1✔
2439

2440
        case *lnwire.RevokeAndAck:
1✔
2441
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
1✔
2442
                        msg.ChanID, msg.Revocation[:],
1✔
2443
                        msg.NextRevocationKey.SerializeCompressed())
1✔
2444

2445
        case *lnwire.UpdateFailMalformedHTLC:
1✔
2446
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
1✔
2447
                        msg.ChanID, msg.ID, msg.FailureCode)
1✔
2448

2449
        case *lnwire.Warning:
×
2450
                return fmt.Sprintf("%v", msg.Warning())
×
2451

2452
        case *lnwire.Error:
1✔
2453
                return fmt.Sprintf("%v", msg.Error())
1✔
2454

2455
        case *lnwire.AnnounceSignatures1:
1✔
2456
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
1✔
2457
                        msg.ShortChannelID.ToUint64())
1✔
2458

2459
        case *lnwire.ChannelAnnouncement1:
1✔
2460
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
1✔
2461
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
1✔
2462

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

2469
        case *lnwire.NodeAnnouncement:
1✔
2470
                return fmt.Sprintf("node=%x, update_time=%v",
1✔
2471
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
1✔
2472

2473
        case *lnwire.Ping:
×
2474
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
2475

2476
        case *lnwire.Pong:
×
2477
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
×
2478

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

2483
        case *lnwire.ChannelReestablish:
1✔
2484
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
1✔
2485
                        "remote_tail_height=%v", msg.ChanID,
1✔
2486
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
1✔
2487

2488
        case *lnwire.ReplyShortChanIDsEnd:
1✔
2489
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
1✔
2490
                        msg.Complete)
1✔
2491

2492
        case *lnwire.ReplyChannelRange:
1✔
2493
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
1✔
2494
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
1✔
2495
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
1✔
2496
                        msg.EncodingType)
1✔
2497

2498
        case *lnwire.QueryShortChanIDs:
1✔
2499
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
1✔
2500
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
1✔
2501

2502
        case *lnwire.QueryChannelRange:
1✔
2503
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
1✔
2504
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
1✔
2505
                        msg.LastBlockHeight())
1✔
2506

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

2513
        case *lnwire.Stfu:
1✔
2514
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
1✔
2515
                        msg.Initiator)
1✔
2516

2517
        case *lnwire.Custom:
1✔
2518
                return fmt.Sprintf("type=%d", msg.Type)
1✔
2519
        }
2520

2521
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2522
}
2523

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

2535
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
2✔
2536
                // Debug summary of message.
1✔
2537
                summary := messageSummary(msg)
1✔
2538
                if len(summary) > 0 {
2✔
2539
                        summary = "(" + summary + ")"
1✔
2540
                }
1✔
2541

2542
                preposition := "to"
1✔
2543
                if read {
2✔
2544
                        preposition = "from"
1✔
2545
                }
1✔
2546

2547
                var msgType string
1✔
2548
                if msg.MsgType() < lnwire.CustomTypeStart {
2✔
2549
                        msgType = msg.MsgType().String()
1✔
2550
                } else {
2✔
2551
                        msgType = "custom"
1✔
2552
                }
1✔
2553

2554
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
1✔
2555
                        msgType, summary, preposition, p)
1✔
2556
        }))
2557

2558
        prefix := "readMessage from peer"
1✔
2559
        if !read {
2✔
2560
                prefix = "writeMessage to peer"
1✔
2561
        }
1✔
2562

2563
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
1✔
2564
}
2565

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

2583
        noiseConn := p.cfg.Conn
1✔
2584

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

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

1✔
2601
                // Record the number of bytes written on the wire, if any.
1✔
2602
                if n > 0 {
2✔
2603
                        atomic.AddUint64(&p.bytesSent, uint64(n))
1✔
2604
                }
1✔
2605

2606
                return err
1✔
2607
        }
2608

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

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

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

2636
        return flushMsg()
1✔
2637
}
2638

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

2654
        var exitErr error
1✔
2655

1✔
2656
out:
1✔
2657
        for {
2✔
2658
                select {
1✔
2659
                case outMsg := <-p.sendQueue:
1✔
2660
                        // Record the time at which we first attempt to send the
1✔
2661
                        // message.
1✔
2662
                        startTime := time.Now()
1✔
2663

1✔
2664
                retry:
1✔
2665
                        // Write out the message to the socket. If a timeout
2666
                        // error is encountered, we will catch this and retry
2667
                        // after backing off in case the remote peer is just
2668
                        // slow to process messages from the wire.
2669
                        err := p.writeMessage(outMsg.msg)
1✔
2670
                        if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
1✔
2671
                                p.log.Debugf("Write timeout detected for "+
×
2672
                                        "peer, first write for message "+
×
2673
                                        "attempted %v ago",
×
2674
                                        time.Since(startTime))
×
2675

×
2676
                                // If we received a timeout error, this implies
×
2677
                                // that the message was buffered on the
×
2678
                                // connection successfully and that a flush was
×
2679
                                // attempted. We'll set the message to nil so
×
2680
                                // that on a subsequent pass we only try to
×
2681
                                // flush the buffered message, and forgo
×
2682
                                // reserializing or reencrypting it.
×
2683
                                outMsg.msg = nil
×
2684

×
2685
                                goto retry
×
2686
                        }
2687

2688
                        // The write succeeded, reset the idle timer to prevent
2689
                        // us from disconnecting the peer.
2690
                        if !idleTimer.Stop() {
1✔
2691
                                select {
×
2692
                                case <-idleTimer.C:
×
2693
                                default:
×
2694
                                }
2695
                        }
2696
                        idleTimer.Reset(idleTimeout)
1✔
2697

1✔
2698
                        // If the peer requested a synchronous write, respond
1✔
2699
                        // with the error.
1✔
2700
                        if outMsg.errChan != nil {
2✔
2701
                                outMsg.errChan <- err
1✔
2702
                        }
1✔
2703

2704
                        if err != nil {
1✔
2705
                                exitErr = fmt.Errorf("unable to write "+
×
2706
                                        "message: %v", err)
×
2707
                                break out
×
2708
                        }
2709

2710
                case <-p.cg.Done():
1✔
2711
                        exitErr = lnpeer.ErrPeerExiting
1✔
2712
                        break out
1✔
2713
                }
2714
        }
2715

2716
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2717
        // disconnect.
2718
        p.cg.WgDone()
1✔
2719

1✔
2720
        p.Disconnect(exitErr)
1✔
2721

1✔
2722
        p.log.Trace("writeHandler for peer done")
1✔
2723
}
2724

2725
// queueHandler is responsible for accepting messages from outside subsystems
2726
// to be eventually sent out on the wire by the writeHandler.
2727
//
2728
// NOTE: This method MUST be run as a goroutine.
2729
func (p *Brontide) queueHandler() {
1✔
2730
        defer p.cg.WgDone()
1✔
2731

1✔
2732
        // priorityMsgs holds an in order list of messages deemed high-priority
1✔
2733
        // to be added to the sendQueue. This predominately includes messages
1✔
2734
        // from the funding manager and htlcswitch.
1✔
2735
        priorityMsgs := list.New()
1✔
2736

1✔
2737
        // lazyMsgs holds an in order list of messages deemed low-priority to be
1✔
2738
        // added to the sendQueue only after all high-priority messages have
1✔
2739
        // been queued. This predominately includes messages from the gossiper.
1✔
2740
        lazyMsgs := list.New()
1✔
2741

1✔
2742
        for {
2✔
2743
                // Examine the front of the priority queue, if it is empty check
1✔
2744
                // the low priority queue.
1✔
2745
                elem := priorityMsgs.Front()
1✔
2746
                if elem == nil {
2✔
2747
                        elem = lazyMsgs.Front()
1✔
2748
                }
1✔
2749

2750
                if elem != nil {
2✔
2751
                        front := elem.Value.(outgoingMsg)
1✔
2752

1✔
2753
                        // There's an element on the queue, try adding
1✔
2754
                        // it to the sendQueue. We also watch for
1✔
2755
                        // messages on the outgoingQueue, in case the
1✔
2756
                        // writeHandler cannot accept messages on the
1✔
2757
                        // sendQueue.
1✔
2758
                        select {
1✔
2759
                        case p.sendQueue <- front:
1✔
2760
                                if front.priority {
2✔
2761
                                        priorityMsgs.Remove(elem)
1✔
2762
                                } else {
2✔
2763
                                        lazyMsgs.Remove(elem)
1✔
2764
                                }
1✔
2765
                        case msg := <-p.outgoingQueue:
1✔
2766
                                if msg.priority {
2✔
2767
                                        priorityMsgs.PushBack(msg)
1✔
2768
                                } else {
2✔
2769
                                        lazyMsgs.PushBack(msg)
1✔
2770
                                }
1✔
2771
                        case <-p.cg.Done():
×
2772
                                return
×
2773
                        }
2774
                } else {
1✔
2775
                        // If there weren't any messages to send to the
1✔
2776
                        // writeHandler, then we'll accept a new message
1✔
2777
                        // into the queue from outside sub-systems.
1✔
2778
                        select {
1✔
2779
                        case msg := <-p.outgoingQueue:
1✔
2780
                                if msg.priority {
2✔
2781
                                        priorityMsgs.PushBack(msg)
1✔
2782
                                } else {
2✔
2783
                                        lazyMsgs.PushBack(msg)
1✔
2784
                                }
1✔
2785
                        case <-p.cg.Done():
1✔
2786
                                return
1✔
2787
                        }
2788
                }
2789
        }
2790
}
2791

2792
// PingTime returns the estimated ping time to the peer in microseconds.
2793
func (p *Brontide) PingTime() int64 {
1✔
2794
        return p.pingManager.GetPingTimeMicroSeconds()
1✔
2795
}
1✔
2796

2797
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2798
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2799
// or failed to write, and nil otherwise.
2800
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
1✔
2801
        p.queue(true, msg, errChan)
1✔
2802
}
1✔
2803

2804
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2805
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2806
// queue or failed to write, and nil otherwise.
2807
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
1✔
2808
        p.queue(false, msg, errChan)
1✔
2809
}
1✔
2810

2811
// queue sends a given message to the queueHandler using the passed priority. If
2812
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2813
// failed to write, and nil otherwise.
2814
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2815
        errChan chan error) {
1✔
2816

1✔
2817
        select {
1✔
2818
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
1✔
2819
        case <-p.cg.Done():
×
2820
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
×
2821
                        spew.Sdump(msg))
×
2822
                if errChan != nil {
×
2823
                        errChan <- lnpeer.ErrPeerExiting
×
2824
                }
×
2825
        }
2826
}
2827

2828
// ChannelSnapshots returns a slice of channel snapshots detailing all
2829
// currently active channels maintained with the remote peer.
2830
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
1✔
2831
        snapshots := make(
1✔
2832
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
1✔
2833
        )
1✔
2834

1✔
2835
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
1✔
2836
                activeChan *lnwallet.LightningChannel) error {
2✔
2837

1✔
2838
                // If the activeChan is nil, then we skip it as the channel is
1✔
2839
                // pending.
1✔
2840
                if activeChan == nil {
2✔
2841
                        return nil
1✔
2842
                }
1✔
2843

2844
                // We'll only return a snapshot for channels that are
2845
                // *immediately* available for routing payments over.
2846
                if activeChan.RemoteNextRevocation() == nil {
2✔
2847
                        return nil
1✔
2848
                }
1✔
2849

2850
                snapshot := activeChan.StateSnapshot()
1✔
2851
                snapshots = append(snapshots, snapshot)
1✔
2852

1✔
2853
                return nil
1✔
2854
        })
2855

2856
        return snapshots
1✔
2857
}
2858

2859
// genDeliveryScript returns a new script to be used to send our funds to in
2860
// the case of a cooperative channel close negotiation.
2861
func (p *Brontide) genDeliveryScript() ([]byte, error) {
1✔
2862
        // We'll send a normal p2wkh address unless we've negotiated the
1✔
2863
        // shutdown-any-segwit feature.
1✔
2864
        addrType := lnwallet.WitnessPubKey
1✔
2865
        if p.taprootShutdownAllowed() {
2✔
2866
                addrType = lnwallet.TaprootPubkey
1✔
2867
        }
1✔
2868

2869
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
1✔
2870
                addrType, false, lnwallet.DefaultAccountName,
1✔
2871
        )
1✔
2872
        if err != nil {
1✔
2873
                return nil, err
×
2874
        }
×
2875
        p.log.Infof("Delivery addr for channel close: %v",
1✔
2876
                deliveryAddr)
1✔
2877

1✔
2878
        return txscript.PayToAddrScript(deliveryAddr)
1✔
2879
}
2880

2881
// channelManager is goroutine dedicated to handling all requests/signals
2882
// pertaining to the opening, cooperative closing, and force closing of all
2883
// channels maintained with the remote peer.
2884
//
2885
// NOTE: This method MUST be run as a goroutine.
2886
func (p *Brontide) channelManager() {
1✔
2887
        defer p.cg.WgDone()
1✔
2888

1✔
2889
        // reenableTimeout will fire once after the configured channel status
1✔
2890
        // interval has elapsed. This will trigger us to sign new channel
1✔
2891
        // updates and broadcast them with the "disabled" flag unset.
1✔
2892
        reenableTimeout := time.After(p.cfg.ChanActiveTimeout)
1✔
2893

1✔
2894
out:
1✔
2895
        for {
2✔
2896
                select {
1✔
2897
                // A new pending channel has arrived which means we are about
2898
                // to complete a funding workflow and is waiting for the final
2899
                // `ChannelReady` messages to be exchanged. We will add this
2900
                // channel to the `activeChannels` with a nil value to indicate
2901
                // this is a pending channel.
2902
                case req := <-p.newPendingChannel:
1✔
2903
                        p.handleNewPendingChannel(req)
1✔
2904

2905
                // A new channel has arrived which means we've just completed a
2906
                // funding workflow. We'll initialize the necessary local
2907
                // state, and notify the htlc switch of a new link.
2908
                case req := <-p.newActiveChannel:
1✔
2909
                        p.handleNewActiveChannel(req)
1✔
2910

2911
                // The funding flow for a pending channel is failed, we will
2912
                // remove it from Brontide.
2913
                case req := <-p.removePendingChannel:
1✔
2914
                        p.handleRemovePendingChannel(req)
1✔
2915

2916
                // We've just received a local request to close an active
2917
                // channel. It will either kick of a cooperative channel
2918
                // closure negotiation, or be a notification of a breached
2919
                // contract that should be abandoned.
2920
                case req := <-p.localCloseChanReqs:
1✔
2921
                        p.handleLocalCloseReq(req)
1✔
2922

2923
                // We've received a link failure from a link that was added to
2924
                // the switch. This will initiate the teardown of the link, and
2925
                // initiate any on-chain closures if necessary.
2926
                case failure := <-p.linkFailures:
1✔
2927
                        p.handleLinkFailure(failure)
1✔
2928

2929
                // We've received a new cooperative channel closure related
2930
                // message from the remote peer, we'll use this message to
2931
                // advance the chan closer state machine.
2932
                case closeMsg := <-p.chanCloseMsgs:
1✔
2933
                        p.handleCloseMsg(closeMsg)
1✔
2934

2935
                // The channel reannounce delay has elapsed, broadcast the
2936
                // reenabled channel updates to the network. This should only
2937
                // fire once, so we set the reenableTimeout channel to nil to
2938
                // mark it for garbage collection. If the peer is torn down
2939
                // before firing, reenabling will not be attempted.
2940
                // TODO(conner): consolidate reenables timers inside chan status
2941
                // manager
2942
                case <-reenableTimeout:
1✔
2943
                        p.reenableActiveChannels()
1✔
2944

1✔
2945
                        // Since this channel will never fire again during the
1✔
2946
                        // lifecycle of the peer, we nil the channel to mark it
1✔
2947
                        // eligible for garbage collection, and make this
1✔
2948
                        // explicitly ineligible to receive in future calls to
1✔
2949
                        // select. This also shaves a few CPU cycles since the
1✔
2950
                        // select will ignore this case entirely.
1✔
2951
                        reenableTimeout = nil
1✔
2952

1✔
2953
                        // Once the reenabling is attempted, we also cancel the
1✔
2954
                        // channel event subscription to free up the overflow
1✔
2955
                        // queue used in channel notifier.
1✔
2956
                        //
1✔
2957
                        // NOTE: channelEventClient will be nil if the
1✔
2958
                        // reenableTimeout is greater than 1 minute.
1✔
2959
                        if p.channelEventClient != nil {
2✔
2960
                                p.channelEventClient.Cancel()
1✔
2961
                        }
1✔
2962

2963
                case <-p.cg.Done():
1✔
2964
                        // As, we've been signalled to exit, we'll reset all
1✔
2965
                        // our active channel back to their default state.
1✔
2966
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
1✔
2967
                                lc *lnwallet.LightningChannel) error {
2✔
2968

1✔
2969
                                // Exit if the channel is nil as it's a pending
1✔
2970
                                // channel.
1✔
2971
                                if lc == nil {
2✔
2972
                                        return nil
1✔
2973
                                }
1✔
2974

2975
                                lc.ResetState()
1✔
2976

1✔
2977
                                return nil
1✔
2978
                        })
2979

2980
                        break out
1✔
2981
                }
2982
        }
2983
}
2984

2985
// reenableActiveChannels searches the index of channels maintained with this
2986
// peer, and reenables each public, non-pending channel. This is done at the
2987
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
2988
// No message will be sent if the channel is already enabled.
2989
func (p *Brontide) reenableActiveChannels() {
1✔
2990
        // First, filter all known channels with this peer for ones that are
1✔
2991
        // both public and not pending.
1✔
2992
        activePublicChans := p.filterChannelsToEnable()
1✔
2993

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

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

1✔
3003
                switch {
1✔
3004
                // No error occurred, continue to request the next channel.
3005
                case err == nil:
1✔
3006
                        continue
1✔
3007

3008
                // Cannot auto enable a manually disabled channel so we do
3009
                // nothing but proceed to the next channel.
3010
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
1✔
3011
                        p.log.Debugf("Channel(%v) was manually disabled, "+
1✔
3012
                                "ignoring automatic enable request", chanPoint)
1✔
3013

1✔
3014
                        continue
1✔
3015

3016
                // If the channel is reported as inactive, we will give it
3017
                // another chance. When handling the request, ChanStatusManager
3018
                // will check whether the link is active or not. One of the
3019
                // conditions is whether the link has been marked as
3020
                // reestablished, which happens inside a goroutine(htlcManager)
3021
                // after the link is started. And we may get a false negative
3022
                // saying the link is not active because that goroutine hasn't
3023
                // reached the line to mark the reestablishment. Thus we give
3024
                // it a second chance to send the request.
3025
                case errors.Is(err, netann.ErrEnableInactiveChan):
×
3026
                        // If we don't have a client created, it means we
×
3027
                        // shouldn't retry enabling the channel.
×
3028
                        if p.channelEventClient == nil {
×
3029
                                p.log.Errorf("Channel(%v) request enabling "+
×
3030
                                        "failed due to inactive link",
×
3031
                                        chanPoint)
×
3032

×
3033
                                continue
×
3034
                        }
3035

3036
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
3037
                                "ChanStatusManager reported inactive, retrying")
×
3038

×
3039
                        // Add the channel to the retry map.
×
3040
                        retryChans[chanPoint] = struct{}{}
×
3041
                }
3042
        }
3043

3044
        // Retry the channels if we have any.
3045
        if len(retryChans) != 0 {
1✔
3046
                p.retryRequestEnable(retryChans)
×
3047
        }
×
3048
}
3049

3050
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
3051
// for the target channel ID. If the channel isn't active an error is returned.
3052
// Otherwise, either an existing state machine will be returned, or a new one
3053
// will be created.
3054
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
3055
        *chanCloserFsm, error) {
1✔
3056

1✔
3057
        chanCloser, found := p.activeChanCloses.Load(chanID)
1✔
3058
        if found {
2✔
3059
                // An entry will only be found if the closer has already been
1✔
3060
                // created for a non-pending channel or for a channel that had
1✔
3061
                // previously started the shutdown process but the connection
1✔
3062
                // was restarted.
1✔
3063
                return &chanCloser, nil
1✔
3064
        }
1✔
3065

3066
        // First, we'll ensure that we actually know of the target channel. If
3067
        // not, we'll ignore this message.
3068
        channel, ok := p.activeChannels.Load(chanID)
1✔
3069

1✔
3070
        // If the channel isn't in the map or the channel is nil, return
1✔
3071
        // ErrChannelNotFound as the channel is pending.
1✔
3072
        if !ok || channel == nil {
2✔
3073
                return nil, ErrChannelNotFound
1✔
3074
        }
1✔
3075

3076
        // We'll create a valid closing state machine in order to respond to
3077
        // the initiated cooperative channel closure. First, we set the
3078
        // delivery script that our funds will be paid out to. If an upfront
3079
        // shutdown script was set, we will use it. Otherwise, we get a fresh
3080
        // delivery script.
3081
        //
3082
        // TODO: Expose option to allow upfront shutdown script from watch-only
3083
        // accounts.
3084
        deliveryScript := channel.LocalUpfrontShutdownScript()
1✔
3085
        if len(deliveryScript) == 0 {
2✔
3086
                var err error
1✔
3087
                deliveryScript, err = p.genDeliveryScript()
1✔
3088
                if err != nil {
1✔
3089
                        p.log.Errorf("unable to gen delivery script: %v",
×
3090
                                err)
×
3091
                        return nil, fmt.Errorf("close addr unavailable")
×
3092
                }
×
3093
        }
3094

3095
        // In order to begin fee negotiations, we'll first compute our target
3096
        // ideal fee-per-kw.
3097
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
1✔
3098
                p.cfg.CoopCloseTargetConfs,
1✔
3099
        )
1✔
3100
        if err != nil {
1✔
3101
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3102
                return nil, fmt.Errorf("unable to estimate fee")
×
3103
        }
×
3104

3105
        addr, err := p.addrWithInternalKey(deliveryScript)
1✔
3106
        if err != nil {
1✔
3107
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3108
        }
×
3109
        negotiateChanCloser, err := p.createChanCloser(
1✔
3110
                channel, addr, feePerKw, nil, lntypes.Remote,
1✔
3111
        )
1✔
3112
        if err != nil {
1✔
3113
                p.log.Errorf("unable to create chan closer: %v", err)
×
3114
                return nil, fmt.Errorf("unable to create chan closer")
×
3115
        }
×
3116

3117
        chanCloser = makeNegotiateCloser(negotiateChanCloser)
1✔
3118

1✔
3119
        p.activeChanCloses.Store(chanID, chanCloser)
1✔
3120

1✔
3121
        return &chanCloser, nil
1✔
3122
}
3123

3124
// filterChannelsToEnable filters a list of channels to be enabled upon start.
3125
// The filtered channels are active channels that's neither private nor
3126
// pending.
3127
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
1✔
3128
        var activePublicChans []wire.OutPoint
1✔
3129

1✔
3130
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
1✔
3131
                lnChan *lnwallet.LightningChannel) bool {
2✔
3132

1✔
3133
                // If the lnChan is nil, continue as this is a pending channel.
1✔
3134
                if lnChan == nil {
1✔
UNCOV
3135
                        return true
×
UNCOV
3136
                }
×
3137

3138
                dbChan := lnChan.State()
1✔
3139
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
1✔
3140
                if !isPublic || dbChan.IsPending {
1✔
3141
                        return true
×
3142
                }
×
3143

3144
                // We'll also skip any channels added during this peer's
3145
                // lifecycle since they haven't waited out the timeout. Their
3146
                // first announcement will be enabled, and the chan status
3147
                // manager will begin monitoring them passively since they exist
3148
                // in the database.
3149
                if _, ok := p.addedChannels.Load(chanID); ok {
2✔
3150
                        return true
1✔
3151
                }
1✔
3152

3153
                activePublicChans = append(
1✔
3154
                        activePublicChans, dbChan.FundingOutpoint,
1✔
3155
                )
1✔
3156

1✔
3157
                return true
1✔
3158
        })
3159

3160
        return activePublicChans
1✔
3161
}
3162

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

×
3170
        // retryEnable is a helper closure that sends an enable request and
×
3171
        // removes the channel from the map if it's matched.
×
3172
        retryEnable := func(chanPoint wire.OutPoint) error {
×
3173
                // If this is an active channel event, check whether it's in
×
3174
                // our targeted channels map.
×
3175
                _, found := activeChans[chanPoint]
×
3176

×
3177
                // If this channel is irrelevant, return nil so the loop can
×
3178
                // jump to next iteration.
×
3179
                if !found {
×
3180
                        return nil
×
3181
                }
×
3182

3183
                // Otherwise we've just received an active signal for a channel
3184
                // that's previously failed to be enabled, we send the request
3185
                // again.
3186
                //
3187
                // We only give the channel one more shot, so we delete it from
3188
                // our map first to keep it from being attempted again.
3189
                delete(activeChans, chanPoint)
×
3190

×
3191
                // Send the request.
×
3192
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3193
                if err != nil {
×
3194
                        return fmt.Errorf("request enabling channel %v "+
×
3195
                                "failed: %w", chanPoint, err)
×
3196
                }
×
3197

3198
                return nil
×
3199
        }
3200

3201
        for {
×
3202
                // If activeChans is empty, we've done processing all the
×
3203
                // channels.
×
3204
                if len(activeChans) == 0 {
×
3205
                        p.log.Debug("Finished retry enabling channels")
×
3206
                        return
×
3207
                }
×
3208

3209
                select {
×
3210
                // A new event has been sent by the ChannelNotifier. We now
3211
                // check whether it's an active or inactive channel event.
3212
                case e := <-p.channelEventClient.Updates():
×
3213
                        // If this is an active channel event, try enable the
×
3214
                        // channel then jump to the next iteration.
×
3215
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
3216
                        if ok {
×
3217
                                chanPoint := *active.ChannelPoint
×
3218

×
3219
                                // If we received an error for this particular
×
3220
                                // channel, we log an error and won't quit as
×
3221
                                // we still want to retry other channels.
×
3222
                                if err := retryEnable(chanPoint); err != nil {
×
3223
                                        p.log.Errorf("Retry failed: %v", err)
×
3224
                                }
×
3225

3226
                                continue
×
3227
                        }
3228

3229
                        // Otherwise check for inactive link event, and jump to
3230
                        // next iteration if it's not.
3231
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3232
                        if !ok {
×
3233
                                continue
×
3234
                        }
3235

3236
                        // Found an inactive link event, if this is our
3237
                        // targeted channel, remove it from our map.
3238
                        chanPoint := *inactive.ChannelPoint
×
3239
                        _, found := activeChans[chanPoint]
×
3240
                        if !found {
×
3241
                                continue
×
3242
                        }
3243

3244
                        delete(activeChans, chanPoint)
×
3245
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3246
                                "inactive link event", chanPoint)
×
3247

3248
                case <-p.cg.Done():
×
3249
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3250
                        return
×
3251
                }
3252
        }
3253
}
3254

3255
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3256
// a suitable script to close out to. This may be nil if neither script is
3257
// set. If both scripts are set, this function will error if they do not match.
3258
func chooseDeliveryScript(upfront, requested lnwire.DeliveryAddress,
3259
        genDeliveryScript func() ([]byte, error),
3260
) (lnwire.DeliveryAddress, error) {
1✔
3261

1✔
3262
        switch {
1✔
3263
        // If no script was provided, then we'll generate a new delivery script.
3264
        case len(upfront) == 0 && len(requested) == 0:
1✔
3265
                return genDeliveryScript()
1✔
3266

3267
        // If no upfront shutdown script was provided, return the user
3268
        // requested address (which may be nil).
3269
        case len(upfront) == 0:
1✔
3270
                return requested, nil
1✔
3271

3272
        // If an upfront shutdown script was provided, and the user did not
3273
        // request a custom shutdown script, return the upfront address.
3274
        case len(requested) == 0:
1✔
3275
                return upfront, nil
1✔
3276

3277
        // If both an upfront shutdown script and a custom close script were
3278
        // provided, error if the user provided shutdown script does not match
3279
        // the upfront shutdown script (because closing out to a different
3280
        // script would violate upfront shutdown).
UNCOV
3281
        case !bytes.Equal(upfront, requested):
×
UNCOV
3282
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
×
3283

3284
        // The user requested script matches the upfront shutdown script, so we
3285
        // can return it without error.
UNCOV
3286
        default:
×
UNCOV
3287
                return upfront, nil
×
3288
        }
3289
}
3290

3291
// restartCoopClose checks whether we need to restart the cooperative close
3292
// process for a given channel.
3293
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3294
        *lnwire.Shutdown, error) {
1✔
3295

1✔
3296
        isTaprootChan := lnChan.ChanType().IsTaproot()
1✔
3297

1✔
3298
        // If this channel has status ChanStatusCoopBroadcasted and does not
1✔
3299
        // have a closing transaction, then the cooperative close process was
1✔
3300
        // started but never finished. We'll re-create the chanCloser state
1✔
3301
        // machine and resend Shutdown. BOLT#2 requires that we retransmit
1✔
3302
        // Shutdown exactly, but doing so would mean persisting the RPC
1✔
3303
        // provided close script. Instead use the LocalUpfrontShutdownScript
1✔
3304
        // or generate a script.
1✔
3305
        c := lnChan.State()
1✔
3306
        _, err := c.BroadcastedCooperative()
1✔
3307
        if err != nil && err != channeldb.ErrNoCloseTx {
1✔
3308
                // An error other than ErrNoCloseTx was encountered.
×
3309
                return nil, err
×
3310
        } else if err == nil && !p.rbfCoopCloseAllowed() {
1✔
3311
                // This is a channel that doesn't support RBF coop close, and it
×
3312
                // already had a coop close txn broadcast. As a result, we can
×
3313
                // just exit here as all we can do is wait for it to confirm.
×
3314
                return nil, nil
×
3315
        }
×
3316

3317
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
1✔
3318

1✔
3319
        var deliveryScript []byte
1✔
3320

1✔
3321
        shutdownInfo, err := c.ShutdownInfo()
1✔
3322
        switch {
1✔
3323
        // We have previously stored the delivery script that we need to use
3324
        // in the shutdown message. Re-use this script.
3325
        case err == nil:
1✔
3326
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
2✔
3327
                        deliveryScript = info.DeliveryScript.Val
1✔
3328
                })
1✔
3329

3330
        // An error other than ErrNoShutdownInfo was returned
3331
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3332
                return nil, err
×
3333

3334
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3335
                deliveryScript = c.LocalShutdownScript
×
3336
                if len(deliveryScript) == 0 {
×
3337
                        var err error
×
3338
                        deliveryScript, err = p.genDeliveryScript()
×
3339
                        if err != nil {
×
3340
                                p.log.Errorf("unable to gen delivery script: "+
×
3341
                                        "%v", err)
×
3342

×
3343
                                return nil, fmt.Errorf("close addr unavailable")
×
3344
                        }
×
3345
                }
3346
        }
3347

3348
        // If the new RBF co-op close is negotiated, then we'll init and start
3349
        // that state machine, skipping the steps for the negotiate machine
3350
        // below. We don't support this close type for taproot channels though.
3351
        if p.rbfCoopCloseAllowed() && !isTaprootChan {
2✔
3352
                _, err := p.initRbfChanCloser(lnChan)
1✔
3353
                if err != nil {
1✔
3354
                        return nil, fmt.Errorf("unable to init rbf chan "+
×
3355
                                "closer during restart: %w", err)
×
3356
                }
×
3357

3358
                shutdownDesc := fn.MapOption(
1✔
3359
                        newRestartShutdownInit,
1✔
3360
                )(shutdownInfo)
1✔
3361

1✔
3362
                err = p.startRbfChanCloser(
1✔
3363
                        fn.FlattenOption(shutdownDesc), lnChan.ChannelPoint(),
1✔
3364
                )
1✔
3365

1✔
3366
                return nil, err
1✔
3367
        }
3368

3369
        // Compute an ideal fee.
3370
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
3371
                p.cfg.CoopCloseTargetConfs,
×
3372
        )
×
3373
        if err != nil {
×
3374
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3375
                return nil, fmt.Errorf("unable to estimate fee")
×
3376
        }
×
3377

3378
        // Determine whether we or the peer are the initiator of the coop
3379
        // close attempt by looking at the channel's status.
3380
        closingParty := lntypes.Remote
×
3381
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3382
                closingParty = lntypes.Local
×
3383
        }
×
3384

3385
        addr, err := p.addrWithInternalKey(deliveryScript)
×
3386
        if err != nil {
×
3387
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3388
        }
×
3389
        chanCloser, err := p.createChanCloser(
×
3390
                lnChan, addr, feePerKw, nil, closingParty,
×
3391
        )
×
3392
        if err != nil {
×
3393
                p.log.Errorf("unable to create chan closer: %v", err)
×
3394
                return nil, fmt.Errorf("unable to create chan closer")
×
3395
        }
×
3396

3397
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
×
3398

×
3399
        // Create the Shutdown message.
×
3400
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3401
        if err != nil {
×
3402
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3403
                p.activeChanCloses.Delete(chanID)
×
3404
                return nil, err
×
3405
        }
×
3406

3407
        return shutdownMsg, nil
×
3408
}
3409

3410
// createChanCloser constructs a ChanCloser from the passed parameters and is
3411
// used to de-duplicate code.
3412
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3413
        deliveryScript *chancloser.DeliveryAddrWithKey,
3414
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3415
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
1✔
3416

1✔
3417
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
1✔
3418
        if err != nil {
1✔
3419
                p.log.Errorf("unable to obtain best block: %v", err)
×
3420
                return nil, fmt.Errorf("cannot obtain best block")
×
3421
        }
×
3422

3423
        // The req will only be set if we initiated the co-op closing flow.
3424
        var maxFee chainfee.SatPerKWeight
1✔
3425
        if req != nil {
2✔
3426
                maxFee = req.MaxFee
1✔
3427
        }
1✔
3428

3429
        chanCloser := chancloser.NewChanCloser(
1✔
3430
                chancloser.ChanCloseCfg{
1✔
3431
                        Channel:      channel,
1✔
3432
                        MusigSession: NewMusigChanCloser(channel),
1✔
3433
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
1✔
3434
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
1✔
3435
                        AuxCloser:    p.cfg.AuxChanCloser,
1✔
3436
                        DisableChannel: func(op wire.OutPoint) error {
2✔
3437
                                return p.cfg.ChanStatusMgr.RequestDisable(
1✔
3438
                                        op, false,
1✔
3439
                                )
1✔
3440
                        },
1✔
3441
                        MaxFee: maxFee,
3442
                        Disconnect: func() error {
×
3443
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
3444
                        },
×
3445
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3446
                },
3447
                *deliveryScript,
3448
                fee,
3449
                uint32(startingHeight),
3450
                req,
3451
                closer,
3452
        )
3453

3454
        return chanCloser, nil
1✔
3455
}
3456

3457
// initNegotiateChanCloser initializes the channel closer for a channel that is
3458
// using the original "negotiation" based protocol. This path is used when
3459
// we're the one initiating the channel close.
3460
//
3461
// TODO(roasbeef): can make a MsgEndpoint for existing handling logic to
3462
// further abstract.
3463
func (p *Brontide) initNegotiateChanCloser(req *htlcswitch.ChanClose,
3464
        channel *lnwallet.LightningChannel) error {
1✔
3465

1✔
3466
        // First, we'll choose a delivery address that we'll use to send the
1✔
3467
        // funds to in the case of a successful negotiation.
1✔
3468

1✔
3469
        // An upfront shutdown and user provided script are both optional, but
1✔
3470
        // must be equal if both set  (because we cannot serve a request to
1✔
3471
        // close out to a script which violates upfront shutdown). Get the
1✔
3472
        // appropriate address to close out to (which may be nil if neither are
1✔
3473
        // set) and error if they are both set and do not match.
1✔
3474
        deliveryScript, err := chooseDeliveryScript(
1✔
3475
                channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
1✔
3476
                p.genDeliveryScript,
1✔
3477
        )
1✔
3478
        if err != nil {
1✔
UNCOV
3479
                return fmt.Errorf("cannot close channel %v: %w",
×
UNCOV
3480
                        req.ChanPoint, err)
×
UNCOV
3481
        }
×
3482

3483
        addr, err := p.addrWithInternalKey(deliveryScript)
1✔
3484
        if err != nil {
1✔
3485
                return fmt.Errorf("unable to parse addr for channel "+
×
3486
                        "%v: %w", req.ChanPoint, err)
×
3487
        }
×
3488

3489
        chanCloser, err := p.createChanCloser(
1✔
3490
                channel, addr, req.TargetFeePerKw, req, lntypes.Local,
1✔
3491
        )
1✔
3492
        if err != nil {
1✔
3493
                return fmt.Errorf("unable to make chan closer: %w", err)
×
3494
        }
×
3495

3496
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
1✔
3497
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
1✔
3498

1✔
3499
        // Finally, we'll initiate the channel shutdown within the
1✔
3500
        // chanCloser, and send the shutdown message to the remote
1✔
3501
        // party to kick things off.
1✔
3502
        shutdownMsg, err := chanCloser.ShutdownChan()
1✔
3503
        if err != nil {
1✔
3504
                // As we were unable to shutdown the channel, we'll return it
×
3505
                // back to its normal state.
×
3506
                defer channel.ResetState()
×
3507

×
3508
                p.activeChanCloses.Delete(chanID)
×
3509

×
3510
                return fmt.Errorf("unable to shutdown channel: %w", err)
×
3511
        }
×
3512

3513
        link := p.fetchLinkFromKeyAndCid(chanID)
1✔
3514
        if link == nil {
1✔
3515
                // If the link is nil then it means it was already removed from
×
3516
                // the switch or it never existed in the first place. The
×
3517
                // latter case is handled at the beginning of this function, so
×
3518
                // in the case where it has already been removed, we can skip
×
3519
                // adding the commit hook to queue a Shutdown message.
×
3520
                p.log.Warnf("link not found during attempted closure: "+
×
3521
                        "%v", chanID)
×
3522
                return nil
×
3523
        }
×
3524

3525
        if !link.DisableAdds(htlcswitch.Outgoing) {
1✔
3526
                p.log.Warnf("Outgoing link adds already "+
×
3527
                        "disabled: %v", link.ChanID())
×
3528
        }
×
3529

3530
        link.OnCommitOnce(htlcswitch.Outgoing, func() {
2✔
3531
                p.queueMsg(shutdownMsg, nil)
1✔
3532
        })
1✔
3533

3534
        return nil
1✔
3535
}
3536

3537
// chooseAddr returns the provided address if it is non-zero length, otherwise
3538
// None.
3539
func chooseAddr(addr lnwire.DeliveryAddress) fn.Option[lnwire.DeliveryAddress] {
1✔
3540
        if len(addr) == 0 {
2✔
3541
                return fn.None[lnwire.DeliveryAddress]()
1✔
3542
        }
1✔
3543

3544
        return fn.Some(addr)
×
3545
}
3546

3547
// observeRbfCloseUpdates observes the channel for any updates that may
3548
// indicate that a new txid has been broadcasted, or the channel fully closed
3549
// on chain.
3550
func (p *Brontide) observeRbfCloseUpdates(chanCloser *chancloser.RbfChanCloser,
3551
        closeReq *htlcswitch.ChanClose,
3552
        coopCloseStates chancloser.RbfStateSub) {
1✔
3553

1✔
3554
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
1✔
3555
        defer chanCloser.RemoveStateSub(coopCloseStates)
1✔
3556

1✔
3557
        var (
1✔
3558
                lastTxids    lntypes.Dual[chainhash.Hash]
1✔
3559
                lastFeeRates lntypes.Dual[chainfee.SatPerVByte]
1✔
3560
        )
1✔
3561

1✔
3562
        maybeNotifyTxBroadcast := func(state chancloser.AsymmetricPeerState,
1✔
3563
                party lntypes.ChannelParty) {
2✔
3564

1✔
3565
                // First, check to see if we have an error to report to the
1✔
3566
                // caller. If so, then we''ll return that error and exit, as the
1✔
3567
                // stream will exit as well.
1✔
3568
                if closeErr, ok := state.(*chancloser.CloseErr); ok {
2✔
3569
                        // We hit an error during the last state transition, so
1✔
3570
                        // we'll extract the error then send it to the
1✔
3571
                        // user.
1✔
3572
                        err := closeErr.Err()
1✔
3573

1✔
3574
                        peerLog.Warnf("ChannelPoint(%v): encountered close "+
1✔
3575
                                "err: %v", closeReq.ChanPoint, err)
1✔
3576

1✔
3577
                        select {
1✔
3578
                        case closeReq.Err <- err:
1✔
3579
                        case <-closeReq.Ctx.Done():
×
3580
                        case <-p.cg.Done():
×
3581
                        }
3582

3583
                        return
1✔
3584
                }
3585

3586
                closePending, ok := state.(*chancloser.ClosePending)
1✔
3587

1✔
3588
                // If this isn't the close pending state, we aren't at the
1✔
3589
                // terminal state yet.
1✔
3590
                if !ok {
2✔
3591
                        return
1✔
3592
                }
1✔
3593

3594
                // Only notify if the fee rate is greater.
3595
                newFeeRate := closePending.FeeRate
1✔
3596
                lastFeeRate := lastFeeRates.GetForParty(party)
1✔
3597
                if newFeeRate <= lastFeeRate {
2✔
3598
                        peerLog.Debugf("ChannelPoint(%v): remote party made "+
1✔
3599
                                "update for fee rate %v, but we already have "+
1✔
3600
                                "a higher fee rate of %v", closeReq.ChanPoint,
1✔
3601
                                newFeeRate, lastFeeRate)
1✔
3602

1✔
3603
                        return
1✔
3604
                }
1✔
3605

3606
                feeRate := closePending.FeeRate
1✔
3607
                lastFeeRates.SetForParty(party, feeRate)
1✔
3608

1✔
3609
                // At this point, we'll have a txid that we can use to notify
1✔
3610
                // the client, but only if it's different from the last one we
1✔
3611
                // sent. If the user attempted to bump, but was rejected due to
1✔
3612
                // RBF, then we'll send a redundant update.
1✔
3613
                closingTxid := closePending.CloseTx.TxHash()
1✔
3614
                lastTxid := lastTxids.GetForParty(party)
1✔
3615
                if closeReq != nil && closingTxid != lastTxid {
2✔
3616
                        select {
1✔
3617
                        case closeReq.Updates <- &PendingUpdate{
3618
                                Txid:        closingTxid[:],
3619
                                FeePerVbyte: fn.Some(closePending.FeeRate),
3620
                                IsLocalCloseTx: fn.Some(
3621
                                        party == lntypes.Local,
3622
                                ),
3623
                        }:
1✔
3624

3625
                        case <-closeReq.Ctx.Done():
×
3626
                                return
×
3627

3628
                        case <-p.cg.Done():
×
3629
                                return
×
3630
                        }
3631
                }
3632

3633
                lastTxids.SetForParty(party, closingTxid)
1✔
3634
        }
3635

3636
        peerLog.Infof("Observing RBF close updates for channel %v",
1✔
3637
                closeReq.ChanPoint)
1✔
3638

1✔
3639
        // We'll consume each new incoming state to send out the appropriate
1✔
3640
        // RPC update.
1✔
3641
        for {
2✔
3642
                select {
1✔
3643
                case newState := <-newStateChan:
1✔
3644

1✔
3645
                        switch closeState := newState.(type) {
1✔
3646
                        // Once we've reached the state of pending close, we
3647
                        // have a txid that we broadcasted.
3648
                        case *chancloser.ClosingNegotiation:
1✔
3649
                                peerState := closeState.PeerState
1✔
3650

1✔
3651
                                // Each side may have gained a new co-op close
1✔
3652
                                // tx, so we'll examine both to see if they've
1✔
3653
                                // changed.
1✔
3654
                                maybeNotifyTxBroadcast(
1✔
3655
                                        peerState.GetForParty(lntypes.Local),
1✔
3656
                                        lntypes.Local,
1✔
3657
                                )
1✔
3658
                                maybeNotifyTxBroadcast(
1✔
3659
                                        peerState.GetForParty(lntypes.Remote),
1✔
3660
                                        lntypes.Remote,
1✔
3661
                                )
1✔
3662

3663
                        // Otherwise, if we're transition to CloseFin, then we
3664
                        // know that we're done.
3665
                        case *chancloser.CloseFin:
1✔
3666
                                // To clean up, we'll remove the chan closer
1✔
3667
                                // from the active map, and send the final
1✔
3668
                                // update to the client.
1✔
3669
                                closingTxid := closeState.ConfirmedTx.TxHash()
1✔
3670
                                if closeReq != nil {
2✔
3671
                                        closeReq.Updates <- &ChannelCloseUpdate{
1✔
3672
                                                ClosingTxid: closingTxid[:],
1✔
3673
                                                Success:     true,
1✔
3674
                                        }
1✔
3675
                                }
1✔
3676
                                chanID := lnwire.NewChanIDFromOutPoint(
1✔
3677
                                        *closeReq.ChanPoint,
1✔
3678
                                )
1✔
3679
                                p.activeChanCloses.Delete(chanID)
1✔
3680

1✔
3681
                                return
1✔
3682
                        }
3683

3684
                case <-closeReq.Ctx.Done():
1✔
3685
                        return
1✔
3686

3687
                case <-p.cg.Done():
1✔
3688
                        return
1✔
3689
                }
3690
        }
3691
}
3692

3693
// chanErrorReporter is a simple implementation of the
3694
// chancloser.ErrorReporter. This is bound to a single channel by the channel
3695
// ID.
3696
type chanErrorReporter struct {
3697
        chanID lnwire.ChannelID
3698
        peer   *Brontide
3699
}
3700

3701
// newChanErrorReporter creates a new instance of the chanErrorReporter.
3702
func newChanErrorReporter(chanID lnwire.ChannelID,
3703
        peer *Brontide) *chanErrorReporter {
1✔
3704

1✔
3705
        return &chanErrorReporter{
1✔
3706
                chanID: chanID,
1✔
3707
                peer:   peer,
1✔
3708
        }
1✔
3709
}
1✔
3710

3711
// ReportError is a method that's used to report an error that occurred during
3712
// state machine execution. This is used by the RBF close state machine to
3713
// terminate the state machine and send an error to the remote peer.
3714
//
3715
// This is a part of the chancloser.ErrorReporter interface.
3716
func (c *chanErrorReporter) ReportError(chanErr error) {
×
3717
        c.peer.log.Errorf("coop close error for channel %v: %v",
×
3718
                c.chanID, chanErr)
×
3719

×
3720
        var errMsg []byte
×
3721
        if errors.Is(chanErr, chancloser.ErrInvalidStateTransition) {
×
3722
                errMsg = []byte("unexpected protocol message")
×
3723
        } else {
×
3724
                errMsg = []byte(chanErr.Error())
×
3725
        }
×
3726

3727
        err := c.peer.SendMessageLazy(false, &lnwire.Error{
×
3728
                ChanID: c.chanID,
×
3729
                Data:   errMsg,
×
3730
        })
×
3731
        if err != nil {
×
3732
                c.peer.log.Warnf("unable to send error message to peer: %v",
×
3733
                        err)
×
3734
        }
×
3735

3736
        // After we send the error message to the peer, we'll re-initialize the
3737
        // coop close state machine as they may send a shutdown message to
3738
        // retry the coop close.
3739
        lnChan, ok := c.peer.activeChannels.Load(c.chanID)
×
3740
        if !ok {
×
3741
                return
×
3742
        }
×
3743

3744
        if lnChan == nil {
×
3745
                c.peer.log.Debugf("channel %v is pending, not "+
×
3746
                        "re-initializing coop close state machine",
×
3747
                        c.chanID)
×
3748

×
3749
                return
×
3750
        }
×
3751

3752
        if _, err := c.peer.initRbfChanCloser(lnChan); err != nil {
×
3753
                c.peer.activeChanCloses.Delete(c.chanID)
×
3754

×
3755
                c.peer.log.Errorf("unable to init RBF chan closer after "+
×
3756
                        "error case: %v", err)
×
3757
        }
×
3758
}
3759

3760
// chanFlushEventSentinel is used to send the RBF coop close state machine the
3761
// channel flushed event. We'll wait until the state machine enters the
3762
// ChannelFlushing state, then request the link to send the event once flushed.
3763
//
3764
// NOTE: This MUST be run as a goroutine.
3765
func (p *Brontide) chanFlushEventSentinel(chanCloser *chancloser.RbfChanCloser,
3766
        link htlcswitch.ChannelUpdateHandler,
3767
        channel *lnwallet.LightningChannel) {
1✔
3768

1✔
3769
        defer p.cg.WgDone()
1✔
3770

1✔
3771
        // If there's no link, then the channel has already been flushed, so we
1✔
3772
        // don't need to continue.
1✔
3773
        if link == nil {
2✔
3774
                return
1✔
3775
        }
1✔
3776

3777
        coopCloseStates := chanCloser.RegisterStateEvents()
1✔
3778
        defer chanCloser.RemoveStateSub(coopCloseStates)
1✔
3779

1✔
3780
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
1✔
3781

1✔
3782
        sendChanFlushed := func() {
2✔
3783
                chanState := channel.StateSnapshot()
1✔
3784

1✔
3785
                peerLog.Infof("ChannelPoint(%v) has been flushed for co-op "+
1✔
3786
                        "close, sending event to chan closer",
1✔
3787
                        channel.ChannelPoint())
1✔
3788

1✔
3789
                chanBalances := chancloser.ShutdownBalances{
1✔
3790
                        LocalBalance:  chanState.LocalBalance,
1✔
3791
                        RemoteBalance: chanState.RemoteBalance,
1✔
3792
                }
1✔
3793
                ctx := context.Background()
1✔
3794
                chanCloser.SendEvent(ctx, &chancloser.ChannelFlushed{
1✔
3795
                        ShutdownBalances: chanBalances,
1✔
3796
                        FreshFlush:       true,
1✔
3797
                })
1✔
3798
        }
1✔
3799

3800
        // We'll wait until the channel enters the ChannelFlushing state. We
3801
        // exit after a success loop. As after the first RBF iteration, the
3802
        // channel will always be flushed.
3803
        for newState := range newStateChan {
2✔
3804
                if _, ok := newState.(*chancloser.ChannelFlushing); ok {
2✔
3805
                        peerLog.Infof("ChannelPoint(%v): rbf coop "+
1✔
3806
                                "close is awaiting a flushed state, "+
1✔
3807
                                "registering with link..., ",
1✔
3808
                                channel.ChannelPoint())
1✔
3809

1✔
3810
                        // Request the link to send the event once the channel
1✔
3811
                        // is flushed. We only need this event sent once, so we
1✔
3812
                        // can exit now.
1✔
3813
                        link.OnFlushedOnce(sendChanFlushed)
1✔
3814

1✔
3815
                        return
1✔
3816
                }
1✔
3817
        }
3818
}
3819

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

1✔
3826
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
1✔
3827

1✔
3828
        link := p.fetchLinkFromKeyAndCid(chanID)
1✔
3829

1✔
3830
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
1✔
3831
        if err != nil {
1✔
3832
                return nil, fmt.Errorf("cannot obtain best block: %w", err)
×
3833
        }
×
3834

3835
        defaultFeePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
1✔
3836
                p.cfg.CoopCloseTargetConfs,
1✔
3837
        )
1✔
3838
        if err != nil {
1✔
3839
                return nil, fmt.Errorf("unable to estimate fee: %w", err)
×
3840
        }
×
3841

3842
        thawHeight, err := channel.AbsoluteThawHeight()
1✔
3843
        if err != nil {
1✔
3844
                return nil, fmt.Errorf("unable to get thaw height: %w", err)
×
3845
        }
×
3846

3847
        peerPub := *p.IdentityKey()
1✔
3848

1✔
3849
        msgMapper := chancloser.NewRbfMsgMapper(
1✔
3850
                uint32(startingHeight), chanID, peerPub,
1✔
3851
        )
1✔
3852

1✔
3853
        initialState := chancloser.ChannelActive{}
1✔
3854

1✔
3855
        scid := channel.ZeroConfRealScid().UnwrapOr(
1✔
3856
                channel.ShortChanID(),
1✔
3857
        )
1✔
3858

1✔
3859
        env := chancloser.Environment{
1✔
3860
                ChainParams:    p.cfg.Wallet.Cfg.NetParams,
1✔
3861
                ChanPeer:       peerPub,
1✔
3862
                ChanPoint:      channel.ChannelPoint(),
1✔
3863
                ChanID:         chanID,
1✔
3864
                Scid:           scid,
1✔
3865
                ChanType:       channel.ChanType(),
1✔
3866
                DefaultFeeRate: defaultFeePerKw.FeePerVByte(),
1✔
3867
                ThawHeight:     fn.Some(thawHeight),
1✔
3868
                RemoteUpfrontShutdown: chooseAddr(
1✔
3869
                        channel.RemoteUpfrontShutdownScript(),
1✔
3870
                ),
1✔
3871
                LocalUpfrontShutdown: chooseAddr(
1✔
3872
                        channel.LocalUpfrontShutdownScript(),
1✔
3873
                ),
1✔
3874
                NewDeliveryScript: func() (lnwire.DeliveryAddress, error) {
2✔
3875
                        return p.genDeliveryScript()
1✔
3876
                },
1✔
3877
                FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
3878
                CloseSigner:  channel,
3879
                ChanObserver: newChanObserver(
3880
                        channel, link, p.cfg.ChanStatusMgr,
3881
                ),
3882
        }
3883

3884
        spendEvent := protofsm.RegisterSpend[chancloser.ProtocolEvent]{
1✔
3885
                OutPoint:   channel.ChannelPoint(),
1✔
3886
                PkScript:   channel.FundingTxOut().PkScript,
1✔
3887
                HeightHint: channel.DeriveHeightHint(),
1✔
3888
                PostSpendEvent: fn.Some[chancloser.RbfSpendMapper](
1✔
3889
                        chancloser.SpendMapper,
1✔
3890
                ),
1✔
3891
        }
1✔
3892

1✔
3893
        daemonAdapters := NewLndDaemonAdapters(LndAdapterCfg{
1✔
3894
                MsgSender:     newPeerMsgSender(peerPub, p),
1✔
3895
                TxBroadcaster: p.cfg.Wallet,
1✔
3896
                ChainNotifier: p.cfg.ChainNotifier,
1✔
3897
        })
1✔
3898

1✔
3899
        protoCfg := chancloser.RbfChanCloserCfg{
1✔
3900
                Daemon:        daemonAdapters,
1✔
3901
                InitialState:  &initialState,
1✔
3902
                Env:           &env,
1✔
3903
                InitEvent:     fn.Some[protofsm.DaemonEvent](&spendEvent),
1✔
3904
                ErrorReporter: newChanErrorReporter(chanID, p),
1✔
3905
                MsgMapper: fn.Some[protofsm.MsgMapper[chancloser.ProtocolEvent]]( //nolint:ll
1✔
3906
                        msgMapper,
1✔
3907
                ),
1✔
3908
        }
1✔
3909

1✔
3910
        ctx := context.Background()
1✔
3911
        chanCloser := protofsm.NewStateMachine(protoCfg)
1✔
3912
        chanCloser.Start(ctx)
1✔
3913

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

1✔
3919
                return r.RegisterEndpoint(&chanCloser)
1✔
3920
        })
1✔
3921
        if err != nil {
1✔
3922
                chanCloser.Stop()
×
3923

×
3924
                return nil, fmt.Errorf("unable to register endpoint for co-op "+
×
3925
                        "close: %w", err)
×
3926
        }
×
3927

3928
        p.activeChanCloses.Store(chanID, makeRbfCloser(&chanCloser))
1✔
3929

1✔
3930
        // Now that we've created the rbf closer state machine, we'll launch a
1✔
3931
        // new goroutine to eventually send in the ChannelFlushed event once
1✔
3932
        // needed.
1✔
3933
        p.cg.WgAdd(1)
1✔
3934
        go p.chanFlushEventSentinel(&chanCloser, link, channel)
1✔
3935

1✔
3936
        return &chanCloser, nil
1✔
3937
}
3938

3939
// shutdownInit describes the two ways we can initiate a new shutdown. Either we
3940
// got an RPC request to do so (left), or we sent a shutdown message to the
3941
// party (for w/e reason), but crashed before the close was complete.
3942
//
3943
//nolint:ll
3944
type shutdownInit = fn.Option[fn.Either[*htlcswitch.ChanClose, channeldb.ShutdownInfo]]
3945

3946
// shutdownStartFeeRate returns the fee rate that should be used for the
3947
// shutdown.  This returns a doubly wrapped option as the shutdown info might
3948
// be none, and the fee rate is only defined for the user initiated shutdown.
3949
func shutdownStartFeeRate(s shutdownInit) fn.Option[chainfee.SatPerKWeight] {
1✔
3950
        feeRateOpt := fn.MapOption(func(init fn.Either[*htlcswitch.ChanClose,
1✔
3951
                channeldb.ShutdownInfo]) fn.Option[chainfee.SatPerKWeight] {
2✔
3952

1✔
3953
                var feeRate fn.Option[chainfee.SatPerKWeight]
1✔
3954
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
2✔
3955
                        feeRate = fn.Some(req.TargetFeePerKw)
1✔
3956
                })
1✔
3957

3958
                return feeRate
1✔
3959
        })(s)
3960

3961
        return fn.FlattenOption(feeRateOpt)
1✔
3962
}
3963

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

1✔
3971
                var addr fn.Option[lnwire.DeliveryAddress]
1✔
3972
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
2✔
3973
                        if len(req.DeliveryScript) != 0 {
2✔
3974
                                addr = fn.Some(req.DeliveryScript)
1✔
3975
                        }
1✔
3976
                })
3977
                init.WhenRight(func(info channeldb.ShutdownInfo) {
2✔
3978
                        addr = fn.Some(info.DeliveryScript.Val)
1✔
3979
                })
1✔
3980

3981
                return addr
1✔
3982
        })(s)
3983

3984
        return fn.FlattenOption(addrOpt)
1✔
3985
}
3986

3987
// whenRPCShutdown registers a callback to be executed when the shutdown init
3988
// type is and RPC request.
3989
func whenRPCShutdown(s shutdownInit, f func(r *htlcswitch.ChanClose)) {
1✔
3990
        s.WhenSome(func(init fn.Either[*htlcswitch.ChanClose,
1✔
3991
                channeldb.ShutdownInfo]) {
2✔
3992

1✔
3993
                init.WhenLeft(f)
1✔
3994
        })
1✔
3995
}
3996

3997
// newRestartShutdownInit creates a new shutdownInit for the case where we need
3998
// to restart the shutdown flow after a restart.
3999
func newRestartShutdownInit(info channeldb.ShutdownInfo) shutdownInit {
1✔
4000
        return fn.Some(fn.NewRight[*htlcswitch.ChanClose](info))
1✔
4001
}
1✔
4002

4003
// newRPCShutdownInit creates a new shutdownInit for the case where we
4004
// initiated the shutdown via an RPC client.
4005
func newRPCShutdownInit(req *htlcswitch.ChanClose) shutdownInit {
1✔
4006
        return fn.Some(
1✔
4007
                fn.NewLeft[*htlcswitch.ChanClose, channeldb.ShutdownInfo](req),
1✔
4008
        )
1✔
4009
}
1✔
4010

4011
// waitUntilRbfCoastClear waits until the RBF co-op close state machine has
4012
// advanced to a terminal state before attempting another fee bump.
4013
func waitUntilRbfCoastClear(ctx context.Context,
4014
        rbfCloser *chancloser.RbfChanCloser) error {
1✔
4015

1✔
4016
        coopCloseStates := rbfCloser.RegisterStateEvents()
1✔
4017
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
1✔
4018
        defer rbfCloser.RemoveStateSub(coopCloseStates)
1✔
4019

1✔
4020
        isTerminalState := func(newState chancloser.RbfState) bool {
2✔
4021
                // If we're not in the negotiation sub-state, then we aren't at
1✔
4022
                // the terminal state yet.
1✔
4023
                state, ok := newState.(*chancloser.ClosingNegotiation)
1✔
4024
                if !ok {
1✔
4025
                        return false
×
4026
                }
×
4027

4028
                localState := state.PeerState.GetForParty(lntypes.Local)
1✔
4029

1✔
4030
                // If this isn't the close pending state, we aren't at the
1✔
4031
                // terminal state yet.
1✔
4032
                _, ok = localState.(*chancloser.ClosePending)
1✔
4033

1✔
4034
                return ok
1✔
4035
        }
4036

4037
        // Before we enter the subscription loop below, check to see if we're
4038
        // already in the terminal state.
4039
        rbfState, err := rbfCloser.CurrentState()
1✔
4040
        if err != nil {
1✔
4041
                return err
×
4042
        }
×
4043
        if isTerminalState(rbfState) {
2✔
4044
                return nil
1✔
4045
        }
1✔
4046

4047
        peerLog.Debugf("Waiting for RBF iteration to complete...")
×
4048

×
4049
        for {
×
4050
                select {
×
4051
                case newState := <-newStateChan:
×
4052
                        if isTerminalState(newState) {
×
4053
                                return nil
×
4054
                        }
×
4055

4056
                case <-ctx.Done():
×
4057
                        return fmt.Errorf("context canceled")
×
4058
                }
4059
        }
4060
}
4061

4062
// startRbfChanCloser kicks off the co-op close process using the new RBF based
4063
// co-op close protocol. This is called when we're the one that's initiating
4064
// the cooperative channel close.
4065
//
4066
// TODO(roasbeef): just accept the two shutdown pointer params instead??
4067
func (p *Brontide) startRbfChanCloser(shutdown shutdownInit,
4068
        chanPoint wire.OutPoint) error {
1✔
4069

1✔
4070
        // Unlike the old negotiate chan closer, we'll always create the RBF
1✔
4071
        // chan closer on startup, so we can skip init here.
1✔
4072
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
1✔
4073
        chanCloser, found := p.activeChanCloses.Load(chanID)
1✔
4074
        if !found {
1✔
4075
                return fmt.Errorf("rbf chan closer not found for channel %v",
×
4076
                        chanPoint)
×
4077
        }
×
4078

4079
        defaultFeePerKw, err := shutdownStartFeeRate(
1✔
4080
                shutdown,
1✔
4081
        ).UnwrapOrFuncErr(func() (chainfee.SatPerKWeight, error) {
2✔
4082
                return p.cfg.FeeEstimator.EstimateFeePerKW(
1✔
4083
                        p.cfg.CoopCloseTargetConfs,
1✔
4084
                )
1✔
4085
        })
1✔
4086
        if err != nil {
1✔
4087
                return fmt.Errorf("unable to estimate fee: %w", err)
×
4088
        }
×
4089

4090
        chanCloser.WhenRight(func(rbfCloser *chancloser.RbfChanCloser) {
2✔
4091
                peerLog.Infof("ChannelPoint(%v): rbf-coop close requested, "+
1✔
4092
                        "sending shutdown", chanPoint)
1✔
4093

1✔
4094
                rbfState, err := rbfCloser.CurrentState()
1✔
4095
                if err != nil {
1✔
4096
                        peerLog.Warnf("ChannelPoint(%v): unable to get "+
×
4097
                                "current state for rbf-coop close: %v",
×
4098
                                chanPoint, err)
×
4099

×
4100
                        return
×
4101
                }
×
4102

4103
                coopCloseStates := rbfCloser.RegisterStateEvents()
1✔
4104

1✔
4105
                // Before we send our event below, we'll launch a goroutine to
1✔
4106
                // watch for the final terminal state to send updates to the RPC
1✔
4107
                // client. We only need to do this if there's an RPC caller.
1✔
4108
                var rpcShutdown bool
1✔
4109
                whenRPCShutdown(shutdown, func(req *htlcswitch.ChanClose) {
2✔
4110
                        rpcShutdown = true
1✔
4111

1✔
4112
                        p.cg.WgAdd(1)
1✔
4113
                        go func() {
2✔
4114
                                defer p.cg.WgDone()
1✔
4115

1✔
4116
                                p.observeRbfCloseUpdates(
1✔
4117
                                        rbfCloser, req, coopCloseStates,
1✔
4118
                                )
1✔
4119
                        }()
1✔
4120
                })
4121

4122
                if !rpcShutdown {
2✔
4123
                        defer rbfCloser.RemoveStateSub(coopCloseStates)
1✔
4124
                }
1✔
4125

4126
                ctx, _ := p.cg.Create(context.Background())
1✔
4127
                feeRate := defaultFeePerKw.FeePerVByte()
1✔
4128

1✔
4129
                // Depending on the state of the state machine, we'll either
1✔
4130
                // kick things off by sending shutdown, or attempt to send a new
1✔
4131
                // offer to the remote party.
1✔
4132
                switch rbfState.(type) {
1✔
4133
                // The channel is still active, so we'll now kick off the co-op
4134
                // close process by instructing it to send a shutdown message to
4135
                // the remote party.
4136
                case *chancloser.ChannelActive:
1✔
4137
                        rbfCloser.SendEvent(
1✔
4138
                                context.Background(),
1✔
4139
                                &chancloser.SendShutdown{
1✔
4140
                                        IdealFeeRate: feeRate,
1✔
4141
                                        DeliveryAddr: shutdownStartAddr(
1✔
4142
                                                shutdown,
1✔
4143
                                        ),
1✔
4144
                                },
1✔
4145
                        )
1✔
4146

4147
                // If we haven't yet sent an offer (didn't have enough funds at
4148
                // the prior fee rate), or we've sent an offer, then we'll
4149
                // trigger a new offer event.
4150
                case *chancloser.ClosingNegotiation:
1✔
4151
                        // Before we send the event below, we'll wait until
1✔
4152
                        // we're in a semi-terminal state.
1✔
4153
                        err := waitUntilRbfCoastClear(ctx, rbfCloser)
1✔
4154
                        if err != nil {
1✔
4155
                                peerLog.Warnf("ChannelPoint(%v): unable to "+
×
4156
                                        "wait for coast to clear: %v",
×
4157
                                        chanPoint, err)
×
4158

×
4159
                                return
×
4160
                        }
×
4161

4162
                        event := chancloser.ProtocolEvent(
1✔
4163
                                &chancloser.SendOfferEvent{
1✔
4164
                                        TargetFeeRate: feeRate,
1✔
4165
                                },
1✔
4166
                        )
1✔
4167
                        rbfCloser.SendEvent(ctx, event)
1✔
4168

4169
                default:
×
4170
                        peerLog.Warnf("ChannelPoint(%v): unexpected state "+
×
4171
                                "for rbf-coop close: %T", chanPoint, rbfState)
×
4172
                }
4173
        })
4174

4175
        return nil
1✔
4176
}
4177

4178
// handleLocalCloseReq kicks-off the workflow to execute a cooperative or
4179
// forced unilateral closure of the channel initiated by a local subsystem.
4180
func (p *Brontide) handleLocalCloseReq(req *htlcswitch.ChanClose) {
1✔
4181
        chanID := lnwire.NewChanIDFromOutPoint(*req.ChanPoint)
1✔
4182

1✔
4183
        channel, ok := p.activeChannels.Load(chanID)
1✔
4184

1✔
4185
        // Though this function can't be called for pending channels, we still
1✔
4186
        // check whether channel is nil for safety.
1✔
4187
        if !ok || channel == nil {
1✔
4188
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
×
4189
                        "unknown", chanID)
×
4190
                p.log.Errorf(err.Error())
×
4191
                req.Err <- err
×
4192
                return
×
4193
        }
×
4194

4195
        isTaprootChan := channel.ChanType().IsTaproot()
1✔
4196

1✔
4197
        switch req.CloseType {
1✔
4198
        // A type of CloseRegular indicates that the user has opted to close
4199
        // out this channel on-chain, so we execute the cooperative channel
4200
        // closure workflow.
4201
        case contractcourt.CloseRegular:
1✔
4202
                var err error
1✔
4203
                switch {
1✔
4204
                // If this is the RBF coop state machine, then we'll instruct
4205
                // it to send the shutdown message. This also might be an RBF
4206
                // iteration, in which case we'll be obtaining a new
4207
                // transaction w/ a higher fee rate.
4208
                //
4209
                // We don't support this close type for taproot channels yet
4210
                // however.
4211
                case !isTaprootChan && p.rbfCoopCloseAllowed():
1✔
4212
                        err = p.startRbfChanCloser(
1✔
4213
                                newRPCShutdownInit(req), channel.ChannelPoint(),
1✔
4214
                        )
1✔
4215
                default:
1✔
4216
                        err = p.initNegotiateChanCloser(req, channel)
1✔
4217
                }
4218

4219
                if err != nil {
1✔
UNCOV
4220
                        p.log.Errorf(err.Error())
×
UNCOV
4221
                        req.Err <- err
×
UNCOV
4222
                }
×
4223

4224
        // A type of CloseBreach indicates that the counterparty has breached
4225
        // the channel therefore we need to clean up our local state.
4226
        case contractcourt.CloseBreach:
×
4227
                // TODO(roasbeef): no longer need with newer beach logic?
×
4228
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
×
4229
                        "channel", req.ChanPoint)
×
4230
                p.WipeChannel(req.ChanPoint)
×
4231
        }
4232
}
4233

4234
// linkFailureReport is sent to the channelManager whenever a link reports a
4235
// link failure, and is forced to exit. The report houses the necessary
4236
// information to clean up the channel state, send back the error message, and
4237
// force close if necessary.
4238
type linkFailureReport struct {
4239
        chanPoint   wire.OutPoint
4240
        chanID      lnwire.ChannelID
4241
        shortChanID lnwire.ShortChannelID
4242
        linkErr     htlcswitch.LinkFailureError
4243
}
4244

4245
// handleLinkFailure processes a link failure report when a link in the switch
4246
// fails. It facilitates the removal of all channel state within the peer,
4247
// force closing the channel depending on severity, and sending the error
4248
// message back to the remote party.
4249
func (p *Brontide) handleLinkFailure(failure linkFailureReport) {
1✔
4250
        // Retrieve the channel from the map of active channels. We do this to
1✔
4251
        // have access to it even after WipeChannel remove it from the map.
1✔
4252
        chanID := lnwire.NewChanIDFromOutPoint(failure.chanPoint)
1✔
4253
        lnChan, _ := p.activeChannels.Load(chanID)
1✔
4254

1✔
4255
        // We begin by wiping the link, which will remove it from the switch,
1✔
4256
        // such that it won't be attempted used for any more updates.
1✔
4257
        //
1✔
4258
        // TODO(halseth): should introduce a way to atomically stop/pause the
1✔
4259
        // link and cancel back any adds in its mailboxes such that we can
1✔
4260
        // safely force close without the link being added again and updates
1✔
4261
        // being applied.
1✔
4262
        p.WipeChannel(&failure.chanPoint)
1✔
4263

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

1✔
4269
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
1✔
4270
                        failure.chanPoint,
1✔
4271
                )
1✔
4272
                if err != nil {
2✔
4273
                        p.log.Errorf("unable to force close "+
1✔
4274
                                "link(%v): %v", failure.shortChanID, err)
1✔
4275
                } else {
2✔
4276
                        p.log.Infof("channel(%v) force "+
1✔
4277
                                "closed with txid %v",
1✔
4278
                                failure.shortChanID, closeTx.TxHash())
1✔
4279
                }
1✔
4280
        }
4281

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

×
4287
                if err := lnChan.State().MarkBorked(); err != nil {
×
4288
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
4289
                                failure.shortChanID, err)
×
4290
                }
×
4291
        }
4292

4293
        // Send an error to the peer, why we failed the channel.
4294
        if failure.linkErr.ShouldSendToPeer() {
2✔
4295
                // If SendData is set, send it to the peer. If not, we'll use
1✔
4296
                // the standard error messages in the payload. We only include
1✔
4297
                // sendData in the cases where the error data does not contain
1✔
4298
                // sensitive information.
1✔
4299
                data := []byte(failure.linkErr.Error())
1✔
4300
                if failure.linkErr.SendData != nil {
1✔
4301
                        data = failure.linkErr.SendData
×
4302
                }
×
4303

4304
                var networkMsg lnwire.Message
1✔
4305
                if failure.linkErr.Warning {
1✔
4306
                        networkMsg = &lnwire.Warning{
×
4307
                                ChanID: failure.chanID,
×
4308
                                Data:   data,
×
4309
                        }
×
4310
                } else {
1✔
4311
                        networkMsg = &lnwire.Error{
1✔
4312
                                ChanID: failure.chanID,
1✔
4313
                                Data:   data,
1✔
4314
                        }
1✔
4315
                }
1✔
4316

4317
                err := p.SendMessage(true, networkMsg)
1✔
4318
                if err != nil {
1✔
4319
                        p.log.Errorf("unable to send msg to "+
×
4320
                                "remote peer: %v", err)
×
4321
                }
×
4322
        }
4323

4324
        // If the failure action is disconnect, then we'll execute that now. If
4325
        // we had to send an error above, it was a sync call, so we expect the
4326
        // message to be flushed on the wire by now.
4327
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
1✔
4328
                p.Disconnect(fmt.Errorf("link requested disconnect"))
×
4329
        }
×
4330
}
4331

4332
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
4333
// public key and the channel id.
4334
func (p *Brontide) fetchLinkFromKeyAndCid(
4335
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
1✔
4336

1✔
4337
        var chanLink htlcswitch.ChannelUpdateHandler
1✔
4338

1✔
4339
        // We don't need to check the error here, and can instead just loop
1✔
4340
        // over the slice and return nil.
1✔
4341
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
1✔
4342
        for _, link := range links {
2✔
4343
                if link.ChanID() == cid {
2✔
4344
                        chanLink = link
1✔
4345
                        break
1✔
4346
                }
4347
        }
4348

4349
        return chanLink
1✔
4350
}
4351

4352
// finalizeChanClosure performs the final clean up steps once the cooperative
4353
// closure transaction has been fully broadcast. The finalized closing state
4354
// machine should be passed in. Once the transaction has been sufficiently
4355
// confirmed, the channel will be marked as fully closed within the database,
4356
// and any clients will be notified of updates to the closing state.
4357
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
1✔
4358
        closeReq := chanCloser.CloseRequest()
1✔
4359

1✔
4360
        // First, we'll clear all indexes related to the channel in question.
1✔
4361
        chanPoint := chanCloser.Channel().ChannelPoint()
1✔
4362
        p.WipeChannel(&chanPoint)
1✔
4363

1✔
4364
        // Also clear the activeChanCloses map of this channel.
1✔
4365
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
1✔
4366
        p.activeChanCloses.Delete(cid) // TODO(roasbeef): existing race
1✔
4367

1✔
4368
        // Next, we'll launch a goroutine which will request to be notified by
1✔
4369
        // the ChainNotifier once the closure transaction obtains a single
1✔
4370
        // confirmation.
1✔
4371
        notifier := p.cfg.ChainNotifier
1✔
4372

1✔
4373
        // If any error happens during waitForChanToClose, forward it to
1✔
4374
        // closeReq. If this channel closure is not locally initiated, closeReq
1✔
4375
        // will be nil, so just ignore the error.
1✔
4376
        errChan := make(chan error, 1)
1✔
4377
        if closeReq != nil {
2✔
4378
                errChan = closeReq.Err
1✔
4379
        }
1✔
4380

4381
        closingTx, err := chanCloser.ClosingTx()
1✔
4382
        if err != nil {
1✔
4383
                if closeReq != nil {
×
4384
                        p.log.Error(err)
×
4385
                        closeReq.Err <- err
×
4386
                }
×
4387
        }
4388

4389
        closingTxid := closingTx.TxHash()
1✔
4390

1✔
4391
        // If this is a locally requested shutdown, update the caller with a
1✔
4392
        // new event detailing the current pending state of this request.
1✔
4393
        if closeReq != nil {
2✔
4394
                closeReq.Updates <- &PendingUpdate{
1✔
4395
                        Txid: closingTxid[:],
1✔
4396
                }
1✔
4397
        }
1✔
4398

4399
        localOut := chanCloser.LocalCloseOutput()
1✔
4400
        remoteOut := chanCloser.RemoteCloseOutput()
1✔
4401
        auxOut := chanCloser.AuxOutputs()
1✔
4402
        go WaitForChanToClose(
1✔
4403
                chanCloser.NegotiationHeight(), notifier, errChan,
1✔
4404
                &chanPoint, &closingTxid, closingTx.TxOut[0].PkScript, func() {
2✔
4405
                        // Respond to the local subsystem which requested the
1✔
4406
                        // channel closure.
1✔
4407
                        if closeReq != nil {
2✔
4408
                                closeReq.Updates <- &ChannelCloseUpdate{
1✔
4409
                                        ClosingTxid:       closingTxid[:],
1✔
4410
                                        Success:           true,
1✔
4411
                                        LocalCloseOutput:  localOut,
1✔
4412
                                        RemoteCloseOutput: remoteOut,
1✔
4413
                                        AuxOutputs:        auxOut,
1✔
4414
                                }
1✔
4415
                        }
1✔
4416
                },
4417
        )
4418
}
4419

4420
// WaitForChanToClose uses the passed notifier to wait until the channel has
4421
// been detected as closed on chain and then concludes by executing the
4422
// following actions: the channel point will be sent over the settleChan, and
4423
// finally the callback will be executed. If any error is encountered within
4424
// the function, then it will be sent over the errChan.
4425
func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
4426
        errChan chan error, chanPoint *wire.OutPoint,
4427
        closingTxID *chainhash.Hash, closeScript []byte, cb func()) {
1✔
4428

1✔
4429
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
1✔
4430
                "with txid: %v", chanPoint, closingTxID)
1✔
4431

1✔
4432
        // TODO(roasbeef): add param for num needed confs
1✔
4433
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
1✔
4434
                closingTxID, closeScript, 1, bestHeight,
1✔
4435
        )
1✔
4436
        if err != nil {
1✔
4437
                if errChan != nil {
×
4438
                        errChan <- err
×
4439
                }
×
4440
                return
×
4441
        }
4442

4443
        // In the case that the ChainNotifier is shutting down, all subscriber
4444
        // notification channels will be closed, generating a nil receive.
4445
        height, ok := <-confNtfn.Confirmed
1✔
4446
        if !ok {
2✔
4447
                return
1✔
4448
        }
1✔
4449

4450
        // The channel has been closed, remove it from any active indexes, and
4451
        // the database state.
4452
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
1✔
4453
                "height %v", chanPoint, height.BlockHeight)
1✔
4454

1✔
4455
        // Finally, execute the closure call back to mark the confirmation of
1✔
4456
        // the transaction closing the contract.
1✔
4457
        cb()
1✔
4458
}
4459

4460
// WipeChannel removes the passed channel point from all indexes associated with
4461
// the peer and the switch.
4462
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
1✔
4463
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
1✔
4464

1✔
4465
        p.activeChannels.Delete(chanID)
1✔
4466

1✔
4467
        // Instruct the HtlcSwitch to close this link as the channel is no
1✔
4468
        // longer active.
1✔
4469
        p.cfg.Switch.RemoveLink(chanID)
1✔
4470
}
1✔
4471

4472
// handleInitMsg handles the incoming init message which contains global and
4473
// local feature vectors. If feature vectors are incompatible then disconnect.
4474
func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
1✔
4475
        // First, merge any features from the legacy global features field into
1✔
4476
        // those presented in the local features fields.
1✔
4477
        err := msg.Features.Merge(msg.GlobalFeatures)
1✔
4478
        if err != nil {
1✔
4479
                return fmt.Errorf("unable to merge legacy global features: %w",
×
4480
                        err)
×
4481
        }
×
4482

4483
        // Then, finalize the remote feature vector providing the flattened
4484
        // feature bit namespace.
4485
        p.remoteFeatures = lnwire.NewFeatureVector(
1✔
4486
                msg.Features, lnwire.Features,
1✔
4487
        )
1✔
4488

1✔
4489
        // Now that we have their features loaded, we'll ensure that they
1✔
4490
        // didn't set any required bits that we don't know of.
1✔
4491
        err = feature.ValidateRequired(p.remoteFeatures)
1✔
4492
        if err != nil {
1✔
4493
                return fmt.Errorf("invalid remote features: %w", err)
×
4494
        }
×
4495

4496
        // Ensure the remote party's feature vector contains all transitive
4497
        // dependencies. We know ours are correct since they are validated
4498
        // during the feature manager's instantiation.
4499
        err = feature.ValidateDeps(p.remoteFeatures)
1✔
4500
        if err != nil {
1✔
4501
                return fmt.Errorf("invalid remote features: %w", err)
×
4502
        }
×
4503

4504
        // Now that we know we understand their requirements, we'll check to
4505
        // see if they don't support anything that we deem to be mandatory.
4506
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
1✔
4507
                return fmt.Errorf("data loss protection required")
×
4508
        }
×
4509

4510
        return nil
1✔
4511
}
4512

4513
// LocalFeatures returns the set of global features that has been advertised by
4514
// the local node. This allows sub-systems that use this interface to gate their
4515
// behavior off the set of negotiated feature bits.
4516
//
4517
// NOTE: Part of the lnpeer.Peer interface.
4518
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
1✔
4519
        return p.cfg.Features
1✔
4520
}
1✔
4521

4522
// RemoteFeatures returns the set of global features that has been advertised by
4523
// the remote node. This allows sub-systems that use this interface to gate
4524
// their behavior off the set of negotiated feature bits.
4525
//
4526
// NOTE: Part of the lnpeer.Peer interface.
4527
func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector {
1✔
4528
        return p.remoteFeatures
1✔
4529
}
1✔
4530

4531
// hasNegotiatedScidAlias returns true if we've negotiated the
4532
// option-scid-alias feature bit with the peer.
4533
func (p *Brontide) hasNegotiatedScidAlias() bool {
1✔
4534
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
1✔
4535
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
1✔
4536
        return peerHas && localHas
1✔
4537
}
1✔
4538

4539
// sendInitMsg sends the Init message to the remote peer. This message contains
4540
// our currently supported local and global features.
4541
func (p *Brontide) sendInitMsg(legacyChan bool) error {
1✔
4542
        features := p.cfg.Features.Clone()
1✔
4543
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
1✔
4544

1✔
4545
        // If we have a legacy channel open with a peer, we downgrade static
1✔
4546
        // remote required to optional in case the peer does not understand the
1✔
4547
        // required feature bit. If we do not do this, the peer will reject our
1✔
4548
        // connection because it does not understand a required feature bit, and
1✔
4549
        // our channel will be unusable.
1✔
4550
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
1✔
UNCOV
4551
                p.log.Infof("Legacy channel open with peer, " +
×
UNCOV
4552
                        "downgrading static remote required feature bit to " +
×
UNCOV
4553
                        "optional")
×
UNCOV
4554

×
UNCOV
4555
                // Unset and set in both the local and global features to
×
UNCOV
4556
                // ensure both sets are consistent and merge able by old and
×
UNCOV
4557
                // new nodes.
×
UNCOV
4558
                features.Unset(lnwire.StaticRemoteKeyRequired)
×
UNCOV
4559
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
×
UNCOV
4560

×
UNCOV
4561
                features.Set(lnwire.StaticRemoteKeyOptional)
×
UNCOV
4562
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
×
UNCOV
4563
        }
×
4564

4565
        msg := lnwire.NewInitMessage(
1✔
4566
                legacyFeatures.RawFeatureVector,
1✔
4567
                features.RawFeatureVector,
1✔
4568
        )
1✔
4569

1✔
4570
        return p.writeMessage(msg)
1✔
4571
}
4572

4573
// resendChanSyncMsg will attempt to find a channel sync message for the closed
4574
// channel and resend it to our peer.
4575
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
1✔
4576
        // If we already re-sent the mssage for this channel, we won't do it
1✔
4577
        // again.
1✔
4578
        if _, ok := p.resentChanSyncMsg[cid]; ok {
2✔
4579
                return nil
1✔
4580
        }
1✔
4581

4582
        // Check if we have any channel sync messages stored for this channel.
4583
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
1✔
4584
        if err != nil {
2✔
4585
                return fmt.Errorf("unable to fetch channel sync messages for "+
1✔
4586
                        "peer %v: %v", p, err)
1✔
4587
        }
1✔
4588

4589
        if c.LastChanSyncMsg == nil {
1✔
4590
                return fmt.Errorf("no chan sync message stored for channel %v",
×
4591
                        cid)
×
4592
        }
×
4593

4594
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
1✔
4595
                return fmt.Errorf("ignoring channel reestablish from "+
×
4596
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
4597
        }
×
4598

4599
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
1✔
4600
                "peer", cid)
1✔
4601

1✔
4602
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
1✔
4603
                return fmt.Errorf("failed resending channel sync "+
×
4604
                        "message to peer %v: %v", p, err)
×
4605
        }
×
4606

4607
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
1✔
4608
                cid)
1✔
4609

1✔
4610
        // Note down that we sent the message, so we won't resend it again for
1✔
4611
        // this connection.
1✔
4612
        p.resentChanSyncMsg[cid] = struct{}{}
1✔
4613

1✔
4614
        return nil
1✔
4615
}
4616

4617
// SendMessage sends a variadic number of high-priority messages to the remote
4618
// peer. The first argument denotes if the method should block until the
4619
// messages have been sent to the remote peer or an error is returned,
4620
// otherwise it returns immediately after queuing.
4621
//
4622
// NOTE: Part of the lnpeer.Peer interface.
4623
func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error {
1✔
4624
        return p.sendMessage(sync, true, msgs...)
1✔
4625
}
1✔
4626

4627
// SendMessageLazy sends a variadic number of low-priority messages to the
4628
// remote peer. The first argument denotes if the method should block until
4629
// the messages have been sent to the remote peer or an error is returned,
4630
// otherwise it returns immediately after queueing.
4631
//
4632
// NOTE: Part of the lnpeer.Peer interface.
4633
func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
1✔
4634
        return p.sendMessage(sync, false, msgs...)
1✔
4635
}
1✔
4636

4637
// sendMessage queues a variadic number of messages using the passed priority
4638
// to the remote peer. If sync is true, this method will block until the
4639
// messages have been sent to the remote peer or an error is returned, otherwise
4640
// it returns immediately after queueing.
4641
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
1✔
4642
        // Add all incoming messages to the outgoing queue. A list of error
1✔
4643
        // chans is populated for each message if the caller requested a sync
1✔
4644
        // send.
1✔
4645
        var errChans []chan error
1✔
4646
        if sync {
2✔
4647
                errChans = make([]chan error, 0, len(msgs))
1✔
4648
        }
1✔
4649
        for _, msg := range msgs {
2✔
4650
                // If a sync send was requested, create an error chan to listen
1✔
4651
                // for an ack from the writeHandler.
1✔
4652
                var errChan chan error
1✔
4653
                if sync {
2✔
4654
                        errChan = make(chan error, 1)
1✔
4655
                        errChans = append(errChans, errChan)
1✔
4656
                }
1✔
4657

4658
                if priority {
2✔
4659
                        p.queueMsg(msg, errChan)
1✔
4660
                } else {
2✔
4661
                        p.queueMsgLazy(msg, errChan)
1✔
4662
                }
1✔
4663
        }
4664

4665
        // Wait for all replies from the writeHandler. For async sends, this
4666
        // will be a NOP as the list of error chans is nil.
4667
        for _, errChan := range errChans {
2✔
4668
                select {
1✔
4669
                case err := <-errChan:
1✔
4670
                        return err
1✔
4671
                case <-p.cg.Done():
×
4672
                        return lnpeer.ErrPeerExiting
×
4673
                case <-p.cfg.Quit:
×
4674
                        return lnpeer.ErrPeerExiting
×
4675
                }
4676
        }
4677

4678
        return nil
1✔
4679
}
4680

4681
// PubKey returns the pubkey of the peer in compressed serialized format.
4682
//
4683
// NOTE: Part of the lnpeer.Peer interface.
4684
func (p *Brontide) PubKey() [33]byte {
1✔
4685
        return p.cfg.PubKeyBytes
1✔
4686
}
1✔
4687

4688
// IdentityKey returns the public key of the remote peer.
4689
//
4690
// NOTE: Part of the lnpeer.Peer interface.
4691
func (p *Brontide) IdentityKey() *btcec.PublicKey {
1✔
4692
        return p.cfg.Addr.IdentityKey
1✔
4693
}
1✔
4694

4695
// Address returns the network address of the remote peer.
4696
//
4697
// NOTE: Part of the lnpeer.Peer interface.
4698
func (p *Brontide) Address() net.Addr {
1✔
4699
        return p.cfg.Addr.Address
1✔
4700
}
1✔
4701

4702
// AddNewChannel adds a new channel to the peer. The channel should fail to be
4703
// added if the cancel channel is closed.
4704
//
4705
// NOTE: Part of the lnpeer.Peer interface.
4706
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
4707
        cancel <-chan struct{}) error {
1✔
4708

1✔
4709
        errChan := make(chan error, 1)
1✔
4710
        newChanMsg := &newChannelMsg{
1✔
4711
                channel: newChan,
1✔
4712
                err:     errChan,
1✔
4713
        }
1✔
4714

1✔
4715
        select {
1✔
4716
        case p.newActiveChannel <- newChanMsg:
1✔
4717
        case <-cancel:
×
4718
                return errors.New("canceled adding new channel")
×
4719
        case <-p.cg.Done():
×
4720
                return lnpeer.ErrPeerExiting
×
4721
        }
4722

4723
        // We pause here to wait for the peer to recognize the new channel
4724
        // before we close the channel barrier corresponding to the channel.
4725
        select {
1✔
4726
        case err := <-errChan:
1✔
4727
                return err
1✔
4728
        case <-p.cg.Done():
×
4729
                return lnpeer.ErrPeerExiting
×
4730
        }
4731
}
4732

4733
// AddPendingChannel adds a pending open channel to the peer. The channel
4734
// should fail to be added if the cancel channel is closed.
4735
//
4736
// NOTE: Part of the lnpeer.Peer interface.
4737
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
4738
        cancel <-chan struct{}) error {
1✔
4739

1✔
4740
        errChan := make(chan error, 1)
1✔
4741
        newChanMsg := &newChannelMsg{
1✔
4742
                channelID: cid,
1✔
4743
                err:       errChan,
1✔
4744
        }
1✔
4745

1✔
4746
        select {
1✔
4747
        case p.newPendingChannel <- newChanMsg:
1✔
4748

4749
        case <-cancel:
×
4750
                return errors.New("canceled adding pending channel")
×
4751

4752
        case <-p.cg.Done():
×
4753
                return lnpeer.ErrPeerExiting
×
4754
        }
4755

4756
        // We pause here to wait for the peer to recognize the new pending
4757
        // channel before we close the channel barrier corresponding to the
4758
        // channel.
4759
        select {
1✔
4760
        case err := <-errChan:
1✔
4761
                return err
1✔
4762

4763
        case <-cancel:
×
4764
                return errors.New("canceled adding pending channel")
×
4765

4766
        case <-p.cg.Done():
×
4767
                return lnpeer.ErrPeerExiting
×
4768
        }
4769
}
4770

4771
// RemovePendingChannel removes a pending open channel from the peer.
4772
//
4773
// NOTE: Part of the lnpeer.Peer interface.
4774
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
1✔
4775
        errChan := make(chan error, 1)
1✔
4776
        newChanMsg := &newChannelMsg{
1✔
4777
                channelID: cid,
1✔
4778
                err:       errChan,
1✔
4779
        }
1✔
4780

1✔
4781
        select {
1✔
4782
        case p.removePendingChannel <- newChanMsg:
1✔
4783
        case <-p.cg.Done():
×
4784
                return lnpeer.ErrPeerExiting
×
4785
        }
4786

4787
        // We pause here to wait for the peer to respond to the cancellation of
4788
        // the pending channel before we close the channel barrier
4789
        // corresponding to the channel.
4790
        select {
1✔
4791
        case err := <-errChan:
1✔
4792
                return err
1✔
4793

4794
        case <-p.cg.Done():
×
4795
                return lnpeer.ErrPeerExiting
×
4796
        }
4797
}
4798

4799
// StartTime returns the time at which the connection was established if the
4800
// peer started successfully, and zero otherwise.
4801
func (p *Brontide) StartTime() time.Time {
1✔
4802
        return p.startTime
1✔
4803
}
1✔
4804

4805
// handleCloseMsg is called when a new cooperative channel closure related
4806
// message is received from the remote peer. We'll use this message to advance
4807
// the chan closer state machine.
4808
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
1✔
4809
        link := p.fetchLinkFromKeyAndCid(msg.cid)
1✔
4810

1✔
4811
        // We'll now fetch the matching closing state machine in order to
1✔
4812
        // continue, or finalize the channel closure process.
1✔
4813
        chanCloserE, err := p.fetchActiveChanCloser(msg.cid)
1✔
4814
        if err != nil {
2✔
4815
                // If the channel is not known to us, we'll simply ignore this
1✔
4816
                // message.
1✔
4817
                if err == ErrChannelNotFound {
2✔
4818
                        return
1✔
4819
                }
1✔
4820

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

×
4823
                errMsg := &lnwire.Error{
×
4824
                        ChanID: msg.cid,
×
4825
                        Data:   lnwire.ErrorData(err.Error()),
×
4826
                }
×
4827
                p.queueMsg(errMsg, nil)
×
4828
                return
×
4829
        }
4830

4831
        if chanCloserE.IsRight() {
1✔
4832
                // TODO(roasbeef): assert?
×
4833
                return
×
4834
        }
×
4835

4836
        // At this point, we'll only enter this call path if a negotiate chan
4837
        // closer was used. So we'll extract that from the either now.
4838
        //
4839
        // TODO(roabeef): need extra helper func for either to make cleaner
4840
        var chanCloser *chancloser.ChanCloser
1✔
4841
        chanCloserE.WhenLeft(func(c *chancloser.ChanCloser) {
2✔
4842
                chanCloser = c
1✔
4843
        })
1✔
4844

4845
        handleErr := func(err error) {
1✔
UNCOV
4846
                err = fmt.Errorf("unable to process close msg: %w", err)
×
UNCOV
4847
                p.log.Error(err)
×
UNCOV
4848

×
UNCOV
4849
                // As the negotiations failed, we'll reset the channel state
×
UNCOV
4850
                // machine to ensure we act to on-chain events as normal.
×
UNCOV
4851
                chanCloser.Channel().ResetState()
×
UNCOV
4852
                if chanCloser.CloseRequest() != nil {
×
4853
                        chanCloser.CloseRequest().Err <- err
×
4854
                }
×
4855

UNCOV
4856
                p.activeChanCloses.Delete(msg.cid)
×
UNCOV
4857

×
UNCOV
4858
                p.Disconnect(err)
×
4859
        }
4860

4861
        // Next, we'll process the next message using the target state machine.
4862
        // We'll either continue negotiation, or halt.
4863
        switch typed := msg.msg.(type) {
1✔
4864
        case *lnwire.Shutdown:
1✔
4865
                // Disable incoming adds immediately.
1✔
4866
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
1✔
4867
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
4868
                                link.ChanID())
×
4869
                }
×
4870

4871
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
1✔
4872
                if err != nil {
1✔
4873
                        handleErr(err)
×
4874
                        return
×
4875
                }
×
4876

4877
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
2✔
4878
                        // If the link is nil it means we can immediately queue
1✔
4879
                        // the Shutdown message since we don't have to wait for
1✔
4880
                        // commitment transaction synchronization.
1✔
4881
                        if link == nil {
1✔
UNCOV
4882
                                p.queueMsg(&msg, nil)
×
UNCOV
4883
                                return
×
UNCOV
4884
                        }
×
4885

4886
                        // Immediately disallow any new HTLC's from being added
4887
                        // in the outgoing direction.
4888
                        if !link.DisableAdds(htlcswitch.Outgoing) {
1✔
4889
                                p.log.Warnf("Outgoing link adds already "+
×
4890
                                        "disabled: %v", link.ChanID())
×
4891
                        }
×
4892

4893
                        // When we have a Shutdown to send, we defer it till the
4894
                        // next time we send a CommitSig to remain spec
4895
                        // compliant.
4896
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
2✔
4897
                                p.queueMsg(&msg, nil)
1✔
4898
                        })
1✔
4899
                })
4900

4901
                beginNegotiation := func() {
2✔
4902
                        oClosingSigned, err := chanCloser.BeginNegotiation()
1✔
4903
                        if err != nil {
1✔
4904
                                handleErr(err)
×
4905
                                return
×
4906
                        }
×
4907

4908
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
2✔
4909
                                p.queueMsg(&msg, nil)
1✔
4910
                        })
1✔
4911
                }
4912

4913
                if link == nil {
1✔
UNCOV
4914
                        beginNegotiation()
×
4915
                } else {
1✔
4916
                        // Now we register a flush hook to advance the
1✔
4917
                        // ChanCloser and possibly send out a ClosingSigned
1✔
4918
                        // when the link finishes draining.
1✔
4919
                        link.OnFlushedOnce(func() {
2✔
4920
                                // Remove link in goroutine to prevent deadlock.
1✔
4921
                                go p.cfg.Switch.RemoveLink(msg.cid)
1✔
4922
                                beginNegotiation()
1✔
4923
                        })
1✔
4924
                }
4925

4926
        case *lnwire.ClosingSigned:
1✔
4927
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
1✔
4928
                if err != nil {
1✔
UNCOV
4929
                        handleErr(err)
×
UNCOV
4930
                        return
×
UNCOV
4931
                }
×
4932

4933
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
2✔
4934
                        p.queueMsg(&msg, nil)
1✔
4935
                })
1✔
4936

4937
        default:
×
4938
                panic("impossible closeMsg type")
×
4939
        }
4940

4941
        // If we haven't finished close negotiations, then we'll continue as we
4942
        // can't yet finalize the closure.
4943
        if _, err := chanCloser.ClosingTx(); err != nil {
2✔
4944
                return
1✔
4945
        }
1✔
4946

4947
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
4948
        // the channel closure by notifying relevant sub-systems and launching a
4949
        // goroutine to wait for close tx conf.
4950
        p.finalizeChanClosure(chanCloser)
1✔
4951
}
4952

4953
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
4954
// the channelManager goroutine, which will shut down the link and possibly
4955
// close the channel.
4956
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
1✔
4957
        select {
1✔
4958
        case p.localCloseChanReqs <- req:
1✔
4959
                p.log.Info("Local close channel request is going to be " +
1✔
4960
                        "delivered to the peer")
1✔
4961
        case <-p.cg.Done():
×
4962
                p.log.Info("Unable to deliver local close channel request " +
×
4963
                        "to peer")
×
4964
        }
4965
}
4966

4967
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
4968
func (p *Brontide) NetAddress() *lnwire.NetAddress {
1✔
4969
        return p.cfg.Addr
1✔
4970
}
1✔
4971

4972
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
4973
func (p *Brontide) Inbound() bool {
1✔
4974
        return p.cfg.Inbound
1✔
4975
}
1✔
4976

4977
// ConnReq is a getter for the Brontide's connReq in cfg.
4978
func (p *Brontide) ConnReq() *connmgr.ConnReq {
1✔
4979
        return p.cfg.ConnReq
1✔
4980
}
1✔
4981

4982
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
4983
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
1✔
4984
        return p.cfg.ErrorBuffer
1✔
4985
}
1✔
4986

4987
// SetAddress sets the remote peer's address given an address.
4988
func (p *Brontide) SetAddress(address net.Addr) {
×
4989
        p.cfg.Addr.Address = address
×
4990
}
×
4991

4992
// ActiveSignal returns the peer's active signal.
4993
func (p *Brontide) ActiveSignal() chan struct{} {
1✔
4994
        return p.activeSignal
1✔
4995
}
1✔
4996

4997
// Conn returns a pointer to the peer's connection struct.
4998
func (p *Brontide) Conn() net.Conn {
1✔
4999
        return p.cfg.Conn
1✔
5000
}
1✔
5001

5002
// BytesReceived returns the number of bytes received from the peer.
5003
func (p *Brontide) BytesReceived() uint64 {
1✔
5004
        return atomic.LoadUint64(&p.bytesReceived)
1✔
5005
}
1✔
5006

5007
// BytesSent returns the number of bytes sent to the peer.
5008
func (p *Brontide) BytesSent() uint64 {
1✔
5009
        return atomic.LoadUint64(&p.bytesSent)
1✔
5010
}
1✔
5011

5012
// LastRemotePingPayload returns the last payload the remote party sent as part
5013
// of their ping.
5014
func (p *Brontide) LastRemotePingPayload() []byte {
1✔
5015
        pingPayload := p.lastPingPayload.Load()
1✔
5016
        if pingPayload == nil {
2✔
5017
                return []byte{}
1✔
5018
        }
1✔
5019

5020
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
5021
        if !ok {
×
5022
                return nil
×
5023
        }
×
5024

5025
        return pingBytes
×
5026
}
5027

5028
// attachChannelEventSubscription creates a channel event subscription and
5029
// attaches to client to Brontide if the reenableTimeout is no greater than 1
5030
// minute.
5031
func (p *Brontide) attachChannelEventSubscription() error {
1✔
5032
        // If the timeout is greater than 1 minute, it's unlikely that the link
1✔
5033
        // hasn't yet finished its reestablishment. Return a nil without
1✔
5034
        // creating the client to specify that we don't want to retry.
1✔
5035
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
2✔
5036
                return nil
1✔
5037
        }
1✔
5038

5039
        // When the reenable timeout is less than 1 minute, it's likely the
5040
        // channel link hasn't finished its reestablishment yet. In that case,
5041
        // we'll give it a second chance by subscribing to the channel update
5042
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
5043
        // enabling the channel again.
5044
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
1✔
5045
        if err != nil {
1✔
5046
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
5047
        }
×
5048

5049
        p.channelEventClient = sub
1✔
5050

1✔
5051
        return nil
1✔
5052
}
5053

5054
// updateNextRevocation updates the existing channel's next revocation if it's
5055
// nil.
5056
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
1✔
5057
        chanPoint := c.FundingOutpoint
1✔
5058
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
1✔
5059

1✔
5060
        // Read the current channel.
1✔
5061
        currentChan, loaded := p.activeChannels.Load(chanID)
1✔
5062

1✔
5063
        // currentChan should exist, but we perform a check anyway to avoid nil
1✔
5064
        // pointer dereference.
1✔
5065
        if !loaded {
1✔
UNCOV
5066
                return fmt.Errorf("missing active channel with chanID=%v",
×
UNCOV
5067
                        chanID)
×
UNCOV
5068
        }
×
5069

5070
        // currentChan should not be nil, but we perform a check anyway to
5071
        // avoid nil pointer dereference.
5072
        if currentChan == nil {
1✔
UNCOV
5073
                return fmt.Errorf("found nil active channel with chanID=%v",
×
UNCOV
5074
                        chanID)
×
UNCOV
5075
        }
×
5076

5077
        // If we're being sent a new channel, and our existing channel doesn't
5078
        // have the next revocation, then we need to update the current
5079
        // existing channel.
5080
        if currentChan.RemoteNextRevocation() != nil {
1✔
5081
                return nil
×
5082
        }
×
5083

5084
        p.log.Infof("Processing retransmitted ChannelReady for "+
1✔
5085
                "ChannelPoint(%v)", chanPoint)
1✔
5086

1✔
5087
        nextRevoke := c.RemoteNextRevocation
1✔
5088

1✔
5089
        err := currentChan.InitNextRevocation(nextRevoke)
1✔
5090
        if err != nil {
1✔
5091
                return fmt.Errorf("unable to init next revocation: %w", err)
×
5092
        }
×
5093

5094
        return nil
1✔
5095
}
5096

5097
// addActiveChannel adds a new active channel to the `activeChannels` map. It
5098
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
5099
// it and assembles it with a channel link.
5100
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
1✔
5101
        chanPoint := c.FundingOutpoint
1✔
5102
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
1✔
5103

1✔
5104
        // If we've reached this point, there are two possible scenarios.  If
1✔
5105
        // the channel was in the active channels map as nil, then it was
1✔
5106
        // loaded from disk and we need to send reestablish. Else, it was not
1✔
5107
        // loaded from disk and we don't need to send reestablish as this is a
1✔
5108
        // fresh channel.
1✔
5109
        shouldReestablish := p.isLoadedFromDisk(chanID)
1✔
5110

1✔
5111
        chanOpts := c.ChanOpts
1✔
5112
        if shouldReestablish {
2✔
5113
                // If we have to do the reestablish dance for this channel,
1✔
5114
                // ensure that we don't try to call InitRemoteMusigNonces twice
1✔
5115
                // by calling SkipNonceInit.
1✔
5116
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
1✔
5117
        }
1✔
5118

5119
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
1✔
5120
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
5121
        })
×
5122
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
1✔
5123
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
5124
        })
×
5125
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
1✔
5126
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
5127
        })
×
5128

5129
        // If not already active, we'll add this channel to the set of active
5130
        // channels, so we can look it up later easily according to its channel
5131
        // ID.
5132
        lnChan, err := lnwallet.NewLightningChannel(
1✔
5133
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
1✔
5134
        )
1✔
5135
        if err != nil {
1✔
5136
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
5137
        }
×
5138

5139
        // Store the channel in the activeChannels map.
5140
        p.activeChannels.Store(chanID, lnChan)
1✔
5141

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

1✔
5144
        // Next, we'll assemble a ChannelLink along with the necessary items it
1✔
5145
        // needs to function.
1✔
5146
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
1✔
5147
        if err != nil {
1✔
5148
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
5149
                        err)
×
5150
        }
×
5151

5152
        // We'll query the channel DB for the new channel's initial forwarding
5153
        // policies to determine the policy we start out with.
5154
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
1✔
5155
        if err != nil {
1✔
5156
                return fmt.Errorf("unable to query for initial forwarding "+
×
5157
                        "policy: %v", err)
×
5158
        }
×
5159

5160
        // Create the link and add it to the switch.
5161
        err = p.addLink(
1✔
5162
                &chanPoint, lnChan, initialPolicy, chainEvents,
1✔
5163
                shouldReestablish, fn.None[lnwire.Shutdown](),
1✔
5164
        )
1✔
5165
        if err != nil {
1✔
5166
                return fmt.Errorf("can't register new channel link(%v) with "+
×
5167
                        "peer", chanPoint)
×
5168
        }
×
5169

5170
        isTaprootChan := c.ChanType.IsTaproot()
1✔
5171

1✔
5172
        // We're using the old co-op close, so we don't need to init the new RBF
1✔
5173
        // chan closer. If this is a taproot channel, then we'll also fall
1✔
5174
        // through, as we don't support this type yet w/ rbf close.
1✔
5175
        if !p.rbfCoopCloseAllowed() || isTaprootChan {
2✔
5176
                return nil
1✔
5177
        }
1✔
5178

5179
        // Now that the link has been added above, we'll also init an RBF chan
5180
        // closer for this channel, but only if the new close feature is
5181
        // negotiated.
5182
        //
5183
        // Creating this here ensures that any shutdown messages sent will be
5184
        // automatically routed by the msg router.
5185
        if _, err := p.initRbfChanCloser(lnChan); err != nil {
1✔
5186
                p.activeChanCloses.Delete(chanID)
×
5187

×
5188
                return fmt.Errorf("unable to init RBF chan closer for new "+
×
5189
                        "chan: %w", err)
×
5190
        }
×
5191

5192
        return nil
1✔
5193
}
5194

5195
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
5196
// know this channel ID or not, we'll either add it to the `activeChannels` map
5197
// or init the next revocation for it.
5198
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
1✔
5199
        newChan := req.channel
1✔
5200
        chanPoint := newChan.FundingOutpoint
1✔
5201
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
1✔
5202

1✔
5203
        // Only update RemoteNextRevocation if the channel is in the
1✔
5204
        // activeChannels map and if we added the link to the switch. Only
1✔
5205
        // active channels will be added to the switch.
1✔
5206
        if p.isActiveChannel(chanID) {
2✔
5207
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
1✔
5208
                        chanPoint)
1✔
5209

1✔
5210
                // Handle it and close the err chan on the request.
1✔
5211
                close(req.err)
1✔
5212

1✔
5213
                // Update the next revocation point.
1✔
5214
                err := p.updateNextRevocation(newChan.OpenChannel)
1✔
5215
                if err != nil {
1✔
5216
                        p.log.Errorf(err.Error())
×
5217
                }
×
5218

5219
                return
1✔
5220
        }
5221

5222
        // This is a new channel, we now add it to the map.
5223
        if err := p.addActiveChannel(req.channel); err != nil {
1✔
5224
                // Log and send back the error to the request.
×
5225
                p.log.Errorf(err.Error())
×
5226
                req.err <- err
×
5227

×
5228
                return
×
5229
        }
×
5230

5231
        // Close the err chan if everything went fine.
5232
        close(req.err)
1✔
5233
}
5234

5235
// handleNewPendingChannel takes a `newChannelMsg` request and add it to
5236
// `activeChannels` map with nil value. This pending channel will be saved as
5237
// it may become active in the future. Once active, the funding manager will
5238
// send it again via `AddNewChannel`, and we'd handle the link creation there.
5239
func (p *Brontide) handleNewPendingChannel(req *newChannelMsg) {
1✔
5240
        defer close(req.err)
1✔
5241

1✔
5242
        chanID := req.channelID
1✔
5243

1✔
5244
        // If we already have this channel, something is wrong with the funding
1✔
5245
        // flow as it will only be marked as active after `ChannelReady` is
1✔
5246
        // handled. In this case, we will do nothing but log an error, just in
1✔
5247
        // case this is a legit channel.
1✔
5248
        if p.isActiveChannel(chanID) {
1✔
UNCOV
5249
                p.log.Errorf("Channel(%v) is already active, ignoring "+
×
UNCOV
5250
                        "pending channel request", chanID)
×
UNCOV
5251

×
UNCOV
5252
                return
×
UNCOV
5253
        }
×
5254

5255
        // The channel has already been added, we will do nothing and return.
5256
        if p.isPendingChannel(chanID) {
1✔
UNCOV
5257
                p.log.Infof("Channel(%v) is already added, ignoring "+
×
UNCOV
5258
                        "pending channel request", chanID)
×
UNCOV
5259

×
UNCOV
5260
                return
×
UNCOV
5261
        }
×
5262

5263
        // This is a new channel, we now add it to the map `activeChannels`
5264
        // with nil value and mark it as a newly added channel in
5265
        // `addedChannels`.
5266
        p.activeChannels.Store(chanID, nil)
1✔
5267
        p.addedChannels.Store(chanID, struct{}{})
1✔
5268
}
5269

5270
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
5271
// from `activeChannels` map. The request will be ignored if the channel is
5272
// considered active by Brontide. Noop if the channel ID cannot be found.
5273
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
1✔
5274
        defer close(req.err)
1✔
5275

1✔
5276
        chanID := req.channelID
1✔
5277

1✔
5278
        // If we already have this channel, something is wrong with the funding
1✔
5279
        // flow as it will only be marked as active after `ChannelReady` is
1✔
5280
        // handled. In this case, we will log an error and exit.
1✔
5281
        if p.isActiveChannel(chanID) {
1✔
UNCOV
5282
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
×
UNCOV
5283
                        chanID)
×
UNCOV
5284
                return
×
UNCOV
5285
        }
×
5286

5287
        // The channel has not been added yet, we will log a warning as there
5288
        // is an unexpected call from funding manager.
5289
        if !p.isPendingChannel(chanID) {
2✔
5290
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
1✔
5291
        }
1✔
5292

5293
        // Remove the record of this pending channel.
5294
        p.activeChannels.Delete(chanID)
1✔
5295
        p.addedChannels.Delete(chanID)
1✔
5296
}
5297

5298
// sendLinkUpdateMsg sends a message that updates the channel to the
5299
// channel's message stream.
5300
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
1✔
5301
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
1✔
5302

1✔
5303
        chanStream, ok := p.activeMsgStreams[cid]
1✔
5304
        if !ok {
2✔
5305
                // If a stream hasn't yet been created, then we'll do so, add
1✔
5306
                // it to the map, and finally start it.
1✔
5307
                chanStream = newChanMsgStream(p, cid)
1✔
5308
                p.activeMsgStreams[cid] = chanStream
1✔
5309
                chanStream.Start()
1✔
5310

1✔
5311
                // Stop the stream when quit.
1✔
5312
                go func() {
2✔
5313
                        <-p.cg.Done()
1✔
5314
                        chanStream.Stop()
1✔
5315
                }()
1✔
5316
        }
5317

5318
        // With the stream obtained, add the message to the stream so we can
5319
        // continue processing message.
5320
        chanStream.AddMsg(msg)
1✔
5321
}
5322

5323
// scaleTimeout multiplies the argument duration by a constant factor depending
5324
// on variious heuristics. Currently this is only used to check whether our peer
5325
// appears to be connected over Tor and relaxes the timout deadline. However,
5326
// this is subject to change and should be treated as opaque.
5327
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
1✔
5328
        if p.isTorConnection {
2✔
5329
                return timeout * time.Duration(torTimeoutMultiplier)
1✔
5330
        }
1✔
5331

UNCOV
5332
        return timeout
×
5333
}
5334

5335
// CoopCloseUpdates is a struct used to communicate updates for an active close
5336
// to the caller.
5337
type CoopCloseUpdates struct {
5338
        UpdateChan chan interface{}
5339

5340
        ErrChan chan error
5341
}
5342

5343
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5344
// point has an active RBF chan closer.
5345
func (p *Brontide) ChanHasRbfCoopCloser(chanPoint wire.OutPoint) bool {
1✔
5346
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
1✔
5347
        chanCloser, found := p.activeChanCloses.Load(chanID)
1✔
5348
        if !found {
2✔
5349
                return false
1✔
5350
        }
1✔
5351

5352
        return chanCloser.IsRight()
1✔
5353
}
5354

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

1✔
5363
        // If RBF coop close isn't permitted, then we'll an error.
1✔
5364
        if !p.rbfCoopCloseAllowed() {
1✔
5365
                return nil, fmt.Errorf("rbf coop close not enabled for " +
×
5366
                        "channel")
×
5367
        }
×
5368

5369
        closeUpdates := &CoopCloseUpdates{
1✔
5370
                UpdateChan: make(chan interface{}, 1),
1✔
5371
                ErrChan:    make(chan error, 1),
1✔
5372
        }
1✔
5373

1✔
5374
        // We'll re-use the existing switch struct here, even though we're
1✔
5375
        // bypassing the switch entirely.
1✔
5376
        closeReq := htlcswitch.ChanClose{
1✔
5377
                CloseType:      contractcourt.CloseRegular,
1✔
5378
                ChanPoint:      &chanPoint,
1✔
5379
                TargetFeePerKw: feeRate,
1✔
5380
                DeliveryScript: deliveryScript,
1✔
5381
                Updates:        closeUpdates.UpdateChan,
1✔
5382
                Err:            closeUpdates.ErrChan,
1✔
5383
                Ctx:            ctx,
1✔
5384
        }
1✔
5385

1✔
5386
        err := p.startRbfChanCloser(newRPCShutdownInit(&closeReq), chanPoint)
1✔
5387
        if err != nil {
1✔
5388
                return nil, err
×
5389
        }
×
5390

5391
        return closeUpdates, nil
1✔
5392
}
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