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

lightningnetwork / lnd / 15782265189

20 Jun 2025 03:23PM UTC coverage: 68.14% (-0.003%) from 68.143%
15782265189

Pull #9958

github

web-flow
Merge ae1a1d1ba into 7857d2c6a
Pull Request #9958: improve CloseChannel docs

134478 of 197355 relevant lines covered (68.14%)

22170.18 hits per line

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

78.65
/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 {
12✔
475
        return fn.NewLeft[*chancloser.ChanCloser, *chancloser.RbfChanCloser](
12✔
476
                chanCloser,
12✔
477
        )
12✔
478
}
12✔
479

480
// makeRbfCloser creates a new RBF closer from a chancloser.RbfChanCloser.
481
func makeRbfCloser(rbfCloser *chancloser.RbfChanCloser) chanCloserFsm {
3✔
482
        return fn.NewRight[*chancloser.ChanCloser](
3✔
483
                rbfCloser,
3✔
484
        )
3✔
485
}
3✔
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 {
28✔
644
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
28✔
645

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

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

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

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

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

691
        var (
28✔
692
                lastBlockHeader           *wire.BlockHeader
28✔
693
                lastSerializedBlockHeader [wire.MaxBlockHeaderPayload]byte
28✔
694
        )
28✔
695
        newPingPayload := func() []byte {
28✔
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 {
28✔
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{
28✔
735
                NewPingPayload:   newPingPayload,
28✔
736
                NewPongSize:      randPongSize,
28✔
737
                IntervalDuration: p.scaleTimeout(pingInterval),
28✔
738
                TimeoutDuration:  p.scaleTimeout(pingTimeout),
28✔
739
                SendPing: func(ping *lnwire.Ping) {
28✔
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
28✔
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 {
6✔
772
        if atomic.AddInt32(&p.started, 1) != 1 {
6✔
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)
6✔
780

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

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

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

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

807
                haveLegacyChan = true
3✔
808
                break
3✔
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 {
8✔
814
                return fmt.Errorf("unable to send init msg: %w", err)
2✔
815
        }
2✔
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)
6✔
821
        msgChan := make(chan lnwire.Message, 1)
6✔
822
        p.cg.WgAdd(1)
6✔
823
        go func() {
12✔
824
                defer p.cg.WgDone()
6✔
825

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

836
        select {
6✔
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:
6✔
843
                if err != nil {
7✔
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
6✔
851
        if msg, ok := msg.(*lnwire.Init); ok {
12✔
852
                if err := p.handleInitMsg(msg); err != nil {
6✔
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",
6✔
865
                len(activeChans))
6✔
866

6✔
867
        // Conditionally subscribe to channel events before loading channels so
6✔
868
        // we won't miss events. This subscription is used to listen to active
6✔
869
        // channel event when reenabling channels. Once the reenabling process
6✔
870
        // is finished, this subscription will be canceled.
6✔
871
        //
6✔
872
        // NOTE: ChannelNotifier must be started before subscribing events
6✔
873
        // otherwise we'd panic here.
6✔
874
        if err := p.attachChannelEventSubscription(); err != nil {
6✔
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) {
12✔
881
                router.Start(context.Background())
6✔
882
        })
6✔
883

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

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

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

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

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

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

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

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

6✔
937
        return nil
6✔
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() {
6✔
943
        // If the remote peer knows of the new gossip queries feature, then
6✔
944
        // we'll create a new gossipSyncer in the AuthenticatedGossiper for it.
6✔
945
        if p.remoteFeatures.HasFeature(lnwire.GossipQueriesOptional) {
12✔
946
                p.log.Info("Negotiated chan series queries")
6✔
947

6✔
948
                if p.cfg.AuthGossiper == nil {
9✔
949
                        // This should only ever be hit in the unit tests.
3✔
950
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
3✔
951
                                "gossip sync.")
3✔
952
                        return
3✔
953
                }
3✔
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)
3✔
965
        }
966
}
967

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

975
// rbfCoopCloseAllowed returns true if both parties have negotiated the new RBF
976
// coop close feature.
977
func (p *Brontide) rbfCoopCloseAllowed() bool {
10✔
978
        bothHaveBit := func(bit lnwire.FeatureBit) bool {
27✔
979
                return p.RemoteFeatures().HasFeature(bit) &&
17✔
980
                        p.LocalFeatures().HasFeature(bit)
17✔
981
        }
17✔
982

983
        return bothHaveBit(lnwire.RbfCoopCloseOptional) ||
10✔
984
                bothHaveBit(lnwire.RbfCoopCloseOptionalStaging)
10✔
985
}
986

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

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

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

1014
        return &chancloser.DeliveryAddrWithKey{
12✔
1015
                DeliveryAddress: deliveryScript,
12✔
1016
                InternalKey: fn.MapOption(
12✔
1017
                        func(desc keychain.KeyDescriptor) btcec.PublicKey {
15✔
1018
                                return *desc.PubKey
3✔
1019
                        },
3✔
1020
                )(internalKeyDesc),
1021
        }, nil
1022
}
1023

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

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

6✔
1035
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
6✔
1036

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

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

1065
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
1066
                                        dbChan.FundingOutpoint,
3✔
1067
                                )
3✔
1068

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

1076
                                channelReadyMsg := lnwire.NewChannelReady(
3✔
1077
                                        chanID, second,
3✔
1078
                                )
3✔
1079
                                channelReadyMsg.AliasScid = &aliasScid
3✔
1080

3✔
1081
                                msgs = append(msgs, channelReadyMsg)
3✔
1082
                        }
1083

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

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

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

1118
                chanPoint := dbChan.FundingOutpoint
5✔
1119

5✔
1120
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
5✔
1121

5✔
1122
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
5✔
1123
                        chanPoint, lnChan.IsPending())
5✔
1124

5✔
1125
                // Skip adding any permanently irreconcilable channels to the
5✔
1126
                // htlcswitch.
5✔
1127
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
5✔
1128
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
10✔
1129

5✔
1130
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
5✔
1131
                                "start.", chanPoint, dbChan.ChanStatus())
5✔
1132

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

1147
                        msgs = append(msgs, chanSync)
5✔
1148

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

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

1164
                                if shutdownMsg == nil {
6✔
1165
                                        continue
3✔
1166
                                }
1167

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

1173
                        continue
5✔
1174
                }
1175

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

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

3✔
1198
                        selfPolicy = p1
3✔
1199
                } else {
6✔
1200
                        selfPolicy = p2
3✔
1201
                }
3✔
1202

1203
                // If we don't yet have an advertised routing policy, then
1204
                // we'll use the current default, otherwise we'll translate the
1205
                // routing policy into a forwarding policy.
1206
                var forwardingPolicy *models.ForwardingPolicy
3✔
1207
                if selfPolicy != nil {
6✔
1208
                        forwardingPolicy = &models.ForwardingPolicy{
3✔
1209
                                MinHTLCOut:    selfPolicy.MinHTLC,
3✔
1210
                                MaxHTLC:       selfPolicy.MaxHTLC,
3✔
1211
                                BaseFee:       selfPolicy.FeeBaseMSat,
3✔
1212
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
3✔
1213
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
3✔
1214
                        }
3✔
1215
                        selfPolicy.InboundFee.WhenSome(func(fee lnwire.Fee) {
3✔
1216
                                inboundFee := models.NewInboundFeeFromWire(fee)
×
1217
                                forwardingPolicy.InboundFee = inboundFee
×
1218
                        })
×
1219
                } else {
3✔
1220
                        p.log.Warnf("Unable to find our forwarding policy "+
3✔
1221
                                "for channel %v, using default values",
3✔
1222
                                chanPoint)
3✔
1223
                        forwardingPolicy = &p.cfg.RoutingPolicy
3✔
1224
                }
3✔
1225

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

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

3✔
1238
                        continue
3✔
1239
                }
1240

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

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

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

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

×
1268
                                return
×
1269
                        }
×
1270

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

×
1287
                                return
×
1288
                        }
×
1289

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

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

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

×
1304
                                return
×
1305
                        }
×
1306

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

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

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

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

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

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

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

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

1369
        return msgs, nil
6✔
1370
}
1371

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
1542
                        return nil
3✔
1543
                }
3✔
1544

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

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

×
1557
                        return err
×
1558
                }
×
1559

1560
                return nil
5✔
1561
        }
1562

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

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

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

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

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

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

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

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

3✔
1618
        p.log.Infof(err.Error())
3✔
1619

3✔
1620
        // Stop PingManager before closing TCP connection.
3✔
1621
        p.pingManager.Stop()
3✔
1622

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

3✔
1626
        p.cg.Quit()
3✔
1627

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

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

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

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

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

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

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

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

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

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

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

1718
        peer *Brontide
1719

1720
        apply func(lnwire.Message)
1721

1722
        startMsg string
1723
        stopMsg  string
1724

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

1728
        mtx sync.Mutex
1729

1730
        producerSema chan struct{}
1731

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

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

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

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

1762
        return stream
6✔
1763
}
1764

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1916
                        chanPoint := event.ChannelPoint
3✔
1917

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

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

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

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

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

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

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

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

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

1979
// newDiscMsgStream is used to setup a msgStream between the peer and the
1980
// authenticated gossiper. This stream should be used to forward all remote
1981
// channel announcements.
1982
func newDiscMsgStream(p *Brontide) *msgStream {
6✔
1983
        apply := func(msg lnwire.Message) {
9✔
1984
                // TODO(elle): thread contexts through the peer system properly
3✔
1985
                // so that a parent context can be passed in here.
3✔
1986
                ctx := context.TODO()
3✔
1987

3✔
1988
                p.log.Debugf("Processing remote msg %T", msg)
3✔
1989

3✔
1990
                errChan := p.cfg.AuthGossiper.ProcessRemoteAnnouncement(
3✔
1991
                        ctx, msg, p,
3✔
1992
                )
3✔
1993

3✔
1994
                // Start a goroutine to process the error channel for logging
3✔
1995
                // purposes.
3✔
1996
                //
3✔
1997
                // TODO(ziggie): Maybe use the error to potentially punish the
3✔
1998
                // peer depending on the error ?
3✔
1999
                go func() {
6✔
2000
                        select {
3✔
2001
                        case <-p.cg.Done():
3✔
2002
                                return
3✔
2003

2004
                        case err := <-errChan:
3✔
2005
                                if err != nil {
6✔
2006
                                        p.log.Warnf("Error processing remote "+
3✔
2007
                                                "msg %T: %v", msg,
3✔
2008
                                                err)
3✔
2009
                                }
3✔
2010
                        }
2011

2012
                        p.log.Debugf("Processed remote msg %T", msg)
3✔
2013
                }()
2014
        }
2015

2016
        return newMsgStream(
6✔
2017
                p,
6✔
2018
                "Update stream for gossiper created",
6✔
2019
                "Update stream for gossiper exited",
6✔
2020
                msgStreamSize,
6✔
2021
                apply,
6✔
2022
        )
6✔
2023
}
2024

2025
// readHandler is responsible for reading messages off the wire in series, then
2026
// properly dispatching the handling of the message to the proper subsystem.
2027
//
2028
// NOTE: This method MUST be run as a goroutine.
2029
func (p *Brontide) readHandler() {
6✔
2030
        defer p.cg.WgDone()
6✔
2031

6✔
2032
        // We'll stop the timer after a new messages is received, and also
6✔
2033
        // reset it after we process the next message.
6✔
2034
        idleTimer := time.AfterFunc(idleTimeout, func() {
6✔
2035
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
2036
                        p, idleTimeout)
×
2037
                p.Disconnect(err)
×
2038
        })
×
2039

2040
        // Initialize our negotiated gossip sync method before reading messages
2041
        // off the wire. When using gossip queries, this ensures a gossip
2042
        // syncer is active by the time query messages arrive.
2043
        //
2044
        // TODO(conner): have peer store gossip syncer directly and bypass
2045
        // gossiper?
2046
        p.initGossipSync()
6✔
2047

6✔
2048
        discStream := newDiscMsgStream(p)
6✔
2049
        discStream.Start()
6✔
2050
        defer discStream.Stop()
6✔
2051
out:
6✔
2052
        for atomic.LoadInt32(&p.disconnect) == 0 {
13✔
2053
                nextMsg, err := p.readNextMessage()
7✔
2054
                if !idleTimer.Stop() {
10✔
2055
                        select {
3✔
2056
                        case <-idleTimer.C:
×
2057
                        default:
3✔
2058
                        }
2059
                }
2060
                if err != nil {
7✔
2061
                        p.log.Infof("unable to read message from peer: %v", err)
3✔
2062

3✔
2063
                        // If we could not read our peer's message due to an
3✔
2064
                        // unknown type or invalid alias, we continue processing
3✔
2065
                        // as normal. We store unknown message and address
3✔
2066
                        // types, as they may provide debugging insight.
3✔
2067
                        switch e := err.(type) {
3✔
2068
                        // If this is just a message we don't yet recognize,
2069
                        // we'll continue processing as normal as this allows
2070
                        // us to introduce new messages in a forwards
2071
                        // compatible manner.
2072
                        case *lnwire.UnknownMessage:
3✔
2073
                                p.storeError(e)
3✔
2074
                                idleTimer.Reset(idleTimeout)
3✔
2075
                                continue
3✔
2076

2077
                        // If they sent us an address type that we don't yet
2078
                        // know of, then this isn't a wire error, so we'll
2079
                        // simply continue parsing the remainder of their
2080
                        // messages.
2081
                        case *lnwire.ErrUnknownAddrType:
×
2082
                                p.storeError(e)
×
2083
                                idleTimer.Reset(idleTimeout)
×
2084
                                continue
×
2085

2086
                        // If the NodeAnnouncement has an invalid alias, then
2087
                        // we'll log that error above and continue so we can
2088
                        // continue to read messages from the peer. We do not
2089
                        // store this error because it is of little debugging
2090
                        // value.
2091
                        case *lnwire.ErrInvalidNodeAlias:
×
2092
                                idleTimer.Reset(idleTimeout)
×
2093
                                continue
×
2094

2095
                        // If the error we encountered wasn't just a message we
2096
                        // didn't recognize, then we'll stop all processing as
2097
                        // this is a fatal error.
2098
                        default:
3✔
2099
                                break out
3✔
2100
                        }
2101
                }
2102

2103
                // If a message router is active, then we'll try to have it
2104
                // handle this message. If it can, then we're able to skip the
2105
                // rest of the message handling logic.
2106
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
8✔
2107
                        return r.RouteMsg(msgmux.PeerMsg{
4✔
2108
                                PeerPub: *p.IdentityKey(),
4✔
2109
                                Message: nextMsg,
4✔
2110
                        })
4✔
2111
                })
4✔
2112

2113
                // No error occurred, and the message was handled by the
2114
                // router.
2115
                if err == nil {
7✔
2116
                        continue
3✔
2117
                }
2118

2119
                var (
4✔
2120
                        targetChan   lnwire.ChannelID
4✔
2121
                        isLinkUpdate bool
4✔
2122
                )
4✔
2123

4✔
2124
                switch msg := nextMsg.(type) {
4✔
2125
                case *lnwire.Pong:
×
2126
                        // When we receive a Pong message in response to our
×
2127
                        // last ping message, we send it to the pingManager
×
2128
                        p.pingManager.ReceivedPong(msg)
×
2129

2130
                case *lnwire.Ping:
×
2131
                        // First, we'll store their latest ping payload within
×
2132
                        // the relevant atomic variable.
×
2133
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
2134

×
2135
                        // Next, we'll send over the amount of specified pong
×
2136
                        // bytes.
×
2137
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
×
2138
                        p.queueMsg(pong, nil)
×
2139

2140
                case *lnwire.OpenChannel,
2141
                        *lnwire.AcceptChannel,
2142
                        *lnwire.FundingCreated,
2143
                        *lnwire.FundingSigned,
2144
                        *lnwire.ChannelReady:
3✔
2145

3✔
2146
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2147

2148
                case *lnwire.Shutdown:
3✔
2149
                        select {
3✔
2150
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
2151
                        case <-p.cg.Done():
×
2152
                                break out
×
2153
                        }
2154
                case *lnwire.ClosingSigned:
3✔
2155
                        select {
3✔
2156
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
2157
                        case <-p.cg.Done():
×
2158
                                break out
×
2159
                        }
2160

2161
                case *lnwire.Warning:
×
2162
                        targetChan = msg.ChanID
×
2163
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2164

2165
                case *lnwire.Error:
3✔
2166
                        targetChan = msg.ChanID
3✔
2167
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
3✔
2168

2169
                case *lnwire.ChannelReestablish:
3✔
2170
                        targetChan = msg.ChanID
3✔
2171
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2172

3✔
2173
                        // If we failed to find the link in question, and the
3✔
2174
                        // message received was a channel sync message, then
3✔
2175
                        // this might be a peer trying to resync closed channel.
3✔
2176
                        // In this case we'll try to resend our last channel
3✔
2177
                        // sync message, such that the peer can recover funds
3✔
2178
                        // from the closed channel.
3✔
2179
                        if !isLinkUpdate {
6✔
2180
                                err := p.resendChanSyncMsg(targetChan)
3✔
2181
                                if err != nil {
6✔
2182
                                        // TODO(halseth): send error to peer?
3✔
2183
                                        p.log.Errorf("resend failed: %v",
3✔
2184
                                                err)
3✔
2185
                                }
3✔
2186
                        }
2187

2188
                // For messages that implement the LinkUpdater interface, we
2189
                // will consider them as link updates and send them to
2190
                // chanStream. These messages will be queued inside chanStream
2191
                // if the channel is not active yet.
2192
                case lnwire.LinkUpdater:
3✔
2193
                        targetChan = msg.TargetChanID()
3✔
2194
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2195

3✔
2196
                        // Log an error if we don't have this channel. This
3✔
2197
                        // means the peer has sent us a message with unknown
3✔
2198
                        // channel ID.
3✔
2199
                        if !isLinkUpdate {
6✔
2200
                                p.log.Errorf("Unknown channel ID: %v found "+
3✔
2201
                                        "in received msg=%s", targetChan,
3✔
2202
                                        nextMsg.MsgType())
3✔
2203
                        }
3✔
2204

2205
                case *lnwire.ChannelUpdate1,
2206
                        *lnwire.ChannelAnnouncement1,
2207
                        *lnwire.NodeAnnouncement,
2208
                        *lnwire.AnnounceSignatures1,
2209
                        *lnwire.GossipTimestampRange,
2210
                        *lnwire.QueryShortChanIDs,
2211
                        *lnwire.QueryChannelRange,
2212
                        *lnwire.ReplyChannelRange,
2213
                        *lnwire.ReplyShortChanIDsEnd:
3✔
2214

3✔
2215
                        discStream.AddMsg(msg)
3✔
2216

2217
                case *lnwire.Custom:
4✔
2218
                        err := p.handleCustomMessage(msg)
4✔
2219
                        if err != nil {
4✔
2220
                                p.storeError(err)
×
2221
                                p.log.Errorf("%v", err)
×
2222
                        }
×
2223

2224
                default:
×
2225
                        // If the message we received is unknown to us, store
×
2226
                        // the type to track the failure.
×
2227
                        err := fmt.Errorf("unknown message type %v received",
×
2228
                                uint16(msg.MsgType()))
×
2229
                        p.storeError(err)
×
2230

×
2231
                        p.log.Errorf("%v", err)
×
2232
                }
2233

2234
                if isLinkUpdate {
7✔
2235
                        // If this is a channel update, then we need to feed it
3✔
2236
                        // into the channel's in-order message stream.
3✔
2237
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
3✔
2238
                }
3✔
2239

2240
                idleTimer.Reset(idleTimeout)
4✔
2241
        }
2242

2243
        p.Disconnect(errors.New("read handler closed"))
3✔
2244

3✔
2245
        p.log.Trace("readHandler for peer done")
3✔
2246
}
2247

2248
// handleCustomMessage handles the given custom message if a handler is
2249
// registered.
2250
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
4✔
2251
        if p.cfg.HandleCustomMessage == nil {
4✔
2252
                return fmt.Errorf("no custom message handler for "+
×
2253
                        "message type %v", uint16(msg.MsgType()))
×
2254
        }
×
2255

2256
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
4✔
2257
}
2258

2259
// isLoadedFromDisk returns true if the provided channel ID is loaded from
2260
// disk.
2261
//
2262
// NOTE: only returns true for pending channels.
2263
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
3✔
2264
        // If this is a newly added channel, no need to reestablish.
3✔
2265
        _, added := p.addedChannels.Load(chanID)
3✔
2266
        if added {
6✔
2267
                return false
3✔
2268
        }
3✔
2269

2270
        // Return false if the channel is unknown.
2271
        channel, ok := p.activeChannels.Load(chanID)
3✔
2272
        if !ok {
3✔
2273
                return false
×
2274
        }
×
2275

2276
        // During startup, we will use a nil value to mark a pending channel
2277
        // that's loaded from disk.
2278
        return channel == nil
3✔
2279
}
2280

2281
// isActiveChannel returns true if the provided channel id is active, otherwise
2282
// returns false.
2283
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
11✔
2284
        // The channel would be nil if,
11✔
2285
        // - the channel doesn't exist, or,
11✔
2286
        // - the channel exists, but is pending. In this case, we don't
11✔
2287
        //   consider this channel active.
11✔
2288
        channel, _ := p.activeChannels.Load(chanID)
11✔
2289

11✔
2290
        return channel != nil
11✔
2291
}
11✔
2292

2293
// isPendingChannel returns true if the provided channel ID is pending, and
2294
// returns false if the channel is active or unknown.
2295
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
9✔
2296
        // Return false if the channel is unknown.
9✔
2297
        channel, ok := p.activeChannels.Load(chanID)
9✔
2298
        if !ok {
15✔
2299
                return false
6✔
2300
        }
6✔
2301

2302
        return channel == nil
6✔
2303
}
2304

2305
// hasChannel returns true if the peer has a pending/active channel specified
2306
// by the channel ID.
2307
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
3✔
2308
        _, ok := p.activeChannels.Load(chanID)
3✔
2309
        return ok
3✔
2310
}
3✔
2311

2312
// storeError stores an error in our peer's buffer of recent errors with the
2313
// current timestamp. Errors are only stored if we have at least one active
2314
// channel with the peer to mitigate a dos vector where a peer costlessly
2315
// connects to us and spams us with errors.
2316
func (p *Brontide) storeError(err error) {
3✔
2317
        var haveChannels bool
3✔
2318

3✔
2319
        p.activeChannels.Range(func(_ lnwire.ChannelID,
3✔
2320
                channel *lnwallet.LightningChannel) bool {
6✔
2321

3✔
2322
                // Pending channels will be nil in the activeChannels map.
3✔
2323
                if channel == nil {
6✔
2324
                        // Return true to continue the iteration.
3✔
2325
                        return true
3✔
2326
                }
3✔
2327

2328
                haveChannels = true
3✔
2329

3✔
2330
                // Return false to break the iteration.
3✔
2331
                return false
3✔
2332
        })
2333

2334
        // If we do not have any active channels with the peer, we do not store
2335
        // errors as a dos mitigation.
2336
        if !haveChannels {
6✔
2337
                p.log.Trace("no channels with peer, not storing err")
3✔
2338
                return
3✔
2339
        }
3✔
2340

2341
        p.cfg.ErrorBuffer.Add(
3✔
2342
                &TimestampedError{Timestamp: time.Now(), Error: err},
3✔
2343
        )
3✔
2344
}
2345

2346
// handleWarningOrError processes a warning or error msg and returns true if
2347
// msg should be forwarded to the associated channel link. False is returned if
2348
// any necessary forwarding of msg was already handled by this method. If msg is
2349
// an error from a peer with an active channel, we'll store it in memory.
2350
//
2351
// NOTE: This method should only be called from within the readHandler.
2352
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
2353
        msg lnwire.Message) bool {
3✔
2354

3✔
2355
        if errMsg, ok := msg.(*lnwire.Error); ok {
6✔
2356
                p.storeError(errMsg)
3✔
2357
        }
3✔
2358

2359
        switch {
3✔
2360
        // Connection wide messages should be forwarded to all channel links
2361
        // with this peer.
2362
        case chanID == lnwire.ConnectionWideID:
×
2363
                for _, chanStream := range p.activeMsgStreams {
×
2364
                        chanStream.AddMsg(msg)
×
2365
                }
×
2366

2367
                return false
×
2368

2369
        // If the channel ID for the message corresponds to a pending channel,
2370
        // then the funding manager will handle it.
2371
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
3✔
2372
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2373
                return false
3✔
2374

2375
        // If not we hand the message to the channel link for this channel.
2376
        case p.isActiveChannel(chanID):
3✔
2377
                return true
3✔
2378

2379
        default:
3✔
2380
                return false
3✔
2381
        }
2382
}
2383

2384
// messageSummary returns a human-readable string that summarizes a
2385
// incoming/outgoing message. Not all messages will have a summary, only those
2386
// which have additional data that can be informative at a glance.
2387
func messageSummary(msg lnwire.Message) string {
3✔
2388
        switch msg := msg.(type) {
3✔
2389
        case *lnwire.Init:
3✔
2390
                // No summary.
3✔
2391
                return ""
3✔
2392

2393
        case *lnwire.OpenChannel:
3✔
2394
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
3✔
2395
                        "push_amt=%v, reserve=%v, flags=%v",
3✔
2396
                        msg.PendingChannelID[:], msg.ChainHash,
3✔
2397
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
3✔
2398
                        msg.ChannelReserve, msg.ChannelFlags)
3✔
2399

2400
        case *lnwire.AcceptChannel:
3✔
2401
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
3✔
2402
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
3✔
2403
                        msg.MinAcceptDepth)
3✔
2404

2405
        case *lnwire.FundingCreated:
3✔
2406
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
3✔
2407
                        msg.PendingChannelID[:], msg.FundingPoint)
3✔
2408

2409
        case *lnwire.FundingSigned:
3✔
2410
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
3✔
2411

2412
        case *lnwire.ChannelReady:
3✔
2413
                return fmt.Sprintf("chan_id=%v, next_point=%x",
3✔
2414
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
3✔
2415

2416
        case *lnwire.Shutdown:
3✔
2417
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
3✔
2418
                        msg.Address[:])
3✔
2419

2420
        case *lnwire.ClosingComplete:
3✔
2421
                return fmt.Sprintf("chan_id=%v, fee_sat=%v, locktime=%v",
3✔
2422
                        msg.ChannelID, msg.FeeSatoshis, msg.LockTime)
3✔
2423

2424
        case *lnwire.ClosingSig:
3✔
2425
                return fmt.Sprintf("chan_id=%v", msg.ChannelID)
3✔
2426

2427
        case *lnwire.ClosingSigned:
3✔
2428
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
3✔
2429
                        msg.FeeSatoshis)
3✔
2430

2431
        case *lnwire.UpdateAddHTLC:
3✔
2432
                var blindingPoint []byte
3✔
2433
                msg.BlindingPoint.WhenSome(
3✔
2434
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
3✔
2435
                                *btcec.PublicKey]) {
6✔
2436

3✔
2437
                                blindingPoint = b.Val.SerializeCompressed()
3✔
2438
                        },
3✔
2439
                )
2440

2441
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
3✔
2442
                        "hash=%x, blinding_point=%x, custom_records=%v",
3✔
2443
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
3✔
2444
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
3✔
2445

2446
        case *lnwire.UpdateFailHTLC:
3✔
2447
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
3✔
2448
                        msg.ID, msg.Reason)
3✔
2449

2450
        case *lnwire.UpdateFulfillHTLC:
3✔
2451
                return fmt.Sprintf("chan_id=%v, id=%v, preimage=%x, "+
3✔
2452
                        "custom_records=%v", msg.ChanID, msg.ID,
3✔
2453
                        msg.PaymentPreimage[:], msg.CustomRecords)
3✔
2454

2455
        case *lnwire.CommitSig:
3✔
2456
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
3✔
2457
                        len(msg.HtlcSigs))
3✔
2458

2459
        case *lnwire.RevokeAndAck:
3✔
2460
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
3✔
2461
                        msg.ChanID, msg.Revocation[:],
3✔
2462
                        msg.NextRevocationKey.SerializeCompressed())
3✔
2463

2464
        case *lnwire.UpdateFailMalformedHTLC:
3✔
2465
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
3✔
2466
                        msg.ChanID, msg.ID, msg.FailureCode)
3✔
2467

2468
        case *lnwire.Warning:
×
2469
                return fmt.Sprintf("%v", msg.Warning())
×
2470

2471
        case *lnwire.Error:
3✔
2472
                return fmt.Sprintf("%v", msg.Error())
3✔
2473

2474
        case *lnwire.AnnounceSignatures1:
3✔
2475
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
3✔
2476
                        msg.ShortChannelID.ToUint64())
3✔
2477

2478
        case *lnwire.ChannelAnnouncement1:
3✔
2479
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
3✔
2480
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
3✔
2481

2482
        case *lnwire.ChannelUpdate1:
3✔
2483
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
3✔
2484
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
3✔
2485
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
3✔
2486
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
3✔
2487

2488
        case *lnwire.NodeAnnouncement:
3✔
2489
                return fmt.Sprintf("node=%x, update_time=%v",
3✔
2490
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
3✔
2491

2492
        case *lnwire.Ping:
×
2493
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
2494

2495
        case *lnwire.Pong:
×
2496
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
×
2497

2498
        case *lnwire.UpdateFee:
×
2499
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2500
                        msg.ChanID, int64(msg.FeePerKw))
×
2501

2502
        case *lnwire.ChannelReestablish:
3✔
2503
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
3✔
2504
                        "remote_tail_height=%v", msg.ChanID,
3✔
2505
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
3✔
2506

2507
        case *lnwire.ReplyShortChanIDsEnd:
3✔
2508
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
3✔
2509
                        msg.Complete)
3✔
2510

2511
        case *lnwire.ReplyChannelRange:
3✔
2512
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
3✔
2513
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
3✔
2514
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
3✔
2515
                        msg.EncodingType)
3✔
2516

2517
        case *lnwire.QueryShortChanIDs:
3✔
2518
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
3✔
2519
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
3✔
2520

2521
        case *lnwire.QueryChannelRange:
3✔
2522
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
3✔
2523
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
3✔
2524
                        msg.LastBlockHeight())
3✔
2525

2526
        case *lnwire.GossipTimestampRange:
3✔
2527
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
3✔
2528
                        "stamp_range=%v", msg.ChainHash,
3✔
2529
                        time.Unix(int64(msg.FirstTimestamp), 0),
3✔
2530
                        msg.TimestampRange)
3✔
2531

2532
        case *lnwire.Stfu:
3✔
2533
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
3✔
2534
                        msg.Initiator)
3✔
2535

2536
        case *lnwire.Custom:
3✔
2537
                return fmt.Sprintf("type=%d", msg.Type)
3✔
2538
        }
2539

2540
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2541
}
2542

2543
// logWireMessage logs the receipt or sending of particular wire message. This
2544
// function is used rather than just logging the message in order to produce
2545
// less spammy log messages in trace mode by setting the 'Curve" parameter to
2546
// nil. Doing this avoids printing out each of the field elements in the curve
2547
// parameters for secp256k1.
2548
func (p *Brontide) logWireMessage(msg lnwire.Message, read bool) {
20✔
2549
        summaryPrefix := "Received"
20✔
2550
        if !read {
36✔
2551
                summaryPrefix = "Sending"
16✔
2552
        }
16✔
2553

2554
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
23✔
2555
                // Debug summary of message.
3✔
2556
                summary := messageSummary(msg)
3✔
2557
                if len(summary) > 0 {
6✔
2558
                        summary = "(" + summary + ")"
3✔
2559
                }
3✔
2560

2561
                preposition := "to"
3✔
2562
                if read {
6✔
2563
                        preposition = "from"
3✔
2564
                }
3✔
2565

2566
                var msgType string
3✔
2567
                if msg.MsgType() < lnwire.CustomTypeStart {
6✔
2568
                        msgType = msg.MsgType().String()
3✔
2569
                } else {
6✔
2570
                        msgType = "custom"
3✔
2571
                }
3✔
2572

2573
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
3✔
2574
                        msgType, summary, preposition, p)
3✔
2575
        }))
2576

2577
        prefix := "readMessage from peer"
20✔
2578
        if !read {
36✔
2579
                prefix = "writeMessage to peer"
16✔
2580
        }
16✔
2581

2582
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
20✔
2583
}
2584

2585
// writeMessage writes and flushes the target lnwire.Message to the remote peer.
2586
// If the passed message is nil, this method will only try to flush an existing
2587
// message buffered on the connection. It is safe to call this method again
2588
// with a nil message iff a timeout error is returned. This will continue to
2589
// flush the pending message to the wire.
2590
//
2591
// NOTE:
2592
// Besides its usage in Start, this function should not be used elsewhere
2593
// except in writeHandler. If multiple goroutines call writeMessage at the same
2594
// time, panics can occur because WriteMessage and Flush don't use any locking
2595
// internally.
2596
func (p *Brontide) writeMessage(msg lnwire.Message) error {
16✔
2597
        // Only log the message on the first attempt.
16✔
2598
        if msg != nil {
32✔
2599
                p.logWireMessage(msg, false)
16✔
2600
        }
16✔
2601

2602
        noiseConn := p.cfg.Conn
16✔
2603

16✔
2604
        flushMsg := func() error {
32✔
2605
                // Ensure the write deadline is set before we attempt to send
16✔
2606
                // the message.
16✔
2607
                writeDeadline := time.Now().Add(
16✔
2608
                        p.scaleTimeout(writeMessageTimeout),
16✔
2609
                )
16✔
2610
                err := noiseConn.SetWriteDeadline(writeDeadline)
16✔
2611
                if err != nil {
16✔
2612
                        return err
×
2613
                }
×
2614

2615
                // Flush the pending message to the wire. If an error is
2616
                // encountered, e.g. write timeout, the number of bytes written
2617
                // so far will be returned.
2618
                n, err := noiseConn.Flush()
16✔
2619

16✔
2620
                // Record the number of bytes written on the wire, if any.
16✔
2621
                if n > 0 {
19✔
2622
                        atomic.AddUint64(&p.bytesSent, uint64(n))
3✔
2623
                }
3✔
2624

2625
                return err
16✔
2626
        }
2627

2628
        // If the current message has already been serialized, encrypted, and
2629
        // buffered on the underlying connection we will skip straight to
2630
        // flushing it to the wire.
2631
        if msg == nil {
16✔
2632
                return flushMsg()
×
2633
        }
×
2634

2635
        // Otherwise, this is a new message. We'll acquire a write buffer to
2636
        // serialize the message and buffer the ciphertext on the connection.
2637
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
32✔
2638
                // Using a buffer allocated by the write pool, encode the
16✔
2639
                // message directly into the buffer.
16✔
2640
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
16✔
2641
                if writeErr != nil {
16✔
2642
                        return writeErr
×
2643
                }
×
2644

2645
                // Finally, write the message itself in a single swoop. This
2646
                // will buffer the ciphertext on the underlying connection. We
2647
                // will defer flushing the message until the write pool has been
2648
                // released.
2649
                return noiseConn.WriteMessage(buf.Bytes())
16✔
2650
        })
2651
        if err != nil {
16✔
2652
                return err
×
2653
        }
×
2654

2655
        return flushMsg()
16✔
2656
}
2657

2658
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2659
// queue, and writing them out to the wire. This goroutine coordinates with the
2660
// queueHandler in order to ensure the incoming message queue is quickly
2661
// drained.
2662
//
2663
// NOTE: This method MUST be run as a goroutine.
2664
func (p *Brontide) writeHandler() {
6✔
2665
        // We'll stop the timer after a new messages is sent, and also reset it
6✔
2666
        // after we process the next message.
6✔
2667
        idleTimer := time.AfterFunc(idleTimeout, func() {
6✔
2668
                err := fmt.Errorf("peer %s no write for %s -- disconnecting",
×
2669
                        p, idleTimeout)
×
2670
                p.Disconnect(err)
×
2671
        })
×
2672

2673
        var exitErr error
6✔
2674

6✔
2675
out:
6✔
2676
        for {
16✔
2677
                select {
10✔
2678
                case outMsg := <-p.sendQueue:
7✔
2679
                        // Record the time at which we first attempt to send the
7✔
2680
                        // message.
7✔
2681
                        startTime := time.Now()
7✔
2682

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

×
2695
                                // If we received a timeout error, this implies
×
2696
                                // that the message was buffered on the
×
2697
                                // connection successfully and that a flush was
×
2698
                                // attempted. We'll set the message to nil so
×
2699
                                // that on a subsequent pass we only try to
×
2700
                                // flush the buffered message, and forgo
×
2701
                                // reserializing or reencrypting it.
×
2702
                                outMsg.msg = nil
×
2703

×
2704
                                goto retry
×
2705
                        }
2706

2707
                        // The write succeeded, reset the idle timer to prevent
2708
                        // us from disconnecting the peer.
2709
                        if !idleTimer.Stop() {
7✔
2710
                                select {
×
2711
                                case <-idleTimer.C:
×
2712
                                default:
×
2713
                                }
2714
                        }
2715
                        idleTimer.Reset(idleTimeout)
7✔
2716

7✔
2717
                        // If the peer requested a synchronous write, respond
7✔
2718
                        // with the error.
7✔
2719
                        if outMsg.errChan != nil {
11✔
2720
                                outMsg.errChan <- err
4✔
2721
                        }
4✔
2722

2723
                        if err != nil {
7✔
2724
                                exitErr = fmt.Errorf("unable to write "+
×
2725
                                        "message: %v", err)
×
2726
                                break out
×
2727
                        }
2728

2729
                case <-p.cg.Done():
3✔
2730
                        exitErr = lnpeer.ErrPeerExiting
3✔
2731
                        break out
3✔
2732
                }
2733
        }
2734

2735
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2736
        // disconnect.
2737
        p.cg.WgDone()
3✔
2738

3✔
2739
        p.Disconnect(exitErr)
3✔
2740

3✔
2741
        p.log.Trace("writeHandler for peer done")
3✔
2742
}
2743

2744
// queueHandler is responsible for accepting messages from outside subsystems
2745
// to be eventually sent out on the wire by the writeHandler.
2746
//
2747
// NOTE: This method MUST be run as a goroutine.
2748
func (p *Brontide) queueHandler() {
6✔
2749
        defer p.cg.WgDone()
6✔
2750

6✔
2751
        // priorityMsgs holds an in order list of messages deemed high-priority
6✔
2752
        // to be added to the sendQueue. This predominately includes messages
6✔
2753
        // from the funding manager and htlcswitch.
6✔
2754
        priorityMsgs := list.New()
6✔
2755

6✔
2756
        // lazyMsgs holds an in order list of messages deemed low-priority to be
6✔
2757
        // added to the sendQueue only after all high-priority messages have
6✔
2758
        // been queued. This predominately includes messages from the gossiper.
6✔
2759
        lazyMsgs := list.New()
6✔
2760

6✔
2761
        for {
20✔
2762
                // Examine the front of the priority queue, if it is empty check
14✔
2763
                // the low priority queue.
14✔
2764
                elem := priorityMsgs.Front()
14✔
2765
                if elem == nil {
25✔
2766
                        elem = lazyMsgs.Front()
11✔
2767
                }
11✔
2768

2769
                if elem != nil {
21✔
2770
                        front := elem.Value.(outgoingMsg)
7✔
2771

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

2811
// PingTime returns the estimated ping time to the peer in microseconds.
2812
func (p *Brontide) PingTime() int64 {
3✔
2813
        return p.pingManager.GetPingTimeMicroSeconds()
3✔
2814
}
3✔
2815

2816
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2817
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2818
// or failed to write, and nil otherwise.
2819
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
28✔
2820
        p.queue(true, msg, errChan)
28✔
2821
}
28✔
2822

2823
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2824
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2825
// queue or failed to write, and nil otherwise.
2826
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
4✔
2827
        p.queue(false, msg, errChan)
4✔
2828
}
4✔
2829

2830
// queue sends a given message to the queueHandler using the passed priority. If
2831
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2832
// failed to write, and nil otherwise.
2833
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2834
        errChan chan error) {
29✔
2835

29✔
2836
        select {
29✔
2837
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
28✔
2838
        case <-p.cg.Done():
×
2839
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
×
2840
                        spew.Sdump(msg))
×
2841
                if errChan != nil {
×
2842
                        errChan <- lnpeer.ErrPeerExiting
×
2843
                }
×
2844
        }
2845
}
2846

2847
// ChannelSnapshots returns a slice of channel snapshots detailing all
2848
// currently active channels maintained with the remote peer.
2849
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
3✔
2850
        snapshots := make(
3✔
2851
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
3✔
2852
        )
3✔
2853

3✔
2854
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2855
                activeChan *lnwallet.LightningChannel) error {
6✔
2856

3✔
2857
                // If the activeChan is nil, then we skip it as the channel is
3✔
2858
                // pending.
3✔
2859
                if activeChan == nil {
6✔
2860
                        return nil
3✔
2861
                }
3✔
2862

2863
                // We'll only return a snapshot for channels that are
2864
                // *immediately* available for routing payments over.
2865
                if activeChan.RemoteNextRevocation() == nil {
6✔
2866
                        return nil
3✔
2867
                }
3✔
2868

2869
                snapshot := activeChan.StateSnapshot()
3✔
2870
                snapshots = append(snapshots, snapshot)
3✔
2871

3✔
2872
                return nil
3✔
2873
        })
2874

2875
        return snapshots
3✔
2876
}
2877

2878
// genDeliveryScript returns a new script to be used to send our funds to in
2879
// the case of a cooperative channel close negotiation.
2880
func (p *Brontide) genDeliveryScript() ([]byte, error) {
9✔
2881
        // We'll send a normal p2wkh address unless we've negotiated the
9✔
2882
        // shutdown-any-segwit feature.
9✔
2883
        addrType := lnwallet.WitnessPubKey
9✔
2884
        if p.taprootShutdownAllowed() {
12✔
2885
                addrType = lnwallet.TaprootPubkey
3✔
2886
        }
3✔
2887

2888
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
9✔
2889
                addrType, false, lnwallet.DefaultAccountName,
9✔
2890
        )
9✔
2891
        if err != nil {
9✔
2892
                return nil, err
×
2893
        }
×
2894
        p.log.Infof("Delivery addr for channel close: %v",
9✔
2895
                deliveryAddr)
9✔
2896

9✔
2897
        return txscript.PayToAddrScript(deliveryAddr)
9✔
2898
}
2899

2900
// channelManager is goroutine dedicated to handling all requests/signals
2901
// pertaining to the opening, cooperative closing, and force closing of all
2902
// channels maintained with the remote peer.
2903
//
2904
// NOTE: This method MUST be run as a goroutine.
2905
func (p *Brontide) channelManager() {
20✔
2906
        defer p.cg.WgDone()
20✔
2907

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

20✔
2913
out:
20✔
2914
        for {
61✔
2915
                select {
41✔
2916
                // A new pending channel has arrived which means we are about
2917
                // to complete a funding workflow and is waiting for the final
2918
                // `ChannelReady` messages to be exchanged. We will add this
2919
                // channel to the `activeChannels` with a nil value to indicate
2920
                // this is a pending channel.
2921
                case req := <-p.newPendingChannel:
4✔
2922
                        p.handleNewPendingChannel(req)
4✔
2923

2924
                // A new channel has arrived which means we've just completed a
2925
                // funding workflow. We'll initialize the necessary local
2926
                // state, and notify the htlc switch of a new link.
2927
                case req := <-p.newActiveChannel:
3✔
2928
                        p.handleNewActiveChannel(req)
3✔
2929

2930
                // The funding flow for a pending channel is failed, we will
2931
                // remove it from Brontide.
2932
                case req := <-p.removePendingChannel:
4✔
2933
                        p.handleRemovePendingChannel(req)
4✔
2934

2935
                // We've just received a local request to close an active
2936
                // channel. It will either kick of a cooperative channel
2937
                // closure negotiation, or be a notification of a breached
2938
                // contract that should be abandoned.
2939
                case req := <-p.localCloseChanReqs:
10✔
2940
                        p.handleLocalCloseReq(req)
10✔
2941

2942
                // We've received a link failure from a link that was added to
2943
                // the switch. This will initiate the teardown of the link, and
2944
                // initiate any on-chain closures if necessary.
2945
                case failure := <-p.linkFailures:
3✔
2946
                        p.handleLinkFailure(failure)
3✔
2947

2948
                // We've received a new cooperative channel closure related
2949
                // message from the remote peer, we'll use this message to
2950
                // advance the chan closer state machine.
2951
                case closeMsg := <-p.chanCloseMsgs:
16✔
2952
                        p.handleCloseMsg(closeMsg)
16✔
2953

2954
                // The channel reannounce delay has elapsed, broadcast the
2955
                // reenabled channel updates to the network. This should only
2956
                // fire once, so we set the reenableTimeout channel to nil to
2957
                // mark it for garbage collection. If the peer is torn down
2958
                // before firing, reenabling will not be attempted.
2959
                // TODO(conner): consolidate reenables timers inside chan status
2960
                // manager
2961
                case <-reenableTimeout:
3✔
2962
                        p.reenableActiveChannels()
3✔
2963

3✔
2964
                        // Since this channel will never fire again during the
3✔
2965
                        // lifecycle of the peer, we nil the channel to mark it
3✔
2966
                        // eligible for garbage collection, and make this
3✔
2967
                        // explicitly ineligible to receive in future calls to
3✔
2968
                        // select. This also shaves a few CPU cycles since the
3✔
2969
                        // select will ignore this case entirely.
3✔
2970
                        reenableTimeout = nil
3✔
2971

3✔
2972
                        // Once the reenabling is attempted, we also cancel the
3✔
2973
                        // channel event subscription to free up the overflow
3✔
2974
                        // queue used in channel notifier.
3✔
2975
                        //
3✔
2976
                        // NOTE: channelEventClient will be nil if the
3✔
2977
                        // reenableTimeout is greater than 1 minute.
3✔
2978
                        if p.channelEventClient != nil {
6✔
2979
                                p.channelEventClient.Cancel()
3✔
2980
                        }
3✔
2981

2982
                case <-p.cg.Done():
3✔
2983
                        // As, we've been signalled to exit, we'll reset all
3✔
2984
                        // our active channel back to their default state.
3✔
2985
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2986
                                lc *lnwallet.LightningChannel) error {
6✔
2987

3✔
2988
                                // Exit if the channel is nil as it's a pending
3✔
2989
                                // channel.
3✔
2990
                                if lc == nil {
6✔
2991
                                        return nil
3✔
2992
                                }
3✔
2993

2994
                                lc.ResetState()
3✔
2995

3✔
2996
                                return nil
3✔
2997
                        })
2998

2999
                        break out
3✔
3000
                }
3001
        }
3002
}
3003

3004
// reenableActiveChannels searches the index of channels maintained with this
3005
// peer, and reenables each public, non-pending channel. This is done at the
3006
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
3007
// No message will be sent if the channel is already enabled.
3008
func (p *Brontide) reenableActiveChannels() {
3✔
3009
        // First, filter all known channels with this peer for ones that are
3✔
3010
        // both public and not pending.
3✔
3011
        activePublicChans := p.filterChannelsToEnable()
3✔
3012

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

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

3✔
3022
                switch {
3✔
3023
                // No error occurred, continue to request the next channel.
3024
                case err == nil:
3✔
3025
                        continue
3✔
3026

3027
                // Cannot auto enable a manually disabled channel so we do
3028
                // nothing but proceed to the next channel.
3029
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
3✔
3030
                        p.log.Debugf("Channel(%v) was manually disabled, "+
3✔
3031
                                "ignoring automatic enable request", chanPoint)
3✔
3032

3✔
3033
                        continue
3✔
3034

3035
                // If the channel is reported as inactive, we will give it
3036
                // another chance. When handling the request, ChanStatusManager
3037
                // will check whether the link is active or not. One of the
3038
                // conditions is whether the link has been marked as
3039
                // reestablished, which happens inside a goroutine(htlcManager)
3040
                // after the link is started. And we may get a false negative
3041
                // saying the link is not active because that goroutine hasn't
3042
                // reached the line to mark the reestablishment. Thus we give
3043
                // it a second chance to send the request.
3044
                case errors.Is(err, netann.ErrEnableInactiveChan):
×
3045
                        // If we don't have a client created, it means we
×
3046
                        // shouldn't retry enabling the channel.
×
3047
                        if p.channelEventClient == nil {
×
3048
                                p.log.Errorf("Channel(%v) request enabling "+
×
3049
                                        "failed due to inactive link",
×
3050
                                        chanPoint)
×
3051

×
3052
                                continue
×
3053
                        }
3054

3055
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
3056
                                "ChanStatusManager reported inactive, retrying")
×
3057

×
3058
                        // Add the channel to the retry map.
×
3059
                        retryChans[chanPoint] = struct{}{}
×
3060
                }
3061
        }
3062

3063
        // Retry the channels if we have any.
3064
        if len(retryChans) != 0 {
3✔
3065
                p.retryRequestEnable(retryChans)
×
3066
        }
×
3067
}
3068

3069
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
3070
// for the target channel ID. If the channel isn't active an error is returned.
3071
// Otherwise, either an existing state machine will be returned, or a new one
3072
// will be created.
3073
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
3074
        *chanCloserFsm, error) {
16✔
3075

16✔
3076
        chanCloser, found := p.activeChanCloses.Load(chanID)
16✔
3077
        if found {
29✔
3078
                // An entry will only be found if the closer has already been
13✔
3079
                // created for a non-pending channel or for a channel that had
13✔
3080
                // previously started the shutdown process but the connection
13✔
3081
                // was restarted.
13✔
3082
                return &chanCloser, nil
13✔
3083
        }
13✔
3084

3085
        // First, we'll ensure that we actually know of the target channel. If
3086
        // not, we'll ignore this message.
3087
        channel, ok := p.activeChannels.Load(chanID)
6✔
3088

6✔
3089
        // If the channel isn't in the map or the channel is nil, return
6✔
3090
        // ErrChannelNotFound as the channel is pending.
6✔
3091
        if !ok || channel == nil {
9✔
3092
                return nil, ErrChannelNotFound
3✔
3093
        }
3✔
3094

3095
        // We'll create a valid closing state machine in order to respond to
3096
        // the initiated cooperative channel closure. First, we set the
3097
        // delivery script that our funds will be paid out to. If an upfront
3098
        // shutdown script was set, we will use it. Otherwise, we get a fresh
3099
        // delivery script.
3100
        //
3101
        // TODO: Expose option to allow upfront shutdown script from watch-only
3102
        // accounts.
3103
        deliveryScript := channel.LocalUpfrontShutdownScript()
6✔
3104
        if len(deliveryScript) == 0 {
12✔
3105
                var err error
6✔
3106
                deliveryScript, err = p.genDeliveryScript()
6✔
3107
                if err != nil {
6✔
3108
                        p.log.Errorf("unable to gen delivery script: %v",
×
3109
                                err)
×
3110
                        return nil, fmt.Errorf("close addr unavailable")
×
3111
                }
×
3112
        }
3113

3114
        // In order to begin fee negotiations, we'll first compute our target
3115
        // ideal fee-per-kw.
3116
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
6✔
3117
                p.cfg.CoopCloseTargetConfs,
6✔
3118
        )
6✔
3119
        if err != nil {
6✔
3120
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3121
                return nil, fmt.Errorf("unable to estimate fee")
×
3122
        }
×
3123

3124
        addr, err := p.addrWithInternalKey(deliveryScript)
6✔
3125
        if err != nil {
6✔
3126
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3127
        }
×
3128
        negotiateChanCloser, err := p.createChanCloser(
6✔
3129
                channel, addr, feePerKw, nil, lntypes.Remote,
6✔
3130
        )
6✔
3131
        if err != nil {
6✔
3132
                p.log.Errorf("unable to create chan closer: %v", err)
×
3133
                return nil, fmt.Errorf("unable to create chan closer")
×
3134
        }
×
3135

3136
        chanCloser = makeNegotiateCloser(negotiateChanCloser)
6✔
3137

6✔
3138
        p.activeChanCloses.Store(chanID, chanCloser)
6✔
3139

6✔
3140
        return &chanCloser, nil
6✔
3141
}
3142

3143
// filterChannelsToEnable filters a list of channels to be enabled upon start.
3144
// The filtered channels are active channels that's neither private nor
3145
// pending.
3146
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
3✔
3147
        var activePublicChans []wire.OutPoint
3✔
3148

3✔
3149
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
3✔
3150
                lnChan *lnwallet.LightningChannel) bool {
6✔
3151

3✔
3152
                // If the lnChan is nil, continue as this is a pending channel.
3✔
3153
                if lnChan == nil {
5✔
3154
                        return true
2✔
3155
                }
2✔
3156

3157
                dbChan := lnChan.State()
3✔
3158
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
3159
                if !isPublic || dbChan.IsPending {
3✔
3160
                        return true
×
3161
                }
×
3162

3163
                // We'll also skip any channels added during this peer's
3164
                // lifecycle since they haven't waited out the timeout. Their
3165
                // first announcement will be enabled, and the chan status
3166
                // manager will begin monitoring them passively since they exist
3167
                // in the database.
3168
                if _, ok := p.addedChannels.Load(chanID); ok {
4✔
3169
                        return true
1✔
3170
                }
1✔
3171

3172
                activePublicChans = append(
3✔
3173
                        activePublicChans, dbChan.FundingOutpoint,
3✔
3174
                )
3✔
3175

3✔
3176
                return true
3✔
3177
        })
3178

3179
        return activePublicChans
3✔
3180
}
3181

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

×
3189
        // retryEnable is a helper closure that sends an enable request and
×
3190
        // removes the channel from the map if it's matched.
×
3191
        retryEnable := func(chanPoint wire.OutPoint) error {
×
3192
                // If this is an active channel event, check whether it's in
×
3193
                // our targeted channels map.
×
3194
                _, found := activeChans[chanPoint]
×
3195

×
3196
                // If this channel is irrelevant, return nil so the loop can
×
3197
                // jump to next iteration.
×
3198
                if !found {
×
3199
                        return nil
×
3200
                }
×
3201

3202
                // Otherwise we've just received an active signal for a channel
3203
                // that's previously failed to be enabled, we send the request
3204
                // again.
3205
                //
3206
                // We only give the channel one more shot, so we delete it from
3207
                // our map first to keep it from being attempted again.
3208
                delete(activeChans, chanPoint)
×
3209

×
3210
                // Send the request.
×
3211
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3212
                if err != nil {
×
3213
                        return fmt.Errorf("request enabling channel %v "+
×
3214
                                "failed: %w", chanPoint, err)
×
3215
                }
×
3216

3217
                return nil
×
3218
        }
3219

3220
        for {
×
3221
                // If activeChans is empty, we've done processing all the
×
3222
                // channels.
×
3223
                if len(activeChans) == 0 {
×
3224
                        p.log.Debug("Finished retry enabling channels")
×
3225
                        return
×
3226
                }
×
3227

3228
                select {
×
3229
                // A new event has been sent by the ChannelNotifier. We now
3230
                // check whether it's an active or inactive channel event.
3231
                case e := <-p.channelEventClient.Updates():
×
3232
                        // If this is an active channel event, try enable the
×
3233
                        // channel then jump to the next iteration.
×
3234
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
3235
                        if ok {
×
3236
                                chanPoint := *active.ChannelPoint
×
3237

×
3238
                                // If we received an error for this particular
×
3239
                                // channel, we log an error and won't quit as
×
3240
                                // we still want to retry other channels.
×
3241
                                if err := retryEnable(chanPoint); err != nil {
×
3242
                                        p.log.Errorf("Retry failed: %v", err)
×
3243
                                }
×
3244

3245
                                continue
×
3246
                        }
3247

3248
                        // Otherwise check for inactive link event, and jump to
3249
                        // next iteration if it's not.
3250
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3251
                        if !ok {
×
3252
                                continue
×
3253
                        }
3254

3255
                        // Found an inactive link event, if this is our
3256
                        // targeted channel, remove it from our map.
3257
                        chanPoint := *inactive.ChannelPoint
×
3258
                        _, found := activeChans[chanPoint]
×
3259
                        if !found {
×
3260
                                continue
×
3261
                        }
3262

3263
                        delete(activeChans, chanPoint)
×
3264
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3265
                                "inactive link event", chanPoint)
×
3266

3267
                case <-p.cg.Done():
×
3268
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3269
                        return
×
3270
                }
3271
        }
3272
}
3273

3274
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3275
// a suitable script to close out to. This may be nil if neither script is
3276
// set. If both scripts are set, this function will error if they do not match.
3277
func chooseDeliveryScript(upfront, requested lnwire.DeliveryAddress,
3278
        genDeliveryScript func() ([]byte, error),
3279
) (lnwire.DeliveryAddress, error) {
15✔
3280

15✔
3281
        switch {
15✔
3282
        // If no script was provided, then we'll generate a new delivery script.
3283
        case len(upfront) == 0 && len(requested) == 0:
7✔
3284
                return genDeliveryScript()
7✔
3285

3286
        // If no upfront shutdown script was provided, return the user
3287
        // requested address (which may be nil).
3288
        case len(upfront) == 0:
5✔
3289
                return requested, nil
5✔
3290

3291
        // If an upfront shutdown script was provided, and the user did not
3292
        // request a custom shutdown script, return the upfront address.
3293
        case len(requested) == 0:
5✔
3294
                return upfront, nil
5✔
3295

3296
        // If both an upfront shutdown script and a custom close script were
3297
        // provided, error if the user provided shutdown script does not match
3298
        // the upfront shutdown script (because closing out to a different
3299
        // script would violate upfront shutdown).
3300
        case !bytes.Equal(upfront, requested):
2✔
3301
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
3302

3303
        // The user requested script matches the upfront shutdown script, so we
3304
        // can return it without error.
3305
        default:
2✔
3306
                return upfront, nil
2✔
3307
        }
3308
}
3309

3310
// restartCoopClose checks whether we need to restart the cooperative close
3311
// process for a given channel.
3312
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3313
        *lnwire.Shutdown, error) {
3✔
3314

3✔
3315
        isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
3316

3✔
3317
        // If this channel has status ChanStatusCoopBroadcasted and does not
3✔
3318
        // have a closing transaction, then the cooperative close process was
3✔
3319
        // started but never finished. We'll re-create the chanCloser state
3✔
3320
        // machine and resend Shutdown. BOLT#2 requires that we retransmit
3✔
3321
        // Shutdown exactly, but doing so would mean persisting the RPC
3✔
3322
        // provided close script. Instead use the LocalUpfrontShutdownScript
3✔
3323
        // or generate a script.
3✔
3324
        c := lnChan.State()
3✔
3325
        _, err := c.BroadcastedCooperative()
3✔
3326
        if err != nil && err != channeldb.ErrNoCloseTx {
3✔
3327
                // An error other than ErrNoCloseTx was encountered.
×
3328
                return nil, err
×
3329
        } else if err == nil && !p.rbfCoopCloseAllowed() {
3✔
3330
                // This is a channel that doesn't support RBF coop close, and it
×
3331
                // already had a coop close txn broadcast. As a result, we can
×
3332
                // just exit here as all we can do is wait for it to confirm.
×
3333
                return nil, nil
×
3334
        }
×
3335

3336
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
3✔
3337

3✔
3338
        var deliveryScript []byte
3✔
3339

3✔
3340
        shutdownInfo, err := c.ShutdownInfo()
3✔
3341
        switch {
3✔
3342
        // We have previously stored the delivery script that we need to use
3343
        // in the shutdown message. Re-use this script.
3344
        case err == nil:
3✔
3345
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
6✔
3346
                        deliveryScript = info.DeliveryScript.Val
3✔
3347
                })
3✔
3348

3349
        // An error other than ErrNoShutdownInfo was returned
3350
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3351
                return nil, err
×
3352

3353
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3354
                deliveryScript = c.LocalShutdownScript
×
3355
                if len(deliveryScript) == 0 {
×
3356
                        var err error
×
3357
                        deliveryScript, err = p.genDeliveryScript()
×
3358
                        if err != nil {
×
3359
                                p.log.Errorf("unable to gen delivery script: "+
×
3360
                                        "%v", err)
×
3361

×
3362
                                return nil, fmt.Errorf("close addr unavailable")
×
3363
                        }
×
3364
                }
3365
        }
3366

3367
        // If the new RBF co-op close is negotiated, then we'll init and start
3368
        // that state machine, skipping the steps for the negotiate machine
3369
        // below. We don't support this close type for taproot channels though.
3370
        if p.rbfCoopCloseAllowed() && !isTaprootChan {
6✔
3371
                _, err := p.initRbfChanCloser(lnChan)
3✔
3372
                if err != nil {
3✔
3373
                        return nil, fmt.Errorf("unable to init rbf chan "+
×
3374
                                "closer during restart: %w", err)
×
3375
                }
×
3376

3377
                shutdownDesc := fn.MapOption(
3✔
3378
                        newRestartShutdownInit,
3✔
3379
                )(shutdownInfo)
3✔
3380

3✔
3381
                err = p.startRbfChanCloser(
3✔
3382
                        fn.FlattenOption(shutdownDesc), lnChan.ChannelPoint(),
3✔
3383
                )
3✔
3384

3✔
3385
                return nil, err
3✔
3386
        }
3387

3388
        // Compute an ideal fee.
3389
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
3390
                p.cfg.CoopCloseTargetConfs,
×
3391
        )
×
3392
        if err != nil {
×
3393
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3394
                return nil, fmt.Errorf("unable to estimate fee")
×
3395
        }
×
3396

3397
        // Determine whether we or the peer are the initiator of the coop
3398
        // close attempt by looking at the channel's status.
3399
        closingParty := lntypes.Remote
×
3400
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3401
                closingParty = lntypes.Local
×
3402
        }
×
3403

3404
        addr, err := p.addrWithInternalKey(deliveryScript)
×
3405
        if err != nil {
×
3406
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3407
        }
×
3408
        chanCloser, err := p.createChanCloser(
×
3409
                lnChan, addr, feePerKw, nil, closingParty,
×
3410
        )
×
3411
        if err != nil {
×
3412
                p.log.Errorf("unable to create chan closer: %v", err)
×
3413
                return nil, fmt.Errorf("unable to create chan closer")
×
3414
        }
×
3415

3416
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
×
3417

×
3418
        // Create the Shutdown message.
×
3419
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3420
        if err != nil {
×
3421
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3422
                p.activeChanCloses.Delete(chanID)
×
3423
                return nil, err
×
3424
        }
×
3425

3426
        return shutdownMsg, nil
×
3427
}
3428

3429
// createChanCloser constructs a ChanCloser from the passed parameters and is
3430
// used to de-duplicate code.
3431
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3432
        deliveryScript *chancloser.DeliveryAddrWithKey,
3433
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3434
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
12✔
3435

12✔
3436
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
12✔
3437
        if err != nil {
12✔
3438
                p.log.Errorf("unable to obtain best block: %v", err)
×
3439
                return nil, fmt.Errorf("cannot obtain best block")
×
3440
        }
×
3441

3442
        // The req will only be set if we initiated the co-op closing flow.
3443
        var maxFee chainfee.SatPerKWeight
12✔
3444
        if req != nil {
21✔
3445
                maxFee = req.MaxFee
9✔
3446
        }
9✔
3447

3448
        chanCloser := chancloser.NewChanCloser(
12✔
3449
                chancloser.ChanCloseCfg{
12✔
3450
                        Channel:      channel,
12✔
3451
                        MusigSession: NewMusigChanCloser(channel),
12✔
3452
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
12✔
3453
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
12✔
3454
                        AuxCloser:    p.cfg.AuxChanCloser,
12✔
3455
                        DisableChannel: func(op wire.OutPoint) error {
24✔
3456
                                return p.cfg.ChanStatusMgr.RequestDisable(
12✔
3457
                                        op, false,
12✔
3458
                                )
12✔
3459
                        },
12✔
3460
                        MaxFee: maxFee,
3461
                        Disconnect: func() error {
×
3462
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
3463
                        },
×
3464
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3465
                },
3466
                *deliveryScript,
3467
                fee,
3468
                uint32(startingHeight),
3469
                req,
3470
                closer,
3471
        )
3472

3473
        return chanCloser, nil
12✔
3474
}
3475

3476
// initNegotiateChanCloser initializes the channel closer for a channel that is
3477
// using the original "negotiation" based protocol. This path is used when
3478
// we're the one initiating the channel close.
3479
//
3480
// TODO(roasbeef): can make a MsgEndpoint for existing handling logic to
3481
// further abstract.
3482
func (p *Brontide) initNegotiateChanCloser(req *htlcswitch.ChanClose,
3483
        channel *lnwallet.LightningChannel) error {
10✔
3484

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

10✔
3488
        // An upfront shutdown and user provided script are both optional, but
10✔
3489
        // must be equal if both set  (because we cannot serve a request to
10✔
3490
        // close out to a script which violates upfront shutdown). Get the
10✔
3491
        // appropriate address to close out to (which may be nil if neither are
10✔
3492
        // set) and error if they are both set and do not match.
10✔
3493
        deliveryScript, err := chooseDeliveryScript(
10✔
3494
                channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
10✔
3495
                p.genDeliveryScript,
10✔
3496
        )
10✔
3497
        if err != nil {
11✔
3498
                return fmt.Errorf("cannot close channel %v: %w",
1✔
3499
                        req.ChanPoint, err)
1✔
3500
        }
1✔
3501

3502
        addr, err := p.addrWithInternalKey(deliveryScript)
9✔
3503
        if err != nil {
9✔
3504
                return fmt.Errorf("unable to parse addr for channel "+
×
3505
                        "%v: %w", req.ChanPoint, err)
×
3506
        }
×
3507

3508
        chanCloser, err := p.createChanCloser(
9✔
3509
                channel, addr, req.TargetFeePerKw, req, lntypes.Local,
9✔
3510
        )
9✔
3511
        if err != nil {
9✔
3512
                return fmt.Errorf("unable to make chan closer: %w", err)
×
3513
        }
×
3514

3515
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
9✔
3516
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
9✔
3517

9✔
3518
        // Finally, we'll initiate the channel shutdown within the
9✔
3519
        // chanCloser, and send the shutdown message to the remote
9✔
3520
        // party to kick things off.
9✔
3521
        shutdownMsg, err := chanCloser.ShutdownChan()
9✔
3522
        if err != nil {
9✔
3523
                // As we were unable to shutdown the channel, we'll return it
×
3524
                // back to its normal state.
×
3525
                defer channel.ResetState()
×
3526

×
3527
                p.activeChanCloses.Delete(chanID)
×
3528

×
3529
                return fmt.Errorf("unable to shutdown channel: %w", err)
×
3530
        }
×
3531

3532
        link := p.fetchLinkFromKeyAndCid(chanID)
9✔
3533
        if link == nil {
9✔
3534
                // If the link is nil then it means it was already removed from
×
3535
                // the switch or it never existed in the first place. The
×
3536
                // latter case is handled at the beginning of this function, so
×
3537
                // in the case where it has already been removed, we can skip
×
3538
                // adding the commit hook to queue a Shutdown message.
×
3539
                p.log.Warnf("link not found during attempted closure: "+
×
3540
                        "%v", chanID)
×
3541
                return nil
×
3542
        }
×
3543

3544
        if !link.DisableAdds(htlcswitch.Outgoing) {
9✔
3545
                p.log.Warnf("Outgoing link adds already "+
×
3546
                        "disabled: %v", link.ChanID())
×
3547
        }
×
3548

3549
        link.OnCommitOnce(htlcswitch.Outgoing, func() {
18✔
3550
                p.queueMsg(shutdownMsg, nil)
9✔
3551
        })
9✔
3552

3553
        return nil
9✔
3554
}
3555

3556
// chooseAddr returns the provided address if it is non-zero length, otherwise
3557
// None.
3558
func chooseAddr(addr lnwire.DeliveryAddress) fn.Option[lnwire.DeliveryAddress] {
3✔
3559
        if len(addr) == 0 {
6✔
3560
                return fn.None[lnwire.DeliveryAddress]()
3✔
3561
        }
3✔
3562

3563
        return fn.Some(addr)
×
3564
}
3565

3566
// observeRbfCloseUpdates observes the channel for any updates that may
3567
// indicate that a new txid has been broadcasted, or the channel fully closed
3568
// on chain.
3569
func (p *Brontide) observeRbfCloseUpdates(chanCloser *chancloser.RbfChanCloser,
3570
        closeReq *htlcswitch.ChanClose,
3571
        coopCloseStates chancloser.RbfStateSub) {
3✔
3572

3✔
3573
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3574
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3575

3✔
3576
        var (
3✔
3577
                lastTxids    lntypes.Dual[chainhash.Hash]
3✔
3578
                lastFeeRates lntypes.Dual[chainfee.SatPerVByte]
3✔
3579
        )
3✔
3580

3✔
3581
        maybeNotifyTxBroadcast := func(state chancloser.AsymmetricPeerState,
3✔
3582
                party lntypes.ChannelParty) {
6✔
3583

3✔
3584
                // First, check to see if we have an error to report to the
3✔
3585
                // caller. If so, then we''ll return that error and exit, as the
3✔
3586
                // stream will exit as well.
3✔
3587
                if closeErr, ok := state.(*chancloser.CloseErr); ok {
6✔
3588
                        // We hit an error during the last state transition, so
3✔
3589
                        // we'll extract the error then send it to the
3✔
3590
                        // user.
3✔
3591
                        err := closeErr.Err()
3✔
3592

3✔
3593
                        peerLog.Warnf("ChannelPoint(%v): encountered close "+
3✔
3594
                                "err: %v", closeReq.ChanPoint, err)
3✔
3595

3✔
3596
                        select {
3✔
3597
                        case closeReq.Err <- err:
3✔
3598
                        case <-closeReq.Ctx.Done():
×
3599
                        case <-p.cg.Done():
×
3600
                        }
3601

3602
                        return
3✔
3603
                }
3604

3605
                closePending, ok := state.(*chancloser.ClosePending)
3✔
3606

3✔
3607
                // If this isn't the close pending state, we aren't at the
3✔
3608
                // terminal state yet.
3✔
3609
                if !ok {
6✔
3610
                        return
3✔
3611
                }
3✔
3612

3613
                // Only notify if the fee rate is greater.
3614
                newFeeRate := closePending.FeeRate
3✔
3615
                lastFeeRate := lastFeeRates.GetForParty(party)
3✔
3616
                if newFeeRate <= lastFeeRate {
6✔
3617
                        peerLog.Debugf("ChannelPoint(%v): remote party made "+
3✔
3618
                                "update for fee rate %v, but we already have "+
3✔
3619
                                "a higher fee rate of %v", closeReq.ChanPoint,
3✔
3620
                                newFeeRate, lastFeeRate)
3✔
3621

3✔
3622
                        return
3✔
3623
                }
3✔
3624

3625
                feeRate := closePending.FeeRate
3✔
3626
                lastFeeRates.SetForParty(party, feeRate)
3✔
3627

3✔
3628
                // At this point, we'll have a txid that we can use to notify
3✔
3629
                // the client, but only if it's different from the last one we
3✔
3630
                // sent. If the user attempted to bump, but was rejected due to
3✔
3631
                // RBF, then we'll send a redundant update.
3✔
3632
                closingTxid := closePending.CloseTx.TxHash()
3✔
3633
                lastTxid := lastTxids.GetForParty(party)
3✔
3634
                if closeReq != nil && closingTxid != lastTxid {
6✔
3635
                        select {
3✔
3636
                        case closeReq.Updates <- &PendingUpdate{
3637
                                Txid:        closingTxid[:],
3638
                                FeePerVbyte: fn.Some(closePending.FeeRate),
3639
                                IsLocalCloseTx: fn.Some(
3640
                                        party == lntypes.Local,
3641
                                ),
3642
                        }:
3✔
3643

3644
                        case <-closeReq.Ctx.Done():
×
3645
                                return
×
3646

3647
                        case <-p.cg.Done():
×
3648
                                return
×
3649
                        }
3650
                }
3651

3652
                lastTxids.SetForParty(party, closingTxid)
3✔
3653
        }
3654

3655
        peerLog.Infof("Observing RBF close updates for channel %v",
3✔
3656
                closeReq.ChanPoint)
3✔
3657

3✔
3658
        // We'll consume each new incoming state to send out the appropriate
3✔
3659
        // RPC update.
3✔
3660
        for {
6✔
3661
                select {
3✔
3662
                case newState := <-newStateChan:
3✔
3663

3✔
3664
                        switch closeState := newState.(type) {
3✔
3665
                        // Once we've reached the state of pending close, we
3666
                        // have a txid that we broadcasted.
3667
                        case *chancloser.ClosingNegotiation:
3✔
3668
                                peerState := closeState.PeerState
3✔
3669

3✔
3670
                                // Each side may have gained a new co-op close
3✔
3671
                                // tx, so we'll examine both to see if they've
3✔
3672
                                // changed.
3✔
3673
                                maybeNotifyTxBroadcast(
3✔
3674
                                        peerState.GetForParty(lntypes.Local),
3✔
3675
                                        lntypes.Local,
3✔
3676
                                )
3✔
3677
                                maybeNotifyTxBroadcast(
3✔
3678
                                        peerState.GetForParty(lntypes.Remote),
3✔
3679
                                        lntypes.Remote,
3✔
3680
                                )
3✔
3681

3682
                        // Otherwise, if we're transition to CloseFin, then we
3683
                        // know that we're done.
3684
                        case *chancloser.CloseFin:
3✔
3685
                                // To clean up, we'll remove the chan closer
3✔
3686
                                // from the active map, and send the final
3✔
3687
                                // update to the client.
3✔
3688
                                closingTxid := closeState.ConfirmedTx.TxHash()
3✔
3689
                                if closeReq != nil {
6✔
3690
                                        closeReq.Updates <- &ChannelCloseUpdate{
3✔
3691
                                                ClosingTxid: closingTxid[:],
3✔
3692
                                                Success:     true,
3✔
3693
                                        }
3✔
3694
                                }
3✔
3695
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
3696
                                        *closeReq.ChanPoint,
3✔
3697
                                )
3✔
3698
                                p.activeChanCloses.Delete(chanID)
3✔
3699

3✔
3700
                                return
3✔
3701
                        }
3702

3703
                case <-closeReq.Ctx.Done():
3✔
3704
                        return
3✔
3705

3706
                case <-p.cg.Done():
3✔
3707
                        return
3✔
3708
                }
3709
        }
3710
}
3711

3712
// chanErrorReporter is a simple implementation of the
3713
// chancloser.ErrorReporter. This is bound to a single channel by the channel
3714
// ID.
3715
type chanErrorReporter struct {
3716
        chanID lnwire.ChannelID
3717
        peer   *Brontide
3718
}
3719

3720
// newChanErrorReporter creates a new instance of the chanErrorReporter.
3721
func newChanErrorReporter(chanID lnwire.ChannelID,
3722
        peer *Brontide) *chanErrorReporter {
3✔
3723

3✔
3724
        return &chanErrorReporter{
3✔
3725
                chanID: chanID,
3✔
3726
                peer:   peer,
3✔
3727
        }
3✔
3728
}
3✔
3729

3730
// ReportError is a method that's used to report an error that occurred during
3731
// state machine execution. This is used by the RBF close state machine to
3732
// terminate the state machine and send an error to the remote peer.
3733
//
3734
// This is a part of the chancloser.ErrorReporter interface.
3735
func (c *chanErrorReporter) ReportError(chanErr error) {
×
3736
        c.peer.log.Errorf("coop close error for channel %v: %v",
×
3737
                c.chanID, chanErr)
×
3738

×
3739
        var errMsg []byte
×
3740
        if errors.Is(chanErr, chancloser.ErrInvalidStateTransition) {
×
3741
                errMsg = []byte("unexpected protocol message")
×
3742
        } else {
×
3743
                errMsg = []byte(chanErr.Error())
×
3744
        }
×
3745

3746
        err := c.peer.SendMessageLazy(false, &lnwire.Error{
×
3747
                ChanID: c.chanID,
×
3748
                Data:   errMsg,
×
3749
        })
×
3750
        if err != nil {
×
3751
                c.peer.log.Warnf("unable to send error message to peer: %v",
×
3752
                        err)
×
3753
        }
×
3754

3755
        // After we send the error message to the peer, we'll re-initialize the
3756
        // coop close state machine as they may send a shutdown message to
3757
        // retry the coop close.
3758
        lnChan, ok := c.peer.activeChannels.Load(c.chanID)
×
3759
        if !ok {
×
3760
                return
×
3761
        }
×
3762

3763
        if lnChan == nil {
×
3764
                c.peer.log.Debugf("channel %v is pending, not "+
×
3765
                        "re-initializing coop close state machine",
×
3766
                        c.chanID)
×
3767

×
3768
                return
×
3769
        }
×
3770

3771
        if _, err := c.peer.initRbfChanCloser(lnChan); err != nil {
×
3772
                c.peer.activeChanCloses.Delete(c.chanID)
×
3773

×
3774
                c.peer.log.Errorf("unable to init RBF chan closer after "+
×
3775
                        "error case: %v", err)
×
3776
        }
×
3777
}
3778

3779
// chanFlushEventSentinel is used to send the RBF coop close state machine the
3780
// channel flushed event. We'll wait until the state machine enters the
3781
// ChannelFlushing state, then request the link to send the event once flushed.
3782
//
3783
// NOTE: This MUST be run as a goroutine.
3784
func (p *Brontide) chanFlushEventSentinel(chanCloser *chancloser.RbfChanCloser,
3785
        link htlcswitch.ChannelUpdateHandler,
3786
        channel *lnwallet.LightningChannel) {
3✔
3787

3✔
3788
        defer p.cg.WgDone()
3✔
3789

3✔
3790
        // If there's no link, then the channel has already been flushed, so we
3✔
3791
        // don't need to continue.
3✔
3792
        if link == nil {
6✔
3793
                return
3✔
3794
        }
3✔
3795

3796
        coopCloseStates := chanCloser.RegisterStateEvents()
3✔
3797
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3798

3✔
3799
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3800

3✔
3801
        sendChanFlushed := func() {
6✔
3802
                chanState := channel.StateSnapshot()
3✔
3803

3✔
3804
                peerLog.Infof("ChannelPoint(%v) has been flushed for co-op "+
3✔
3805
                        "close, sending event to chan closer",
3✔
3806
                        channel.ChannelPoint())
3✔
3807

3✔
3808
                chanBalances := chancloser.ShutdownBalances{
3✔
3809
                        LocalBalance:  chanState.LocalBalance,
3✔
3810
                        RemoteBalance: chanState.RemoteBalance,
3✔
3811
                }
3✔
3812
                ctx := context.Background()
3✔
3813
                chanCloser.SendEvent(ctx, &chancloser.ChannelFlushed{
3✔
3814
                        ShutdownBalances: chanBalances,
3✔
3815
                        FreshFlush:       true,
3✔
3816
                })
3✔
3817
        }
3✔
3818

3819
        // We'll wait until the channel enters the ChannelFlushing state. We
3820
        // exit after a success loop. As after the first RBF iteration, the
3821
        // channel will always be flushed.
3822
        for {
6✔
3823
                select {
3✔
3824
                case newState, ok := <-newStateChan:
3✔
3825
                        if !ok {
3✔
3826
                                return
×
3827
                        }
×
3828

3829
                        if _, ok := newState.(*chancloser.ChannelFlushing); ok {
6✔
3830
                                peerLog.Infof("ChannelPoint(%v): rbf coop "+
3✔
3831
                                        "close is awaiting a flushed state, "+
3✔
3832
                                        "registering with link..., ",
3✔
3833
                                        channel.ChannelPoint())
3✔
3834

3✔
3835
                                // Request the link to send the event once the
3✔
3836
                                // channel is flushed. We only need this event
3✔
3837
                                // sent once, so we can exit now.
3✔
3838
                                link.OnFlushedOnce(sendChanFlushed)
3✔
3839

3✔
3840
                                return
3✔
3841
                        }
3✔
3842

3843
                case <-p.cg.Done():
3✔
3844
                        return
3✔
3845
                }
3846
        }
3847
}
3848

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

3✔
3855
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
3✔
3856

3✔
3857
        link := p.fetchLinkFromKeyAndCid(chanID)
3✔
3858

3✔
3859
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
3✔
3860
        if err != nil {
3✔
3861
                return nil, fmt.Errorf("cannot obtain best block: %w", err)
×
3862
        }
×
3863

3864
        defaultFeePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
3865
                p.cfg.CoopCloseTargetConfs,
3✔
3866
        )
3✔
3867
        if err != nil {
3✔
3868
                return nil, fmt.Errorf("unable to estimate fee: %w", err)
×
3869
        }
×
3870

3871
        thawHeight, err := channel.AbsoluteThawHeight()
3✔
3872
        if err != nil {
3✔
3873
                return nil, fmt.Errorf("unable to get thaw height: %w", err)
×
3874
        }
×
3875

3876
        peerPub := *p.IdentityKey()
3✔
3877

3✔
3878
        msgMapper := chancloser.NewRbfMsgMapper(
3✔
3879
                uint32(startingHeight), chanID, peerPub,
3✔
3880
        )
3✔
3881

3✔
3882
        initialState := chancloser.ChannelActive{}
3✔
3883

3✔
3884
        scid := channel.ZeroConfRealScid().UnwrapOr(
3✔
3885
                channel.ShortChanID(),
3✔
3886
        )
3✔
3887

3✔
3888
        env := chancloser.Environment{
3✔
3889
                ChainParams:    p.cfg.Wallet.Cfg.NetParams,
3✔
3890
                ChanPeer:       peerPub,
3✔
3891
                ChanPoint:      channel.ChannelPoint(),
3✔
3892
                ChanID:         chanID,
3✔
3893
                Scid:           scid,
3✔
3894
                ChanType:       channel.ChanType(),
3✔
3895
                DefaultFeeRate: defaultFeePerKw.FeePerVByte(),
3✔
3896
                ThawHeight:     fn.Some(thawHeight),
3✔
3897
                RemoteUpfrontShutdown: chooseAddr(
3✔
3898
                        channel.RemoteUpfrontShutdownScript(),
3✔
3899
                ),
3✔
3900
                LocalUpfrontShutdown: chooseAddr(
3✔
3901
                        channel.LocalUpfrontShutdownScript(),
3✔
3902
                ),
3✔
3903
                NewDeliveryScript: func() (lnwire.DeliveryAddress, error) {
6✔
3904
                        return p.genDeliveryScript()
3✔
3905
                },
3✔
3906
                FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
3907
                CloseSigner:  channel,
3908
                ChanObserver: newChanObserver(
3909
                        channel, link, p.cfg.ChanStatusMgr,
3910
                ),
3911
        }
3912

3913
        spendEvent := protofsm.RegisterSpend[chancloser.ProtocolEvent]{
3✔
3914
                OutPoint:   channel.ChannelPoint(),
3✔
3915
                PkScript:   channel.FundingTxOut().PkScript,
3✔
3916
                HeightHint: channel.DeriveHeightHint(),
3✔
3917
                PostSpendEvent: fn.Some[chancloser.RbfSpendMapper](
3✔
3918
                        chancloser.SpendMapper,
3✔
3919
                ),
3✔
3920
        }
3✔
3921

3✔
3922
        daemonAdapters := NewLndDaemonAdapters(LndAdapterCfg{
3✔
3923
                MsgSender:     newPeerMsgSender(peerPub, p),
3✔
3924
                TxBroadcaster: p.cfg.Wallet,
3✔
3925
                ChainNotifier: p.cfg.ChainNotifier,
3✔
3926
        })
3✔
3927

3✔
3928
        protoCfg := chancloser.RbfChanCloserCfg{
3✔
3929
                Daemon:        daemonAdapters,
3✔
3930
                InitialState:  &initialState,
3✔
3931
                Env:           &env,
3✔
3932
                InitEvent:     fn.Some[protofsm.DaemonEvent](&spendEvent),
3✔
3933
                ErrorReporter: newChanErrorReporter(chanID, p),
3✔
3934
                MsgMapper: fn.Some[protofsm.MsgMapper[chancloser.ProtocolEvent]]( //nolint:ll
3✔
3935
                        msgMapper,
3✔
3936
                ),
3✔
3937
        }
3✔
3938

3✔
3939
        ctx := context.Background()
3✔
3940
        chanCloser := protofsm.NewStateMachine(protoCfg)
3✔
3941
        chanCloser.Start(ctx)
3✔
3942

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

3✔
3948
                return r.RegisterEndpoint(&chanCloser)
3✔
3949
        })
3✔
3950
        if err != nil {
3✔
3951
                chanCloser.Stop()
×
3952

×
3953
                return nil, fmt.Errorf("unable to register endpoint for co-op "+
×
3954
                        "close: %w", err)
×
3955
        }
×
3956

3957
        p.activeChanCloses.Store(chanID, makeRbfCloser(&chanCloser))
3✔
3958

3✔
3959
        // Now that we've created the rbf closer state machine, we'll launch a
3✔
3960
        // new goroutine to eventually send in the ChannelFlushed event once
3✔
3961
        // needed.
3✔
3962
        p.cg.WgAdd(1)
3✔
3963
        go p.chanFlushEventSentinel(&chanCloser, link, channel)
3✔
3964

3✔
3965
        return &chanCloser, nil
3✔
3966
}
3967

3968
// shutdownInit describes the two ways we can initiate a new shutdown. Either we
3969
// got an RPC request to do so (left), or we sent a shutdown message to the
3970
// party (for w/e reason), but crashed before the close was complete.
3971
//
3972
//nolint:ll
3973
type shutdownInit = fn.Option[fn.Either[*htlcswitch.ChanClose, channeldb.ShutdownInfo]]
3974

3975
// shutdownStartFeeRate returns the fee rate that should be used for the
3976
// shutdown.  This returns a doubly wrapped option as the shutdown info might
3977
// be none, and the fee rate is only defined for the user initiated shutdown.
3978
func shutdownStartFeeRate(s shutdownInit) fn.Option[chainfee.SatPerKWeight] {
3✔
3979
        feeRateOpt := fn.MapOption(func(init fn.Either[*htlcswitch.ChanClose,
3✔
3980
                channeldb.ShutdownInfo]) fn.Option[chainfee.SatPerKWeight] {
6✔
3981

3✔
3982
                var feeRate fn.Option[chainfee.SatPerKWeight]
3✔
3983
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
6✔
3984
                        feeRate = fn.Some(req.TargetFeePerKw)
3✔
3985
                })
3✔
3986

3987
                return feeRate
3✔
3988
        })(s)
3989

3990
        return fn.FlattenOption(feeRateOpt)
3✔
3991
}
3992

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

3✔
4000
                var addr fn.Option[lnwire.DeliveryAddress]
3✔
4001
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
6✔
4002
                        if len(req.DeliveryScript) != 0 {
6✔
4003
                                addr = fn.Some(req.DeliveryScript)
3✔
4004
                        }
3✔
4005
                })
4006
                init.WhenRight(func(info channeldb.ShutdownInfo) {
6✔
4007
                        addr = fn.Some(info.DeliveryScript.Val)
3✔
4008
                })
3✔
4009

4010
                return addr
3✔
4011
        })(s)
4012

4013
        return fn.FlattenOption(addrOpt)
3✔
4014
}
4015

4016
// whenRPCShutdown registers a callback to be executed when the shutdown init
4017
// type is and RPC request.
4018
func whenRPCShutdown(s shutdownInit, f func(r *htlcswitch.ChanClose)) {
3✔
4019
        s.WhenSome(func(init fn.Either[*htlcswitch.ChanClose,
3✔
4020
                channeldb.ShutdownInfo]) {
6✔
4021

3✔
4022
                init.WhenLeft(f)
3✔
4023
        })
3✔
4024
}
4025

4026
// newRestartShutdownInit creates a new shutdownInit for the case where we need
4027
// to restart the shutdown flow after a restart.
4028
func newRestartShutdownInit(info channeldb.ShutdownInfo) shutdownInit {
3✔
4029
        return fn.Some(fn.NewRight[*htlcswitch.ChanClose](info))
3✔
4030
}
3✔
4031

4032
// newRPCShutdownInit creates a new shutdownInit for the case where we
4033
// initiated the shutdown via an RPC client.
4034
func newRPCShutdownInit(req *htlcswitch.ChanClose) shutdownInit {
3✔
4035
        return fn.Some(
3✔
4036
                fn.NewLeft[*htlcswitch.ChanClose, channeldb.ShutdownInfo](req),
3✔
4037
        )
3✔
4038
}
3✔
4039

4040
// waitUntilRbfCoastClear waits until the RBF co-op close state machine has
4041
// advanced to a terminal state before attempting another fee bump.
4042
func waitUntilRbfCoastClear(ctx context.Context,
4043
        rbfCloser *chancloser.RbfChanCloser) error {
3✔
4044

3✔
4045
        coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4046
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
4047
        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4048

3✔
4049
        isTerminalState := func(newState chancloser.RbfState) bool {
6✔
4050
                // If we're not in the negotiation sub-state, then we aren't at
3✔
4051
                // the terminal state yet.
3✔
4052
                state, ok := newState.(*chancloser.ClosingNegotiation)
3✔
4053
                if !ok {
3✔
4054
                        return false
×
4055
                }
×
4056

4057
                localState := state.PeerState.GetForParty(lntypes.Local)
3✔
4058

3✔
4059
                // If this isn't the close pending state, we aren't at the
3✔
4060
                // terminal state yet.
3✔
4061
                _, ok = localState.(*chancloser.ClosePending)
3✔
4062

3✔
4063
                return ok
3✔
4064
        }
4065

4066
        // Before we enter the subscription loop below, check to see if we're
4067
        // already in the terminal state.
4068
        rbfState, err := rbfCloser.CurrentState()
3✔
4069
        if err != nil {
3✔
4070
                return err
×
4071
        }
×
4072
        if isTerminalState(rbfState) {
6✔
4073
                return nil
3✔
4074
        }
3✔
4075

4076
        peerLog.Debugf("Waiting for RBF iteration to complete...")
×
4077

×
4078
        for {
×
4079
                select {
×
4080
                case newState := <-newStateChan:
×
4081
                        if isTerminalState(newState) {
×
4082
                                return nil
×
4083
                        }
×
4084

4085
                case <-ctx.Done():
×
4086
                        return fmt.Errorf("context canceled")
×
4087
                }
4088
        }
4089
}
4090

4091
// startRbfChanCloser kicks off the co-op close process using the new RBF based
4092
// co-op close protocol. This is called when we're the one that's initiating
4093
// the cooperative channel close.
4094
//
4095
// TODO(roasbeef): just accept the two shutdown pointer params instead??
4096
func (p *Brontide) startRbfChanCloser(shutdown shutdownInit,
4097
        chanPoint wire.OutPoint) error {
3✔
4098

3✔
4099
        // Unlike the old negotiate chan closer, we'll always create the RBF
3✔
4100
        // chan closer on startup, so we can skip init here.
3✔
4101
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4102
        chanCloser, found := p.activeChanCloses.Load(chanID)
3✔
4103
        if !found {
3✔
4104
                return fmt.Errorf("rbf chan closer not found for channel %v",
×
4105
                        chanPoint)
×
4106
        }
×
4107

4108
        defaultFeePerKw, err := shutdownStartFeeRate(
3✔
4109
                shutdown,
3✔
4110
        ).UnwrapOrFuncErr(func() (chainfee.SatPerKWeight, error) {
6✔
4111
                return p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
4112
                        p.cfg.CoopCloseTargetConfs,
3✔
4113
                )
3✔
4114
        })
3✔
4115
        if err != nil {
3✔
4116
                return fmt.Errorf("unable to estimate fee: %w", err)
×
4117
        }
×
4118

4119
        chanCloser.WhenRight(func(rbfCloser *chancloser.RbfChanCloser) {
6✔
4120
                peerLog.Infof("ChannelPoint(%v): rbf-coop close requested, "+
3✔
4121
                        "sending shutdown", chanPoint)
3✔
4122

3✔
4123
                rbfState, err := rbfCloser.CurrentState()
3✔
4124
                if err != nil {
3✔
4125
                        peerLog.Warnf("ChannelPoint(%v): unable to get "+
×
4126
                                "current state for rbf-coop close: %v",
×
4127
                                chanPoint, err)
×
4128

×
4129
                        return
×
4130
                }
×
4131

4132
                coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4133

3✔
4134
                // Before we send our event below, we'll launch a goroutine to
3✔
4135
                // watch for the final terminal state to send updates to the RPC
3✔
4136
                // client. We only need to do this if there's an RPC caller.
3✔
4137
                var rpcShutdown bool
3✔
4138
                whenRPCShutdown(shutdown, func(req *htlcswitch.ChanClose) {
6✔
4139
                        rpcShutdown = true
3✔
4140

3✔
4141
                        p.cg.WgAdd(1)
3✔
4142
                        go func() {
6✔
4143
                                defer p.cg.WgDone()
3✔
4144

3✔
4145
                                p.observeRbfCloseUpdates(
3✔
4146
                                        rbfCloser, req, coopCloseStates,
3✔
4147
                                )
3✔
4148
                        }()
3✔
4149
                })
4150

4151
                if !rpcShutdown {
6✔
4152
                        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4153
                }
3✔
4154

4155
                ctx, _ := p.cg.Create(context.Background())
3✔
4156
                feeRate := defaultFeePerKw.FeePerVByte()
3✔
4157

3✔
4158
                // Depending on the state of the state machine, we'll either
3✔
4159
                // kick things off by sending shutdown, or attempt to send a new
3✔
4160
                // offer to the remote party.
3✔
4161
                switch rbfState.(type) {
3✔
4162
                // The channel is still active, so we'll now kick off the co-op
4163
                // close process by instructing it to send a shutdown message to
4164
                // the remote party.
4165
                case *chancloser.ChannelActive:
3✔
4166
                        rbfCloser.SendEvent(
3✔
4167
                                context.Background(),
3✔
4168
                                &chancloser.SendShutdown{
3✔
4169
                                        IdealFeeRate: feeRate,
3✔
4170
                                        DeliveryAddr: shutdownStartAddr(
3✔
4171
                                                shutdown,
3✔
4172
                                        ),
3✔
4173
                                },
3✔
4174
                        )
3✔
4175

4176
                // If we haven't yet sent an offer (didn't have enough funds at
4177
                // the prior fee rate), or we've sent an offer, then we'll
4178
                // trigger a new offer event.
4179
                case *chancloser.ClosingNegotiation:
3✔
4180
                        // Before we send the event below, we'll wait until
3✔
4181
                        // we're in a semi-terminal state.
3✔
4182
                        err := waitUntilRbfCoastClear(ctx, rbfCloser)
3✔
4183
                        if err != nil {
3✔
4184
                                peerLog.Warnf("ChannelPoint(%v): unable to "+
×
4185
                                        "wait for coast to clear: %v",
×
4186
                                        chanPoint, err)
×
4187

×
4188
                                return
×
4189
                        }
×
4190

4191
                        event := chancloser.ProtocolEvent(
3✔
4192
                                &chancloser.SendOfferEvent{
3✔
4193
                                        TargetFeeRate: feeRate,
3✔
4194
                                },
3✔
4195
                        )
3✔
4196
                        rbfCloser.SendEvent(ctx, event)
3✔
4197

4198
                default:
×
4199
                        peerLog.Warnf("ChannelPoint(%v): unexpected state "+
×
4200
                                "for rbf-coop close: %T", chanPoint, rbfState)
×
4201
                }
4202
        })
4203

4204
        return nil
3✔
4205
}
4206

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

10✔
4212
        channel, ok := p.activeChannels.Load(chanID)
10✔
4213

10✔
4214
        // Though this function can't be called for pending channels, we still
10✔
4215
        // check whether channel is nil for safety.
10✔
4216
        if !ok || channel == nil {
10✔
4217
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
×
4218
                        "unknown", chanID)
×
4219
                p.log.Errorf(err.Error())
×
4220
                req.Err <- err
×
4221
                return
×
4222
        }
×
4223

4224
        isTaprootChan := channel.ChanType().IsTaproot()
10✔
4225

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

4248
                if err != nil {
11✔
4249
                        p.log.Errorf(err.Error())
1✔
4250
                        req.Err <- err
1✔
4251
                }
1✔
4252

4253
        // A type of CloseBreach indicates that the counterparty has breached
4254
        // the channel therefore we need to clean up our local state.
4255
        case contractcourt.CloseBreach:
×
4256
                // TODO(roasbeef): no longer need with newer beach logic?
×
4257
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
×
4258
                        "channel", req.ChanPoint)
×
4259
                p.WipeChannel(req.ChanPoint)
×
4260
        }
4261
}
4262

4263
// linkFailureReport is sent to the channelManager whenever a link reports a
4264
// link failure, and is forced to exit. The report houses the necessary
4265
// information to clean up the channel state, send back the error message, and
4266
// force close if necessary.
4267
type linkFailureReport struct {
4268
        chanPoint   wire.OutPoint
4269
        chanID      lnwire.ChannelID
4270
        shortChanID lnwire.ShortChannelID
4271
        linkErr     htlcswitch.LinkFailureError
4272
}
4273

4274
// handleLinkFailure processes a link failure report when a link in the switch
4275
// fails. It facilitates the removal of all channel state within the peer,
4276
// force closing the channel depending on severity, and sending the error
4277
// message back to the remote party.
4278
func (p *Brontide) handleLinkFailure(failure linkFailureReport) {
3✔
4279
        // Retrieve the channel from the map of active channels. We do this to
3✔
4280
        // have access to it even after WipeChannel remove it from the map.
3✔
4281
        chanID := lnwire.NewChanIDFromOutPoint(failure.chanPoint)
3✔
4282
        lnChan, _ := p.activeChannels.Load(chanID)
3✔
4283

3✔
4284
        // We begin by wiping the link, which will remove it from the switch,
3✔
4285
        // such that it won't be attempted used for any more updates.
3✔
4286
        //
3✔
4287
        // TODO(halseth): should introduce a way to atomically stop/pause the
3✔
4288
        // link and cancel back any adds in its mailboxes such that we can
3✔
4289
        // safely force close without the link being added again and updates
3✔
4290
        // being applied.
3✔
4291
        p.WipeChannel(&failure.chanPoint)
3✔
4292

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

3✔
4298
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
3✔
4299
                        failure.chanPoint,
3✔
4300
                )
3✔
4301
                if err != nil {
6✔
4302
                        p.log.Errorf("unable to force close "+
3✔
4303
                                "link(%v): %v", failure.shortChanID, err)
3✔
4304
                } else {
6✔
4305
                        p.log.Infof("channel(%v) force "+
3✔
4306
                                "closed with txid %v",
3✔
4307
                                failure.shortChanID, closeTx.TxHash())
3✔
4308
                }
3✔
4309
        }
4310

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

×
4316
                if err := lnChan.State().MarkBorked(); err != nil {
×
4317
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
4318
                                failure.shortChanID, err)
×
4319
                }
×
4320
        }
4321

4322
        // Send an error to the peer, why we failed the channel.
4323
        if failure.linkErr.ShouldSendToPeer() {
6✔
4324
                // If SendData is set, send it to the peer. If not, we'll use
3✔
4325
                // the standard error messages in the payload. We only include
3✔
4326
                // sendData in the cases where the error data does not contain
3✔
4327
                // sensitive information.
3✔
4328
                data := []byte(failure.linkErr.Error())
3✔
4329
                if failure.linkErr.SendData != nil {
3✔
4330
                        data = failure.linkErr.SendData
×
4331
                }
×
4332

4333
                var networkMsg lnwire.Message
3✔
4334
                if failure.linkErr.Warning {
3✔
4335
                        networkMsg = &lnwire.Warning{
×
4336
                                ChanID: failure.chanID,
×
4337
                                Data:   data,
×
4338
                        }
×
4339
                } else {
3✔
4340
                        networkMsg = &lnwire.Error{
3✔
4341
                                ChanID: failure.chanID,
3✔
4342
                                Data:   data,
3✔
4343
                        }
3✔
4344
                }
3✔
4345

4346
                err := p.SendMessage(true, networkMsg)
3✔
4347
                if err != nil {
3✔
4348
                        p.log.Errorf("unable to send msg to "+
×
4349
                                "remote peer: %v", err)
×
4350
                }
×
4351
        }
4352

4353
        // If the failure action is disconnect, then we'll execute that now. If
4354
        // we had to send an error above, it was a sync call, so we expect the
4355
        // message to be flushed on the wire by now.
4356
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
3✔
4357
                p.Disconnect(fmt.Errorf("link requested disconnect"))
×
4358
        }
×
4359
}
4360

4361
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
4362
// public key and the channel id.
4363
func (p *Brontide) fetchLinkFromKeyAndCid(
4364
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
22✔
4365

22✔
4366
        var chanLink htlcswitch.ChannelUpdateHandler
22✔
4367

22✔
4368
        // We don't need to check the error here, and can instead just loop
22✔
4369
        // over the slice and return nil.
22✔
4370
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
22✔
4371
        for _, link := range links {
43✔
4372
                if link.ChanID() == cid {
42✔
4373
                        chanLink = link
21✔
4374
                        break
21✔
4375
                }
4376
        }
4377

4378
        return chanLink
22✔
4379
}
4380

4381
// finalizeChanClosure performs the final clean up steps once the cooperative
4382
// closure transaction has been fully broadcast. The finalized closing state
4383
// machine should be passed in. Once the transaction has been sufficiently
4384
// confirmed, the channel will be marked as fully closed within the database,
4385
// and any clients will be notified of updates to the closing state.
4386
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
7✔
4387
        closeReq := chanCloser.CloseRequest()
7✔
4388

7✔
4389
        // First, we'll clear all indexes related to the channel in question.
7✔
4390
        chanPoint := chanCloser.Channel().ChannelPoint()
7✔
4391
        p.WipeChannel(&chanPoint)
7✔
4392

7✔
4393
        // Also clear the activeChanCloses map of this channel.
7✔
4394
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
7✔
4395
        p.activeChanCloses.Delete(cid) // TODO(roasbeef): existing race
7✔
4396

7✔
4397
        // Next, we'll launch a goroutine which will request to be notified by
7✔
4398
        // the ChainNotifier once the closure transaction obtains a single
7✔
4399
        // confirmation.
7✔
4400
        notifier := p.cfg.ChainNotifier
7✔
4401

7✔
4402
        // If any error happens during waitForChanToClose, forward it to
7✔
4403
        // closeReq. If this channel closure is not locally initiated, closeReq
7✔
4404
        // will be nil, so just ignore the error.
7✔
4405
        errChan := make(chan error, 1)
7✔
4406
        if closeReq != nil {
12✔
4407
                errChan = closeReq.Err
5✔
4408
        }
5✔
4409

4410
        closingTx, err := chanCloser.ClosingTx()
7✔
4411
        if err != nil {
7✔
4412
                if closeReq != nil {
×
4413
                        p.log.Error(err)
×
4414
                        closeReq.Err <- err
×
4415
                }
×
4416
        }
4417

4418
        closingTxid := closingTx.TxHash()
7✔
4419

7✔
4420
        // If this is a locally requested shutdown, update the caller with a
7✔
4421
        // new event detailing the current pending state of this request.
7✔
4422
        if closeReq != nil {
12✔
4423
                closeReq.Updates <- &PendingUpdate{
5✔
4424
                        Txid: closingTxid[:],
5✔
4425
                }
5✔
4426
        }
5✔
4427

4428
        localOut := chanCloser.LocalCloseOutput()
7✔
4429
        remoteOut := chanCloser.RemoteCloseOutput()
7✔
4430
        auxOut := chanCloser.AuxOutputs()
7✔
4431
        go WaitForChanToClose(
7✔
4432
                chanCloser.NegotiationHeight(), notifier, errChan,
7✔
4433
                &chanPoint, &closingTxid, closingTx.TxOut[0].PkScript, func() {
14✔
4434
                        // Respond to the local subsystem which requested the
7✔
4435
                        // channel closure.
7✔
4436
                        if closeReq != nil {
12✔
4437
                                closeReq.Updates <- &ChannelCloseUpdate{
5✔
4438
                                        ClosingTxid:       closingTxid[:],
5✔
4439
                                        Success:           true,
5✔
4440
                                        LocalCloseOutput:  localOut,
5✔
4441
                                        RemoteCloseOutput: remoteOut,
5✔
4442
                                        AuxOutputs:        auxOut,
5✔
4443
                                }
5✔
4444
                        }
5✔
4445
                },
4446
        )
4447
}
4448

4449
// WaitForChanToClose uses the passed notifier to wait until the channel has
4450
// been detected as closed on chain and then concludes by executing the
4451
// following actions: the channel point will be sent over the settleChan, and
4452
// finally the callback will be executed. If any error is encountered within
4453
// the function, then it will be sent over the errChan.
4454
func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
4455
        errChan chan error, chanPoint *wire.OutPoint,
4456
        closingTxID *chainhash.Hash, closeScript []byte, cb func()) {
7✔
4457

7✔
4458
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
7✔
4459
                "with txid: %v", chanPoint, closingTxID)
7✔
4460

7✔
4461
        // TODO(roasbeef): add param for num needed confs
7✔
4462
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
7✔
4463
                closingTxID, closeScript, 1, bestHeight,
7✔
4464
        )
7✔
4465
        if err != nil {
7✔
4466
                if errChan != nil {
×
4467
                        errChan <- err
×
4468
                }
×
4469
                return
×
4470
        }
4471

4472
        // In the case that the ChainNotifier is shutting down, all subscriber
4473
        // notification channels will be closed, generating a nil receive.
4474
        height, ok := <-confNtfn.Confirmed
7✔
4475
        if !ok {
10✔
4476
                return
3✔
4477
        }
3✔
4478

4479
        // The channel has been closed, remove it from any active indexes, and
4480
        // the database state.
4481
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
7✔
4482
                "height %v", chanPoint, height.BlockHeight)
7✔
4483

7✔
4484
        // Finally, execute the closure call back to mark the confirmation of
7✔
4485
        // the transaction closing the contract.
7✔
4486
        cb()
7✔
4487
}
4488

4489
// WipeChannel removes the passed channel point from all indexes associated with
4490
// the peer and the switch.
4491
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
7✔
4492
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
7✔
4493

7✔
4494
        p.activeChannels.Delete(chanID)
7✔
4495

7✔
4496
        // Instruct the HtlcSwitch to close this link as the channel is no
7✔
4497
        // longer active.
7✔
4498
        p.cfg.Switch.RemoveLink(chanID)
7✔
4499
}
7✔
4500

4501
// handleInitMsg handles the incoming init message which contains global and
4502
// local feature vectors. If feature vectors are incompatible then disconnect.
4503
func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
6✔
4504
        // First, merge any features from the legacy global features field into
6✔
4505
        // those presented in the local features fields.
6✔
4506
        err := msg.Features.Merge(msg.GlobalFeatures)
6✔
4507
        if err != nil {
6✔
4508
                return fmt.Errorf("unable to merge legacy global features: %w",
×
4509
                        err)
×
4510
        }
×
4511

4512
        // Then, finalize the remote feature vector providing the flattened
4513
        // feature bit namespace.
4514
        p.remoteFeatures = lnwire.NewFeatureVector(
6✔
4515
                msg.Features, lnwire.Features,
6✔
4516
        )
6✔
4517

6✔
4518
        // Now that we have their features loaded, we'll ensure that they
6✔
4519
        // didn't set any required bits that we don't know of.
6✔
4520
        err = feature.ValidateRequired(p.remoteFeatures)
6✔
4521
        if err != nil {
6✔
4522
                return fmt.Errorf("invalid remote features: %w", err)
×
4523
        }
×
4524

4525
        // Ensure the remote party's feature vector contains all transitive
4526
        // dependencies. We know ours are correct since they are validated
4527
        // during the feature manager's instantiation.
4528
        err = feature.ValidateDeps(p.remoteFeatures)
6✔
4529
        if err != nil {
6✔
4530
                return fmt.Errorf("invalid remote features: %w", err)
×
4531
        }
×
4532

4533
        // Now that we know we understand their requirements, we'll check to
4534
        // see if they don't support anything that we deem to be mandatory.
4535
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
6✔
4536
                return fmt.Errorf("data loss protection required")
×
4537
        }
×
4538

4539
        return nil
6✔
4540
}
4541

4542
// LocalFeatures returns the set of global features that has been advertised by
4543
// the local node. This allows sub-systems that use this interface to gate their
4544
// behavior off the set of negotiated feature bits.
4545
//
4546
// NOTE: Part of the lnpeer.Peer interface.
4547
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
3✔
4548
        return p.cfg.Features
3✔
4549
}
3✔
4550

4551
// RemoteFeatures returns the set of global features that has been advertised by
4552
// the remote node. This allows sub-systems that use this interface to gate
4553
// their behavior off the set of negotiated feature bits.
4554
//
4555
// NOTE: Part of the lnpeer.Peer interface.
4556
func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector {
23✔
4557
        return p.remoteFeatures
23✔
4558
}
23✔
4559

4560
// hasNegotiatedScidAlias returns true if we've negotiated the
4561
// option-scid-alias feature bit with the peer.
4562
func (p *Brontide) hasNegotiatedScidAlias() bool {
6✔
4563
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
6✔
4564
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
6✔
4565
        return peerHas && localHas
6✔
4566
}
6✔
4567

4568
// sendInitMsg sends the Init message to the remote peer. This message contains
4569
// our currently supported local and global features.
4570
func (p *Brontide) sendInitMsg(legacyChan bool) error {
10✔
4571
        features := p.cfg.Features.Clone()
10✔
4572
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
10✔
4573

10✔
4574
        // If we have a legacy channel open with a peer, we downgrade static
10✔
4575
        // remote required to optional in case the peer does not understand the
10✔
4576
        // required feature bit. If we do not do this, the peer will reject our
10✔
4577
        // connection because it does not understand a required feature bit, and
10✔
4578
        // our channel will be unusable.
10✔
4579
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
11✔
4580
                p.log.Infof("Legacy channel open with peer, " +
1✔
4581
                        "downgrading static remote required feature bit to " +
1✔
4582
                        "optional")
1✔
4583

1✔
4584
                // Unset and set in both the local and global features to
1✔
4585
                // ensure both sets are consistent and merge able by old and
1✔
4586
                // new nodes.
1✔
4587
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4588
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4589

1✔
4590
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
4591
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
4592
        }
1✔
4593

4594
        msg := lnwire.NewInitMessage(
10✔
4595
                legacyFeatures.RawFeatureVector,
10✔
4596
                features.RawFeatureVector,
10✔
4597
        )
10✔
4598

10✔
4599
        return p.writeMessage(msg)
10✔
4600
}
4601

4602
// resendChanSyncMsg will attempt to find a channel sync message for the closed
4603
// channel and resend it to our peer.
4604
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
3✔
4605
        // If we already re-sent the mssage for this channel, we won't do it
3✔
4606
        // again.
3✔
4607
        if _, ok := p.resentChanSyncMsg[cid]; ok {
4✔
4608
                return nil
1✔
4609
        }
1✔
4610

4611
        // Check if we have any channel sync messages stored for this channel.
4612
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
3✔
4613
        if err != nil {
6✔
4614
                return fmt.Errorf("unable to fetch channel sync messages for "+
3✔
4615
                        "peer %v: %v", p, err)
3✔
4616
        }
3✔
4617

4618
        if c.LastChanSyncMsg == nil {
3✔
4619
                return fmt.Errorf("no chan sync message stored for channel %v",
×
4620
                        cid)
×
4621
        }
×
4622

4623
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
3✔
4624
                return fmt.Errorf("ignoring channel reestablish from "+
×
4625
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
4626
        }
×
4627

4628
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
3✔
4629
                "peer", cid)
3✔
4630

3✔
4631
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
3✔
4632
                return fmt.Errorf("failed resending channel sync "+
×
4633
                        "message to peer %v: %v", p, err)
×
4634
        }
×
4635

4636
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
3✔
4637
                cid)
3✔
4638

3✔
4639
        // Note down that we sent the message, so we won't resend it again for
3✔
4640
        // this connection.
3✔
4641
        p.resentChanSyncMsg[cid] = struct{}{}
3✔
4642

3✔
4643
        return nil
3✔
4644
}
4645

4646
// SendMessage sends a variadic number of high-priority messages to the remote
4647
// peer. The first argument denotes if the method should block until the
4648
// messages have been sent to the remote peer or an error is returned,
4649
// otherwise it returns immediately after queuing.
4650
//
4651
// NOTE: Part of the lnpeer.Peer interface.
4652
func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error {
6✔
4653
        return p.sendMessage(sync, true, msgs...)
6✔
4654
}
6✔
4655

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

4666
// sendMessage queues a variadic number of messages using the passed priority
4667
// to the remote peer. If sync is true, this method will block until the
4668
// messages have been sent to the remote peer or an error is returned, otherwise
4669
// it returns immediately after queueing.
4670
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
7✔
4671
        // Add all incoming messages to the outgoing queue. A list of error
7✔
4672
        // chans is populated for each message if the caller requested a sync
7✔
4673
        // send.
7✔
4674
        var errChans []chan error
7✔
4675
        if sync {
11✔
4676
                errChans = make([]chan error, 0, len(msgs))
4✔
4677
        }
4✔
4678
        for _, msg := range msgs {
14✔
4679
                // If a sync send was requested, create an error chan to listen
7✔
4680
                // for an ack from the writeHandler.
7✔
4681
                var errChan chan error
7✔
4682
                if sync {
11✔
4683
                        errChan = make(chan error, 1)
4✔
4684
                        errChans = append(errChans, errChan)
4✔
4685
                }
4✔
4686

4687
                if priority {
13✔
4688
                        p.queueMsg(msg, errChan)
6✔
4689
                } else {
10✔
4690
                        p.queueMsgLazy(msg, errChan)
4✔
4691
                }
4✔
4692
        }
4693

4694
        // Wait for all replies from the writeHandler. For async sends, this
4695
        // will be a NOP as the list of error chans is nil.
4696
        for _, errChan := range errChans {
11✔
4697
                select {
4✔
4698
                case err := <-errChan:
4✔
4699
                        return err
4✔
4700
                case <-p.cg.Done():
×
4701
                        return lnpeer.ErrPeerExiting
×
4702
                case <-p.cfg.Quit:
×
4703
                        return lnpeer.ErrPeerExiting
×
4704
                }
4705
        }
4706

4707
        return nil
6✔
4708
}
4709

4710
// PubKey returns the pubkey of the peer in compressed serialized format.
4711
//
4712
// NOTE: Part of the lnpeer.Peer interface.
4713
func (p *Brontide) PubKey() [33]byte {
5✔
4714
        return p.cfg.PubKeyBytes
5✔
4715
}
5✔
4716

4717
// IdentityKey returns the public key of the remote peer.
4718
//
4719
// NOTE: Part of the lnpeer.Peer interface.
4720
func (p *Brontide) IdentityKey() *btcec.PublicKey {
18✔
4721
        return p.cfg.Addr.IdentityKey
18✔
4722
}
18✔
4723

4724
// Address returns the network address of the remote peer.
4725
//
4726
// NOTE: Part of the lnpeer.Peer interface.
4727
func (p *Brontide) Address() net.Addr {
3✔
4728
        return p.cfg.Addr.Address
3✔
4729
}
3✔
4730

4731
// AddNewChannel adds a new channel to the peer. The channel should fail to be
4732
// added if the cancel channel is closed.
4733
//
4734
// NOTE: Part of the lnpeer.Peer interface.
4735
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
4736
        cancel <-chan struct{}) error {
3✔
4737

3✔
4738
        errChan := make(chan error, 1)
3✔
4739
        newChanMsg := &newChannelMsg{
3✔
4740
                channel: newChan,
3✔
4741
                err:     errChan,
3✔
4742
        }
3✔
4743

3✔
4744
        select {
3✔
4745
        case p.newActiveChannel <- newChanMsg:
3✔
4746
        case <-cancel:
×
4747
                return errors.New("canceled adding new channel")
×
4748
        case <-p.cg.Done():
×
4749
                return lnpeer.ErrPeerExiting
×
4750
        }
4751

4752
        // We pause here to wait for the peer to recognize the new channel
4753
        // before we close the channel barrier corresponding to the channel.
4754
        select {
3✔
4755
        case err := <-errChan:
3✔
4756
                return err
3✔
4757
        case <-p.cg.Done():
×
4758
                return lnpeer.ErrPeerExiting
×
4759
        }
4760
}
4761

4762
// AddPendingChannel adds a pending open channel to the peer. The channel
4763
// should fail to be added if the cancel channel is closed.
4764
//
4765
// NOTE: Part of the lnpeer.Peer interface.
4766
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
4767
        cancel <-chan struct{}) error {
3✔
4768

3✔
4769
        errChan := make(chan error, 1)
3✔
4770
        newChanMsg := &newChannelMsg{
3✔
4771
                channelID: cid,
3✔
4772
                err:       errChan,
3✔
4773
        }
3✔
4774

3✔
4775
        select {
3✔
4776
        case p.newPendingChannel <- newChanMsg:
3✔
4777

4778
        case <-cancel:
×
4779
                return errors.New("canceled adding pending channel")
×
4780

4781
        case <-p.cg.Done():
×
4782
                return lnpeer.ErrPeerExiting
×
4783
        }
4784

4785
        // We pause here to wait for the peer to recognize the new pending
4786
        // channel before we close the channel barrier corresponding to the
4787
        // channel.
4788
        select {
3✔
4789
        case err := <-errChan:
3✔
4790
                return err
3✔
4791

4792
        case <-cancel:
×
4793
                return errors.New("canceled adding pending channel")
×
4794

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

4800
// RemovePendingChannel removes a pending open channel from the peer.
4801
//
4802
// NOTE: Part of the lnpeer.Peer interface.
4803
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
3✔
4804
        errChan := make(chan error, 1)
3✔
4805
        newChanMsg := &newChannelMsg{
3✔
4806
                channelID: cid,
3✔
4807
                err:       errChan,
3✔
4808
        }
3✔
4809

3✔
4810
        select {
3✔
4811
        case p.removePendingChannel <- newChanMsg:
3✔
4812
        case <-p.cg.Done():
×
4813
                return lnpeer.ErrPeerExiting
×
4814
        }
4815

4816
        // We pause here to wait for the peer to respond to the cancellation of
4817
        // the pending channel before we close the channel barrier
4818
        // corresponding to the channel.
4819
        select {
3✔
4820
        case err := <-errChan:
3✔
4821
                return err
3✔
4822

4823
        case <-p.cg.Done():
×
4824
                return lnpeer.ErrPeerExiting
×
4825
        }
4826
}
4827

4828
// StartTime returns the time at which the connection was established if the
4829
// peer started successfully, and zero otherwise.
4830
func (p *Brontide) StartTime() time.Time {
3✔
4831
        return p.startTime
3✔
4832
}
3✔
4833

4834
// handleCloseMsg is called when a new cooperative channel closure related
4835
// message is received from the remote peer. We'll use this message to advance
4836
// the chan closer state machine.
4837
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
16✔
4838
        link := p.fetchLinkFromKeyAndCid(msg.cid)
16✔
4839

16✔
4840
        // We'll now fetch the matching closing state machine in order to
16✔
4841
        // continue, or finalize the channel closure process.
16✔
4842
        chanCloserE, err := p.fetchActiveChanCloser(msg.cid)
16✔
4843
        if err != nil {
19✔
4844
                // If the channel is not known to us, we'll simply ignore this
3✔
4845
                // message.
3✔
4846
                if err == ErrChannelNotFound {
6✔
4847
                        return
3✔
4848
                }
3✔
4849

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

×
4852
                errMsg := &lnwire.Error{
×
4853
                        ChanID: msg.cid,
×
4854
                        Data:   lnwire.ErrorData(err.Error()),
×
4855
                }
×
4856
                p.queueMsg(errMsg, nil)
×
4857
                return
×
4858
        }
4859

4860
        if chanCloserE.IsRight() {
16✔
4861
                // TODO(roasbeef): assert?
×
4862
                return
×
4863
        }
×
4864

4865
        // At this point, we'll only enter this call path if a negotiate chan
4866
        // closer was used. So we'll extract that from the either now.
4867
        //
4868
        // TODO(roabeef): need extra helper func for either to make cleaner
4869
        var chanCloser *chancloser.ChanCloser
16✔
4870
        chanCloserE.WhenLeft(func(c *chancloser.ChanCloser) {
32✔
4871
                chanCloser = c
16✔
4872
        })
16✔
4873

4874
        handleErr := func(err error) {
17✔
4875
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
4876
                p.log.Error(err)
1✔
4877

1✔
4878
                // As the negotiations failed, we'll reset the channel state
1✔
4879
                // machine to ensure we act to on-chain events as normal.
1✔
4880
                chanCloser.Channel().ResetState()
1✔
4881
                if chanCloser.CloseRequest() != nil {
1✔
4882
                        chanCloser.CloseRequest().Err <- err
×
4883
                }
×
4884

4885
                p.activeChanCloses.Delete(msg.cid)
1✔
4886

1✔
4887
                p.Disconnect(err)
1✔
4888
        }
4889

4890
        // Next, we'll process the next message using the target state machine.
4891
        // We'll either continue negotiation, or halt.
4892
        switch typed := msg.msg.(type) {
16✔
4893
        case *lnwire.Shutdown:
8✔
4894
                // Disable incoming adds immediately.
8✔
4895
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
8✔
4896
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
4897
                                link.ChanID())
×
4898
                }
×
4899

4900
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
8✔
4901
                if err != nil {
8✔
4902
                        handleErr(err)
×
4903
                        return
×
4904
                }
×
4905

4906
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
14✔
4907
                        // If the link is nil it means we can immediately queue
6✔
4908
                        // the Shutdown message since we don't have to wait for
6✔
4909
                        // commitment transaction synchronization.
6✔
4910
                        if link == nil {
7✔
4911
                                p.queueMsg(&msg, nil)
1✔
4912
                                return
1✔
4913
                        }
1✔
4914

4915
                        // Immediately disallow any new HTLC's from being added
4916
                        // in the outgoing direction.
4917
                        if !link.DisableAdds(htlcswitch.Outgoing) {
5✔
4918
                                p.log.Warnf("Outgoing link adds already "+
×
4919
                                        "disabled: %v", link.ChanID())
×
4920
                        }
×
4921

4922
                        // When we have a Shutdown to send, we defer it till the
4923
                        // next time we send a CommitSig to remain spec
4924
                        // compliant.
4925
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
10✔
4926
                                p.queueMsg(&msg, nil)
5✔
4927
                        })
5✔
4928
                })
4929

4930
                beginNegotiation := func() {
16✔
4931
                        oClosingSigned, err := chanCloser.BeginNegotiation()
8✔
4932
                        if err != nil {
8✔
4933
                                handleErr(err)
×
4934
                                return
×
4935
                        }
×
4936

4937
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
16✔
4938
                                p.queueMsg(&msg, nil)
8✔
4939
                        })
8✔
4940
                }
4941

4942
                if link == nil {
9✔
4943
                        beginNegotiation()
1✔
4944
                } else {
8✔
4945
                        // Now we register a flush hook to advance the
7✔
4946
                        // ChanCloser and possibly send out a ClosingSigned
7✔
4947
                        // when the link finishes draining.
7✔
4948
                        link.OnFlushedOnce(func() {
14✔
4949
                                // Remove link in goroutine to prevent deadlock.
7✔
4950
                                go p.cfg.Switch.RemoveLink(msg.cid)
7✔
4951
                                beginNegotiation()
7✔
4952
                        })
7✔
4953
                }
4954

4955
        case *lnwire.ClosingSigned:
11✔
4956
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
11✔
4957
                if err != nil {
12✔
4958
                        handleErr(err)
1✔
4959
                        return
1✔
4960
                }
1✔
4961

4962
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
22✔
4963
                        p.queueMsg(&msg, nil)
11✔
4964
                })
11✔
4965

4966
        default:
×
4967
                panic("impossible closeMsg type")
×
4968
        }
4969

4970
        // If we haven't finished close negotiations, then we'll continue as we
4971
        // can't yet finalize the closure.
4972
        if _, err := chanCloser.ClosingTx(); err != nil {
26✔
4973
                return
11✔
4974
        }
11✔
4975

4976
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
4977
        // the channel closure by notifying relevant sub-systems and launching a
4978
        // goroutine to wait for close tx conf.
4979
        p.finalizeChanClosure(chanCloser)
7✔
4980
}
4981

4982
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
4983
// the channelManager goroutine, which will shut down the link and possibly
4984
// close the channel.
4985
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
3✔
4986
        select {
3✔
4987
        case p.localCloseChanReqs <- req:
3✔
4988
                p.log.Info("Local close channel request is going to be " +
3✔
4989
                        "delivered to the peer")
3✔
4990
        case <-p.cg.Done():
×
4991
                p.log.Info("Unable to deliver local close channel request " +
×
4992
                        "to peer")
×
4993
        }
4994
}
4995

4996
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
4997
func (p *Brontide) NetAddress() *lnwire.NetAddress {
3✔
4998
        return p.cfg.Addr
3✔
4999
}
3✔
5000

5001
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
5002
func (p *Brontide) Inbound() bool {
3✔
5003
        return p.cfg.Inbound
3✔
5004
}
3✔
5005

5006
// ConnReq is a getter for the Brontide's connReq in cfg.
5007
func (p *Brontide) ConnReq() *connmgr.ConnReq {
3✔
5008
        return p.cfg.ConnReq
3✔
5009
}
3✔
5010

5011
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
5012
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
3✔
5013
        return p.cfg.ErrorBuffer
3✔
5014
}
3✔
5015

5016
// SetAddress sets the remote peer's address given an address.
5017
func (p *Brontide) SetAddress(address net.Addr) {
×
5018
        p.cfg.Addr.Address = address
×
5019
}
×
5020

5021
// ActiveSignal returns the peer's active signal.
5022
func (p *Brontide) ActiveSignal() chan struct{} {
3✔
5023
        return p.activeSignal
3✔
5024
}
3✔
5025

5026
// Conn returns a pointer to the peer's connection struct.
5027
func (p *Brontide) Conn() net.Conn {
3✔
5028
        return p.cfg.Conn
3✔
5029
}
3✔
5030

5031
// BytesReceived returns the number of bytes received from the peer.
5032
func (p *Brontide) BytesReceived() uint64 {
3✔
5033
        return atomic.LoadUint64(&p.bytesReceived)
3✔
5034
}
3✔
5035

5036
// BytesSent returns the number of bytes sent to the peer.
5037
func (p *Brontide) BytesSent() uint64 {
3✔
5038
        return atomic.LoadUint64(&p.bytesSent)
3✔
5039
}
3✔
5040

5041
// LastRemotePingPayload returns the last payload the remote party sent as part
5042
// of their ping.
5043
func (p *Brontide) LastRemotePingPayload() []byte {
3✔
5044
        pingPayload := p.lastPingPayload.Load()
3✔
5045
        if pingPayload == nil {
6✔
5046
                return []byte{}
3✔
5047
        }
3✔
5048

5049
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
5050
        if !ok {
×
5051
                return nil
×
5052
        }
×
5053

5054
        return pingBytes
×
5055
}
5056

5057
// attachChannelEventSubscription creates a channel event subscription and
5058
// attaches to client to Brontide if the reenableTimeout is no greater than 1
5059
// minute.
5060
func (p *Brontide) attachChannelEventSubscription() error {
6✔
5061
        // If the timeout is greater than 1 minute, it's unlikely that the link
6✔
5062
        // hasn't yet finished its reestablishment. Return a nil without
6✔
5063
        // creating the client to specify that we don't want to retry.
6✔
5064
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
9✔
5065
                return nil
3✔
5066
        }
3✔
5067

5068
        // When the reenable timeout is less than 1 minute, it's likely the
5069
        // channel link hasn't finished its reestablishment yet. In that case,
5070
        // we'll give it a second chance by subscribing to the channel update
5071
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
5072
        // enabling the channel again.
5073
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
6✔
5074
        if err != nil {
6✔
5075
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
5076
        }
×
5077

5078
        p.channelEventClient = sub
6✔
5079

6✔
5080
        return nil
6✔
5081
}
5082

5083
// updateNextRevocation updates the existing channel's next revocation if it's
5084
// nil.
5085
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
6✔
5086
        chanPoint := c.FundingOutpoint
6✔
5087
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
6✔
5088

6✔
5089
        // Read the current channel.
6✔
5090
        currentChan, loaded := p.activeChannels.Load(chanID)
6✔
5091

6✔
5092
        // currentChan should exist, but we perform a check anyway to avoid nil
6✔
5093
        // pointer dereference.
6✔
5094
        if !loaded {
7✔
5095
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
5096
                        chanID)
1✔
5097
        }
1✔
5098

5099
        // currentChan should not be nil, but we perform a check anyway to
5100
        // avoid nil pointer dereference.
5101
        if currentChan == nil {
6✔
5102
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
5103
                        chanID)
1✔
5104
        }
1✔
5105

5106
        // If we're being sent a new channel, and our existing channel doesn't
5107
        // have the next revocation, then we need to update the current
5108
        // existing channel.
5109
        if currentChan.RemoteNextRevocation() != nil {
4✔
5110
                return nil
×
5111
        }
×
5112

5113
        p.log.Infof("Processing retransmitted ChannelReady for "+
4✔
5114
                "ChannelPoint(%v)", chanPoint)
4✔
5115

4✔
5116
        nextRevoke := c.RemoteNextRevocation
4✔
5117

4✔
5118
        err := currentChan.InitNextRevocation(nextRevoke)
4✔
5119
        if err != nil {
4✔
5120
                return fmt.Errorf("unable to init next revocation: %w", err)
×
5121
        }
×
5122

5123
        return nil
4✔
5124
}
5125

5126
// addActiveChannel adds a new active channel to the `activeChannels` map. It
5127
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
5128
// it and assembles it with a channel link.
5129
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
3✔
5130
        chanPoint := c.FundingOutpoint
3✔
5131
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5132

3✔
5133
        // If we've reached this point, there are two possible scenarios.  If
3✔
5134
        // the channel was in the active channels map as nil, then it was
3✔
5135
        // loaded from disk and we need to send reestablish. Else, it was not
3✔
5136
        // loaded from disk and we don't need to send reestablish as this is a
3✔
5137
        // fresh channel.
3✔
5138
        shouldReestablish := p.isLoadedFromDisk(chanID)
3✔
5139

3✔
5140
        chanOpts := c.ChanOpts
3✔
5141
        if shouldReestablish {
6✔
5142
                // If we have to do the reestablish dance for this channel,
3✔
5143
                // ensure that we don't try to call InitRemoteMusigNonces twice
3✔
5144
                // by calling SkipNonceInit.
3✔
5145
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
3✔
5146
        }
3✔
5147

5148
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
3✔
5149
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
5150
        })
×
5151
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
3✔
5152
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
5153
        })
×
5154
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
3✔
5155
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
5156
        })
×
5157

5158
        // If not already active, we'll add this channel to the set of active
5159
        // channels, so we can look it up later easily according to its channel
5160
        // ID.
5161
        lnChan, err := lnwallet.NewLightningChannel(
3✔
5162
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
3✔
5163
        )
3✔
5164
        if err != nil {
3✔
5165
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
5166
        }
×
5167

5168
        // Store the channel in the activeChannels map.
5169
        p.activeChannels.Store(chanID, lnChan)
3✔
5170

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

3✔
5173
        // Next, we'll assemble a ChannelLink along with the necessary items it
3✔
5174
        // needs to function.
3✔
5175
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
3✔
5176
        if err != nil {
3✔
5177
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
5178
                        err)
×
5179
        }
×
5180

5181
        // We'll query the channel DB for the new channel's initial forwarding
5182
        // policies to determine the policy we start out with.
5183
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
3✔
5184
        if err != nil {
3✔
5185
                return fmt.Errorf("unable to query for initial forwarding "+
×
5186
                        "policy: %v", err)
×
5187
        }
×
5188

5189
        // Create the link and add it to the switch.
5190
        err = p.addLink(
3✔
5191
                &chanPoint, lnChan, initialPolicy, chainEvents,
3✔
5192
                shouldReestablish, fn.None[lnwire.Shutdown](),
3✔
5193
        )
3✔
5194
        if err != nil {
3✔
5195
                return fmt.Errorf("can't register new channel link(%v) with "+
×
5196
                        "peer", chanPoint)
×
5197
        }
×
5198

5199
        isTaprootChan := c.ChanType.IsTaproot()
3✔
5200

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

5208
        // Now that the link has been added above, we'll also init an RBF chan
5209
        // closer for this channel, but only if the new close feature is
5210
        // negotiated.
5211
        //
5212
        // Creating this here ensures that any shutdown messages sent will be
5213
        // automatically routed by the msg router.
5214
        if _, err := p.initRbfChanCloser(lnChan); err != nil {
3✔
5215
                p.activeChanCloses.Delete(chanID)
×
5216

×
5217
                return fmt.Errorf("unable to init RBF chan closer for new "+
×
5218
                        "chan: %w", err)
×
5219
        }
×
5220

5221
        return nil
3✔
5222
}
5223

5224
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
5225
// know this channel ID or not, we'll either add it to the `activeChannels` map
5226
// or init the next revocation for it.
5227
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
3✔
5228
        newChan := req.channel
3✔
5229
        chanPoint := newChan.FundingOutpoint
3✔
5230
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5231

3✔
5232
        // Only update RemoteNextRevocation if the channel is in the
3✔
5233
        // activeChannels map and if we added the link to the switch. Only
3✔
5234
        // active channels will be added to the switch.
3✔
5235
        if p.isActiveChannel(chanID) {
6✔
5236
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
3✔
5237
                        chanPoint)
3✔
5238

3✔
5239
                // Handle it and close the err chan on the request.
3✔
5240
                close(req.err)
3✔
5241

3✔
5242
                // Update the next revocation point.
3✔
5243
                err := p.updateNextRevocation(newChan.OpenChannel)
3✔
5244
                if err != nil {
3✔
5245
                        p.log.Errorf(err.Error())
×
5246
                }
×
5247

5248
                return
3✔
5249
        }
5250

5251
        // This is a new channel, we now add it to the map.
5252
        if err := p.addActiveChannel(req.channel); err != nil {
3✔
5253
                // Log and send back the error to the request.
×
5254
                p.log.Errorf(err.Error())
×
5255
                req.err <- err
×
5256

×
5257
                return
×
5258
        }
×
5259

5260
        // Close the err chan if everything went fine.
5261
        close(req.err)
3✔
5262
}
5263

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

7✔
5271
        chanID := req.channelID
7✔
5272

7✔
5273
        // If we already have this channel, something is wrong with the funding
7✔
5274
        // flow as it will only be marked as active after `ChannelReady` is
7✔
5275
        // handled. In this case, we will do nothing but log an error, just in
7✔
5276
        // case this is a legit channel.
7✔
5277
        if p.isActiveChannel(chanID) {
8✔
5278
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
5279
                        "pending channel request", chanID)
1✔
5280

1✔
5281
                return
1✔
5282
        }
1✔
5283

5284
        // The channel has already been added, we will do nothing and return.
5285
        if p.isPendingChannel(chanID) {
7✔
5286
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
5287
                        "pending channel request", chanID)
1✔
5288

1✔
5289
                return
1✔
5290
        }
1✔
5291

5292
        // This is a new channel, we now add it to the map `activeChannels`
5293
        // with nil value and mark it as a newly added channel in
5294
        // `addedChannels`.
5295
        p.activeChannels.Store(chanID, nil)
5✔
5296
        p.addedChannels.Store(chanID, struct{}{})
5✔
5297
}
5298

5299
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
5300
// from `activeChannels` map. The request will be ignored if the channel is
5301
// considered active by Brontide. Noop if the channel ID cannot be found.
5302
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
7✔
5303
        defer close(req.err)
7✔
5304

7✔
5305
        chanID := req.channelID
7✔
5306

7✔
5307
        // If we already have this channel, something is wrong with the funding
7✔
5308
        // flow as it will only be marked as active after `ChannelReady` is
7✔
5309
        // handled. In this case, we will log an error and exit.
7✔
5310
        if p.isActiveChannel(chanID) {
8✔
5311
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
5312
                        chanID)
1✔
5313
                return
1✔
5314
        }
1✔
5315

5316
        // The channel has not been added yet, we will log a warning as there
5317
        // is an unexpected call from funding manager.
5318
        if !p.isPendingChannel(chanID) {
10✔
5319
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
4✔
5320
        }
4✔
5321

5322
        // Remove the record of this pending channel.
5323
        p.activeChannels.Delete(chanID)
6✔
5324
        p.addedChannels.Delete(chanID)
6✔
5325
}
5326

5327
// sendLinkUpdateMsg sends a message that updates the channel to the
5328
// channel's message stream.
5329
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
3✔
5330
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
3✔
5331

3✔
5332
        chanStream, ok := p.activeMsgStreams[cid]
3✔
5333
        if !ok {
6✔
5334
                // If a stream hasn't yet been created, then we'll do so, add
3✔
5335
                // it to the map, and finally start it.
3✔
5336
                chanStream = newChanMsgStream(p, cid)
3✔
5337
                p.activeMsgStreams[cid] = chanStream
3✔
5338
                chanStream.Start()
3✔
5339

3✔
5340
                // Stop the stream when quit.
3✔
5341
                go func() {
6✔
5342
                        <-p.cg.Done()
3✔
5343
                        chanStream.Stop()
3✔
5344
                }()
3✔
5345
        }
5346

5347
        // With the stream obtained, add the message to the stream so we can
5348
        // continue processing message.
5349
        chanStream.AddMsg(msg)
3✔
5350
}
5351

5352
// scaleTimeout multiplies the argument duration by a constant factor depending
5353
// on variious heuristics. Currently this is only used to check whether our peer
5354
// appears to be connected over Tor and relaxes the timout deadline. However,
5355
// this is subject to change and should be treated as opaque.
5356
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
70✔
5357
        if p.isTorConnection {
73✔
5358
                return timeout * time.Duration(torTimeoutMultiplier)
3✔
5359
        }
3✔
5360

5361
        return timeout
67✔
5362
}
5363

5364
// CoopCloseUpdates is a struct used to communicate updates for an active close
5365
// to the caller.
5366
type CoopCloseUpdates struct {
5367
        UpdateChan chan interface{}
5368

5369
        ErrChan chan error
5370
}
5371

5372
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5373
// point has an active RBF chan closer.
5374
func (p *Brontide) ChanHasRbfCoopCloser(chanPoint wire.OutPoint) bool {
3✔
5375
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5376
        chanCloser, found := p.activeChanCloses.Load(chanID)
3✔
5377
        if !found {
6✔
5378
                return false
3✔
5379
        }
3✔
5380

5381
        return chanCloser.IsRight()
3✔
5382
}
5383

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

3✔
5392
        // If RBF coop close isn't permitted, then we'll an error.
3✔
5393
        if !p.rbfCoopCloseAllowed() {
3✔
5394
                return nil, fmt.Errorf("rbf coop close not enabled for " +
×
5395
                        "channel")
×
5396
        }
×
5397

5398
        closeUpdates := &CoopCloseUpdates{
3✔
5399
                UpdateChan: make(chan interface{}, 1),
3✔
5400
                ErrChan:    make(chan error, 1),
3✔
5401
        }
3✔
5402

3✔
5403
        // We'll re-use the existing switch struct here, even though we're
3✔
5404
        // bypassing the switch entirely.
3✔
5405
        closeReq := htlcswitch.ChanClose{
3✔
5406
                CloseType:      contractcourt.CloseRegular,
3✔
5407
                ChanPoint:      &chanPoint,
3✔
5408
                TargetFeePerKw: feeRate,
3✔
5409
                DeliveryScript: deliveryScript,
3✔
5410
                Updates:        closeUpdates.UpdateChan,
3✔
5411
                Err:            closeUpdates.ErrChan,
3✔
5412
                Ctx:            ctx,
3✔
5413
        }
3✔
5414

3✔
5415
        err := p.startRbfChanCloser(newRPCShutdownInit(&closeReq), chanPoint)
3✔
5416
        if err != nil {
3✔
5417
                return nil, err
×
5418
        }
×
5419

5420
        return closeUpdates, nil
3✔
5421
}
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