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

lightningnetwork / lnd / 18312972447

07 Oct 2025 12:41PM UTC coverage: 66.645% (+0.004%) from 66.641%
18312972447

Pull #9868

github

web-flow
Merge c72c70415 into 87aed739e
Pull Request #9868: Basic structures for onion messages into LND

162 of 243 new or added lines in 11 files covered. (66.67%)

67 existing lines in 16 files now uncovered.

137388 of 206148 relevant lines covered (66.65%)

21327.61 hits per line

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

78.25
/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/lightningnetwork/lnd/aliasmgr"
23
        "github.com/lightningnetwork/lnd/brontide"
24
        "github.com/lightningnetwork/lnd/buffer"
25
        "github.com/lightningnetwork/lnd/chainntnfs"
26
        "github.com/lightningnetwork/lnd/channeldb"
27
        "github.com/lightningnetwork/lnd/channelnotifier"
28
        "github.com/lightningnetwork/lnd/contractcourt"
29
        "github.com/lightningnetwork/lnd/discovery"
30
        "github.com/lightningnetwork/lnd/feature"
31
        "github.com/lightningnetwork/lnd/fn/v2"
32
        "github.com/lightningnetwork/lnd/funding"
33
        graphdb "github.com/lightningnetwork/lnd/graph/db"
34
        "github.com/lightningnetwork/lnd/graph/db/models"
35
        "github.com/lightningnetwork/lnd/htlcswitch"
36
        "github.com/lightningnetwork/lnd/htlcswitch/hodl"
37
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
38
        "github.com/lightningnetwork/lnd/input"
39
        "github.com/lightningnetwork/lnd/invoices"
40
        "github.com/lightningnetwork/lnd/keychain"
41
        "github.com/lightningnetwork/lnd/lnpeer"
42
        "github.com/lightningnetwork/lnd/lntypes"
43
        "github.com/lightningnetwork/lnd/lnutils"
44
        "github.com/lightningnetwork/lnd/lnwallet"
45
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
46
        "github.com/lightningnetwork/lnd/lnwallet/chancloser"
47
        "github.com/lightningnetwork/lnd/lnwire"
48
        "github.com/lightningnetwork/lnd/msgmux"
49
        "github.com/lightningnetwork/lnd/netann"
50
        "github.com/lightningnetwork/lnd/onionmessage"
51
        "github.com/lightningnetwork/lnd/pool"
52
        "github.com/lightningnetwork/lnd/protofsm"
53
        "github.com/lightningnetwork/lnd/queue"
54
        "github.com/lightningnetwork/lnd/subscribe"
55
        "github.com/lightningnetwork/lnd/ticker"
56
        "github.com/lightningnetwork/lnd/tlv"
57
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
58
)
59

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

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

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

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

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

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

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

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

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

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

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

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

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

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

128
        err chan error
129
}
130

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

443
        // QuiescenceTimeout is the max duration that the channel can be
444
        // quiesced. Any dependent protocols (dynamic commitments, splicing,
445
        // etc.) must finish their operations under this timeout value,
446
        // otherwise the node will disconnect.
447
        QuiescenceTimeout time.Duration
448

449
        // MaxFeeExposure limits the number of outstanding fees in a channel.
450
        // This value will be passed to created links.
451
        MaxFeeExposure lnwire.MilliSatoshi
452

453
        // MsgRouter is an optional instance of the main message router that
454
        // the peer will use. If None, then a new default version will be used
455
        // in place.
456
        MsgRouter fn.Option[msgmux.Router]
457

458
        // AuxChanCloser is an optional instance of an abstraction that can be
459
        // used to modify the way the co-op close transaction is constructed.
460
        AuxChanCloser fn.Option[chancloser.AuxChanCloser]
461

462
        // AuxChannelNegotiator is an optional interface that allows aux channel
463
        // implementations to inject and process custom records over channel
464
        // related wire messages.
465
        AuxChannelNegotiator fn.Option[lnwallet.AuxChannelNegotiator]
466

467
        // OnionMessageServer is an instance of a message server that dispatches
468
        // onion messages to subscribers.
469
        OnionMessageServer *subscribe.Server
470

471
        // ShouldFwdExpEndorsement is a closure that indicates whether
472
        // experimental endorsement signals should be set.
473
        ShouldFwdExpEndorsement func() bool
474

475
        // NoDisconnectOnPongFailure indicates whether the peer should *not* be
476
        // disconnected if a pong is not received in time or is mismatched.
477
        NoDisconnectOnPongFailure bool
478

479
        // Quit is the server's quit channel. If this is closed, we halt operation.
480
        Quit chan struct{}
481
}
482

483
// chanCloserFsm is a union-like type that can hold the two versions of co-op
484
// close we support: negotiation, and RBF based.
485
//
486
// TODO(roasbeef): rename to chancloser.Negotiator and chancloser.RBF?
487
type chanCloserFsm = fn.Either[*chancloser.ChanCloser, *chancloser.RbfChanCloser] //nolint:ll
488

489
// makeNegotiateCloser creates a new negotiate closer from a
490
// chancloser.ChanCloser.
491
func makeNegotiateCloser(chanCloser *chancloser.ChanCloser) chanCloserFsm {
12✔
492
        return fn.NewLeft[*chancloser.ChanCloser, *chancloser.RbfChanCloser](
12✔
493
                chanCloser,
12✔
494
        )
12✔
495
}
12✔
496

497
// makeRbfCloser creates a new RBF closer from a chancloser.RbfChanCloser.
498
func makeRbfCloser(rbfCloser *chancloser.RbfChanCloser) chanCloserFsm {
3✔
499
        return fn.NewRight[*chancloser.ChanCloser](
3✔
500
                rbfCloser,
3✔
501
        )
3✔
502
}
3✔
503

504
// Brontide is an active peer on the Lightning Network. This struct is responsible
505
// for managing any channel state related to this peer. To do so, it has
506
// several helper goroutines to handle events such as HTLC timeouts, new
507
// funding workflow, and detecting an uncooperative closure of any active
508
// channels.
509
type Brontide struct {
510
        // MUST be used atomically.
511
        started    int32
512
        disconnect int32
513

514
        // MUST be used atomically.
515
        bytesReceived uint64
516
        bytesSent     uint64
517

518
        // isTorConnection is a flag that indicates whether or not we believe
519
        // the remote peer is a tor connection. It is not always possible to
520
        // know this with certainty but we have heuristics we use that should
521
        // catch most cases.
522
        //
523
        // NOTE: We judge the tor-ness of a connection by if the remote peer has
524
        // ".onion" in the address OR if it's connected over localhost.
525
        // This will miss cases where our peer is connected to our clearnet
526
        // address over the tor network (via exit nodes). It will also misjudge
527
        // actual localhost connections as tor. We need to include this because
528
        // inbound connections to our tor address will appear to come from the
529
        // local socks5 proxy. This heuristic is only used to expand the timeout
530
        // window for peers so it is OK to misjudge this. If you use this field
531
        // for any other purpose you should seriously consider whether or not
532
        // this heuristic is good enough for your use case.
533
        isTorConnection bool
534

535
        pingManager *PingManager
536

537
        // lastPingPayload stores an unsafe pointer wrapped as an atomic
538
        // variable which points to the last payload the remote party sent us
539
        // as their ping.
540
        //
541
        // MUST be used atomically.
542
        lastPingPayload atomic.Value
543

544
        cfg Config
545

546
        // activeSignal when closed signals that the peer is now active and
547
        // ready to process messages.
548
        activeSignal chan struct{}
549

550
        // startTime is the time this peer connection was successfully established.
551
        // It will be zero for peers that did not successfully call Start().
552
        startTime time.Time
553

554
        // sendQueue is the channel which is used to queue outgoing messages to be
555
        // written onto the wire. Note that this channel is unbuffered.
556
        sendQueue chan outgoingMsg
557

558
        // outgoingQueue is a buffered channel which allows second/third party
559
        // objects to queue messages to be sent out on the wire.
560
        outgoingQueue chan outgoingMsg
561

562
        // activeChannels is a map which stores the state machines of all
563
        // active channels. Channels are indexed into the map by the txid of
564
        // the funding transaction which opened the channel.
565
        //
566
        // NOTE: On startup, pending channels are stored as nil in this map.
567
        // Confirmed channels have channel data populated in the map. This means
568
        // that accesses to this map should nil-check the LightningChannel to
569
        // see if this is a pending channel or not. The tradeoff here is either
570
        // having two maps everywhere (one for pending, one for confirmed chans)
571
        // or having an extra nil-check per access.
572
        activeChannels *lnutils.SyncMap[
573
                lnwire.ChannelID, *lnwallet.LightningChannel]
574

575
        // addedChannels tracks any new channels opened during this peer's
576
        // lifecycle. We use this to filter out these new channels when the time
577
        // comes to request a reenable for active channels, since they will have
578
        // waited a shorter duration.
579
        addedChannels *lnutils.SyncMap[lnwire.ChannelID, struct{}]
580

581
        // newActiveChannel is used by the fundingManager to send fully opened
582
        // channels to the source peer which handled the funding workflow.
583
        newActiveChannel chan *newChannelMsg
584

585
        // newPendingChannel is used by the fundingManager to send pending open
586
        // channels to the source peer which handled the funding workflow.
587
        newPendingChannel chan *newChannelMsg
588

589
        // removePendingChannel is used by the fundingManager to cancel pending
590
        // open channels to the source peer when the funding flow is failed.
591
        removePendingChannel chan *newChannelMsg
592

593
        // activeMsgStreams is a map from channel id to the channel streams that
594
        // proxy messages to individual, active links.
595
        activeMsgStreams map[lnwire.ChannelID]*msgStream
596

597
        // activeChanCloses is a map that keeps track of all the active
598
        // cooperative channel closures. Any channel closing messages are directed
599
        // to one of these active state machines. Once the channel has been closed,
600
        // the state machine will be deleted from the map.
601
        activeChanCloses *lnutils.SyncMap[lnwire.ChannelID, chanCloserFsm]
602

603
        // localCloseChanReqs is a channel in which any local requests to close
604
        // a particular channel are sent over.
605
        localCloseChanReqs chan *htlcswitch.ChanClose
606

607
        // linkFailures receives all reported channel failures from the switch,
608
        // and instructs the channelManager to clean remaining channel state.
609
        linkFailures chan linkFailureReport
610

611
        // chanCloseMsgs is a channel that any message related to channel
612
        // closures are sent over. This includes lnwire.Shutdown message as
613
        // well as lnwire.ClosingSigned messages.
614
        chanCloseMsgs chan *closeMsg
615

616
        // remoteFeatures is the feature vector received from the peer during
617
        // the connection handshake.
618
        remoteFeatures *lnwire.FeatureVector
619

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

626
        // channelEventClient is the channel event subscription client that's
627
        // used to assist retry enabling the channels. This client is only
628
        // created when the reenableTimeout is no greater than 1 minute. Once
629
        // created, it is canceled once the reenabling has been finished.
630
        //
631
        // NOTE: we choose to create the client conditionally to avoid
632
        // potentially holding lots of un-consumed events.
633
        channelEventClient *subscribe.Client
634

635
        // msgRouter is an instance of the msgmux.Router which is used to send
636
        // off new wire messages for handing.
637
        msgRouter fn.Option[msgmux.Router]
638

639
        // globalMsgRouter is a flag that indicates whether we have a global
640
        // msg router. If so, then we don't worry about stopping the msg router
641
        // when a peer disconnects.
642
        globalMsgRouter bool
643

644
        startReady chan struct{}
645

646
        // cg is a helper that encapsulates a wait group and quit channel and
647
        // allows contexts that either block or cancel on those depending on
648
        // the use case.
649
        cg *fn.ContextGuard
650

651
        // log is a peer-specific logging instance.
652
        log btclog.Logger
653
}
654

655
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer
656
// interface.
657
var _ lnpeer.Peer = (*Brontide)(nil)
658

659
// NewBrontide creates a new Brontide from a peer.Config struct.
660
func NewBrontide(cfg Config) *Brontide {
28✔
661
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
28✔
662

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

28✔
668
        // We'll either use the msg router instance passed in, or create a new
28✔
669
        // blank instance.
28✔
670
        msgRouter := cfg.MsgRouter.Alt(fn.Some[msgmux.Router](
28✔
671
                msgmux.NewMultiMsgRouter(),
28✔
672
        ))
28✔
673

28✔
674
        p := &Brontide{
28✔
675
                cfg:           cfg,
28✔
676
                activeSignal:  make(chan struct{}),
28✔
677
                sendQueue:     make(chan outgoingMsg),
28✔
678
                outgoingQueue: make(chan outgoingMsg),
28✔
679
                addedChannels: &lnutils.SyncMap[lnwire.ChannelID, struct{}]{},
28✔
680
                activeChannels: &lnutils.SyncMap[
28✔
681
                        lnwire.ChannelID, *lnwallet.LightningChannel,
28✔
682
                ]{},
28✔
683
                newActiveChannel:     make(chan *newChannelMsg, 1),
28✔
684
                newPendingChannel:    make(chan *newChannelMsg, 1),
28✔
685
                removePendingChannel: make(chan *newChannelMsg),
28✔
686

28✔
687
                activeMsgStreams: make(map[lnwire.ChannelID]*msgStream),
28✔
688
                activeChanCloses: &lnutils.SyncMap[
28✔
689
                        lnwire.ChannelID, chanCloserFsm,
28✔
690
                ]{},
28✔
691
                localCloseChanReqs: make(chan *htlcswitch.ChanClose),
28✔
692
                linkFailures:       make(chan linkFailureReport),
28✔
693
                chanCloseMsgs:      make(chan *closeMsg),
28✔
694
                resentChanSyncMsg:  make(map[lnwire.ChannelID]struct{}),
28✔
695
                startReady:         make(chan struct{}),
28✔
696
                log:                peerLog.WithPrefix(logPrefix),
28✔
697
                msgRouter:          msgRouter,
28✔
698
                globalMsgRouter:    globalMsgRouter,
28✔
699
                cg:                 fn.NewContextGuard(),
28✔
700
        }
28✔
701

28✔
702
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
31✔
703
                remoteAddr := cfg.Conn.RemoteAddr().String()
3✔
704
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
3✔
705
                        strings.Contains(remoteAddr, "127.0.0.1")
3✔
706
        }
3✔
707

708
        var (
28✔
709
                lastBlockHeader           *wire.BlockHeader
28✔
710
                lastSerializedBlockHeader [wire.MaxBlockHeaderPayload]byte
28✔
711
        )
28✔
712
        newPingPayload := func() []byte {
28✔
713
                // We query the BestBlockHeader from our BestBlockView each time
×
714
                // this is called, and update our serialized block header if
×
715
                // they differ.  Over time, we'll use this to disseminate the
×
716
                // latest block header between all our peers, which can later be
×
717
                // used to cross-check our own view of the network to mitigate
×
718
                // various types of eclipse attacks.
×
719
                header, err := p.cfg.BestBlockView.BestBlockHeader()
×
720
                if err != nil && header == lastBlockHeader {
×
721
                        return lastSerializedBlockHeader[:]
×
722
                }
×
723

724
                buf := bytes.NewBuffer(lastSerializedBlockHeader[0:0])
×
725
                err = header.Serialize(buf)
×
726
                if err == nil {
×
727
                        lastBlockHeader = header
×
728
                } else {
×
729
                        p.log.Warn("unable to serialize current block" +
×
730
                                "header for ping payload generation." +
×
731
                                "This should be impossible and means" +
×
732
                                "there is an implementation bug.")
×
733
                }
×
734

735
                return lastSerializedBlockHeader[:]
×
736
        }
737

738
        // TODO(roasbeef): make dynamic in order to create fake cover traffic.
739
        //
740
        // NOTE(proofofkeags): this was changed to be dynamic to allow better
741
        // pong identification, however, more thought is needed to make this
742
        // actually usable as a traffic decoy.
743
        randPongSize := func() uint16 {
28✔
744
                return uint16(
×
745
                        // We don't need cryptographic randomness here.
×
746
                        /* #nosec */
×
747
                        rand.Intn(pongSizeCeiling) + 1,
×
748
                )
×
749
        }
×
750

751
        p.pingManager = NewPingManager(&PingManagerConfig{
28✔
752
                NewPingPayload:   newPingPayload,
28✔
753
                NewPongSize:      randPongSize,
28✔
754
                IntervalDuration: p.scaleTimeout(pingInterval),
28✔
755
                TimeoutDuration:  p.scaleTimeout(pingTimeout),
28✔
756
                SendPing: func(ping *lnwire.Ping) {
28✔
757
                        p.queueMsg(ping, nil)
×
758
                },
×
759
                OnPongFailure: func(reason error,
760
                        timeWaitedForPong time.Duration,
761
                        lastKnownRTT time.Duration) {
×
762

×
763
                        logMsg := fmt.Sprintf("pong response "+
×
764
                                "failure for %s: %v. Time waited for this "+
×
765
                                "pong: %v. Last successful RTT: %v.",
×
766
                                p, reason, timeWaitedForPong, lastKnownRTT)
×
767

×
768
                        // If NoDisconnectOnPongFailure is true, we don't
×
769
                        // disconnect. Otherwise (if it's false, the default),
×
770
                        // we disconnect.
×
771
                        if p.cfg.NoDisconnectOnPongFailure {
×
772
                                p.log.Warnf("%s -- not disconnecting "+
×
773
                                        "due to config", logMsg)
×
774
                                return
×
775
                        }
×
776

777
                        p.log.Warnf("%s -- disconnecting", logMsg)
×
778

×
779
                        go p.Disconnect(fmt.Errorf("pong failure: %w", reason))
×
780
                },
781
        })
782

783
        return p
28✔
784
}
785

786
// Start starts all helper goroutines the peer needs for normal operations.  In
787
// the case this peer has already been started, then this function is a noop.
788
func (p *Brontide) Start() error {
6✔
789
        if atomic.AddInt32(&p.started, 1) != 1 {
6✔
790
                return nil
×
791
        }
×
792

793
        // Once we've finished starting up the peer, we'll signal to other
794
        // goroutines that the they can move forward to tear down the peer, or
795
        // carry out other relevant changes.
796
        defer close(p.startReady)
6✔
797

6✔
798
        p.log.Tracef("starting with conn[%v->%v]",
6✔
799
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
6✔
800

6✔
801
        // Fetch and then load all the active channels we have with this remote
6✔
802
        // peer from the database.
6✔
803
        activeChans, err := p.cfg.ChannelDB.FetchOpenChannels(
6✔
804
                p.cfg.Addr.IdentityKey,
6✔
805
        )
6✔
806
        if err != nil {
6✔
807
                p.log.Errorf("Unable to fetch active chans "+
×
808
                        "for peer: %v", err)
×
809
                return err
×
810
        }
×
811

812
        if len(activeChans) == 0 {
10✔
813
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
4✔
814
        }
4✔
815

816
        // Quickly check if we have any existing legacy channels with this
817
        // peer.
818
        haveLegacyChan := false
6✔
819
        for _, c := range activeChans {
11✔
820
                if c.ChanType.IsTweakless() {
10✔
821
                        continue
5✔
822
                }
823

824
                haveLegacyChan = true
3✔
825
                break
3✔
826
        }
827

828
        // Exchange local and global features, the init message should be very
829
        // first between two nodes.
830
        if err := p.sendInitMsg(haveLegacyChan); err != nil {
9✔
831
                return fmt.Errorf("unable to send init msg: %w", err)
3✔
832
        }
3✔
833

834
        // Before we launch any of the helper goroutines off the peer struct,
835
        // we'll first ensure proper adherence to the p2p protocol. The init
836
        // message MUST be sent before any other message.
837
        readErr := make(chan error, 1)
6✔
838
        msgChan := make(chan lnwire.Message, 1)
6✔
839
        p.cg.WgAdd(1)
6✔
840
        go func() {
12✔
841
                defer p.cg.WgDone()
6✔
842

6✔
843
                msg, err := p.readNextMessage()
6✔
844
                if err != nil {
9✔
845
                        readErr <- err
3✔
846
                        msgChan <- nil
3✔
847
                        return
3✔
848
                }
3✔
849
                readErr <- nil
6✔
850
                msgChan <- msg
6✔
851
        }()
852

853
        select {
6✔
854
        // In order to avoid blocking indefinitely, we'll give the other peer
855
        // an upper timeout to respond before we bail out early.
856
        case <-time.After(handshakeTimeout):
×
857
                return fmt.Errorf("peer did not complete handshake within %v",
×
858
                        handshakeTimeout)
×
859
        case err := <-readErr:
6✔
860
                if err != nil {
9✔
861
                        return fmt.Errorf("unable to read init msg: %w", err)
3✔
862
                }
3✔
863
        }
864

865
        // Once the init message arrives, we can parse it so we can figure out
866
        // the negotiation of features for this session.
867
        msg := <-msgChan
6✔
868
        if msg, ok := msg.(*lnwire.Init); ok {
12✔
869
                if err := p.handleInitMsg(msg); err != nil {
6✔
870
                        p.storeError(err)
×
871
                        return err
×
872
                }
×
873
        } else {
×
874
                return errors.New("very first message between nodes " +
×
875
                        "must be init message")
×
876
        }
×
877

878
        // Next, load all the active channels we have with this peer,
879
        // registering them with the switch and launching the necessary
880
        // goroutines required to operate them.
881
        p.log.Debugf("Loaded %v active channels from database",
6✔
882
                len(activeChans))
6✔
883

6✔
884
        // Conditionally subscribe to channel events before loading channels so
6✔
885
        // we won't miss events. This subscription is used to listen to active
6✔
886
        // channel event when reenabling channels. Once the reenabling process
6✔
887
        // is finished, this subscription will be canceled.
6✔
888
        //
6✔
889
        // NOTE: ChannelNotifier must be started before subscribing events
6✔
890
        // otherwise we'd panic here.
6✔
891
        if err := p.attachChannelEventSubscription(); err != nil {
6✔
892
                return err
×
893
        }
×
894

895
        // Register the message router now as we may need to register some
896
        // endpoints while loading the channels below.
897
        p.msgRouter.WhenSome(func(router msgmux.Router) {
12✔
898
                router.Start(context.Background())
6✔
899
        })
6✔
900

901
        msgs, err := p.loadActiveChannels(activeChans)
6✔
902
        if err != nil {
6✔
903
                return fmt.Errorf("unable to load channels: %w", err)
×
904
        }
×
905

906
        onionMessageEndpoint := onionmessage.NewOnionEndpoint(
6✔
907
                p.cfg.OnionMessageServer,
6✔
908
        )
6✔
909

6✔
910
        // We register the onion message endpoint with the message router.
6✔
911
        err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
12✔
912
                _ = r.UnregisterEndpoint(onionMessageEndpoint.Name())
6✔
913

6✔
914
                return r.RegisterEndpoint(onionMessageEndpoint)
6✔
915
        })
6✔
916
        if err != nil {
6✔
NEW
917
                return fmt.Errorf("unable to register endpoint for onion "+
×
NEW
918
                        "messaging: %w", err)
×
NEW
919
        }
×
920

921
        p.startTime = time.Now()
6✔
922

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

5✔
930
                // Send the messages directly via writeMessage and bypass the
5✔
931
                // writeHandler goroutine.
5✔
932
                for _, msg := range msgs {
10✔
933
                        if err := p.writeMessage(msg); err != nil {
5✔
934
                                return fmt.Errorf("unable to send "+
×
935
                                        "reestablish msg: %v", err)
×
936
                        }
×
937
                }
938
        }
939

940
        err = p.pingManager.Start()
6✔
941
        if err != nil {
6✔
942
                return fmt.Errorf("could not start ping manager %w", err)
×
943
        }
×
944

945
        p.cg.WgAdd(4)
6✔
946
        go p.queueHandler()
6✔
947
        go p.writeHandler()
6✔
948
        go p.channelManager()
6✔
949
        go p.readHandler()
6✔
950

6✔
951
        // Signal to any external processes that the peer is now active.
6✔
952
        close(p.activeSignal)
6✔
953

6✔
954
        // Node announcements don't propagate very well throughout the network
6✔
955
        // as there isn't a way to efficiently query for them through their
6✔
956
        // timestamp, mostly affecting nodes that were offline during the time
6✔
957
        // of broadcast. We'll resend our node announcement to the remote peer
6✔
958
        // as a best-effort delivery such that it can also propagate to their
6✔
959
        // peers. To ensure they can successfully process it in most cases,
6✔
960
        // we'll only resend it as long as we have at least one confirmed
6✔
961
        // advertised channel with the remote peer.
6✔
962
        //
6✔
963
        // TODO(wilmer): Remove this once we're able to query for node
6✔
964
        // announcements through their timestamps.
6✔
965
        p.cg.WgAdd(2)
6✔
966
        go p.maybeSendNodeAnn(activeChans)
6✔
967
        go p.maybeSendChannelUpdates()
6✔
968

6✔
969
        return nil
6✔
970
}
971

972
// initGossipSync initializes either a gossip syncer or an initial routing
973
// dump, depending on the negotiated synchronization method.
974
func (p *Brontide) initGossipSync() {
6✔
975
        // If the remote peer knows of the new gossip queries feature, then
6✔
976
        // we'll create a new gossipSyncer in the AuthenticatedGossiper for it.
6✔
977
        if p.remoteFeatures.HasFeature(lnwire.GossipQueriesOptional) {
12✔
978
                p.log.Info("Negotiated chan series queries")
6✔
979

6✔
980
                if p.cfg.AuthGossiper == nil {
9✔
981
                        // This should only ever be hit in the unit tests.
3✔
982
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
3✔
983
                                "gossip sync.")
3✔
984
                        return
3✔
985
                }
3✔
986

987
                // Register the peer's gossip syncer with the gossiper.
988
                // This blocks synchronously to ensure the gossip syncer is
989
                // registered with the gossiper before attempting to read
990
                // messages from the remote peer.
991
                //
992
                // TODO(wilmer): Only sync updates from non-channel peers. This
993
                // requires an improved version of the current network
994
                // bootstrapper to ensure we can find and connect to non-channel
995
                // peers.
996
                p.cfg.AuthGossiper.InitSyncState(p)
3✔
997
        }
998
}
999

1000
// taprootShutdownAllowed returns true if both parties have negotiated the
1001
// shutdown-any-segwit feature.
1002
func (p *Brontide) taprootShutdownAllowed() bool {
9✔
1003
        return p.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
9✔
1004
                p.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
9✔
1005
}
9✔
1006

1007
// rbfCoopCloseAllowed returns true if both parties have negotiated the new RBF
1008
// coop close feature.
1009
func (p *Brontide) rbfCoopCloseAllowed() bool {
10✔
1010
        bothHaveBit := func(bit lnwire.FeatureBit) bool {
27✔
1011
                return p.RemoteFeatures().HasFeature(bit) &&
17✔
1012
                        p.LocalFeatures().HasFeature(bit)
17✔
1013
        }
17✔
1014

1015
        return bothHaveBit(lnwire.RbfCoopCloseOptional) ||
10✔
1016
                bothHaveBit(lnwire.RbfCoopCloseOptionalStaging)
10✔
1017
}
1018

1019
// QuitSignal is a method that should return a channel which will be sent upon
1020
// or closed once the backing peer exits. This allows callers using the
1021
// interface to cancel any processing in the event the backing implementation
1022
// exits.
1023
//
1024
// NOTE: Part of the lnpeer.Peer interface.
1025
func (p *Brontide) QuitSignal() <-chan struct{} {
3✔
1026
        return p.cg.Done()
3✔
1027
}
3✔
1028

1029
// addrWithInternalKey takes a delivery script, then attempts to supplement it
1030
// with information related to the internal key for the addr, but only if it's
1031
// a taproot addr.
1032
func (p *Brontide) addrWithInternalKey(
1033
        deliveryScript []byte) (*chancloser.DeliveryAddrWithKey, error) {
12✔
1034

12✔
1035
        // Currently, custom channels cannot be created with external upfront
12✔
1036
        // shutdown addresses, so this shouldn't be an issue. We only require
12✔
1037
        // the internal key for taproot addresses to be able to provide a non
12✔
1038
        // inclusion proof of any scripts.
12✔
1039
        internalKeyDesc, err := lnwallet.InternalKeyForAddr(
12✔
1040
                p.cfg.Wallet, &p.cfg.Wallet.Cfg.NetParams, deliveryScript,
12✔
1041
        )
12✔
1042
        if err != nil {
12✔
1043
                return nil, fmt.Errorf("unable to fetch internal key: %w", err)
×
1044
        }
×
1045

1046
        return &chancloser.DeliveryAddrWithKey{
12✔
1047
                DeliveryAddress: deliveryScript,
12✔
1048
                InternalKey: fn.MapOption(
12✔
1049
                        func(desc keychain.KeyDescriptor) btcec.PublicKey {
15✔
1050
                                return *desc.PubKey
3✔
1051
                        },
3✔
1052
                )(internalKeyDesc),
1053
        }, nil
1054
}
1055

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

6✔
1063
        // Return a slice of messages to send to the peers in case the channel
6✔
1064
        // cannot be loaded normally.
6✔
1065
        var msgs []lnwire.Message
6✔
1066

6✔
1067
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
6✔
1068

6✔
1069
        for _, dbChan := range chans {
11✔
1070
                hasScidFeature := dbChan.ChanType.HasScidAliasFeature()
5✔
1071
                if scidAliasNegotiated && !hasScidFeature {
8✔
1072
                        // We'll request and store an alias, making sure that a
3✔
1073
                        // gossiper mapping is not created for the alias to the
3✔
1074
                        // real SCID. This is done because the peer and funding
3✔
1075
                        // manager are not aware of each other's states and if
3✔
1076
                        // we did not do this, we would accept alias channel
3✔
1077
                        // updates after 6 confirmations, which would be buggy.
3✔
1078
                        // We'll queue a channel_ready message with the new
3✔
1079
                        // alias. This should technically be done *after* the
3✔
1080
                        // reestablish, but this behavior is pre-existing since
3✔
1081
                        // the funding manager may already queue a
3✔
1082
                        // channel_ready before the channel_reestablish.
3✔
1083
                        if !dbChan.IsPending {
6✔
1084
                                aliasScid, err := p.cfg.RequestAlias()
3✔
1085
                                if err != nil {
3✔
1086
                                        return nil, err
×
1087
                                }
×
1088

1089
                                err = p.cfg.AddLocalAlias(
3✔
1090
                                        aliasScid, dbChan.ShortChanID(), false,
3✔
1091
                                        false,
3✔
1092
                                )
3✔
1093
                                if err != nil {
3✔
1094
                                        return nil, err
×
1095
                                }
×
1096

1097
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
1098
                                        dbChan.FundingOutpoint,
3✔
1099
                                )
3✔
1100

3✔
1101
                                // Fetch the second commitment point to send in
3✔
1102
                                // the channel_ready message.
3✔
1103
                                second, err := dbChan.SecondCommitmentPoint()
3✔
1104
                                if err != nil {
3✔
1105
                                        return nil, err
×
1106
                                }
×
1107

1108
                                channelReadyMsg := lnwire.NewChannelReady(
3✔
1109
                                        chanID, second,
3✔
1110
                                )
3✔
1111
                                channelReadyMsg.AliasScid = &aliasScid
3✔
1112

3✔
1113
                                msgs = append(msgs, channelReadyMsg)
3✔
1114
                        }
1115

1116
                        // If we've negotiated the option-scid-alias feature
1117
                        // and this channel does not have ScidAliasFeature set
1118
                        // to true due to an upgrade where the feature bit was
1119
                        // turned on, we'll update the channel's database
1120
                        // state.
1121
                        err := dbChan.MarkScidAliasNegotiated()
3✔
1122
                        if err != nil {
3✔
1123
                                return nil, err
×
1124
                        }
×
1125
                }
1126

1127
                var chanOpts []lnwallet.ChannelOpt
5✔
1128
                p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
5✔
1129
                        chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
1130
                })
×
1131
                p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
5✔
1132
                        chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
1133
                })
×
1134
                p.cfg.AuxResolver.WhenSome(
5✔
1135
                        func(s lnwallet.AuxContractResolver) {
5✔
1136
                                chanOpts = append(
×
1137
                                        chanOpts, lnwallet.WithAuxResolver(s),
×
1138
                                )
×
1139
                        },
×
1140
                )
1141

1142
                lnChan, err := lnwallet.NewLightningChannel(
5✔
1143
                        p.cfg.Signer, dbChan, p.cfg.SigPool, chanOpts...,
5✔
1144
                )
5✔
1145
                if err != nil {
5✔
1146
                        return nil, fmt.Errorf("unable to create channel "+
×
1147
                                "state machine: %w", err)
×
1148
                }
×
1149

1150
                chanPoint := dbChan.FundingOutpoint
5✔
1151

5✔
1152
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
5✔
1153

5✔
1154
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
5✔
1155
                        chanPoint, lnChan.IsPending())
5✔
1156

5✔
1157
                // Skip adding any permanently irreconcilable channels to the
5✔
1158
                // htlcswitch.
5✔
1159
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
5✔
1160
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
10✔
1161

5✔
1162
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
5✔
1163
                                "start.", chanPoint, dbChan.ChanStatus())
5✔
1164

5✔
1165
                        // To help our peer recover from a potential data loss,
5✔
1166
                        // we resend our channel reestablish message if the
5✔
1167
                        // channel is in a borked state. We won't process any
5✔
1168
                        // channel reestablish message sent from the peer, but
5✔
1169
                        // that's okay since the assumption is that we did when
5✔
1170
                        // marking the channel borked.
5✔
1171
                        chanSync, err := dbChan.ChanSyncMsg()
5✔
1172
                        if err != nil {
5✔
1173
                                p.log.Errorf("Unable to create channel "+
×
1174
                                        "reestablish message for channel %v: "+
×
1175
                                        "%v", chanPoint, err)
×
1176
                                continue
×
1177
                        }
1178

1179
                        msgs = append(msgs, chanSync)
5✔
1180

5✔
1181
                        // Check if this channel needs to have the cooperative
5✔
1182
                        // close process restarted. If so, we'll need to send
5✔
1183
                        // the Shutdown message that is returned.
5✔
1184
                        if dbChan.HasChanStatus(
5✔
1185
                                channeldb.ChanStatusCoopBroadcasted,
5✔
1186
                        ) {
8✔
1187

3✔
1188
                                shutdownMsg, err := p.restartCoopClose(lnChan)
3✔
1189
                                if err != nil {
3✔
1190
                                        p.log.Errorf("Unable to restart "+
×
1191
                                                "coop close for channel: %v",
×
1192
                                                err)
×
1193
                                        continue
×
1194
                                }
1195

1196
                                if shutdownMsg == nil {
6✔
1197
                                        continue
3✔
1198
                                }
1199

1200
                                // Append the message to the set of messages to
1201
                                // send.
1202
                                msgs = append(msgs, shutdownMsg)
×
1203
                        }
1204

1205
                        continue
5✔
1206
                }
1207

1208
                // Before we register this new link with the HTLC Switch, we'll
1209
                // need to fetch its current link-layer forwarding policy from
1210
                // the database.
1211
                graph := p.cfg.ChannelGraph
3✔
1212
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
3✔
1213
                        &chanPoint,
3✔
1214
                )
3✔
1215
                if err != nil && !errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1216
                        return nil, err
×
1217
                }
×
1218

1219
                // We'll filter out our policy from the directional channel
1220
                // edges based whom the edge connects to. If it doesn't connect
1221
                // to us, then we know that we were the one that advertised the
1222
                // policy.
1223
                //
1224
                // TODO(roasbeef): can add helper method to get policy for
1225
                // particular channel.
1226
                var selfPolicy *models.ChannelEdgePolicy
3✔
1227
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
3✔
1228
                        p.cfg.ServerPubKey[:]) {
6✔
1229

3✔
1230
                        selfPolicy = p1
3✔
1231
                } else {
6✔
1232
                        selfPolicy = p2
3✔
1233
                }
3✔
1234

1235
                // If we don't yet have an advertised routing policy, then
1236
                // we'll use the current default, otherwise we'll translate the
1237
                // routing policy into a forwarding policy.
1238
                var forwardingPolicy *models.ForwardingPolicy
3✔
1239
                if selfPolicy != nil {
6✔
1240
                        forwardingPolicy = &models.ForwardingPolicy{
3✔
1241
                                MinHTLCOut:    selfPolicy.MinHTLC,
3✔
1242
                                MaxHTLC:       selfPolicy.MaxHTLC,
3✔
1243
                                BaseFee:       selfPolicy.FeeBaseMSat,
3✔
1244
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
3✔
1245
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
3✔
1246
                        }
3✔
1247
                        selfPolicy.InboundFee.WhenSome(func(fee lnwire.Fee) {
3✔
1248
                                inboundFee := models.NewInboundFeeFromWire(fee)
×
1249
                                forwardingPolicy.InboundFee = inboundFee
×
1250
                        })
×
1251
                } else {
3✔
1252
                        p.log.Warnf("Unable to find our forwarding policy "+
3✔
1253
                                "for channel %v, using default values",
3✔
1254
                                chanPoint)
3✔
1255
                        forwardingPolicy = &p.cfg.RoutingPolicy
3✔
1256
                }
3✔
1257

1258
                p.log.Tracef("Using link policy of: %v",
3✔
1259
                        lnutils.SpewLogClosure(forwardingPolicy))
3✔
1260

3✔
1261
                // If the channel is pending, set the value to nil in the
3✔
1262
                // activeChannels map. This is done to signify that the channel
3✔
1263
                // is pending. We don't add the link to the switch here - it's
3✔
1264
                // the funding manager's responsibility to spin up pending
3✔
1265
                // channels. Adding them here would just be extra work as we'll
3✔
1266
                // tear them down when creating + adding the final link.
3✔
1267
                if lnChan.IsPending() {
6✔
1268
                        p.activeChannels.Store(chanID, nil)
3✔
1269

3✔
1270
                        continue
3✔
1271
                }
1272

1273
                shutdownInfo, err := lnChan.State().ShutdownInfo()
3✔
1274
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
3✔
1275
                        return nil, err
×
1276
                }
×
1277

1278
                isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
1279

3✔
1280
                var (
3✔
1281
                        shutdownMsg     fn.Option[lnwire.Shutdown]
3✔
1282
                        shutdownInfoErr error
3✔
1283
                )
3✔
1284
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
6✔
1285
                        // If we can use the new RBF close feature, we don't
3✔
1286
                        // need to create the legacy closer. However for taproot
3✔
1287
                        // channels, we'll continue to use the legacy closer.
3✔
1288
                        if p.rbfCoopCloseAllowed() && !isTaprootChan {
6✔
1289
                                return
3✔
1290
                        }
3✔
1291

1292
                        // Compute an ideal fee.
1293
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
1294
                                p.cfg.CoopCloseTargetConfs,
3✔
1295
                        )
3✔
1296
                        if err != nil {
3✔
1297
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1298
                                        "estimate fee: %w", err)
×
1299

×
1300
                                return
×
1301
                        }
×
1302

1303
                        addr, err := p.addrWithInternalKey(
3✔
1304
                                info.DeliveryScript.Val,
3✔
1305
                        )
3✔
1306
                        if err != nil {
3✔
1307
                                shutdownInfoErr = fmt.Errorf("unable to make "+
×
1308
                                        "delivery addr: %w", err)
×
1309
                                return
×
1310
                        }
×
1311
                        negotiateChanCloser, err := p.createChanCloser(
3✔
1312
                                lnChan, addr, feePerKw, nil,
3✔
1313
                                info.Closer(),
3✔
1314
                        )
3✔
1315
                        if err != nil {
3✔
1316
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1317
                                        "create chan closer: %w", err)
×
1318

×
1319
                                return
×
1320
                        }
×
1321

1322
                        chanID := lnwire.NewChanIDFromOutPoint(
3✔
1323
                                lnChan.State().FundingOutpoint,
3✔
1324
                        )
3✔
1325

3✔
1326
                        p.activeChanCloses.Store(chanID, makeNegotiateCloser(
3✔
1327
                                negotiateChanCloser,
3✔
1328
                        ))
3✔
1329

3✔
1330
                        // Create the Shutdown message.
3✔
1331
                        shutdown, err := negotiateChanCloser.ShutdownChan()
3✔
1332
                        if err != nil {
3✔
1333
                                p.activeChanCloses.Delete(chanID)
×
1334
                                shutdownInfoErr = err
×
1335

×
1336
                                return
×
1337
                        }
×
1338

1339
                        shutdownMsg = fn.Some(*shutdown)
3✔
1340
                })
1341
                if shutdownInfoErr != nil {
3✔
1342
                        return nil, shutdownInfoErr
×
1343
                }
×
1344

1345
                // Subscribe to the set of on-chain events for this channel.
1346
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
3✔
1347
                        chanPoint,
3✔
1348
                )
3✔
1349
                if err != nil {
3✔
1350
                        return nil, err
×
1351
                }
×
1352

1353
                err = p.addLink(
3✔
1354
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
3✔
1355
                        true, shutdownMsg,
3✔
1356
                )
3✔
1357
                if err != nil {
3✔
1358
                        return nil, fmt.Errorf("unable to add link %v to "+
×
1359
                                "switch: %v", chanPoint, err)
×
1360
                }
×
1361

1362
                p.activeChannels.Store(chanID, lnChan)
3✔
1363

3✔
1364
                // We're using the old co-op close, so we don't need to init
3✔
1365
                // the new RBF chan closer. If we have a taproot chan, then
3✔
1366
                // we'll also use the legacy type, so we don't need to make the
3✔
1367
                // new closer.
3✔
1368
                if !p.rbfCoopCloseAllowed() || isTaprootChan {
6✔
1369
                        continue
3✔
1370
                }
1371

1372
                // Now that the link has been added above, we'll also init an
1373
                // RBF chan closer for this channel, but only if the new close
1374
                // feature is negotiated.
1375
                //
1376
                // Creating this here ensures that any shutdown messages sent
1377
                // will be automatically routed by the msg router.
1378
                if _, err := p.initRbfChanCloser(lnChan); err != nil {
3✔
1379
                        p.activeChanCloses.Delete(chanID)
×
1380

×
1381
                        return nil, fmt.Errorf("unable to init RBF chan "+
×
1382
                                "closer during peer connect: %w", err)
×
1383
                }
×
1384

1385
                // If the shutdown info isn't blank, then we should kick things
1386
                // off by sending a shutdown message to the remote party to
1387
                // continue the old shutdown flow.
1388
                restartShutdown := func(s channeldb.ShutdownInfo) error {
6✔
1389
                        return p.startRbfChanCloser(
3✔
1390
                                newRestartShutdownInit(s),
3✔
1391
                                lnChan.ChannelPoint(),
3✔
1392
                        )
3✔
1393
                }
3✔
1394
                err = fn.MapOptionZ(shutdownInfo, restartShutdown)
3✔
1395
                if err != nil {
3✔
1396
                        return nil, fmt.Errorf("unable to start RBF "+
×
1397
                                "chan closer: %w", err)
×
1398
                }
×
1399
        }
1400

1401
        return msgs, nil
6✔
1402
}
1403

1404
// addLink creates and adds a new ChannelLink from the specified channel.
1405
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1406
        lnChan *lnwallet.LightningChannel,
1407
        forwardingPolicy *models.ForwardingPolicy,
1408
        chainEvents *contractcourt.ChainEventSubscription,
1409
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
3✔
1410

3✔
1411
        // onChannelFailure will be called by the link in case the channel
3✔
1412
        // fails for some reason.
3✔
1413
        onChannelFailure := func(chanID lnwire.ChannelID,
3✔
1414
                shortChanID lnwire.ShortChannelID,
3✔
1415
                linkErr htlcswitch.LinkFailureError) {
6✔
1416

3✔
1417
                failure := linkFailureReport{
3✔
1418
                        chanPoint:   *chanPoint,
3✔
1419
                        chanID:      chanID,
3✔
1420
                        shortChanID: shortChanID,
3✔
1421
                        linkErr:     linkErr,
3✔
1422
                }
3✔
1423

3✔
1424
                select {
3✔
1425
                case p.linkFailures <- failure:
3✔
1426
                case <-p.cg.Done():
×
1427
                case <-p.cfg.Quit:
×
1428
                }
1429
        }
1430

1431
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
6✔
1432
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
3✔
1433
        }
3✔
1434

1435
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
6✔
1436
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
3✔
1437
        }
3✔
1438

1439
        //nolint:ll
1440
        linkCfg := htlcswitch.ChannelLinkConfig{
3✔
1441
                Peer:                   p,
3✔
1442
                DecodeHopIterators:     p.cfg.Sphinx.DecodeHopIterators,
3✔
1443
                ExtractErrorEncrypter:  p.cfg.Sphinx.ExtractErrorEncrypter,
3✔
1444
                FetchLastChannelUpdate: p.cfg.FetchLastChanUpdate,
3✔
1445
                HodlMask:               p.cfg.Hodl.Mask(),
3✔
1446
                Registry:               p.cfg.Invoices,
3✔
1447
                BestHeight:             p.cfg.Switch.BestHeight,
3✔
1448
                Circuits:               p.cfg.Switch.CircuitModifier(),
3✔
1449
                ForwardPackets:         p.cfg.InterceptSwitch.ForwardPackets,
3✔
1450
                FwrdingPolicy:          *forwardingPolicy,
3✔
1451
                FeeEstimator:           p.cfg.FeeEstimator,
3✔
1452
                PreimageCache:          p.cfg.WitnessBeacon,
3✔
1453
                ChainEvents:            chainEvents,
3✔
1454
                UpdateContractSignals:  updateContractSignals,
3✔
1455
                NotifyContractUpdate:   notifyContractUpdate,
3✔
1456
                OnChannelFailure:       onChannelFailure,
3✔
1457
                SyncStates:             syncStates,
3✔
1458
                BatchTicker:            ticker.New(p.cfg.ChannelCommitInterval),
3✔
1459
                FwdPkgGCTicker:         ticker.New(time.Hour),
3✔
1460
                PendingCommitTicker: ticker.New(
3✔
1461
                        p.cfg.PendingCommitInterval,
3✔
1462
                ),
3✔
1463
                BatchSize:               p.cfg.ChannelCommitBatchSize,
3✔
1464
                UnsafeReplay:            p.cfg.UnsafeReplay,
3✔
1465
                MinUpdateTimeout:        htlcswitch.DefaultMinLinkFeeUpdateTimeout,
3✔
1466
                MaxUpdateTimeout:        htlcswitch.DefaultMaxLinkFeeUpdateTimeout,
3✔
1467
                OutgoingCltvRejectDelta: p.cfg.OutgoingCltvRejectDelta,
3✔
1468
                TowerClient:             p.cfg.TowerClient,
3✔
1469
                MaxOutgoingCltvExpiry:   p.cfg.MaxOutgoingCltvExpiry,
3✔
1470
                MaxFeeAllocation:        p.cfg.MaxChannelFeeAllocation,
3✔
1471
                MaxAnchorsCommitFeeRate: p.cfg.MaxAnchorsCommitFeeRate,
3✔
1472
                NotifyActiveLink:        p.cfg.ChannelNotifier.NotifyActiveLinkEvent,
3✔
1473
                NotifyActiveChannel:     p.cfg.ChannelNotifier.NotifyActiveChannelEvent,
3✔
1474
                NotifyInactiveChannel:   p.cfg.ChannelNotifier.NotifyInactiveChannelEvent,
3✔
1475
                NotifyInactiveLinkEvent: p.cfg.ChannelNotifier.NotifyInactiveLinkEvent,
3✔
1476
                HtlcNotifier:            p.cfg.HtlcNotifier,
3✔
1477
                GetAliases:              p.cfg.GetAliases,
3✔
1478
                PreviouslySentShutdown:  shutdownMsg,
3✔
1479
                DisallowRouteBlinding:   p.cfg.DisallowRouteBlinding,
3✔
1480
                MaxFeeExposure:          p.cfg.MaxFeeExposure,
3✔
1481
                ShouldFwdExpEndorsement: p.cfg.ShouldFwdExpEndorsement,
3✔
1482
                DisallowQuiescence: p.cfg.DisallowQuiescence ||
3✔
1483
                        !p.remoteFeatures.HasFeature(lnwire.QuiescenceOptional),
3✔
1484
                AuxTrafficShaper:     p.cfg.AuxTrafficShaper,
3✔
1485
                AuxChannelNegotiator: p.cfg.AuxChannelNegotiator,
3✔
1486
                QuiescenceTimeout:    p.cfg.QuiescenceTimeout,
3✔
1487
        }
3✔
1488

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

3✔
1496
        // With the channel link created, we'll now notify the htlc switch so
3✔
1497
        // this channel can be used to dispatch local payments and also
3✔
1498
        // passively forward payments.
3✔
1499
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
3✔
1500
}
1501

1502
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1503
// one confirmed public channel exists with them.
1504
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
6✔
1505
        defer p.cg.WgDone()
6✔
1506

6✔
1507
        hasConfirmedPublicChan := false
6✔
1508
        for _, channel := range channels {
11✔
1509
                if channel.IsPending {
8✔
1510
                        continue
3✔
1511
                }
1512
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
10✔
1513
                        continue
5✔
1514
                }
1515

1516
                hasConfirmedPublicChan = true
3✔
1517
                break
3✔
1518
        }
1519
        if !hasConfirmedPublicChan {
12✔
1520
                return
6✔
1521
        }
6✔
1522

1523
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
3✔
1524
        if err != nil {
3✔
1525
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1526
                return
×
1527
        }
×
1528

1529
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
3✔
1530
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1531
        }
×
1532
}
1533

1534
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1535
// have any active channels with them.
1536
func (p *Brontide) maybeSendChannelUpdates() {
6✔
1537
        defer p.cg.WgDone()
6✔
1538

6✔
1539
        // If we don't have any active channels, then we can exit early.
6✔
1540
        if p.activeChannels.Len() == 0 {
10✔
1541
                return
4✔
1542
        }
4✔
1543

1544
        maybeSendUpd := func(cid lnwire.ChannelID,
5✔
1545
                lnChan *lnwallet.LightningChannel) error {
10✔
1546

5✔
1547
                // Nil channels are pending, so we'll skip them.
5✔
1548
                if lnChan == nil {
8✔
1549
                        return nil
3✔
1550
                }
3✔
1551

1552
                dbChan := lnChan.State()
5✔
1553
                scid := func() lnwire.ShortChannelID {
10✔
1554
                        switch {
5✔
1555
                        // Otherwise if it's a zero conf channel and confirmed,
1556
                        // then we need to use the "real" scid.
1557
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
3✔
1558
                                return dbChan.ZeroConfRealScid()
3✔
1559

1560
                        // Otherwise, we can use the normal scid.
1561
                        default:
5✔
1562
                                return dbChan.ShortChanID()
5✔
1563
                        }
1564
                }()
1565

1566
                // Now that we know the channel is in a good state, we'll try
1567
                // to fetch the update to send to the remote peer. If the
1568
                // channel is pending, and not a zero conf channel, we'll get
1569
                // an error here which we'll ignore.
1570
                chanUpd, err := p.cfg.FetchLastChanUpdate(scid)
5✔
1571
                if err != nil {
8✔
1572
                        p.log.Debugf("Unable to fetch channel update for "+
3✔
1573
                                "ChannelPoint(%v), scid=%v: %v",
3✔
1574
                                dbChan.FundingOutpoint, dbChan.ShortChanID, err)
3✔
1575

3✔
1576
                        return nil
3✔
1577
                }
3✔
1578

1579
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
5✔
1580
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
5✔
1581

5✔
1582
                // We'll send it as a normal message instead of using the lazy
5✔
1583
                // queue to prioritize transmission of the fresh update.
5✔
1584
                if err := p.SendMessage(false, chanUpd); err != nil {
5✔
1585
                        err := fmt.Errorf("unable to send channel update for "+
×
1586
                                "ChannelPoint(%v), scid=%v: %w",
×
1587
                                dbChan.FundingOutpoint, dbChan.ShortChanID(),
×
1588
                                err)
×
1589
                        p.log.Errorf(err.Error())
×
1590

×
1591
                        return err
×
1592
                }
×
1593

1594
                return nil
5✔
1595
        }
1596

1597
        p.activeChannels.ForEach(maybeSendUpd)
5✔
1598
}
1599

1600
// WaitForDisconnect waits until the peer has disconnected. A peer may be
1601
// disconnected if the local or remote side terminates the connection, or an
1602
// irrecoverable protocol error has been encountered. This method will only
1603
// begin watching the peer's waitgroup after the ready channel or the peer's
1604
// quit channel are signaled. The ready channel should only be signaled if a
1605
// call to Start returns no error. Otherwise, if the peer fails to start,
1606
// calling Disconnect will signal the quit channel and the method will not
1607
// block, since no goroutines were spawned.
1608
func (p *Brontide) WaitForDisconnect(ready chan struct{}) {
3✔
1609
        // Before we try to call the `Wait` goroutine, we'll make sure the main
3✔
1610
        // set of goroutines are already active.
3✔
1611
        select {
3✔
1612
        case <-p.startReady:
3✔
UNCOV
1613
        case <-p.cg.Done():
×
UNCOV
1614
                return
×
1615
        }
1616

1617
        select {
3✔
1618
        case <-ready:
3✔
1619
        case <-p.cg.Done():
3✔
1620
        }
1621

1622
        p.cg.WgWait()
3✔
1623
}
1624

1625
// Disconnect terminates the connection with the remote peer. Additionally, a
1626
// signal is sent to the server and htlcSwitch indicating the resources
1627
// allocated to the peer can now be cleaned up.
1628
//
1629
// NOTE: Be aware that this method will block if the peer is still starting up.
1630
// Therefore consider starting it in a goroutine if you cannot guarantee that
1631
// the peer has finished starting up before calling this method.
1632
func (p *Brontide) Disconnect(reason error) {
3✔
1633
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
6✔
1634
                return
3✔
1635
        }
3✔
1636

1637
        // Make sure initialization has completed before we try to tear things
1638
        // down.
1639
        //
1640
        // NOTE: We only read the `startReady` chan if the peer has been
1641
        // started, otherwise we will skip reading it as this chan won't be
1642
        // closed, hence blocks forever.
1643
        if atomic.LoadInt32(&p.started) == 1 {
6✔
1644
                p.log.Debugf("Peer hasn't finished starting up yet, waiting " +
3✔
1645
                        "on startReady signal before closing connection")
3✔
1646

3✔
1647
                select {
3✔
1648
                case <-p.startReady:
3✔
1649
                case <-p.cg.Done():
×
1650
                        return
×
1651
                }
1652
        }
1653

1654
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
3✔
1655
        p.storeError(err)
3✔
1656

3✔
1657
        p.log.Infof(err.Error())
3✔
1658

3✔
1659
        // Stop PingManager before closing TCP connection.
3✔
1660
        p.pingManager.Stop()
3✔
1661

3✔
1662
        // Ensure that the TCP connection is properly closed before continuing.
3✔
1663
        p.cfg.Conn.Close()
3✔
1664

3✔
1665
        p.cg.Quit()
3✔
1666

3✔
1667
        // If our msg router isn't global (local to this instance), then we'll
3✔
1668
        // stop it. Otherwise, we'll leave it running.
3✔
1669
        if !p.globalMsgRouter {
6✔
1670
                p.msgRouter.WhenSome(func(router msgmux.Router) {
6✔
1671
                        router.Stop()
3✔
1672
                })
3✔
1673
        }
1674
}
1675

1676
// String returns the string representation of this peer.
1677
func (p *Brontide) String() string {
3✔
1678
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
3✔
1679
}
3✔
1680

1681
// readNextMessage reads, and returns the next message on the wire along with
1682
// any additional raw payload.
1683
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
10✔
1684
        noiseConn := p.cfg.Conn
10✔
1685
        err := noiseConn.SetReadDeadline(time.Time{})
10✔
1686
        if err != nil {
10✔
1687
                return nil, err
×
1688
        }
×
1689

1690
        pktLen, err := noiseConn.ReadNextHeader()
10✔
1691
        if err != nil {
13✔
1692
                return nil, fmt.Errorf("read next header: %w", err)
3✔
1693
        }
3✔
1694

1695
        // First we'll read the next _full_ message. We do this rather than
1696
        // reading incrementally from the stream as the Lightning wire protocol
1697
        // is message oriented and allows nodes to pad on additional data to
1698
        // the message stream.
1699
        var (
7✔
1700
                nextMsg lnwire.Message
7✔
1701
                msgLen  uint64
7✔
1702
        )
7✔
1703
        err = p.cfg.ReadPool.Submit(func(buf *buffer.Read) error {
14✔
1704
                // Before reading the body of the message, set the read timeout
7✔
1705
                // accordingly to ensure we don't block other readers using the
7✔
1706
                // pool. We do so only after the task has been scheduled to
7✔
1707
                // ensure the deadline doesn't expire while the message is in
7✔
1708
                // the process of being scheduled.
7✔
1709
                readDeadline := time.Now().Add(
7✔
1710
                        p.scaleTimeout(readMessageTimeout),
7✔
1711
                )
7✔
1712
                readErr := noiseConn.SetReadDeadline(readDeadline)
7✔
1713
                if readErr != nil {
7✔
1714
                        return readErr
×
1715
                }
×
1716

1717
                // The ReadNextBody method will actually end up re-using the
1718
                // buffer, so within this closure, we can continue to use
1719
                // rawMsg as it's just a slice into the buf from the buffer
1720
                // pool.
1721
                rawMsg, readErr := noiseConn.ReadNextBody(buf[:pktLen])
7✔
1722
                if readErr != nil {
7✔
1723
                        return fmt.Errorf("read next body: %w", readErr)
×
1724
                }
×
1725
                msgLen = uint64(len(rawMsg))
7✔
1726

7✔
1727
                // Next, create a new io.Reader implementation from the raw
7✔
1728
                // message, and use this to decode the message directly from.
7✔
1729
                msgReader := bytes.NewReader(rawMsg)
7✔
1730
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
7✔
1731
                if err != nil {
10✔
1732
                        return err
3✔
1733
                }
3✔
1734

1735
                // At this point, rawMsg and buf will be returned back to the
1736
                // buffer pool for re-use.
1737
                return nil
7✔
1738
        })
1739
        atomic.AddUint64(&p.bytesReceived, msgLen)
7✔
1740
        if err != nil {
10✔
1741
                return nil, err
3✔
1742
        }
3✔
1743

1744
        p.logWireMessage(nextMsg, true)
7✔
1745

7✔
1746
        return nextMsg, nil
7✔
1747
}
1748

1749
// msgStream implements a goroutine-safe, in-order stream of messages to be
1750
// delivered via closure to a receiver. These messages MUST be in order due to
1751
// the nature of the lightning channel commitment and gossiper state machines.
1752
// TODO(conner): use stream handler interface to abstract out stream
1753
// state/logging.
1754
type msgStream struct {
1755
        streamShutdown int32 // To be used atomically.
1756

1757
        peer *Brontide
1758

1759
        apply func(lnwire.Message)
1760

1761
        startMsg string
1762
        stopMsg  string
1763

1764
        msgCond *sync.Cond
1765
        msgs    []lnwire.Message
1766

1767
        mtx sync.Mutex
1768

1769
        producerSema chan struct{}
1770

1771
        wg   sync.WaitGroup
1772
        quit chan struct{}
1773
}
1774

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

6✔
1783
        stream := &msgStream{
6✔
1784
                peer:         p,
6✔
1785
                apply:        apply,
6✔
1786
                startMsg:     startMsg,
6✔
1787
                stopMsg:      stopMsg,
6✔
1788
                producerSema: make(chan struct{}, bufSize),
6✔
1789
                quit:         make(chan struct{}),
6✔
1790
        }
6✔
1791
        stream.msgCond = sync.NewCond(&stream.mtx)
6✔
1792

6✔
1793
        // Before we return the active stream, we'll populate the producer's
6✔
1794
        // semaphore channel. We'll use this to ensure that the producer won't
6✔
1795
        // attempt to allocate memory in the queue for an item until it has
6✔
1796
        // sufficient extra space.
6✔
1797
        for i := uint32(0); i < bufSize; i++ {
159✔
1798
                stream.producerSema <- struct{}{}
153✔
1799
        }
153✔
1800

1801
        return stream
6✔
1802
}
1803

1804
// Start starts the chanMsgStream.
1805
func (ms *msgStream) Start() {
6✔
1806
        ms.wg.Add(1)
6✔
1807
        go ms.msgConsumer()
6✔
1808
}
6✔
1809

1810
// Stop stops the chanMsgStream.
1811
func (ms *msgStream) Stop() {
3✔
1812
        // TODO(roasbeef): signal too?
3✔
1813

3✔
1814
        close(ms.quit)
3✔
1815

3✔
1816
        // Now that we've closed the channel, we'll repeatedly signal the msg
3✔
1817
        // consumer until we've detected that it has exited.
3✔
1818
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
6✔
1819
                ms.msgCond.Signal()
3✔
1820
                time.Sleep(time.Millisecond * 100)
3✔
1821
        }
3✔
1822

1823
        ms.wg.Wait()
3✔
1824
}
1825

1826
// msgConsumer is the main goroutine that streams messages from the peer's
1827
// readHandler directly to the target channel.
1828
func (ms *msgStream) msgConsumer() {
6✔
1829
        defer ms.wg.Done()
6✔
1830
        defer peerLog.Tracef(ms.stopMsg)
6✔
1831
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
6✔
1832

6✔
1833
        peerLog.Tracef(ms.startMsg)
6✔
1834

6✔
1835
        for {
12✔
1836
                // First, we'll check our condition. If the queue of messages
6✔
1837
                // is empty, then we'll wait until a new item is added.
6✔
1838
                ms.msgCond.L.Lock()
6✔
1839
                for len(ms.msgs) == 0 {
12✔
1840
                        ms.msgCond.Wait()
6✔
1841

6✔
1842
                        // If we woke up in order to exit, then we'll do so.
6✔
1843
                        // Otherwise, we'll check the message queue for any new
6✔
1844
                        // items.
6✔
1845
                        select {
6✔
1846
                        case <-ms.peer.cg.Done():
3✔
1847
                                ms.msgCond.L.Unlock()
3✔
1848
                                return
3✔
1849
                        case <-ms.quit:
3✔
1850
                                ms.msgCond.L.Unlock()
3✔
1851
                                return
3✔
1852
                        default:
3✔
1853
                        }
1854
                }
1855

1856
                // Grab the message off the front of the queue, shifting the
1857
                // slice's reference down one in order to remove the message
1858
                // from the queue.
1859
                msg := ms.msgs[0]
3✔
1860
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
3✔
1861
                ms.msgs = ms.msgs[1:]
3✔
1862

3✔
1863
                ms.msgCond.L.Unlock()
3✔
1864

3✔
1865
                ms.apply(msg)
3✔
1866

3✔
1867
                // We've just successfully processed an item, so we'll signal
3✔
1868
                // to the producer that a new slot in the buffer. We'll use
3✔
1869
                // this to bound the size of the buffer to avoid allowing it to
3✔
1870
                // grow indefinitely.
3✔
1871
                select {
3✔
1872
                case ms.producerSema <- struct{}{}:
3✔
1873
                case <-ms.peer.cg.Done():
3✔
1874
                        return
3✔
1875
                case <-ms.quit:
3✔
1876
                        return
3✔
1877
                }
1878
        }
1879
}
1880

1881
// AddMsg adds a new message to the msgStream. This function is safe for
1882
// concurrent access.
1883
func (ms *msgStream) AddMsg(msg lnwire.Message) {
3✔
1884
        // First, we'll attempt to receive from the producerSema struct. This
3✔
1885
        // acts as a semaphore to prevent us from indefinitely buffering
3✔
1886
        // incoming items from the wire. Either the msg queue isn't full, and
3✔
1887
        // we'll not block, or the queue is full, and we'll block until either
3✔
1888
        // we're signalled to quit, or a slot is freed up.
3✔
1889
        select {
3✔
1890
        case <-ms.producerSema:
3✔
1891
        case <-ms.peer.cg.Done():
×
1892
                return
×
1893
        case <-ms.quit:
×
1894
                return
×
1895
        }
1896

1897
        // Next, we'll lock the condition, and add the message to the end of
1898
        // the message queue.
1899
        ms.msgCond.L.Lock()
3✔
1900
        ms.msgs = append(ms.msgs, msg)
3✔
1901
        ms.msgCond.L.Unlock()
3✔
1902

3✔
1903
        // With the message added, we signal to the msgConsumer that there are
3✔
1904
        // additional messages to consume.
3✔
1905
        ms.msgCond.Signal()
3✔
1906
}
1907

1908
// waitUntilLinkActive waits until the target link is active and returns a
1909
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1910
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1911
func waitUntilLinkActive(p *Brontide,
1912
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
3✔
1913

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

3✔
1916
        // Subscribe to receive channel events.
3✔
1917
        //
3✔
1918
        // NOTE: If the link is already active by SubscribeChannelEvents, then
3✔
1919
        // GetLink will retrieve the link and we can send messages. If the link
3✔
1920
        // becomes active between SubscribeChannelEvents and GetLink, then GetLink
3✔
1921
        // will retrieve the link. If the link becomes active after GetLink, then
3✔
1922
        // we will get an ActiveLinkEvent notification and retrieve the link. If
3✔
1923
        // the call to GetLink is before SubscribeChannelEvents, however, there
3✔
1924
        // will be a race condition.
3✔
1925
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
3✔
1926
        if err != nil {
5✔
1927
                // If we have a non-nil error, then the server is shutting down and we
2✔
1928
                // can exit here and return nil. This means no message will be delivered
2✔
1929
                // to the link.
2✔
1930
                return nil
2✔
1931
        }
2✔
1932
        defer sub.Cancel()
3✔
1933

3✔
1934
        // The link may already be active by this point, and we may have missed the
3✔
1935
        // ActiveLinkEvent. Check if the link exists.
3✔
1936
        link := p.fetchLinkFromKeyAndCid(cid)
3✔
1937
        if link != nil {
6✔
1938
                return link
3✔
1939
        }
3✔
1940

1941
        // If the link is nil, we must wait for it to be active.
1942
        for {
6✔
1943
                select {
3✔
1944
                // A new event has been sent by the ChannelNotifier. We first check
1945
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1946
                // that the event is for this channel. Otherwise, we discard the
1947
                // message.
1948
                case e := <-sub.Updates():
3✔
1949
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
3✔
1950
                        if !ok {
6✔
1951
                                // Ignore this notification.
3✔
1952
                                continue
3✔
1953
                        }
1954

1955
                        chanPoint := event.ChannelPoint
3✔
1956

3✔
1957
                        // Check whether the retrieved chanPoint matches the target
3✔
1958
                        // channel id.
3✔
1959
                        if !cid.IsChanPoint(chanPoint) {
3✔
1960
                                continue
×
1961
                        }
1962

1963
                        // The link shouldn't be nil as we received an
1964
                        // ActiveLinkEvent. If it is nil, we return nil and the
1965
                        // calling function should catch it.
1966
                        return p.fetchLinkFromKeyAndCid(cid)
3✔
1967

1968
                case <-p.cg.Done():
3✔
1969
                        return nil
3✔
1970
                }
1971
        }
1972
}
1973

1974
// newChanMsgStream is used to create a msgStream between the peer and
1975
// particular channel link in the htlcswitch. We utilize additional
1976
// synchronization with the fundingManager to ensure we don't attempt to
1977
// dispatch a message to a channel before it is fully active. A reference to the
1978
// channel this stream forwards to is held in scope to prevent unnecessary
1979
// lookups.
1980
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
3✔
1981
        var chanLink htlcswitch.ChannelUpdateHandler
3✔
1982

3✔
1983
        apply := func(msg lnwire.Message) {
6✔
1984
                // This check is fine because if the link no longer exists, it will
3✔
1985
                // be removed from the activeChannels map and subsequent messages
3✔
1986
                // shouldn't reach the chan msg stream.
3✔
1987
                if chanLink == nil {
6✔
1988
                        chanLink = waitUntilLinkActive(p, cid)
3✔
1989

3✔
1990
                        // If the link is still not active and the calling function
3✔
1991
                        // errored out, just return.
3✔
1992
                        if chanLink == nil {
6✔
1993
                                p.log.Warnf("Link=%v is not active", cid)
3✔
1994
                                return
3✔
1995
                        }
3✔
1996
                }
1997

1998
                // In order to avoid unnecessarily delivering message
1999
                // as the peer is exiting, we'll check quickly to see
2000
                // if we need to exit.
2001
                select {
3✔
2002
                case <-p.cg.Done():
×
2003
                        return
×
2004
                default:
3✔
2005
                }
2006

2007
                chanLink.HandleChannelUpdate(msg)
3✔
2008
        }
2009

2010
        return newMsgStream(p,
3✔
2011
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
3✔
2012
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
3✔
2013
                msgStreamSize,
3✔
2014
                apply,
3✔
2015
        )
3✔
2016
}
2017

2018
// newDiscMsgStream is used to setup a msgStream between the peer and the
2019
// authenticated gossiper. This stream should be used to forward all remote
2020
// channel announcements.
2021
func newDiscMsgStream(p *Brontide) *msgStream {
6✔
2022
        apply := func(msg lnwire.Message) {
9✔
2023
                // TODO(elle): thread contexts through the peer system properly
3✔
2024
                // so that a parent context can be passed in here.
3✔
2025
                ctx := context.TODO()
3✔
2026

3✔
2027
                // Processing here means we send it to the gossiper which then
3✔
2028
                // decides whether this message is processed immediately or
3✔
2029
                // waits for dependent messages to be processed. It can also
3✔
2030
                // happen that the message is not processed at all if it is
3✔
2031
                // premature and the LRU cache fills up and the message is
3✔
2032
                // deleted.
3✔
2033
                p.log.Debugf("Processing remote msg %T", msg)
3✔
2034

3✔
2035
                // TODO(ziggie): ProcessRemoteAnnouncement returns an error
3✔
2036
                // channel, but we cannot rely on it being written to.
3✔
2037
                // Because some messages might never be processed (e.g.
3✔
2038
                // premature channel updates). We should change the design here
3✔
2039
                // and use the actor model pattern as soon as it is available.
3✔
2040
                // So for now we should NOT use the error channel.
3✔
2041
                // See https://github.com/lightningnetwork/lnd/pull/9820.
3✔
2042
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(ctx, msg, p)
3✔
2043
        }
3✔
2044

2045
        return newMsgStream(
6✔
2046
                p,
6✔
2047
                "Update stream for gossiper created",
6✔
2048
                "Update stream for gossiper exited",
6✔
2049
                msgStreamSize,
6✔
2050
                apply,
6✔
2051
        )
6✔
2052
}
2053

2054
// readHandler is responsible for reading messages off the wire in series, then
2055
// properly dispatching the handling of the message to the proper subsystem.
2056
//
2057
// NOTE: This method MUST be run as a goroutine.
2058
func (p *Brontide) readHandler() {
6✔
2059
        defer p.cg.WgDone()
6✔
2060

6✔
2061
        // We'll stop the timer after a new messages is received, and also
6✔
2062
        // reset it after we process the next message.
6✔
2063
        idleTimer := time.AfterFunc(idleTimeout, func() {
6✔
2064
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
2065
                        p, idleTimeout)
×
2066
                p.Disconnect(err)
×
2067
        })
×
2068

2069
        // Initialize our negotiated gossip sync method before reading messages
2070
        // off the wire. When using gossip queries, this ensures a gossip
2071
        // syncer is active by the time query messages arrive.
2072
        //
2073
        // TODO(conner): have peer store gossip syncer directly and bypass
2074
        // gossiper?
2075
        p.initGossipSync()
6✔
2076

6✔
2077
        discStream := newDiscMsgStream(p)
6✔
2078
        discStream.Start()
6✔
2079
        defer discStream.Stop()
6✔
2080
out:
6✔
2081
        for atomic.LoadInt32(&p.disconnect) == 0 {
13✔
2082
                nextMsg, err := p.readNextMessage()
7✔
2083
                if !idleTimer.Stop() {
10✔
2084
                        select {
3✔
2085
                        case <-idleTimer.C:
×
2086
                        default:
3✔
2087
                        }
2088
                }
2089
                if err != nil {
7✔
2090
                        p.log.Infof("unable to read message from peer: %v", err)
3✔
2091

3✔
2092
                        // If we could not read our peer's message due to an
3✔
2093
                        // unknown type or invalid alias, we continue processing
3✔
2094
                        // as normal. We store unknown message and address
3✔
2095
                        // types, as they may provide debugging insight.
3✔
2096
                        switch e := err.(type) {
3✔
2097
                        // If this is just a message we don't yet recognize,
2098
                        // we'll continue processing as normal as this allows
2099
                        // us to introduce new messages in a forwards
2100
                        // compatible manner.
2101
                        case *lnwire.UnknownMessage:
3✔
2102
                                p.storeError(e)
3✔
2103
                                idleTimer.Reset(idleTimeout)
3✔
2104
                                continue
3✔
2105

2106
                        // If they sent us an address type that we don't yet
2107
                        // know of, then this isn't a wire error, so we'll
2108
                        // simply continue parsing the remainder of their
2109
                        // messages.
2110
                        case *lnwire.ErrUnknownAddrType:
×
2111
                                p.storeError(e)
×
2112
                                idleTimer.Reset(idleTimeout)
×
2113
                                continue
×
2114

2115
                        // If the NodeAnnouncement1 has an invalid alias, then
2116
                        // we'll log that error above and continue so we can
2117
                        // continue to read messages from the peer. We do not
2118
                        // store this error because it is of little debugging
2119
                        // value.
2120
                        case *lnwire.ErrInvalidNodeAlias:
×
2121
                                idleTimer.Reset(idleTimeout)
×
2122
                                continue
×
2123

2124
                        // If the error we encountered wasn't just a message we
2125
                        // didn't recognize, then we'll stop all processing as
2126
                        // this is a fatal error.
2127
                        default:
3✔
2128
                                break out
3✔
2129
                        }
2130
                }
2131

2132
                // If a message router is active, then we'll try to have it
2133
                // handle this message. If it can, then we're able to skip the
2134
                // rest of the message handling logic.
2135
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
8✔
2136
                        return r.RouteMsg(msgmux.PeerMsg{
4✔
2137
                                PeerPub: *p.IdentityKey(),
4✔
2138
                                Message: nextMsg,
4✔
2139
                        })
4✔
2140
                })
4✔
2141

2142
                // No error occurred, and the message was handled by the
2143
                // router.
2144
                if err == nil {
7✔
2145
                        continue
3✔
2146
                }
2147

2148
                var (
4✔
2149
                        targetChan   lnwire.ChannelID
4✔
2150
                        isLinkUpdate bool
4✔
2151
                )
4✔
2152

4✔
2153
                switch msg := nextMsg.(type) {
4✔
2154
                case *lnwire.Pong:
×
2155
                        // When we receive a Pong message in response to our
×
2156
                        // last ping message, we send it to the pingManager
×
2157
                        p.pingManager.ReceivedPong(msg)
×
2158

2159
                case *lnwire.Ping:
×
2160
                        // First, we'll store their latest ping payload within
×
2161
                        // the relevant atomic variable.
×
2162
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
2163

×
2164
                        // Next, we'll send over the amount of specified pong
×
2165
                        // bytes.
×
2166
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
×
2167
                        p.queueMsg(pong, nil)
×
2168

2169
                case *lnwire.OpenChannel,
2170
                        *lnwire.AcceptChannel,
2171
                        *lnwire.FundingCreated,
2172
                        *lnwire.FundingSigned,
2173
                        *lnwire.ChannelReady:
3✔
2174

3✔
2175
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2176

2177
                case *lnwire.Shutdown:
3✔
2178
                        select {
3✔
2179
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
2180
                        case <-p.cg.Done():
×
2181
                                break out
×
2182
                        }
2183
                case *lnwire.ClosingSigned:
3✔
2184
                        select {
3✔
2185
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
2186
                        case <-p.cg.Done():
×
2187
                                break out
×
2188
                        }
2189

2190
                case *lnwire.Warning:
×
2191
                        targetChan = msg.ChanID
×
2192
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2193

2194
                case *lnwire.Error:
3✔
2195
                        targetChan = msg.ChanID
3✔
2196
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
3✔
2197

2198
                case *lnwire.ChannelReestablish:
3✔
2199
                        targetChan = msg.ChanID
3✔
2200
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2201

3✔
2202
                        // If we failed to find the link in question, and the
3✔
2203
                        // message received was a channel sync message, then
3✔
2204
                        // this might be a peer trying to resync closed channel.
3✔
2205
                        // In this case we'll try to resend our last channel
3✔
2206
                        // sync message, such that the peer can recover funds
3✔
2207
                        // from the closed channel.
3✔
2208
                        if !isLinkUpdate {
6✔
2209
                                err := p.resendChanSyncMsg(targetChan)
3✔
2210
                                if err != nil {
6✔
2211
                                        // TODO(halseth): send error to peer?
3✔
2212
                                        p.log.Errorf("resend failed: %v",
3✔
2213
                                                err)
3✔
2214
                                }
3✔
2215
                        }
2216

2217
                // For messages that implement the LinkUpdater interface, we
2218
                // will consider them as link updates and send them to
2219
                // chanStream. These messages will be queued inside chanStream
2220
                // if the channel is not active yet.
2221
                case lnwire.LinkUpdater:
3✔
2222
                        targetChan = msg.TargetChanID()
3✔
2223
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2224

3✔
2225
                        // Log an error if we don't have this channel. This
3✔
2226
                        // means the peer has sent us a message with unknown
3✔
2227
                        // channel ID.
3✔
2228
                        if !isLinkUpdate {
6✔
2229
                                p.log.Errorf("Unknown channel ID: %v found "+
3✔
2230
                                        "in received msg=%s", targetChan,
3✔
2231
                                        nextMsg.MsgType())
3✔
2232
                        }
3✔
2233

2234
                case *lnwire.ChannelUpdate1,
2235
                        *lnwire.ChannelAnnouncement1,
2236
                        *lnwire.NodeAnnouncement1,
2237
                        *lnwire.AnnounceSignatures1,
2238
                        *lnwire.GossipTimestampRange,
2239
                        *lnwire.QueryShortChanIDs,
2240
                        *lnwire.QueryChannelRange,
2241
                        *lnwire.ReplyChannelRange,
2242
                        *lnwire.ReplyShortChanIDsEnd:
3✔
2243

3✔
2244
                        discStream.AddMsg(msg)
3✔
2245

2246
                case *lnwire.Custom:
4✔
2247
                        err := p.handleCustomMessage(msg)
4✔
2248
                        if err != nil {
4✔
2249
                                p.storeError(err)
×
2250
                                p.log.Errorf("%v", err)
×
2251
                        }
×
2252

2253
                default:
×
2254
                        // If the message we received is unknown to us, store
×
2255
                        // the type to track the failure.
×
2256
                        err := fmt.Errorf("unknown message type %v received",
×
2257
                                uint16(msg.MsgType()))
×
2258
                        p.storeError(err)
×
2259

×
2260
                        p.log.Errorf("%v", err)
×
2261
                }
2262

2263
                if isLinkUpdate {
7✔
2264
                        // If this is a channel update, then we need to feed it
3✔
2265
                        // into the channel's in-order message stream.
3✔
2266
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
3✔
2267
                }
3✔
2268

2269
                idleTimer.Reset(idleTimeout)
4✔
2270
        }
2271

2272
        p.Disconnect(errors.New("read handler closed"))
3✔
2273

3✔
2274
        p.log.Trace("readHandler for peer done")
3✔
2275
}
2276

2277
// handleCustomMessage handles the given custom message if a handler is
2278
// registered.
2279
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
4✔
2280
        if p.cfg.HandleCustomMessage == nil {
4✔
2281
                return fmt.Errorf("no custom message handler for "+
×
2282
                        "message type %v", uint16(msg.MsgType()))
×
2283
        }
×
2284

2285
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
4✔
2286
}
2287

2288
// isLoadedFromDisk returns true if the provided channel ID is loaded from
2289
// disk.
2290
//
2291
// NOTE: only returns true for pending channels.
2292
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
3✔
2293
        // If this is a newly added channel, no need to reestablish.
3✔
2294
        _, added := p.addedChannels.Load(chanID)
3✔
2295
        if added {
6✔
2296
                return false
3✔
2297
        }
3✔
2298

2299
        // Return false if the channel is unknown.
2300
        channel, ok := p.activeChannels.Load(chanID)
3✔
2301
        if !ok {
3✔
2302
                return false
×
2303
        }
×
2304

2305
        // During startup, we will use a nil value to mark a pending channel
2306
        // that's loaded from disk.
2307
        return channel == nil
3✔
2308
}
2309

2310
// isActiveChannel returns true if the provided channel id is active, otherwise
2311
// returns false.
2312
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
11✔
2313
        // The channel would be nil if,
11✔
2314
        // - the channel doesn't exist, or,
11✔
2315
        // - the channel exists, but is pending. In this case, we don't
11✔
2316
        //   consider this channel active.
11✔
2317
        channel, _ := p.activeChannels.Load(chanID)
11✔
2318

11✔
2319
        return channel != nil
11✔
2320
}
11✔
2321

2322
// isPendingChannel returns true if the provided channel ID is pending, and
2323
// returns false if the channel is active or unknown.
2324
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
9✔
2325
        // Return false if the channel is unknown.
9✔
2326
        channel, ok := p.activeChannels.Load(chanID)
9✔
2327
        if !ok {
15✔
2328
                return false
6✔
2329
        }
6✔
2330

2331
        return channel == nil
6✔
2332
}
2333

2334
// hasChannel returns true if the peer has a pending/active channel specified
2335
// by the channel ID.
2336
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
3✔
2337
        _, ok := p.activeChannels.Load(chanID)
3✔
2338
        return ok
3✔
2339
}
3✔
2340

2341
// storeError stores an error in our peer's buffer of recent errors with the
2342
// current timestamp. Errors are only stored if we have at least one active
2343
// channel with the peer to mitigate a dos vector where a peer costlessly
2344
// connects to us and spams us with errors.
2345
func (p *Brontide) storeError(err error) {
3✔
2346
        var haveChannels bool
3✔
2347

3✔
2348
        p.activeChannels.Range(func(_ lnwire.ChannelID,
3✔
2349
                channel *lnwallet.LightningChannel) bool {
6✔
2350

3✔
2351
                // Pending channels will be nil in the activeChannels map.
3✔
2352
                if channel == nil {
6✔
2353
                        // Return true to continue the iteration.
3✔
2354
                        return true
3✔
2355
                }
3✔
2356

2357
                haveChannels = true
3✔
2358

3✔
2359
                // Return false to break the iteration.
3✔
2360
                return false
3✔
2361
        })
2362

2363
        // If we do not have any active channels with the peer, we do not store
2364
        // errors as a dos mitigation.
2365
        if !haveChannels {
6✔
2366
                p.log.Trace("no channels with peer, not storing err")
3✔
2367
                return
3✔
2368
        }
3✔
2369

2370
        p.cfg.ErrorBuffer.Add(
3✔
2371
                &TimestampedError{Timestamp: time.Now(), Error: err},
3✔
2372
        )
3✔
2373
}
2374

2375
// handleWarningOrError processes a warning or error msg and returns true if
2376
// msg should be forwarded to the associated channel link. False is returned if
2377
// any necessary forwarding of msg was already handled by this method. If msg is
2378
// an error from a peer with an active channel, we'll store it in memory.
2379
//
2380
// NOTE: This method should only be called from within the readHandler.
2381
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
2382
        msg lnwire.Message) bool {
3✔
2383

3✔
2384
        if errMsg, ok := msg.(*lnwire.Error); ok {
6✔
2385
                p.storeError(errMsg)
3✔
2386
        }
3✔
2387

2388
        switch {
3✔
2389
        // Connection wide messages should be forwarded to all channel links
2390
        // with this peer.
2391
        case chanID == lnwire.ConnectionWideID:
×
2392
                for _, chanStream := range p.activeMsgStreams {
×
2393
                        chanStream.AddMsg(msg)
×
2394
                }
×
2395

2396
                return false
×
2397

2398
        // If the channel ID for the message corresponds to a pending channel,
2399
        // then the funding manager will handle it.
2400
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
3✔
2401
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2402
                return false
3✔
2403

2404
        // If not we hand the message to the channel link for this channel.
2405
        case p.isActiveChannel(chanID):
3✔
2406
                return true
3✔
2407

2408
        default:
3✔
2409
                return false
3✔
2410
        }
2411
}
2412

2413
// messageSummary returns a human-readable string that summarizes a
2414
// incoming/outgoing message. Not all messages will have a summary, only those
2415
// which have additional data that can be informative at a glance.
2416
func messageSummary(msg lnwire.Message) string {
3✔
2417
        switch msg := msg.(type) {
3✔
2418
        case *lnwire.Init:
3✔
2419
                // No summary.
3✔
2420
                return ""
3✔
2421

2422
        case *lnwire.OpenChannel:
3✔
2423
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
3✔
2424
                        "push_amt=%v, reserve=%v, flags=%v",
3✔
2425
                        msg.PendingChannelID[:], msg.ChainHash,
3✔
2426
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
3✔
2427
                        msg.ChannelReserve, msg.ChannelFlags)
3✔
2428

2429
        case *lnwire.AcceptChannel:
3✔
2430
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
3✔
2431
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
3✔
2432
                        msg.MinAcceptDepth)
3✔
2433

2434
        case *lnwire.FundingCreated:
3✔
2435
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
3✔
2436
                        msg.PendingChannelID[:], msg.FundingPoint)
3✔
2437

2438
        case *lnwire.FundingSigned:
3✔
2439
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
3✔
2440

2441
        case *lnwire.ChannelReady:
3✔
2442
                return fmt.Sprintf("chan_id=%v, next_point=%x",
3✔
2443
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
3✔
2444

2445
        case *lnwire.Shutdown:
3✔
2446
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
3✔
2447
                        msg.Address[:])
3✔
2448

2449
        case *lnwire.ClosingComplete:
3✔
2450
                return fmt.Sprintf("chan_id=%v, fee_sat=%v, locktime=%v",
3✔
2451
                        msg.ChannelID, msg.FeeSatoshis, msg.LockTime)
3✔
2452

2453
        case *lnwire.ClosingSig:
3✔
2454
                return fmt.Sprintf("chan_id=%v", msg.ChannelID)
3✔
2455

2456
        case *lnwire.ClosingSigned:
3✔
2457
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
3✔
2458
                        msg.FeeSatoshis)
3✔
2459

2460
        case *lnwire.UpdateAddHTLC:
3✔
2461
                var blindingPoint []byte
3✔
2462
                msg.BlindingPoint.WhenSome(
3✔
2463
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
3✔
2464
                                *btcec.PublicKey]) {
6✔
2465

3✔
2466
                                blindingPoint = b.Val.SerializeCompressed()
3✔
2467
                        },
3✔
2468
                )
2469

2470
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
3✔
2471
                        "hash=%x, blinding_point=%x, custom_records=%v",
3✔
2472
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
3✔
2473
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
3✔
2474

2475
        case *lnwire.UpdateFailHTLC:
3✔
2476
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
3✔
2477
                        msg.ID, msg.Reason)
3✔
2478

2479
        case *lnwire.UpdateFulfillHTLC:
3✔
2480
                return fmt.Sprintf("chan_id=%v, id=%v, preimage=%x, "+
3✔
2481
                        "custom_records=%v", msg.ChanID, msg.ID,
3✔
2482
                        msg.PaymentPreimage[:], msg.CustomRecords)
3✔
2483

2484
        case *lnwire.CommitSig:
3✔
2485
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
3✔
2486
                        len(msg.HtlcSigs))
3✔
2487

2488
        case *lnwire.RevokeAndAck:
3✔
2489
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
3✔
2490
                        msg.ChanID, msg.Revocation[:],
3✔
2491
                        msg.NextRevocationKey.SerializeCompressed())
3✔
2492

2493
        case *lnwire.UpdateFailMalformedHTLC:
3✔
2494
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
3✔
2495
                        msg.ChanID, msg.ID, msg.FailureCode)
3✔
2496

2497
        case *lnwire.Warning:
×
2498
                return fmt.Sprintf("%v", msg.Warning())
×
2499

2500
        case *lnwire.Error:
3✔
2501
                return fmt.Sprintf("%v", msg.Error())
3✔
2502

2503
        case *lnwire.AnnounceSignatures1:
3✔
2504
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
3✔
2505
                        msg.ShortChannelID.ToUint64())
3✔
2506

2507
        case *lnwire.ChannelAnnouncement1:
3✔
2508
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
3✔
2509
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
3✔
2510

2511
        case *lnwire.ChannelUpdate1:
3✔
2512
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
3✔
2513
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
3✔
2514
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
3✔
2515
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
3✔
2516

2517
        case *lnwire.NodeAnnouncement1:
3✔
2518
                return fmt.Sprintf("node=%x, update_time=%v",
3✔
2519
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
3✔
2520

2521
        case *lnwire.Ping:
×
2522
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
2523

2524
        case *lnwire.Pong:
×
2525
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
×
2526

2527
        case *lnwire.UpdateFee:
×
2528
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2529
                        msg.ChanID, int64(msg.FeePerKw))
×
2530

2531
        case *lnwire.ChannelReestablish:
3✔
2532
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
3✔
2533
                        "remote_tail_height=%v", msg.ChanID,
3✔
2534
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
3✔
2535

2536
        case *lnwire.ReplyShortChanIDsEnd:
3✔
2537
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
3✔
2538
                        msg.Complete)
3✔
2539

2540
        case *lnwire.ReplyChannelRange:
3✔
2541
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
3✔
2542
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
3✔
2543
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
3✔
2544
                        msg.EncodingType)
3✔
2545

2546
        case *lnwire.QueryShortChanIDs:
3✔
2547
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
3✔
2548
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
3✔
2549

2550
        case *lnwire.QueryChannelRange:
3✔
2551
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
3✔
2552
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
3✔
2553
                        msg.LastBlockHeight())
3✔
2554

2555
        case *lnwire.GossipTimestampRange:
3✔
2556
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
3✔
2557
                        "stamp_range=%v", msg.ChainHash,
3✔
2558
                        time.Unix(int64(msg.FirstTimestamp), 0),
3✔
2559
                        msg.TimestampRange)
3✔
2560

2561
        case *lnwire.Stfu:
3✔
2562
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
3✔
2563
                        msg.Initiator)
3✔
2564

2565
        case *lnwire.Custom:
3✔
2566
                return fmt.Sprintf("type=%d", msg.Type)
3✔
2567
        }
2568

2569
        return fmt.Sprintf("unknown msg type=%T", msg)
3✔
2570
}
2571

2572
// logWireMessage logs the receipt or sending of particular wire message. This
2573
// function is used rather than just logging the message in order to produce
2574
// less spammy log messages in trace mode by setting the 'Curve" parameter to
2575
// nil. Doing this avoids printing out each of the field elements in the curve
2576
// parameters for secp256k1.
2577
func (p *Brontide) logWireMessage(msg lnwire.Message, read bool) {
20✔
2578
        summaryPrefix := "Received"
20✔
2579
        if !read {
36✔
2580
                summaryPrefix = "Sending"
16✔
2581
        }
16✔
2582

2583
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
23✔
2584
                // Debug summary of message.
3✔
2585
                summary := messageSummary(msg)
3✔
2586
                if len(summary) > 0 {
6✔
2587
                        summary = "(" + summary + ")"
3✔
2588
                }
3✔
2589

2590
                preposition := "to"
3✔
2591
                if read {
6✔
2592
                        preposition = "from"
3✔
2593
                }
3✔
2594

2595
                var msgType string
3✔
2596
                if msg.MsgType() < lnwire.CustomTypeStart {
6✔
2597
                        msgType = msg.MsgType().String()
3✔
2598
                } else {
6✔
2599
                        msgType = "custom"
3✔
2600
                }
3✔
2601

2602
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
3✔
2603
                        msgType, summary, preposition, p)
3✔
2604
        }))
2605

2606
        prefix := "readMessage from peer"
20✔
2607
        if !read {
36✔
2608
                prefix = "writeMessage to peer"
16✔
2609
        }
16✔
2610

2611
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
20✔
2612
}
2613

2614
// writeMessage writes and flushes the target lnwire.Message to the remote peer.
2615
// If the passed message is nil, this method will only try to flush an existing
2616
// message buffered on the connection. It is safe to call this method again
2617
// with a nil message iff a timeout error is returned. This will continue to
2618
// flush the pending message to the wire.
2619
//
2620
// NOTE:
2621
// Besides its usage in Start, this function should not be used elsewhere
2622
// except in writeHandler. If multiple goroutines call writeMessage at the same
2623
// time, panics can occur because WriteMessage and Flush don't use any locking
2624
// internally.
2625
func (p *Brontide) writeMessage(msg lnwire.Message) error {
16✔
2626
        // Only log the message on the first attempt.
16✔
2627
        if msg != nil {
32✔
2628
                p.logWireMessage(msg, false)
16✔
2629
        }
16✔
2630

2631
        noiseConn := p.cfg.Conn
16✔
2632

16✔
2633
        flushMsg := func() error {
32✔
2634
                // Ensure the write deadline is set before we attempt to send
16✔
2635
                // the message.
16✔
2636
                writeDeadline := time.Now().Add(
16✔
2637
                        p.scaleTimeout(writeMessageTimeout),
16✔
2638
                )
16✔
2639
                err := noiseConn.SetWriteDeadline(writeDeadline)
16✔
2640
                if err != nil {
16✔
2641
                        return err
×
2642
                }
×
2643

2644
                // Flush the pending message to the wire. If an error is
2645
                // encountered, e.g. write timeout, the number of bytes written
2646
                // so far will be returned.
2647
                n, err := noiseConn.Flush()
16✔
2648

16✔
2649
                // Record the number of bytes written on the wire, if any.
16✔
2650
                if n > 0 {
19✔
2651
                        atomic.AddUint64(&p.bytesSent, uint64(n))
3✔
2652
                }
3✔
2653

2654
                return err
16✔
2655
        }
2656

2657
        // If the current message has already been serialized, encrypted, and
2658
        // buffered on the underlying connection we will skip straight to
2659
        // flushing it to the wire.
2660
        if msg == nil {
16✔
2661
                return flushMsg()
×
2662
        }
×
2663

2664
        // Otherwise, this is a new message. We'll acquire a write buffer to
2665
        // serialize the message and buffer the ciphertext on the connection.
2666
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
32✔
2667
                // Using a buffer allocated by the write pool, encode the
16✔
2668
                // message directly into the buffer.
16✔
2669
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
16✔
2670
                if writeErr != nil {
16✔
2671
                        return writeErr
×
2672
                }
×
2673

2674
                // Finally, write the message itself in a single swoop. This
2675
                // will buffer the ciphertext on the underlying connection. We
2676
                // will defer flushing the message until the write pool has been
2677
                // released.
2678
                return noiseConn.WriteMessage(buf.Bytes())
16✔
2679
        })
2680
        if err != nil {
16✔
2681
                return err
×
2682
        }
×
2683

2684
        return flushMsg()
16✔
2685
}
2686

2687
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2688
// queue, and writing them out to the wire. This goroutine coordinates with the
2689
// queueHandler in order to ensure the incoming message queue is quickly
2690
// drained.
2691
//
2692
// NOTE: This method MUST be run as a goroutine.
2693
func (p *Brontide) writeHandler() {
6✔
2694
        // We'll stop the timer after a new messages is sent, and also reset it
6✔
2695
        // after we process the next message.
6✔
2696
        idleTimer := time.AfterFunc(idleTimeout, func() {
6✔
2697
                err := fmt.Errorf("peer %s no write for %s -- disconnecting",
×
2698
                        p, idleTimeout)
×
2699
                p.Disconnect(err)
×
2700
        })
×
2701

2702
        var exitErr error
6✔
2703

6✔
2704
out:
6✔
2705
        for {
16✔
2706
                select {
10✔
2707
                case outMsg := <-p.sendQueue:
7✔
2708
                        // Record the time at which we first attempt to send the
7✔
2709
                        // message.
7✔
2710
                        startTime := time.Now()
7✔
2711

7✔
2712
                retry:
7✔
2713
                        // Write out the message to the socket. If a timeout
2714
                        // error is encountered, we will catch this and retry
2715
                        // after backing off in case the remote peer is just
2716
                        // slow to process messages from the wire.
2717
                        err := p.writeMessage(outMsg.msg)
7✔
2718
                        if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
7✔
2719
                                p.log.Debugf("Write timeout detected for "+
×
2720
                                        "peer, first write for message "+
×
2721
                                        "attempted %v ago",
×
2722
                                        time.Since(startTime))
×
2723

×
2724
                                // If we received a timeout error, this implies
×
2725
                                // that the message was buffered on the
×
2726
                                // connection successfully and that a flush was
×
2727
                                // attempted. We'll set the message to nil so
×
2728
                                // that on a subsequent pass we only try to
×
2729
                                // flush the buffered message, and forgo
×
2730
                                // reserializing or reencrypting it.
×
2731
                                outMsg.msg = nil
×
2732

×
2733
                                goto retry
×
2734
                        }
2735

2736
                        // Message has either been successfully sent or an
2737
                        // unrecoverable error occurred.  Either way, we can
2738
                        // free the memory used to store the message.
2739
                        if bConn, ok := p.cfg.Conn.(*brontide.Conn); ok {
10✔
2740
                                bConn.ClearPendingSend()
3✔
2741
                        }
3✔
2742

2743
                        // The write succeeded, reset the idle timer to prevent
2744
                        // us from disconnecting the peer.
2745
                        if !idleTimer.Stop() {
7✔
2746
                                select {
×
2747
                                case <-idleTimer.C:
×
2748
                                default:
×
2749
                                }
2750
                        }
2751
                        idleTimer.Reset(idleTimeout)
7✔
2752

7✔
2753
                        // If the peer requested a synchronous write, respond
7✔
2754
                        // with the error.
7✔
2755
                        if outMsg.errChan != nil {
11✔
2756
                                outMsg.errChan <- err
4✔
2757
                        }
4✔
2758

2759
                        if err != nil {
7✔
2760
                                exitErr = fmt.Errorf("unable to write "+
×
2761
                                        "message: %v", err)
×
2762
                                break out
×
2763
                        }
2764

2765
                case <-p.cg.Done():
3✔
2766
                        exitErr = lnpeer.ErrPeerExiting
3✔
2767
                        break out
3✔
2768
                }
2769
        }
2770

2771
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2772
        // disconnect.
2773
        p.cg.WgDone()
3✔
2774

3✔
2775
        p.Disconnect(exitErr)
3✔
2776

3✔
2777
        p.log.Trace("writeHandler for peer done")
3✔
2778
}
2779

2780
// queueHandler is responsible for accepting messages from outside subsystems
2781
// to be eventually sent out on the wire by the writeHandler.
2782
//
2783
// NOTE: This method MUST be run as a goroutine.
2784
func (p *Brontide) queueHandler() {
6✔
2785
        defer p.cg.WgDone()
6✔
2786

6✔
2787
        // priorityMsgs holds an in order list of messages deemed high-priority
6✔
2788
        // to be added to the sendQueue. This predominately includes messages
6✔
2789
        // from the funding manager and htlcswitch.
6✔
2790
        priorityMsgs := list.New()
6✔
2791

6✔
2792
        // lazyMsgs holds an in order list of messages deemed low-priority to be
6✔
2793
        // added to the sendQueue only after all high-priority messages have
6✔
2794
        // been queued. This predominately includes messages from the gossiper.
6✔
2795
        lazyMsgs := list.New()
6✔
2796

6✔
2797
        for {
20✔
2798
                // Examine the front of the priority queue, if it is empty check
14✔
2799
                // the low priority queue.
14✔
2800
                elem := priorityMsgs.Front()
14✔
2801
                if elem == nil {
25✔
2802
                        elem = lazyMsgs.Front()
11✔
2803
                }
11✔
2804

2805
                if elem != nil {
21✔
2806
                        front := elem.Value.(outgoingMsg)
7✔
2807

7✔
2808
                        // There's an element on the queue, try adding
7✔
2809
                        // it to the sendQueue. We also watch for
7✔
2810
                        // messages on the outgoingQueue, in case the
7✔
2811
                        // writeHandler cannot accept messages on the
7✔
2812
                        // sendQueue.
7✔
2813
                        select {
7✔
2814
                        case p.sendQueue <- front:
7✔
2815
                                if front.priority {
13✔
2816
                                        priorityMsgs.Remove(elem)
6✔
2817
                                } else {
10✔
2818
                                        lazyMsgs.Remove(elem)
4✔
2819
                                }
4✔
2820
                        case msg := <-p.outgoingQueue:
3✔
2821
                                if msg.priority {
6✔
2822
                                        priorityMsgs.PushBack(msg)
3✔
2823
                                } else {
6✔
2824
                                        lazyMsgs.PushBack(msg)
3✔
2825
                                }
3✔
2826
                        case <-p.cg.Done():
×
2827
                                return
×
2828
                        }
2829
                } else {
10✔
2830
                        // If there weren't any messages to send to the
10✔
2831
                        // writeHandler, then we'll accept a new message
10✔
2832
                        // into the queue from outside sub-systems.
10✔
2833
                        select {
10✔
2834
                        case msg := <-p.outgoingQueue:
7✔
2835
                                if msg.priority {
13✔
2836
                                        priorityMsgs.PushBack(msg)
6✔
2837
                                } else {
10✔
2838
                                        lazyMsgs.PushBack(msg)
4✔
2839
                                }
4✔
2840
                        case <-p.cg.Done():
3✔
2841
                                return
3✔
2842
                        }
2843
                }
2844
        }
2845
}
2846

2847
// PingTime returns the estimated ping time to the peer in microseconds.
2848
func (p *Brontide) PingTime() int64 {
3✔
2849
        return p.pingManager.GetPingTimeMicroSeconds()
3✔
2850
}
3✔
2851

2852
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2853
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2854
// or failed to write, and nil otherwise.
2855
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
28✔
2856
        p.queue(true, msg, errChan)
28✔
2857
}
28✔
2858

2859
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2860
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2861
// queue or failed to write, and nil otherwise.
2862
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
4✔
2863
        p.queue(false, msg, errChan)
4✔
2864
}
4✔
2865

2866
// queue sends a given message to the queueHandler using the passed priority. If
2867
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2868
// failed to write, and nil otherwise.
2869
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2870
        errChan chan error) {
29✔
2871

29✔
2872
        select {
29✔
2873
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
28✔
2874
        case <-p.cg.Done():
×
2875
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
×
2876
                        lnutils.SpewLogClosure(msg))
×
2877
                if errChan != nil {
×
2878
                        errChan <- lnpeer.ErrPeerExiting
×
2879
                }
×
2880
        }
2881
}
2882

2883
// ChannelSnapshots returns a slice of channel snapshots detailing all
2884
// currently active channels maintained with the remote peer.
2885
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
3✔
2886
        snapshots := make(
3✔
2887
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
3✔
2888
        )
3✔
2889

3✔
2890
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2891
                activeChan *lnwallet.LightningChannel) error {
6✔
2892

3✔
2893
                // If the activeChan is nil, then we skip it as the channel is
3✔
2894
                // pending.
3✔
2895
                if activeChan == nil {
6✔
2896
                        return nil
3✔
2897
                }
3✔
2898

2899
                // We'll only return a snapshot for channels that are
2900
                // *immediately* available for routing payments over.
2901
                if activeChan.RemoteNextRevocation() == nil {
6✔
2902
                        return nil
3✔
2903
                }
3✔
2904

2905
                snapshot := activeChan.StateSnapshot()
3✔
2906
                snapshots = append(snapshots, snapshot)
3✔
2907

3✔
2908
                return nil
3✔
2909
        })
2910

2911
        return snapshots
3✔
2912
}
2913

2914
// genDeliveryScript returns a new script to be used to send our funds to in
2915
// the case of a cooperative channel close negotiation.
2916
func (p *Brontide) genDeliveryScript() ([]byte, error) {
9✔
2917
        // We'll send a normal p2wkh address unless we've negotiated the
9✔
2918
        // shutdown-any-segwit feature.
9✔
2919
        addrType := lnwallet.WitnessPubKey
9✔
2920
        if p.taprootShutdownAllowed() {
12✔
2921
                addrType = lnwallet.TaprootPubkey
3✔
2922
        }
3✔
2923

2924
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
9✔
2925
                addrType, false, lnwallet.DefaultAccountName,
9✔
2926
        )
9✔
2927
        if err != nil {
9✔
2928
                return nil, err
×
2929
        }
×
2930
        p.log.Infof("Delivery addr for channel close: %v",
9✔
2931
                deliveryAddr)
9✔
2932

9✔
2933
        return txscript.PayToAddrScript(deliveryAddr)
9✔
2934
}
2935

2936
// channelManager is goroutine dedicated to handling all requests/signals
2937
// pertaining to the opening, cooperative closing, and force closing of all
2938
// channels maintained with the remote peer.
2939
//
2940
// NOTE: This method MUST be run as a goroutine.
2941
func (p *Brontide) channelManager() {
20✔
2942
        defer p.cg.WgDone()
20✔
2943

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

20✔
2949
out:
20✔
2950
        for {
61✔
2951
                select {
41✔
2952
                // A new pending channel has arrived which means we are about
2953
                // to complete a funding workflow and is waiting for the final
2954
                // `ChannelReady` messages to be exchanged. We will add this
2955
                // channel to the `activeChannels` with a nil value to indicate
2956
                // this is a pending channel.
2957
                case req := <-p.newPendingChannel:
4✔
2958
                        p.handleNewPendingChannel(req)
4✔
2959

2960
                // A new channel has arrived which means we've just completed a
2961
                // funding workflow. We'll initialize the necessary local
2962
                // state, and notify the htlc switch of a new link.
2963
                case req := <-p.newActiveChannel:
3✔
2964
                        p.handleNewActiveChannel(req)
3✔
2965

2966
                // The funding flow for a pending channel is failed, we will
2967
                // remove it from Brontide.
2968
                case req := <-p.removePendingChannel:
4✔
2969
                        p.handleRemovePendingChannel(req)
4✔
2970

2971
                // We've just received a local request to close an active
2972
                // channel. It will either kick of a cooperative channel
2973
                // closure negotiation, or be a notification of a breached
2974
                // contract that should be abandoned.
2975
                case req := <-p.localCloseChanReqs:
10✔
2976
                        p.handleLocalCloseReq(req)
10✔
2977

2978
                // We've received a link failure from a link that was added to
2979
                // the switch. This will initiate the teardown of the link, and
2980
                // initiate any on-chain closures if necessary.
2981
                case failure := <-p.linkFailures:
3✔
2982
                        p.handleLinkFailure(failure)
3✔
2983

2984
                // We've received a new cooperative channel closure related
2985
                // message from the remote peer, we'll use this message to
2986
                // advance the chan closer state machine.
2987
                case closeMsg := <-p.chanCloseMsgs:
16✔
2988
                        p.handleCloseMsg(closeMsg)
16✔
2989

2990
                // The channel reannounce delay has elapsed, broadcast the
2991
                // reenabled channel updates to the network. This should only
2992
                // fire once, so we set the reenableTimeout channel to nil to
2993
                // mark it for garbage collection. If the peer is torn down
2994
                // before firing, reenabling will not be attempted.
2995
                // TODO(conner): consolidate reenables timers inside chan status
2996
                // manager
2997
                case <-reenableTimeout:
3✔
2998
                        p.reenableActiveChannels()
3✔
2999

3✔
3000
                        // Since this channel will never fire again during the
3✔
3001
                        // lifecycle of the peer, we nil the channel to mark it
3✔
3002
                        // eligible for garbage collection, and make this
3✔
3003
                        // explicitly ineligible to receive in future calls to
3✔
3004
                        // select. This also shaves a few CPU cycles since the
3✔
3005
                        // select will ignore this case entirely.
3✔
3006
                        reenableTimeout = nil
3✔
3007

3✔
3008
                        // Once the reenabling is attempted, we also cancel the
3✔
3009
                        // channel event subscription to free up the overflow
3✔
3010
                        // queue used in channel notifier.
3✔
3011
                        //
3✔
3012
                        // NOTE: channelEventClient will be nil if the
3✔
3013
                        // reenableTimeout is greater than 1 minute.
3✔
3014
                        if p.channelEventClient != nil {
6✔
3015
                                p.channelEventClient.Cancel()
3✔
3016
                        }
3✔
3017

3018
                case <-p.cg.Done():
3✔
3019
                        // As, we've been signalled to exit, we'll reset all
3✔
3020
                        // our active channel back to their default state.
3✔
3021
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
3022
                                lc *lnwallet.LightningChannel) error {
6✔
3023

3✔
3024
                                // Exit if the channel is nil as it's a pending
3✔
3025
                                // channel.
3✔
3026
                                if lc == nil {
6✔
3027
                                        return nil
3✔
3028
                                }
3✔
3029

3030
                                lc.ResetState()
3✔
3031

3✔
3032
                                return nil
3✔
3033
                        })
3034

3035
                        break out
3✔
3036
                }
3037
        }
3038
}
3039

3040
// reenableActiveChannels searches the index of channels maintained with this
3041
// peer, and reenables each public, non-pending channel. This is done at the
3042
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
3043
// No message will be sent if the channel is already enabled.
3044
func (p *Brontide) reenableActiveChannels() {
3✔
3045
        // First, filter all known channels with this peer for ones that are
3✔
3046
        // both public and not pending.
3✔
3047
        activePublicChans := p.filterChannelsToEnable()
3✔
3048

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

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

3✔
3058
                switch {
3✔
3059
                // No error occurred, continue to request the next channel.
3060
                case err == nil:
3✔
3061
                        continue
3✔
3062

3063
                // Cannot auto enable a manually disabled channel so we do
3064
                // nothing but proceed to the next channel.
3065
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
3✔
3066
                        p.log.Debugf("Channel(%v) was manually disabled, "+
3✔
3067
                                "ignoring automatic enable request", chanPoint)
3✔
3068

3✔
3069
                        continue
3✔
3070

3071
                // If the channel is reported as inactive, we will give it
3072
                // another chance. When handling the request, ChanStatusManager
3073
                // will check whether the link is active or not. One of the
3074
                // conditions is whether the link has been marked as
3075
                // reestablished, which happens inside a goroutine(htlcManager)
3076
                // after the link is started. And we may get a false negative
3077
                // saying the link is not active because that goroutine hasn't
3078
                // reached the line to mark the reestablishment. Thus we give
3079
                // it a second chance to send the request.
3080
                case errors.Is(err, netann.ErrEnableInactiveChan):
×
3081
                        // If we don't have a client created, it means we
×
3082
                        // shouldn't retry enabling the channel.
×
3083
                        if p.channelEventClient == nil {
×
3084
                                p.log.Errorf("Channel(%v) request enabling "+
×
3085
                                        "failed due to inactive link",
×
3086
                                        chanPoint)
×
3087

×
3088
                                continue
×
3089
                        }
3090

3091
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
3092
                                "ChanStatusManager reported inactive, retrying")
×
3093

×
3094
                        // Add the channel to the retry map.
×
3095
                        retryChans[chanPoint] = struct{}{}
×
3096
                }
3097
        }
3098

3099
        // Retry the channels if we have any.
3100
        if len(retryChans) != 0 {
3✔
3101
                p.retryRequestEnable(retryChans)
×
3102
        }
×
3103
}
3104

3105
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
3106
// for the target channel ID. If the channel isn't active an error is returned.
3107
// Otherwise, either an existing state machine will be returned, or a new one
3108
// will be created.
3109
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
3110
        *chanCloserFsm, error) {
16✔
3111

16✔
3112
        chanCloser, found := p.activeChanCloses.Load(chanID)
16✔
3113
        if found {
29✔
3114
                // An entry will only be found if the closer has already been
13✔
3115
                // created for a non-pending channel or for a channel that had
13✔
3116
                // previously started the shutdown process but the connection
13✔
3117
                // was restarted.
13✔
3118
                return &chanCloser, nil
13✔
3119
        }
13✔
3120

3121
        // First, we'll ensure that we actually know of the target channel. If
3122
        // not, we'll ignore this message.
3123
        channel, ok := p.activeChannels.Load(chanID)
6✔
3124

6✔
3125
        // If the channel isn't in the map or the channel is nil, return
6✔
3126
        // ErrChannelNotFound as the channel is pending.
6✔
3127
        if !ok || channel == nil {
9✔
3128
                return nil, ErrChannelNotFound
3✔
3129
        }
3✔
3130

3131
        // We'll create a valid closing state machine in order to respond to
3132
        // the initiated cooperative channel closure. First, we set the
3133
        // delivery script that our funds will be paid out to. If an upfront
3134
        // shutdown script was set, we will use it. Otherwise, we get a fresh
3135
        // delivery script.
3136
        //
3137
        // TODO: Expose option to allow upfront shutdown script from watch-only
3138
        // accounts.
3139
        deliveryScript := channel.LocalUpfrontShutdownScript()
6✔
3140
        if len(deliveryScript) == 0 {
12✔
3141
                var err error
6✔
3142
                deliveryScript, err = p.genDeliveryScript()
6✔
3143
                if err != nil {
6✔
3144
                        p.log.Errorf("unable to gen delivery script: %v",
×
3145
                                err)
×
3146
                        return nil, fmt.Errorf("close addr unavailable")
×
3147
                }
×
3148
        }
3149

3150
        // In order to begin fee negotiations, we'll first compute our target
3151
        // ideal fee-per-kw.
3152
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
6✔
3153
                p.cfg.CoopCloseTargetConfs,
6✔
3154
        )
6✔
3155
        if err != nil {
6✔
3156
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3157
                return nil, fmt.Errorf("unable to estimate fee")
×
3158
        }
×
3159

3160
        addr, err := p.addrWithInternalKey(deliveryScript)
6✔
3161
        if err != nil {
6✔
3162
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3163
        }
×
3164
        negotiateChanCloser, err := p.createChanCloser(
6✔
3165
                channel, addr, feePerKw, nil, lntypes.Remote,
6✔
3166
        )
6✔
3167
        if err != nil {
6✔
3168
                p.log.Errorf("unable to create chan closer: %v", err)
×
3169
                return nil, fmt.Errorf("unable to create chan closer")
×
3170
        }
×
3171

3172
        chanCloser = makeNegotiateCloser(negotiateChanCloser)
6✔
3173

6✔
3174
        p.activeChanCloses.Store(chanID, chanCloser)
6✔
3175

6✔
3176
        return &chanCloser, nil
6✔
3177
}
3178

3179
// filterChannelsToEnable filters a list of channels to be enabled upon start.
3180
// The filtered channels are active channels that's neither private nor
3181
// pending.
3182
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
3✔
3183
        var activePublicChans []wire.OutPoint
3✔
3184

3✔
3185
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
3✔
3186
                lnChan *lnwallet.LightningChannel) bool {
6✔
3187

3✔
3188
                // If the lnChan is nil, continue as this is a pending channel.
3✔
3189
                if lnChan == nil {
5✔
3190
                        return true
2✔
3191
                }
2✔
3192

3193
                dbChan := lnChan.State()
3✔
3194
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
3195
                if !isPublic || dbChan.IsPending {
3✔
3196
                        return true
×
3197
                }
×
3198

3199
                // We'll also skip any channels added during this peer's
3200
                // lifecycle since they haven't waited out the timeout. Their
3201
                // first announcement will be enabled, and the chan status
3202
                // manager will begin monitoring them passively since they exist
3203
                // in the database.
3204
                if _, ok := p.addedChannels.Load(chanID); ok {
3✔
UNCOV
3205
                        return true
×
UNCOV
3206
                }
×
3207

3208
                activePublicChans = append(
3✔
3209
                        activePublicChans, dbChan.FundingOutpoint,
3✔
3210
                )
3✔
3211

3✔
3212
                return true
3✔
3213
        })
3214

3215
        return activePublicChans
3✔
3216
}
3217

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

×
3225
        // retryEnable is a helper closure that sends an enable request and
×
3226
        // removes the channel from the map if it's matched.
×
3227
        retryEnable := func(chanPoint wire.OutPoint) error {
×
3228
                // If this is an active channel event, check whether it's in
×
3229
                // our targeted channels map.
×
3230
                _, found := activeChans[chanPoint]
×
3231

×
3232
                // If this channel is irrelevant, return nil so the loop can
×
3233
                // jump to next iteration.
×
3234
                if !found {
×
3235
                        return nil
×
3236
                }
×
3237

3238
                // Otherwise we've just received an active signal for a channel
3239
                // that's previously failed to be enabled, we send the request
3240
                // again.
3241
                //
3242
                // We only give the channel one more shot, so we delete it from
3243
                // our map first to keep it from being attempted again.
3244
                delete(activeChans, chanPoint)
×
3245

×
3246
                // Send the request.
×
3247
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3248
                if err != nil {
×
3249
                        return fmt.Errorf("request enabling channel %v "+
×
3250
                                "failed: %w", chanPoint, err)
×
3251
                }
×
3252

3253
                return nil
×
3254
        }
3255

3256
        for {
×
3257
                // If activeChans is empty, we've done processing all the
×
3258
                // channels.
×
3259
                if len(activeChans) == 0 {
×
3260
                        p.log.Debug("Finished retry enabling channels")
×
3261
                        return
×
3262
                }
×
3263

3264
                select {
×
3265
                // A new event has been sent by the ChannelNotifier. We now
3266
                // check whether it's an active or inactive channel event.
3267
                case e := <-p.channelEventClient.Updates():
×
3268
                        // If this is an active channel event, try enable the
×
3269
                        // channel then jump to the next iteration.
×
3270
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
3271
                        if ok {
×
3272
                                chanPoint := *active.ChannelPoint
×
3273

×
3274
                                // If we received an error for this particular
×
3275
                                // channel, we log an error and won't quit as
×
3276
                                // we still want to retry other channels.
×
3277
                                if err := retryEnable(chanPoint); err != nil {
×
3278
                                        p.log.Errorf("Retry failed: %v", err)
×
3279
                                }
×
3280

3281
                                continue
×
3282
                        }
3283

3284
                        // Otherwise check for inactive link event, and jump to
3285
                        // next iteration if it's not.
3286
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3287
                        if !ok {
×
3288
                                continue
×
3289
                        }
3290

3291
                        // Found an inactive link event, if this is our
3292
                        // targeted channel, remove it from our map.
3293
                        chanPoint := *inactive.ChannelPoint
×
3294
                        _, found := activeChans[chanPoint]
×
3295
                        if !found {
×
3296
                                continue
×
3297
                        }
3298

3299
                        delete(activeChans, chanPoint)
×
3300
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3301
                                "inactive link event", chanPoint)
×
3302

3303
                case <-p.cg.Done():
×
3304
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3305
                        return
×
3306
                }
3307
        }
3308
}
3309

3310
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3311
// a suitable script to close out to. This may be nil if neither script is
3312
// set. If both scripts are set, this function will error if they do not match.
3313
func chooseDeliveryScript(upfront, requested lnwire.DeliveryAddress,
3314
        genDeliveryScript func() ([]byte, error),
3315
) (lnwire.DeliveryAddress, error) {
15✔
3316

15✔
3317
        switch {
15✔
3318
        // If no script was provided, then we'll generate a new delivery script.
3319
        case len(upfront) == 0 && len(requested) == 0:
7✔
3320
                return genDeliveryScript()
7✔
3321

3322
        // If no upfront shutdown script was provided, return the user
3323
        // requested address (which may be nil).
3324
        case len(upfront) == 0:
5✔
3325
                return requested, nil
5✔
3326

3327
        // If an upfront shutdown script was provided, and the user did not
3328
        // request a custom shutdown script, return the upfront address.
3329
        case len(requested) == 0:
5✔
3330
                return upfront, nil
5✔
3331

3332
        // If both an upfront shutdown script and a custom close script were
3333
        // provided, error if the user provided shutdown script does not match
3334
        // the upfront shutdown script (because closing out to a different
3335
        // script would violate upfront shutdown).
3336
        case !bytes.Equal(upfront, requested):
2✔
3337
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
3338

3339
        // The user requested script matches the upfront shutdown script, so we
3340
        // can return it without error.
3341
        default:
2✔
3342
                return upfront, nil
2✔
3343
        }
3344
}
3345

3346
// restartCoopClose checks whether we need to restart the cooperative close
3347
// process for a given channel.
3348
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3349
        *lnwire.Shutdown, error) {
3✔
3350

3✔
3351
        isTaprootChan := lnChan.ChanType().IsTaproot()
3✔
3352

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

3372
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
3✔
3373

3✔
3374
        var deliveryScript []byte
3✔
3375

3✔
3376
        shutdownInfo, err := c.ShutdownInfo()
3✔
3377
        switch {
3✔
3378
        // We have previously stored the delivery script that we need to use
3379
        // in the shutdown message. Re-use this script.
3380
        case err == nil:
3✔
3381
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
6✔
3382
                        deliveryScript = info.DeliveryScript.Val
3✔
3383
                })
3✔
3384

3385
        // An error other than ErrNoShutdownInfo was returned
3386
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3387
                return nil, err
×
3388

3389
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3390
                deliveryScript = c.LocalShutdownScript
×
3391
                if len(deliveryScript) == 0 {
×
3392
                        var err error
×
3393
                        deliveryScript, err = p.genDeliveryScript()
×
3394
                        if err != nil {
×
3395
                                p.log.Errorf("unable to gen delivery script: "+
×
3396
                                        "%v", err)
×
3397

×
3398
                                return nil, fmt.Errorf("close addr unavailable")
×
3399
                        }
×
3400
                }
3401
        }
3402

3403
        // If the new RBF co-op close is negotiated, then we'll init and start
3404
        // that state machine, skipping the steps for the negotiate machine
3405
        // below. We don't support this close type for taproot channels though.
3406
        if p.rbfCoopCloseAllowed() && !isTaprootChan {
6✔
3407
                _, err := p.initRbfChanCloser(lnChan)
3✔
3408
                if err != nil {
3✔
3409
                        return nil, fmt.Errorf("unable to init rbf chan "+
×
3410
                                "closer during restart: %w", err)
×
3411
                }
×
3412

3413
                shutdownDesc := fn.MapOption(
3✔
3414
                        newRestartShutdownInit,
3✔
3415
                )(shutdownInfo)
3✔
3416

3✔
3417
                err = p.startRbfChanCloser(
3✔
3418
                        fn.FlattenOption(shutdownDesc), lnChan.ChannelPoint(),
3✔
3419
                )
3✔
3420

3✔
3421
                return nil, err
3✔
3422
        }
3423

3424
        // Compute an ideal fee.
3425
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
3426
                p.cfg.CoopCloseTargetConfs,
×
3427
        )
×
3428
        if err != nil {
×
3429
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3430
                return nil, fmt.Errorf("unable to estimate fee")
×
3431
        }
×
3432

3433
        // Determine whether we or the peer are the initiator of the coop
3434
        // close attempt by looking at the channel's status.
3435
        closingParty := lntypes.Remote
×
3436
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3437
                closingParty = lntypes.Local
×
3438
        }
×
3439

3440
        addr, err := p.addrWithInternalKey(deliveryScript)
×
3441
        if err != nil {
×
3442
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3443
        }
×
3444
        chanCloser, err := p.createChanCloser(
×
3445
                lnChan, addr, feePerKw, nil, closingParty,
×
3446
        )
×
3447
        if err != nil {
×
3448
                p.log.Errorf("unable to create chan closer: %v", err)
×
3449
                return nil, fmt.Errorf("unable to create chan closer")
×
3450
        }
×
3451

3452
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
×
3453

×
3454
        // Create the Shutdown message.
×
3455
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3456
        if err != nil {
×
3457
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3458
                p.activeChanCloses.Delete(chanID)
×
3459
                return nil, err
×
3460
        }
×
3461

3462
        return shutdownMsg, nil
×
3463
}
3464

3465
// createChanCloser constructs a ChanCloser from the passed parameters and is
3466
// used to de-duplicate code.
3467
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3468
        deliveryScript *chancloser.DeliveryAddrWithKey,
3469
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3470
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
12✔
3471

12✔
3472
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
12✔
3473
        if err != nil {
12✔
3474
                p.log.Errorf("unable to obtain best block: %v", err)
×
3475
                return nil, fmt.Errorf("cannot obtain best block")
×
3476
        }
×
3477

3478
        // The req will only be set if we initiated the co-op closing flow.
3479
        var maxFee chainfee.SatPerKWeight
12✔
3480
        if req != nil {
21✔
3481
                maxFee = req.MaxFee
9✔
3482
        }
9✔
3483

3484
        chanCloser := chancloser.NewChanCloser(
12✔
3485
                chancloser.ChanCloseCfg{
12✔
3486
                        Channel:      channel,
12✔
3487
                        MusigSession: NewMusigChanCloser(channel),
12✔
3488
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
12✔
3489
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
12✔
3490
                        AuxCloser:    p.cfg.AuxChanCloser,
12✔
3491
                        DisableChannel: func(op wire.OutPoint) error {
24✔
3492
                                return p.cfg.ChanStatusMgr.RequestDisable(
12✔
3493
                                        op, false,
12✔
3494
                                )
12✔
3495
                        },
12✔
3496
                        MaxFee: maxFee,
3497
                        Disconnect: func() error {
×
3498
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
3499
                        },
×
3500
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3501
                },
3502
                *deliveryScript,
3503
                fee,
3504
                uint32(startingHeight),
3505
                req,
3506
                closer,
3507
        )
3508

3509
        return chanCloser, nil
12✔
3510
}
3511

3512
// initNegotiateChanCloser initializes the channel closer for a channel that is
3513
// using the original "negotiation" based protocol. This path is used when
3514
// we're the one initiating the channel close.
3515
//
3516
// TODO(roasbeef): can make a MsgEndpoint for existing handling logic to
3517
// further abstract.
3518
func (p *Brontide) initNegotiateChanCloser(req *htlcswitch.ChanClose,
3519
        channel *lnwallet.LightningChannel) error {
10✔
3520

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

10✔
3524
        // An upfront shutdown and user provided script are both optional, but
10✔
3525
        // must be equal if both set  (because we cannot serve a request to
10✔
3526
        // close out to a script which violates upfront shutdown). Get the
10✔
3527
        // appropriate address to close out to (which may be nil if neither are
10✔
3528
        // set) and error if they are both set and do not match.
10✔
3529
        deliveryScript, err := chooseDeliveryScript(
10✔
3530
                channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
10✔
3531
                p.genDeliveryScript,
10✔
3532
        )
10✔
3533
        if err != nil {
11✔
3534
                return fmt.Errorf("cannot close channel %v: %w",
1✔
3535
                        req.ChanPoint, err)
1✔
3536
        }
1✔
3537

3538
        addr, err := p.addrWithInternalKey(deliveryScript)
9✔
3539
        if err != nil {
9✔
3540
                return fmt.Errorf("unable to parse addr for channel "+
×
3541
                        "%v: %w", req.ChanPoint, err)
×
3542
        }
×
3543

3544
        chanCloser, err := p.createChanCloser(
9✔
3545
                channel, addr, req.TargetFeePerKw, req, lntypes.Local,
9✔
3546
        )
9✔
3547
        if err != nil {
9✔
3548
                return fmt.Errorf("unable to make chan closer: %w", err)
×
3549
        }
×
3550

3551
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
9✔
3552
        p.activeChanCloses.Store(chanID, makeNegotiateCloser(chanCloser))
9✔
3553

9✔
3554
        // Finally, we'll initiate the channel shutdown within the
9✔
3555
        // chanCloser, and send the shutdown message to the remote
9✔
3556
        // party to kick things off.
9✔
3557
        shutdownMsg, err := chanCloser.ShutdownChan()
9✔
3558
        if err != nil {
9✔
3559
                // As we were unable to shutdown the channel, we'll return it
×
3560
                // back to its normal state.
×
3561
                defer channel.ResetState()
×
3562

×
3563
                p.activeChanCloses.Delete(chanID)
×
3564

×
3565
                return fmt.Errorf("unable to shutdown channel: %w", err)
×
3566
        }
×
3567

3568
        link := p.fetchLinkFromKeyAndCid(chanID)
9✔
3569
        if link == nil {
9✔
3570
                // If the link is nil then it means it was already removed from
×
3571
                // the switch or it never existed in the first place. The
×
3572
                // latter case is handled at the beginning of this function, so
×
3573
                // in the case where it has already been removed, we can skip
×
3574
                // adding the commit hook to queue a Shutdown message.
×
3575
                p.log.Warnf("link not found during attempted closure: "+
×
3576
                        "%v", chanID)
×
3577
                return nil
×
3578
        }
×
3579

3580
        if !link.DisableAdds(htlcswitch.Outgoing) {
9✔
3581
                p.log.Warnf("Outgoing link adds already "+
×
3582
                        "disabled: %v", link.ChanID())
×
3583
        }
×
3584

3585
        link.OnCommitOnce(htlcswitch.Outgoing, func() {
18✔
3586
                p.queueMsg(shutdownMsg, nil)
9✔
3587
        })
9✔
3588

3589
        return nil
9✔
3590
}
3591

3592
// chooseAddr returns the provided address if it is non-zero length, otherwise
3593
// None.
3594
func chooseAddr(addr lnwire.DeliveryAddress) fn.Option[lnwire.DeliveryAddress] {
3✔
3595
        if len(addr) == 0 {
6✔
3596
                return fn.None[lnwire.DeliveryAddress]()
3✔
3597
        }
3✔
3598

3599
        return fn.Some(addr)
×
3600
}
3601

3602
// observeRbfCloseUpdates observes the channel for any updates that may
3603
// indicate that a new txid has been broadcasted, or the channel fully closed
3604
// on chain.
3605
func (p *Brontide) observeRbfCloseUpdates(chanCloser *chancloser.RbfChanCloser,
3606
        closeReq *htlcswitch.ChanClose,
3607
        coopCloseStates chancloser.RbfStateSub) {
3✔
3608

3✔
3609
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3610
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3611

3✔
3612
        var (
3✔
3613
                lastTxids    lntypes.Dual[chainhash.Hash]
3✔
3614
                lastFeeRates lntypes.Dual[chainfee.SatPerVByte]
3✔
3615
        )
3✔
3616

3✔
3617
        maybeNotifyTxBroadcast := func(state chancloser.AsymmetricPeerState,
3✔
3618
                party lntypes.ChannelParty) {
6✔
3619

3✔
3620
                // First, check to see if we have an error to report to the
3✔
3621
                // caller. If so, then we''ll return that error and exit, as the
3✔
3622
                // stream will exit as well.
3✔
3623
                if closeErr, ok := state.(*chancloser.CloseErr); ok {
6✔
3624
                        // We hit an error during the last state transition, so
3✔
3625
                        // we'll extract the error then send it to the
3✔
3626
                        // user.
3✔
3627
                        err := closeErr.Err()
3✔
3628

3✔
3629
                        peerLog.Warnf("ChannelPoint(%v): encountered close "+
3✔
3630
                                "err: %v", closeReq.ChanPoint, err)
3✔
3631

3✔
3632
                        select {
3✔
3633
                        case closeReq.Err <- err:
3✔
3634
                        case <-closeReq.Ctx.Done():
×
3635
                        case <-p.cg.Done():
×
3636
                        }
3637

3638
                        return
3✔
3639
                }
3640

3641
                closePending, ok := state.(*chancloser.ClosePending)
3✔
3642

3✔
3643
                // If this isn't the close pending state, we aren't at the
3✔
3644
                // terminal state yet.
3✔
3645
                if !ok {
6✔
3646
                        return
3✔
3647
                }
3✔
3648

3649
                // Only notify if the fee rate is greater.
3650
                newFeeRate := closePending.FeeRate
3✔
3651
                lastFeeRate := lastFeeRates.GetForParty(party)
3✔
3652
                if newFeeRate <= lastFeeRate {
6✔
3653
                        peerLog.Debugf("ChannelPoint(%v): remote party made "+
3✔
3654
                                "update for fee rate %v, but we already have "+
3✔
3655
                                "a higher fee rate of %v", closeReq.ChanPoint,
3✔
3656
                                newFeeRate, lastFeeRate)
3✔
3657

3✔
3658
                        return
3✔
3659
                }
3✔
3660

3661
                feeRate := closePending.FeeRate
3✔
3662
                lastFeeRates.SetForParty(party, feeRate)
3✔
3663

3✔
3664
                // At this point, we'll have a txid that we can use to notify
3✔
3665
                // the client, but only if it's different from the last one we
3✔
3666
                // sent. If the user attempted to bump, but was rejected due to
3✔
3667
                // RBF, then we'll send a redundant update.
3✔
3668
                closingTxid := closePending.CloseTx.TxHash()
3✔
3669
                lastTxid := lastTxids.GetForParty(party)
3✔
3670
                if closeReq != nil && closingTxid != lastTxid {
6✔
3671
                        select {
3✔
3672
                        case closeReq.Updates <- &PendingUpdate{
3673
                                Txid:        closingTxid[:],
3674
                                FeePerVbyte: fn.Some(closePending.FeeRate),
3675
                                IsLocalCloseTx: fn.Some(
3676
                                        party == lntypes.Local,
3677
                                ),
3678
                        }:
3✔
3679

3680
                        case <-closeReq.Ctx.Done():
×
3681
                                return
×
3682

3683
                        case <-p.cg.Done():
×
3684
                                return
×
3685
                        }
3686
                }
3687

3688
                lastTxids.SetForParty(party, closingTxid)
3✔
3689
        }
3690

3691
        peerLog.Infof("Observing RBF close updates for channel %v",
3✔
3692
                closeReq.ChanPoint)
3✔
3693

3✔
3694
        // We'll consume each new incoming state to send out the appropriate
3✔
3695
        // RPC update.
3✔
3696
        for {
6✔
3697
                select {
3✔
3698
                case newState := <-newStateChan:
3✔
3699

3✔
3700
                        switch closeState := newState.(type) {
3✔
3701
                        // Once we've reached the state of pending close, we
3702
                        // have a txid that we broadcasted.
3703
                        case *chancloser.ClosingNegotiation:
3✔
3704
                                peerState := closeState.PeerState
3✔
3705

3✔
3706
                                // Each side may have gained a new co-op close
3✔
3707
                                // tx, so we'll examine both to see if they've
3✔
3708
                                // changed.
3✔
3709
                                maybeNotifyTxBroadcast(
3✔
3710
                                        peerState.GetForParty(lntypes.Local),
3✔
3711
                                        lntypes.Local,
3✔
3712
                                )
3✔
3713
                                maybeNotifyTxBroadcast(
3✔
3714
                                        peerState.GetForParty(lntypes.Remote),
3✔
3715
                                        lntypes.Remote,
3✔
3716
                                )
3✔
3717

3718
                        // Otherwise, if we're transition to CloseFin, then we
3719
                        // know that we're done.
3720
                        case *chancloser.CloseFin:
3✔
3721
                                // To clean up, we'll remove the chan closer
3✔
3722
                                // from the active map, and send the final
3✔
3723
                                // update to the client.
3✔
3724
                                closingTxid := closeState.ConfirmedTx.TxHash()
3✔
3725
                                if closeReq != nil {
6✔
3726
                                        closeReq.Updates <- &ChannelCloseUpdate{
3✔
3727
                                                ClosingTxid: closingTxid[:],
3✔
3728
                                                Success:     true,
3✔
3729
                                        }
3✔
3730
                                }
3✔
3731
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
3732
                                        *closeReq.ChanPoint,
3✔
3733
                                )
3✔
3734
                                p.activeChanCloses.Delete(chanID)
3✔
3735

3✔
3736
                                return
3✔
3737
                        }
3738

3739
                case <-closeReq.Ctx.Done():
3✔
3740
                        return
3✔
3741

3742
                case <-p.cg.Done():
3✔
3743
                        return
3✔
3744
                }
3745
        }
3746
}
3747

3748
// chanErrorReporter is a simple implementation of the
3749
// chancloser.ErrorReporter. This is bound to a single channel by the channel
3750
// ID.
3751
type chanErrorReporter struct {
3752
        chanID lnwire.ChannelID
3753
        peer   *Brontide
3754
}
3755

3756
// newChanErrorReporter creates a new instance of the chanErrorReporter.
3757
func newChanErrorReporter(chanID lnwire.ChannelID,
3758
        peer *Brontide) *chanErrorReporter {
3✔
3759

3✔
3760
        return &chanErrorReporter{
3✔
3761
                chanID: chanID,
3✔
3762
                peer:   peer,
3✔
3763
        }
3✔
3764
}
3✔
3765

3766
// ReportError is a method that's used to report an error that occurred during
3767
// state machine execution. This is used by the RBF close state machine to
3768
// terminate the state machine and send an error to the remote peer.
3769
//
3770
// This is a part of the chancloser.ErrorReporter interface.
3771
func (c *chanErrorReporter) ReportError(chanErr error) {
×
3772
        c.peer.log.Errorf("coop close error for channel %v: %v",
×
3773
                c.chanID, chanErr)
×
3774

×
3775
        var errMsg []byte
×
3776
        if errors.Is(chanErr, chancloser.ErrInvalidStateTransition) {
×
3777
                errMsg = []byte("unexpected protocol message")
×
3778
        } else {
×
3779
                errMsg = []byte(chanErr.Error())
×
3780
        }
×
3781

3782
        err := c.peer.SendMessageLazy(false, &lnwire.Error{
×
3783
                ChanID: c.chanID,
×
3784
                Data:   errMsg,
×
3785
        })
×
3786
        if err != nil {
×
3787
                c.peer.log.Warnf("unable to send error message to peer: %v",
×
3788
                        err)
×
3789
        }
×
3790

3791
        // After we send the error message to the peer, we'll re-initialize the
3792
        // coop close state machine as they may send a shutdown message to
3793
        // retry the coop close.
3794
        lnChan, ok := c.peer.activeChannels.Load(c.chanID)
×
3795
        if !ok {
×
3796
                return
×
3797
        }
×
3798

3799
        if lnChan == nil {
×
3800
                c.peer.log.Debugf("channel %v is pending, not "+
×
3801
                        "re-initializing coop close state machine",
×
3802
                        c.chanID)
×
3803

×
3804
                return
×
3805
        }
×
3806

3807
        if _, err := c.peer.initRbfChanCloser(lnChan); err != nil {
×
3808
                c.peer.activeChanCloses.Delete(c.chanID)
×
3809

×
3810
                c.peer.log.Errorf("unable to init RBF chan closer after "+
×
3811
                        "error case: %v", err)
×
3812
        }
×
3813
}
3814

3815
// chanFlushEventSentinel is used to send the RBF coop close state machine the
3816
// channel flushed event. We'll wait until the state machine enters the
3817
// ChannelFlushing state, then request the link to send the event once flushed.
3818
//
3819
// NOTE: This MUST be run as a goroutine.
3820
func (p *Brontide) chanFlushEventSentinel(chanCloser *chancloser.RbfChanCloser,
3821
        link htlcswitch.ChannelUpdateHandler,
3822
        channel *lnwallet.LightningChannel) {
3✔
3823

3✔
3824
        defer p.cg.WgDone()
3✔
3825

3✔
3826
        // If there's no link, then the channel has already been flushed, so we
3✔
3827
        // don't need to continue.
3✔
3828
        if link == nil {
6✔
3829
                return
3✔
3830
        }
3✔
3831

3832
        coopCloseStates := chanCloser.RegisterStateEvents()
3✔
3833
        defer chanCloser.RemoveStateSub(coopCloseStates)
3✔
3834

3✔
3835
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
3836

3✔
3837
        sendChanFlushed := func() {
6✔
3838
                chanState := channel.StateSnapshot()
3✔
3839

3✔
3840
                peerLog.Infof("ChannelPoint(%v) has been flushed for co-op "+
3✔
3841
                        "close, sending event to chan closer",
3✔
3842
                        channel.ChannelPoint())
3✔
3843

3✔
3844
                chanBalances := chancloser.ShutdownBalances{
3✔
3845
                        LocalBalance:  chanState.LocalBalance,
3✔
3846
                        RemoteBalance: chanState.RemoteBalance,
3✔
3847
                }
3✔
3848
                ctx := context.Background()
3✔
3849
                chanCloser.SendEvent(ctx, &chancloser.ChannelFlushed{
3✔
3850
                        ShutdownBalances: chanBalances,
3✔
3851
                        FreshFlush:       true,
3✔
3852
                })
3✔
3853
        }
3✔
3854

3855
        // We'll wait until the channel enters the ChannelFlushing state. We
3856
        // exit after a success loop. As after the first RBF iteration, the
3857
        // channel will always be flushed.
3858
        for {
6✔
3859
                select {
3✔
3860
                case newState, ok := <-newStateChan:
3✔
3861
                        if !ok {
3✔
3862
                                return
×
3863
                        }
×
3864

3865
                        if _, ok := newState.(*chancloser.ChannelFlushing); ok {
6✔
3866
                                peerLog.Infof("ChannelPoint(%v): rbf coop "+
3✔
3867
                                        "close is awaiting a flushed state, "+
3✔
3868
                                        "registering with link..., ",
3✔
3869
                                        channel.ChannelPoint())
3✔
3870

3✔
3871
                                // Request the link to send the event once the
3✔
3872
                                // channel is flushed. We only need this event
3✔
3873
                                // sent once, so we can exit now.
3✔
3874
                                link.OnFlushedOnce(sendChanFlushed)
3✔
3875

3✔
3876
                                return
3✔
3877
                        }
3✔
3878

3879
                case <-p.cg.Done():
3✔
3880
                        return
3✔
3881
                }
3882
        }
3883
}
3884

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

3✔
3891
        chanID := lnwire.NewChanIDFromOutPoint(channel.ChannelPoint())
3✔
3892

3✔
3893
        link := p.fetchLinkFromKeyAndCid(chanID)
3✔
3894

3✔
3895
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
3✔
3896
        if err != nil {
3✔
3897
                return nil, fmt.Errorf("cannot obtain best block: %w", err)
×
3898
        }
×
3899

3900
        defaultFeePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
3901
                p.cfg.CoopCloseTargetConfs,
3✔
3902
        )
3✔
3903
        if err != nil {
3✔
3904
                return nil, fmt.Errorf("unable to estimate fee: %w", err)
×
3905
        }
×
3906

3907
        thawHeight, err := channel.AbsoluteThawHeight()
3✔
3908
        if err != nil {
3✔
3909
                return nil, fmt.Errorf("unable to get thaw height: %w", err)
×
3910
        }
×
3911

3912
        peerPub := *p.IdentityKey()
3✔
3913

3✔
3914
        msgMapper := chancloser.NewRbfMsgMapper(
3✔
3915
                uint32(startingHeight), chanID, peerPub,
3✔
3916
        )
3✔
3917

3✔
3918
        initialState := chancloser.ChannelActive{}
3✔
3919

3✔
3920
        scid := channel.ZeroConfRealScid().UnwrapOr(
3✔
3921
                channel.ShortChanID(),
3✔
3922
        )
3✔
3923

3✔
3924
        env := chancloser.Environment{
3✔
3925
                ChainParams:    p.cfg.Wallet.Cfg.NetParams,
3✔
3926
                ChanPeer:       peerPub,
3✔
3927
                ChanPoint:      channel.ChannelPoint(),
3✔
3928
                ChanID:         chanID,
3✔
3929
                Scid:           scid,
3✔
3930
                ChanType:       channel.ChanType(),
3✔
3931
                DefaultFeeRate: defaultFeePerKw.FeePerVByte(),
3✔
3932
                ThawHeight:     fn.Some(thawHeight),
3✔
3933
                RemoteUpfrontShutdown: chooseAddr(
3✔
3934
                        channel.RemoteUpfrontShutdownScript(),
3✔
3935
                ),
3✔
3936
                LocalUpfrontShutdown: chooseAddr(
3✔
3937
                        channel.LocalUpfrontShutdownScript(),
3✔
3938
                ),
3✔
3939
                NewDeliveryScript: func() (lnwire.DeliveryAddress, error) {
6✔
3940
                        return p.genDeliveryScript()
3✔
3941
                },
3✔
3942
                FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
3943
                CloseSigner:  channel,
3944
                ChanObserver: newChanObserver(
3945
                        channel, link, p.cfg.ChanStatusMgr,
3946
                ),
3947
        }
3948

3949
        spendEvent := protofsm.RegisterSpend[chancloser.ProtocolEvent]{
3✔
3950
                OutPoint:   channel.ChannelPoint(),
3✔
3951
                PkScript:   channel.FundingTxOut().PkScript,
3✔
3952
                HeightHint: channel.DeriveHeightHint(),
3✔
3953
                PostSpendEvent: fn.Some[chancloser.RbfSpendMapper](
3✔
3954
                        chancloser.SpendMapper,
3✔
3955
                ),
3✔
3956
        }
3✔
3957

3✔
3958
        daemonAdapters := NewLndDaemonAdapters(LndAdapterCfg{
3✔
3959
                MsgSender:     newPeerMsgSender(peerPub, p),
3✔
3960
                TxBroadcaster: p.cfg.Wallet,
3✔
3961
                ChainNotifier: p.cfg.ChainNotifier,
3✔
3962
        })
3✔
3963

3✔
3964
        protoCfg := chancloser.RbfChanCloserCfg{
3✔
3965
                Daemon:        daemonAdapters,
3✔
3966
                InitialState:  &initialState,
3✔
3967
                Env:           &env,
3✔
3968
                InitEvent:     fn.Some[protofsm.DaemonEvent](&spendEvent),
3✔
3969
                ErrorReporter: newChanErrorReporter(chanID, p),
3✔
3970
                MsgMapper: fn.Some[protofsm.MsgMapper[chancloser.ProtocolEvent]]( //nolint:ll
3✔
3971
                        msgMapper,
3✔
3972
                ),
3✔
3973
        }
3✔
3974

3✔
3975
        ctx := context.Background()
3✔
3976
        chanCloser := protofsm.NewStateMachine(protoCfg)
3✔
3977
        chanCloser.Start(ctx)
3✔
3978

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

3✔
3984
                return r.RegisterEndpoint(&chanCloser)
3✔
3985
        })
3✔
3986
        if err != nil {
3✔
3987
                chanCloser.Stop()
×
3988

×
3989
                return nil, fmt.Errorf("unable to register endpoint for co-op "+
×
3990
                        "close: %w", err)
×
3991
        }
×
3992

3993
        p.activeChanCloses.Store(chanID, makeRbfCloser(&chanCloser))
3✔
3994

3✔
3995
        // Now that we've created the rbf closer state machine, we'll launch a
3✔
3996
        // new goroutine to eventually send in the ChannelFlushed event once
3✔
3997
        // needed.
3✔
3998
        p.cg.WgAdd(1)
3✔
3999
        go p.chanFlushEventSentinel(&chanCloser, link, channel)
3✔
4000

3✔
4001
        return &chanCloser, nil
3✔
4002
}
4003

4004
// shutdownInit describes the two ways we can initiate a new shutdown. Either we
4005
// got an RPC request to do so (left), or we sent a shutdown message to the
4006
// party (for w/e reason), but crashed before the close was complete.
4007
//
4008
//nolint:ll
4009
type shutdownInit = fn.Option[fn.Either[*htlcswitch.ChanClose, channeldb.ShutdownInfo]]
4010

4011
// shutdownStartFeeRate returns the fee rate that should be used for the
4012
// shutdown.  This returns a doubly wrapped option as the shutdown info might
4013
// be none, and the fee rate is only defined for the user initiated shutdown.
4014
func shutdownStartFeeRate(s shutdownInit) fn.Option[chainfee.SatPerKWeight] {
3✔
4015
        feeRateOpt := fn.MapOption(func(init fn.Either[*htlcswitch.ChanClose,
3✔
4016
                channeldb.ShutdownInfo]) fn.Option[chainfee.SatPerKWeight] {
6✔
4017

3✔
4018
                var feeRate fn.Option[chainfee.SatPerKWeight]
3✔
4019
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
6✔
4020
                        feeRate = fn.Some(req.TargetFeePerKw)
3✔
4021
                })
3✔
4022

4023
                return feeRate
3✔
4024
        })(s)
4025

4026
        return fn.FlattenOption(feeRateOpt)
3✔
4027
}
4028

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

3✔
4036
                var addr fn.Option[lnwire.DeliveryAddress]
3✔
4037
                init.WhenLeft(func(req *htlcswitch.ChanClose) {
6✔
4038
                        if len(req.DeliveryScript) != 0 {
6✔
4039
                                addr = fn.Some(req.DeliveryScript)
3✔
4040
                        }
3✔
4041
                })
4042
                init.WhenRight(func(info channeldb.ShutdownInfo) {
6✔
4043
                        addr = fn.Some(info.DeliveryScript.Val)
3✔
4044
                })
3✔
4045

4046
                return addr
3✔
4047
        })(s)
4048

4049
        return fn.FlattenOption(addrOpt)
3✔
4050
}
4051

4052
// whenRPCShutdown registers a callback to be executed when the shutdown init
4053
// type is and RPC request.
4054
func whenRPCShutdown(s shutdownInit, f func(r *htlcswitch.ChanClose)) {
3✔
4055
        s.WhenSome(func(init fn.Either[*htlcswitch.ChanClose,
3✔
4056
                channeldb.ShutdownInfo]) {
6✔
4057

3✔
4058
                init.WhenLeft(f)
3✔
4059
        })
3✔
4060
}
4061

4062
// newRestartShutdownInit creates a new shutdownInit for the case where we need
4063
// to restart the shutdown flow after a restart.
4064
func newRestartShutdownInit(info channeldb.ShutdownInfo) shutdownInit {
3✔
4065
        return fn.Some(fn.NewRight[*htlcswitch.ChanClose](info))
3✔
4066
}
3✔
4067

4068
// newRPCShutdownInit creates a new shutdownInit for the case where we
4069
// initiated the shutdown via an RPC client.
4070
func newRPCShutdownInit(req *htlcswitch.ChanClose) shutdownInit {
3✔
4071
        return fn.Some(
3✔
4072
                fn.NewLeft[*htlcswitch.ChanClose, channeldb.ShutdownInfo](req),
3✔
4073
        )
3✔
4074
}
3✔
4075

4076
// waitUntilRbfCoastClear waits until the RBF co-op close state machine has
4077
// advanced to a terminal state before attempting another fee bump.
4078
func waitUntilRbfCoastClear(ctx context.Context,
4079
        rbfCloser *chancloser.RbfChanCloser) error {
3✔
4080

3✔
4081
        coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4082
        newStateChan := coopCloseStates.NewItemCreated.ChanOut()
3✔
4083
        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4084

3✔
4085
        isTerminalState := func(newState chancloser.RbfState) bool {
6✔
4086
                // If we're not in the negotiation sub-state, then we aren't at
3✔
4087
                // the terminal state yet.
3✔
4088
                state, ok := newState.(*chancloser.ClosingNegotiation)
3✔
4089
                if !ok {
3✔
4090
                        return false
×
4091
                }
×
4092

4093
                localState := state.PeerState.GetForParty(lntypes.Local)
3✔
4094

3✔
4095
                // If this isn't the close pending state, we aren't at the
3✔
4096
                // terminal state yet.
3✔
4097
                _, ok = localState.(*chancloser.ClosePending)
3✔
4098

3✔
4099
                return ok
3✔
4100
        }
4101

4102
        // Before we enter the subscription loop below, check to see if we're
4103
        // already in the terminal state.
4104
        rbfState, err := rbfCloser.CurrentState()
3✔
4105
        if err != nil {
3✔
4106
                return err
×
4107
        }
×
4108
        if isTerminalState(rbfState) {
6✔
4109
                return nil
3✔
4110
        }
3✔
4111

4112
        peerLog.Debugf("Waiting for RBF iteration to complete...")
×
4113

×
4114
        for {
×
4115
                select {
×
4116
                case newState := <-newStateChan:
×
4117
                        if isTerminalState(newState) {
×
4118
                                return nil
×
4119
                        }
×
4120

4121
                case <-ctx.Done():
×
4122
                        return fmt.Errorf("context canceled")
×
4123
                }
4124
        }
4125
}
4126

4127
// startRbfChanCloser kicks off the co-op close process using the new RBF based
4128
// co-op close protocol. This is called when we're the one that's initiating
4129
// the cooperative channel close.
4130
//
4131
// TODO(roasbeef): just accept the two shutdown pointer params instead??
4132
func (p *Brontide) startRbfChanCloser(shutdown shutdownInit,
4133
        chanPoint wire.OutPoint) error {
3✔
4134

3✔
4135
        // Unlike the old negotiate chan closer, we'll always create the RBF
3✔
4136
        // chan closer on startup, so we can skip init here.
3✔
4137
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4138
        chanCloser, found := p.activeChanCloses.Load(chanID)
3✔
4139
        if !found {
3✔
4140
                return fmt.Errorf("rbf chan closer not found for channel %v",
×
4141
                        chanPoint)
×
4142
        }
×
4143

4144
        defaultFeePerKw, err := shutdownStartFeeRate(
3✔
4145
                shutdown,
3✔
4146
        ).UnwrapOrFuncErr(func() (chainfee.SatPerKWeight, error) {
6✔
4147
                return p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
4148
                        p.cfg.CoopCloseTargetConfs,
3✔
4149
                )
3✔
4150
        })
3✔
4151
        if err != nil {
3✔
4152
                return fmt.Errorf("unable to estimate fee: %w", err)
×
4153
        }
×
4154

4155
        chanCloser.WhenRight(func(rbfCloser *chancloser.RbfChanCloser) {
6✔
4156
                peerLog.Infof("ChannelPoint(%v): rbf-coop close requested, "+
3✔
4157
                        "sending shutdown", chanPoint)
3✔
4158

3✔
4159
                rbfState, err := rbfCloser.CurrentState()
3✔
4160
                if err != nil {
3✔
4161
                        peerLog.Warnf("ChannelPoint(%v): unable to get "+
×
4162
                                "current state for rbf-coop close: %v",
×
4163
                                chanPoint, err)
×
4164

×
4165
                        return
×
4166
                }
×
4167

4168
                coopCloseStates := rbfCloser.RegisterStateEvents()
3✔
4169

3✔
4170
                // Before we send our event below, we'll launch a goroutine to
3✔
4171
                // watch for the final terminal state to send updates to the RPC
3✔
4172
                // client. We only need to do this if there's an RPC caller.
3✔
4173
                var rpcShutdown bool
3✔
4174
                whenRPCShutdown(shutdown, func(req *htlcswitch.ChanClose) {
6✔
4175
                        rpcShutdown = true
3✔
4176

3✔
4177
                        p.cg.WgAdd(1)
3✔
4178
                        go func() {
6✔
4179
                                defer p.cg.WgDone()
3✔
4180

3✔
4181
                                p.observeRbfCloseUpdates(
3✔
4182
                                        rbfCloser, req, coopCloseStates,
3✔
4183
                                )
3✔
4184
                        }()
3✔
4185
                })
4186

4187
                if !rpcShutdown {
6✔
4188
                        defer rbfCloser.RemoveStateSub(coopCloseStates)
3✔
4189
                }
3✔
4190

4191
                ctx, _ := p.cg.Create(context.Background())
3✔
4192
                feeRate := defaultFeePerKw.FeePerVByte()
3✔
4193

3✔
4194
                // Depending on the state of the state machine, we'll either
3✔
4195
                // kick things off by sending shutdown, or attempt to send a new
3✔
4196
                // offer to the remote party.
3✔
4197
                switch rbfState.(type) {
3✔
4198
                // The channel is still active, so we'll now kick off the co-op
4199
                // close process by instructing it to send a shutdown message to
4200
                // the remote party.
4201
                case *chancloser.ChannelActive:
3✔
4202
                        rbfCloser.SendEvent(
3✔
4203
                                context.Background(),
3✔
4204
                                &chancloser.SendShutdown{
3✔
4205
                                        IdealFeeRate: feeRate,
3✔
4206
                                        DeliveryAddr: shutdownStartAddr(
3✔
4207
                                                shutdown,
3✔
4208
                                        ),
3✔
4209
                                },
3✔
4210
                        )
3✔
4211

4212
                // If we haven't yet sent an offer (didn't have enough funds at
4213
                // the prior fee rate), or we've sent an offer, then we'll
4214
                // trigger a new offer event.
4215
                case *chancloser.ClosingNegotiation:
3✔
4216
                        // Before we send the event below, we'll wait until
3✔
4217
                        // we're in a semi-terminal state.
3✔
4218
                        err := waitUntilRbfCoastClear(ctx, rbfCloser)
3✔
4219
                        if err != nil {
3✔
4220
                                peerLog.Warnf("ChannelPoint(%v): unable to "+
×
4221
                                        "wait for coast to clear: %v",
×
4222
                                        chanPoint, err)
×
4223

×
4224
                                return
×
4225
                        }
×
4226

4227
                        event := chancloser.ProtocolEvent(
3✔
4228
                                &chancloser.SendOfferEvent{
3✔
4229
                                        TargetFeeRate: feeRate,
3✔
4230
                                },
3✔
4231
                        )
3✔
4232
                        rbfCloser.SendEvent(ctx, event)
3✔
4233

4234
                default:
×
4235
                        peerLog.Warnf("ChannelPoint(%v): unexpected state "+
×
4236
                                "for rbf-coop close: %T", chanPoint, rbfState)
×
4237
                }
4238
        })
4239

4240
        return nil
3✔
4241
}
4242

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

10✔
4248
        channel, ok := p.activeChannels.Load(chanID)
10✔
4249

10✔
4250
        // Though this function can't be called for pending channels, we still
10✔
4251
        // check whether channel is nil for safety.
10✔
4252
        if !ok || channel == nil {
10✔
4253
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
×
4254
                        "unknown", chanID)
×
4255
                p.log.Errorf(err.Error())
×
4256
                req.Err <- err
×
4257
                return
×
4258
        }
×
4259

4260
        isTaprootChan := channel.ChanType().IsTaproot()
10✔
4261

10✔
4262
        switch req.CloseType {
10✔
4263
        // A type of CloseRegular indicates that the user has opted to close
4264
        // out this channel on-chain, so we execute the cooperative channel
4265
        // closure workflow.
4266
        case contractcourt.CloseRegular:
10✔
4267
                var err error
10✔
4268
                switch {
10✔
4269
                // If this is the RBF coop state machine, then we'll instruct
4270
                // it to send the shutdown message. This also might be an RBF
4271
                // iteration, in which case we'll be obtaining a new
4272
                // transaction w/ a higher fee rate.
4273
                //
4274
                // We don't support this close type for taproot channels yet
4275
                // however.
4276
                case !isTaprootChan && p.rbfCoopCloseAllowed():
3✔
4277
                        err = p.startRbfChanCloser(
3✔
4278
                                newRPCShutdownInit(req), channel.ChannelPoint(),
3✔
4279
                        )
3✔
4280
                default:
10✔
4281
                        err = p.initNegotiateChanCloser(req, channel)
10✔
4282
                }
4283

4284
                if err != nil {
11✔
4285
                        p.log.Errorf(err.Error())
1✔
4286
                        req.Err <- err
1✔
4287
                }
1✔
4288

4289
        // A type of CloseBreach indicates that the counterparty has breached
4290
        // the channel therefore we need to clean up our local state.
4291
        case contractcourt.CloseBreach:
×
4292
                // TODO(roasbeef): no longer need with newer beach logic?
×
4293
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
×
4294
                        "channel", req.ChanPoint)
×
4295
                p.WipeChannel(req.ChanPoint)
×
4296
        }
4297
}
4298

4299
// linkFailureReport is sent to the channelManager whenever a link reports a
4300
// link failure, and is forced to exit. The report houses the necessary
4301
// information to clean up the channel state, send back the error message, and
4302
// force close if necessary.
4303
type linkFailureReport struct {
4304
        chanPoint   wire.OutPoint
4305
        chanID      lnwire.ChannelID
4306
        shortChanID lnwire.ShortChannelID
4307
        linkErr     htlcswitch.LinkFailureError
4308
}
4309

4310
// handleLinkFailure processes a link failure report when a link in the switch
4311
// fails. It facilitates the removal of all channel state within the peer,
4312
// force closing the channel depending on severity, and sending the error
4313
// message back to the remote party.
4314
func (p *Brontide) handleLinkFailure(failure linkFailureReport) {
3✔
4315
        // Retrieve the channel from the map of active channels. We do this to
3✔
4316
        // have access to it even after WipeChannel remove it from the map.
3✔
4317
        chanID := lnwire.NewChanIDFromOutPoint(failure.chanPoint)
3✔
4318
        lnChan, _ := p.activeChannels.Load(chanID)
3✔
4319

3✔
4320
        // We begin by wiping the link, which will remove it from the switch,
3✔
4321
        // such that it won't be attempted used for any more updates.
3✔
4322
        //
3✔
4323
        // TODO(halseth): should introduce a way to atomically stop/pause the
3✔
4324
        // link and cancel back any adds in its mailboxes such that we can
3✔
4325
        // safely force close without the link being added again and updates
3✔
4326
        // being applied.
3✔
4327
        p.WipeChannel(&failure.chanPoint)
3✔
4328

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

3✔
4334
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
3✔
4335
                        failure.chanPoint,
3✔
4336
                )
3✔
4337
                if err != nil {
6✔
4338
                        p.log.Errorf("unable to force close "+
3✔
4339
                                "link(%v): %v", failure.shortChanID, err)
3✔
4340
                } else {
6✔
4341
                        p.log.Infof("channel(%v) force "+
3✔
4342
                                "closed with txid %v",
3✔
4343
                                failure.shortChanID, closeTx.TxHash())
3✔
4344
                }
3✔
4345
        }
4346

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

×
4352
                if err := lnChan.State().MarkBorked(); err != nil {
×
4353
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
4354
                                failure.shortChanID, err)
×
4355
                }
×
4356
        }
4357

4358
        // Send an error to the peer, why we failed the channel.
4359
        if failure.linkErr.ShouldSendToPeer() {
6✔
4360
                // If SendData is set, send it to the peer. If not, we'll use
3✔
4361
                // the standard error messages in the payload. We only include
3✔
4362
                // sendData in the cases where the error data does not contain
3✔
4363
                // sensitive information.
3✔
4364
                data := []byte(failure.linkErr.Error())
3✔
4365
                if failure.linkErr.SendData != nil {
3✔
4366
                        data = failure.linkErr.SendData
×
4367
                }
×
4368

4369
                var networkMsg lnwire.Message
3✔
4370
                if failure.linkErr.Warning {
3✔
4371
                        networkMsg = &lnwire.Warning{
×
4372
                                ChanID: failure.chanID,
×
4373
                                Data:   data,
×
4374
                        }
×
4375
                } else {
3✔
4376
                        networkMsg = &lnwire.Error{
3✔
4377
                                ChanID: failure.chanID,
3✔
4378
                                Data:   data,
3✔
4379
                        }
3✔
4380
                }
3✔
4381

4382
                err := p.SendMessage(true, networkMsg)
3✔
4383
                if err != nil {
3✔
4384
                        p.log.Errorf("unable to send msg to "+
×
4385
                                "remote peer: %v", err)
×
4386
                }
×
4387
        }
4388

4389
        // If the failure action is disconnect, then we'll execute that now. If
4390
        // we had to send an error above, it was a sync call, so we expect the
4391
        // message to be flushed on the wire by now.
4392
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
3✔
4393
                p.Disconnect(fmt.Errorf("link requested disconnect"))
×
4394
        }
×
4395
}
4396

4397
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
4398
// public key and the channel id.
4399
func (p *Brontide) fetchLinkFromKeyAndCid(
4400
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
22✔
4401

22✔
4402
        var chanLink htlcswitch.ChannelUpdateHandler
22✔
4403

22✔
4404
        // We don't need to check the error here, and can instead just loop
22✔
4405
        // over the slice and return nil.
22✔
4406
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
22✔
4407
        for _, link := range links {
43✔
4408
                if link.ChanID() == cid {
42✔
4409
                        chanLink = link
21✔
4410
                        break
21✔
4411
                }
4412
        }
4413

4414
        return chanLink
22✔
4415
}
4416

4417
// finalizeChanClosure performs the final clean up steps once the cooperative
4418
// closure transaction has been fully broadcast. The finalized closing state
4419
// machine should be passed in. Once the transaction has been sufficiently
4420
// confirmed, the channel will be marked as fully closed within the database,
4421
// and any clients will be notified of updates to the closing state.
4422
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
7✔
4423
        closeReq := chanCloser.CloseRequest()
7✔
4424

7✔
4425
        // First, we'll clear all indexes related to the channel in question.
7✔
4426
        chanPoint := chanCloser.Channel().ChannelPoint()
7✔
4427
        p.WipeChannel(&chanPoint)
7✔
4428

7✔
4429
        // Also clear the activeChanCloses map of this channel.
7✔
4430
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
7✔
4431
        p.activeChanCloses.Delete(cid) // TODO(roasbeef): existing race
7✔
4432

7✔
4433
        // Next, we'll launch a goroutine which will request to be notified by
7✔
4434
        // the ChainNotifier once the closure transaction obtains a single
7✔
4435
        // confirmation.
7✔
4436
        notifier := p.cfg.ChainNotifier
7✔
4437

7✔
4438
        // If any error happens during waitForChanToClose, forward it to
7✔
4439
        // closeReq. If this channel closure is not locally initiated, closeReq
7✔
4440
        // will be nil, so just ignore the error.
7✔
4441
        errChan := make(chan error, 1)
7✔
4442
        if closeReq != nil {
12✔
4443
                errChan = closeReq.Err
5✔
4444
        }
5✔
4445

4446
        closingTx, err := chanCloser.ClosingTx()
7✔
4447
        if err != nil {
7✔
4448
                if closeReq != nil {
×
4449
                        p.log.Error(err)
×
4450
                        closeReq.Err <- err
×
4451
                }
×
4452
        }
4453

4454
        closingTxid := closingTx.TxHash()
7✔
4455

7✔
4456
        // If this is a locally requested shutdown, update the caller with a
7✔
4457
        // new event detailing the current pending state of this request.
7✔
4458
        if closeReq != nil {
12✔
4459
                closeReq.Updates <- &PendingUpdate{
5✔
4460
                        Txid: closingTxid[:],
5✔
4461
                }
5✔
4462
        }
5✔
4463

4464
        localOut := chanCloser.LocalCloseOutput()
7✔
4465
        remoteOut := chanCloser.RemoteCloseOutput()
7✔
4466
        auxOut := chanCloser.AuxOutputs()
7✔
4467
        go WaitForChanToClose(
7✔
4468
                chanCloser.NegotiationHeight(), notifier, errChan,
7✔
4469
                &chanPoint, &closingTxid, closingTx.TxOut[0].PkScript, func() {
14✔
4470
                        // Respond to the local subsystem which requested the
7✔
4471
                        // channel closure.
7✔
4472
                        if closeReq != nil {
12✔
4473
                                closeReq.Updates <- &ChannelCloseUpdate{
5✔
4474
                                        ClosingTxid:       closingTxid[:],
5✔
4475
                                        Success:           true,
5✔
4476
                                        LocalCloseOutput:  localOut,
5✔
4477
                                        RemoteCloseOutput: remoteOut,
5✔
4478
                                        AuxOutputs:        auxOut,
5✔
4479
                                }
5✔
4480
                        }
5✔
4481
                },
4482
        )
4483
}
4484

4485
// WaitForChanToClose uses the passed notifier to wait until the channel has
4486
// been detected as closed on chain and then concludes by executing the
4487
// following actions: the channel point will be sent over the settleChan, and
4488
// finally the callback will be executed. If any error is encountered within
4489
// the function, then it will be sent over the errChan.
4490
func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
4491
        errChan chan error, chanPoint *wire.OutPoint,
4492
        closingTxID *chainhash.Hash, closeScript []byte, cb func()) {
7✔
4493

7✔
4494
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
7✔
4495
                "with txid: %v", chanPoint, closingTxID)
7✔
4496

7✔
4497
        // TODO(roasbeef): add param for num needed confs
7✔
4498
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
7✔
4499
                closingTxID, closeScript, 1, bestHeight,
7✔
4500
        )
7✔
4501
        if err != nil {
7✔
4502
                if errChan != nil {
×
4503
                        errChan <- err
×
4504
                }
×
4505
                return
×
4506
        }
4507

4508
        // In the case that the ChainNotifier is shutting down, all subscriber
4509
        // notification channels will be closed, generating a nil receive.
4510
        height, ok := <-confNtfn.Confirmed
7✔
4511
        if !ok {
10✔
4512
                return
3✔
4513
        }
3✔
4514

4515
        // The channel has been closed, remove it from any active indexes, and
4516
        // the database state.
4517
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
7✔
4518
                "height %v", chanPoint, height.BlockHeight)
7✔
4519

7✔
4520
        // Finally, execute the closure call back to mark the confirmation of
7✔
4521
        // the transaction closing the contract.
7✔
4522
        cb()
7✔
4523
}
4524

4525
// WipeChannel removes the passed channel point from all indexes associated with
4526
// the peer and the switch.
4527
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
7✔
4528
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
7✔
4529

7✔
4530
        p.activeChannels.Delete(chanID)
7✔
4531

7✔
4532
        // Instruct the HtlcSwitch to close this link as the channel is no
7✔
4533
        // longer active.
7✔
4534
        p.cfg.Switch.RemoveLink(chanID)
7✔
4535
}
7✔
4536

4537
// handleInitMsg handles the incoming init message which contains global and
4538
// local feature vectors. If feature vectors are incompatible then disconnect.
4539
func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
6✔
4540
        // First, merge any features from the legacy global features field into
6✔
4541
        // those presented in the local features fields.
6✔
4542
        err := msg.Features.Merge(msg.GlobalFeatures)
6✔
4543
        if err != nil {
6✔
4544
                return fmt.Errorf("unable to merge legacy global features: %w",
×
4545
                        err)
×
4546
        }
×
4547

4548
        // Then, finalize the remote feature vector providing the flattened
4549
        // feature bit namespace.
4550
        p.remoteFeatures = lnwire.NewFeatureVector(
6✔
4551
                msg.Features, lnwire.Features,
6✔
4552
        )
6✔
4553

6✔
4554
        // Now that we have their features loaded, we'll ensure that they
6✔
4555
        // didn't set any required bits that we don't know of.
6✔
4556
        err = feature.ValidateRequired(p.remoteFeatures)
6✔
4557
        if err != nil {
6✔
4558
                return fmt.Errorf("invalid remote features: %w", err)
×
4559
        }
×
4560

4561
        // Ensure the remote party's feature vector contains all transitive
4562
        // dependencies. We know ours are correct since they are validated
4563
        // during the feature manager's instantiation.
4564
        err = feature.ValidateDeps(p.remoteFeatures)
6✔
4565
        if err != nil {
6✔
4566
                return fmt.Errorf("invalid remote features: %w", err)
×
4567
        }
×
4568

4569
        // Now that we know we understand their requirements, we'll check to
4570
        // see if they don't support anything that we deem to be mandatory.
4571
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
6✔
4572
                return fmt.Errorf("data loss protection required")
×
4573
        }
×
4574

4575
        // If we have an AuxChannelNegotiator and the peer sent aux features,
4576
        // process them.
4577
        p.cfg.AuxChannelNegotiator.WhenSome(
6✔
4578
                func(acn lnwallet.AuxChannelNegotiator) {
6✔
4579
                        err = acn.ProcessInitRecords(
×
4580
                                p.cfg.PubKeyBytes, msg.CustomRecords.Copy(),
×
4581
                        )
×
4582
                },
×
4583
        )
4584
        if err != nil {
6✔
4585
                return fmt.Errorf("could not process init records: %w", err)
×
4586
        }
×
4587

4588
        return nil
6✔
4589
}
4590

4591
// LocalFeatures returns the set of global features that has been advertised by
4592
// the local node. This allows sub-systems that use this interface to gate their
4593
// behavior off the set of negotiated feature bits.
4594
//
4595
// NOTE: Part of the lnpeer.Peer interface.
4596
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
3✔
4597
        return p.cfg.Features
3✔
4598
}
3✔
4599

4600
// RemoteFeatures returns the set of global features that has been advertised by
4601
// the remote node. This allows sub-systems that use this interface to gate
4602
// their behavior off the set of negotiated feature bits.
4603
//
4604
// NOTE: Part of the lnpeer.Peer interface.
4605
func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector {
23✔
4606
        return p.remoteFeatures
23✔
4607
}
23✔
4608

4609
// hasNegotiatedScidAlias returns true if we've negotiated the
4610
// option-scid-alias feature bit with the peer.
4611
func (p *Brontide) hasNegotiatedScidAlias() bool {
6✔
4612
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
6✔
4613
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
6✔
4614
        return peerHas && localHas
6✔
4615
}
6✔
4616

4617
// sendInitMsg sends the Init message to the remote peer. This message contains
4618
// our currently supported local and global features.
4619
func (p *Brontide) sendInitMsg(legacyChan bool) error {
10✔
4620
        features := p.cfg.Features.Clone()
10✔
4621
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
10✔
4622

10✔
4623
        // If we have a legacy channel open with a peer, we downgrade static
10✔
4624
        // remote required to optional in case the peer does not understand the
10✔
4625
        // required feature bit. If we do not do this, the peer will reject our
10✔
4626
        // connection because it does not understand a required feature bit, and
10✔
4627
        // our channel will be unusable.
10✔
4628
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
11✔
4629
                p.log.Infof("Legacy channel open with peer, " +
1✔
4630
                        "downgrading static remote required feature bit to " +
1✔
4631
                        "optional")
1✔
4632

1✔
4633
                // Unset and set in both the local and global features to
1✔
4634
                // ensure both sets are consistent and merge able by old and
1✔
4635
                // new nodes.
1✔
4636
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4637
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
4638

1✔
4639
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
4640
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
4641
        }
1✔
4642

4643
        msg := lnwire.NewInitMessage(
10✔
4644
                legacyFeatures.RawFeatureVector,
10✔
4645
                features.RawFeatureVector,
10✔
4646
        )
10✔
4647

10✔
4648
        var err error
10✔
4649

10✔
4650
        // If we have an AuxChannelNegotiator, get custom feature bits to
10✔
4651
        // include in the init message.
10✔
4652
        p.cfg.AuxChannelNegotiator.WhenSome(
10✔
4653
                func(negotiator lnwallet.AuxChannelNegotiator) {
10✔
4654
                        var auxRecords lnwire.CustomRecords
×
4655
                        auxRecords, err = negotiator.GetInitRecords(
×
4656
                                p.cfg.PubKeyBytes,
×
4657
                        )
×
4658
                        if err != nil {
×
4659
                                p.log.Warnf("Failed to get aux init features: "+
×
4660
                                        "%v", err)
×
4661
                                return
×
4662
                        }
×
4663

4664
                        mergedRecs := msg.CustomRecords.MergedCopy(auxRecords)
×
4665
                        msg.CustomRecords = mergedRecs
×
4666
                },
4667
        )
4668
        if err != nil {
10✔
4669
                return err
×
4670
        }
×
4671

4672
        return p.writeMessage(msg)
10✔
4673
}
4674

4675
// resendChanSyncMsg will attempt to find a channel sync message for the closed
4676
// channel and resend it to our peer.
4677
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
3✔
4678
        // If we already re-sent the mssage for this channel, we won't do it
3✔
4679
        // again.
3✔
4680
        if _, ok := p.resentChanSyncMsg[cid]; ok {
5✔
4681
                return nil
2✔
4682
        }
2✔
4683

4684
        // Check if we have any channel sync messages stored for this channel.
4685
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
3✔
4686
        if err != nil {
6✔
4687
                return fmt.Errorf("unable to fetch channel sync messages for "+
3✔
4688
                        "peer %v: %v", p, err)
3✔
4689
        }
3✔
4690

4691
        if c.LastChanSyncMsg == nil {
3✔
4692
                return fmt.Errorf("no chan sync message stored for channel %v",
×
4693
                        cid)
×
4694
        }
×
4695

4696
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
3✔
4697
                return fmt.Errorf("ignoring channel reestablish from "+
×
4698
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
4699
        }
×
4700

4701
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
3✔
4702
                "peer", cid)
3✔
4703

3✔
4704
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
3✔
4705
                return fmt.Errorf("failed resending channel sync "+
×
4706
                        "message to peer %v: %v", p, err)
×
4707
        }
×
4708

4709
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
3✔
4710
                cid)
3✔
4711

3✔
4712
        // Note down that we sent the message, so we won't resend it again for
3✔
4713
        // this connection.
3✔
4714
        p.resentChanSyncMsg[cid] = struct{}{}
3✔
4715

3✔
4716
        return nil
3✔
4717
}
4718

4719
// SendMessage sends a variadic number of high-priority messages to the remote
4720
// peer. The first argument denotes if the method should block until the
4721
// messages have been sent to the remote peer or an error is returned,
4722
// otherwise it returns immediately after queuing.
4723
//
4724
// NOTE: Part of the lnpeer.Peer interface.
4725
func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error {
6✔
4726
        return p.sendMessage(sync, true, msgs...)
6✔
4727
}
6✔
4728

4729
// SendMessageLazy sends a variadic number of low-priority messages to the
4730
// remote peer. The first argument denotes if the method should block until
4731
// the messages have been sent to the remote peer or an error is returned,
4732
// otherwise it returns immediately after queueing.
4733
//
4734
// NOTE: Part of the lnpeer.Peer interface.
4735
func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
4✔
4736
        return p.sendMessage(sync, false, msgs...)
4✔
4737
}
4✔
4738

4739
// sendMessage queues a variadic number of messages using the passed priority
4740
// to the remote peer. If sync is true, this method will block until the
4741
// messages have been sent to the remote peer or an error is returned, otherwise
4742
// it returns immediately after queueing.
4743
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
7✔
4744
        // Add all incoming messages to the outgoing queue. A list of error
7✔
4745
        // chans is populated for each message if the caller requested a sync
7✔
4746
        // send.
7✔
4747
        var errChans []chan error
7✔
4748
        if sync {
11✔
4749
                errChans = make([]chan error, 0, len(msgs))
4✔
4750
        }
4✔
4751
        for _, msg := range msgs {
14✔
4752
                // If a sync send was requested, create an error chan to listen
7✔
4753
                // for an ack from the writeHandler.
7✔
4754
                var errChan chan error
7✔
4755
                if sync {
11✔
4756
                        errChan = make(chan error, 1)
4✔
4757
                        errChans = append(errChans, errChan)
4✔
4758
                }
4✔
4759

4760
                if priority {
13✔
4761
                        p.queueMsg(msg, errChan)
6✔
4762
                } else {
10✔
4763
                        p.queueMsgLazy(msg, errChan)
4✔
4764
                }
4✔
4765
        }
4766

4767
        // Wait for all replies from the writeHandler. For async sends, this
4768
        // will be a NOP as the list of error chans is nil.
4769
        for _, errChan := range errChans {
11✔
4770
                select {
4✔
4771
                case err := <-errChan:
4✔
4772
                        return err
4✔
4773
                case <-p.cg.Done():
×
4774
                        return lnpeer.ErrPeerExiting
×
4775
                case <-p.cfg.Quit:
×
4776
                        return lnpeer.ErrPeerExiting
×
4777
                }
4778
        }
4779

4780
        return nil
6✔
4781
}
4782

4783
// PubKey returns the pubkey of the peer in compressed serialized format.
4784
//
4785
// NOTE: Part of the lnpeer.Peer interface.
4786
func (p *Brontide) PubKey() [33]byte {
5✔
4787
        return p.cfg.PubKeyBytes
5✔
4788
}
5✔
4789

4790
// IdentityKey returns the public key of the remote peer.
4791
//
4792
// NOTE: Part of the lnpeer.Peer interface.
4793
func (p *Brontide) IdentityKey() *btcec.PublicKey {
18✔
4794
        return p.cfg.Addr.IdentityKey
18✔
4795
}
18✔
4796

4797
// Address returns the network address of the remote peer.
4798
//
4799
// NOTE: Part of the lnpeer.Peer interface.
4800
func (p *Brontide) Address() net.Addr {
3✔
4801
        return p.cfg.Addr.Address
3✔
4802
}
3✔
4803

4804
// AddNewChannel adds a new channel to the peer. The channel should fail to be
4805
// added if the cancel channel is closed.
4806
//
4807
// NOTE: Part of the lnpeer.Peer interface.
4808
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
4809
        cancel <-chan struct{}) error {
3✔
4810

3✔
4811
        errChan := make(chan error, 1)
3✔
4812
        newChanMsg := &newChannelMsg{
3✔
4813
                channel: newChan,
3✔
4814
                err:     errChan,
3✔
4815
        }
3✔
4816

3✔
4817
        select {
3✔
4818
        case p.newActiveChannel <- newChanMsg:
3✔
4819
        case <-cancel:
×
4820
                return errors.New("canceled adding new channel")
×
4821
        case <-p.cg.Done():
×
4822
                return lnpeer.ErrPeerExiting
×
4823
        }
4824

4825
        // We pause here to wait for the peer to recognize the new channel
4826
        // before we close the channel barrier corresponding to the channel.
4827
        select {
3✔
4828
        case err := <-errChan:
3✔
4829
                return err
3✔
4830
        case <-p.cg.Done():
×
4831
                return lnpeer.ErrPeerExiting
×
4832
        }
4833
}
4834

4835
// AddPendingChannel adds a pending open channel to the peer. The channel
4836
// should fail to be added if the cancel channel is closed.
4837
//
4838
// NOTE: Part of the lnpeer.Peer interface.
4839
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
4840
        cancel <-chan struct{}) error {
3✔
4841

3✔
4842
        errChan := make(chan error, 1)
3✔
4843
        newChanMsg := &newChannelMsg{
3✔
4844
                channelID: cid,
3✔
4845
                err:       errChan,
3✔
4846
        }
3✔
4847

3✔
4848
        select {
3✔
4849
        case p.newPendingChannel <- newChanMsg:
3✔
4850

4851
        case <-cancel:
×
4852
                return errors.New("canceled adding pending channel")
×
4853

4854
        case <-p.cg.Done():
×
4855
                return lnpeer.ErrPeerExiting
×
4856
        }
4857

4858
        // We pause here to wait for the peer to recognize the new pending
4859
        // channel before we close the channel barrier corresponding to the
4860
        // channel.
4861
        select {
3✔
4862
        case err := <-errChan:
3✔
4863
                return err
3✔
4864

4865
        case <-cancel:
×
4866
                return errors.New("canceled adding pending channel")
×
4867

4868
        case <-p.cg.Done():
×
4869
                return lnpeer.ErrPeerExiting
×
4870
        }
4871
}
4872

4873
// RemovePendingChannel removes a pending open channel from the peer.
4874
//
4875
// NOTE: Part of the lnpeer.Peer interface.
4876
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
3✔
4877
        errChan := make(chan error, 1)
3✔
4878
        newChanMsg := &newChannelMsg{
3✔
4879
                channelID: cid,
3✔
4880
                err:       errChan,
3✔
4881
        }
3✔
4882

3✔
4883
        select {
3✔
4884
        case p.removePendingChannel <- newChanMsg:
3✔
4885
        case <-p.cg.Done():
×
4886
                return lnpeer.ErrPeerExiting
×
4887
        }
4888

4889
        // We pause here to wait for the peer to respond to the cancellation of
4890
        // the pending channel before we close the channel barrier
4891
        // corresponding to the channel.
4892
        select {
3✔
4893
        case err := <-errChan:
3✔
4894
                return err
3✔
4895

4896
        case <-p.cg.Done():
×
4897
                return lnpeer.ErrPeerExiting
×
4898
        }
4899
}
4900

4901
// StartTime returns the time at which the connection was established if the
4902
// peer started successfully, and zero otherwise.
4903
func (p *Brontide) StartTime() time.Time {
3✔
4904
        return p.startTime
3✔
4905
}
3✔
4906

4907
// handleCloseMsg is called when a new cooperative channel closure related
4908
// message is received from the remote peer. We'll use this message to advance
4909
// the chan closer state machine.
4910
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
16✔
4911
        link := p.fetchLinkFromKeyAndCid(msg.cid)
16✔
4912

16✔
4913
        // We'll now fetch the matching closing state machine in order to
16✔
4914
        // continue, or finalize the channel closure process.
16✔
4915
        chanCloserE, err := p.fetchActiveChanCloser(msg.cid)
16✔
4916
        if err != nil {
19✔
4917
                // If the channel is not known to us, we'll simply ignore this
3✔
4918
                // message.
3✔
4919
                if err == ErrChannelNotFound {
6✔
4920
                        return
3✔
4921
                }
3✔
4922

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

×
4925
                errMsg := &lnwire.Error{
×
4926
                        ChanID: msg.cid,
×
4927
                        Data:   lnwire.ErrorData(err.Error()),
×
4928
                }
×
4929
                p.queueMsg(errMsg, nil)
×
4930
                return
×
4931
        }
4932

4933
        if chanCloserE.IsRight() {
16✔
4934
                // TODO(roasbeef): assert?
×
4935
                return
×
4936
        }
×
4937

4938
        // At this point, we'll only enter this call path if a negotiate chan
4939
        // closer was used. So we'll extract that from the either now.
4940
        //
4941
        // TODO(roabeef): need extra helper func for either to make cleaner
4942
        var chanCloser *chancloser.ChanCloser
16✔
4943
        chanCloserE.WhenLeft(func(c *chancloser.ChanCloser) {
32✔
4944
                chanCloser = c
16✔
4945
        })
16✔
4946

4947
        handleErr := func(err error) {
17✔
4948
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
4949
                p.log.Error(err)
1✔
4950

1✔
4951
                // As the negotiations failed, we'll reset the channel state
1✔
4952
                // machine to ensure we act to on-chain events as normal.
1✔
4953
                chanCloser.Channel().ResetState()
1✔
4954
                if chanCloser.CloseRequest() != nil {
1✔
4955
                        chanCloser.CloseRequest().Err <- err
×
4956
                }
×
4957

4958
                p.activeChanCloses.Delete(msg.cid)
1✔
4959

1✔
4960
                p.Disconnect(err)
1✔
4961
        }
4962

4963
        // Next, we'll process the next message using the target state machine.
4964
        // We'll either continue negotiation, or halt.
4965
        switch typed := msg.msg.(type) {
16✔
4966
        case *lnwire.Shutdown:
8✔
4967
                // Disable incoming adds immediately.
8✔
4968
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
8✔
4969
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
4970
                                link.ChanID())
×
4971
                }
×
4972

4973
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
8✔
4974
                if err != nil {
8✔
4975
                        handleErr(err)
×
4976
                        return
×
4977
                }
×
4978

4979
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
14✔
4980
                        // If the link is nil it means we can immediately queue
6✔
4981
                        // the Shutdown message since we don't have to wait for
6✔
4982
                        // commitment transaction synchronization.
6✔
4983
                        if link == nil {
7✔
4984
                                p.queueMsg(&msg, nil)
1✔
4985
                                return
1✔
4986
                        }
1✔
4987

4988
                        // Immediately disallow any new HTLC's from being added
4989
                        // in the outgoing direction.
4990
                        if !link.DisableAdds(htlcswitch.Outgoing) {
5✔
4991
                                p.log.Warnf("Outgoing link adds already "+
×
4992
                                        "disabled: %v", link.ChanID())
×
4993
                        }
×
4994

4995
                        // When we have a Shutdown to send, we defer it till the
4996
                        // next time we send a CommitSig to remain spec
4997
                        // compliant.
4998
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
10✔
4999
                                p.queueMsg(&msg, nil)
5✔
5000
                        })
5✔
5001
                })
5002

5003
                beginNegotiation := func() {
16✔
5004
                        oClosingSigned, err := chanCloser.BeginNegotiation()
8✔
5005
                        if err != nil {
8✔
5006
                                handleErr(err)
×
5007
                                return
×
5008
                        }
×
5009

5010
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
16✔
5011
                                p.queueMsg(&msg, nil)
8✔
5012
                        })
8✔
5013
                }
5014

5015
                if link == nil {
9✔
5016
                        beginNegotiation()
1✔
5017
                } else {
8✔
5018
                        // Now we register a flush hook to advance the
7✔
5019
                        // ChanCloser and possibly send out a ClosingSigned
7✔
5020
                        // when the link finishes draining.
7✔
5021
                        link.OnFlushedOnce(func() {
14✔
5022
                                // Remove link in goroutine to prevent deadlock.
7✔
5023
                                go p.cfg.Switch.RemoveLink(msg.cid)
7✔
5024
                                beginNegotiation()
7✔
5025
                        })
7✔
5026
                }
5027

5028
        case *lnwire.ClosingSigned:
11✔
5029
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
11✔
5030
                if err != nil {
12✔
5031
                        handleErr(err)
1✔
5032
                        return
1✔
5033
                }
1✔
5034

5035
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
22✔
5036
                        p.queueMsg(&msg, nil)
11✔
5037
                })
11✔
5038

5039
        default:
×
5040
                panic("impossible closeMsg type")
×
5041
        }
5042

5043
        // If we haven't finished close negotiations, then we'll continue as we
5044
        // can't yet finalize the closure.
5045
        if _, err := chanCloser.ClosingTx(); err != nil {
26✔
5046
                return
11✔
5047
        }
11✔
5048

5049
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
5050
        // the channel closure by notifying relevant sub-systems and launching a
5051
        // goroutine to wait for close tx conf.
5052
        p.finalizeChanClosure(chanCloser)
7✔
5053
}
5054

5055
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
5056
// the channelManager goroutine, which will shut down the link and possibly
5057
// close the channel.
5058
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
3✔
5059
        select {
3✔
5060
        case p.localCloseChanReqs <- req:
3✔
5061
                p.log.Info("Local close channel request is going to be " +
3✔
5062
                        "delivered to the peer")
3✔
5063
        case <-p.cg.Done():
×
5064
                p.log.Info("Unable to deliver local close channel request " +
×
5065
                        "to peer")
×
5066
        }
5067
}
5068

5069
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
5070
func (p *Brontide) NetAddress() *lnwire.NetAddress {
3✔
5071
        return p.cfg.Addr
3✔
5072
}
3✔
5073

5074
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
5075
func (p *Brontide) Inbound() bool {
3✔
5076
        return p.cfg.Inbound
3✔
5077
}
3✔
5078

5079
// ConnReq is a getter for the Brontide's connReq in cfg.
5080
func (p *Brontide) ConnReq() *connmgr.ConnReq {
3✔
5081
        return p.cfg.ConnReq
3✔
5082
}
3✔
5083

5084
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
5085
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
3✔
5086
        return p.cfg.ErrorBuffer
3✔
5087
}
3✔
5088

5089
// SetAddress sets the remote peer's address given an address.
5090
func (p *Brontide) SetAddress(address net.Addr) {
×
5091
        p.cfg.Addr.Address = address
×
5092
}
×
5093

5094
// ActiveSignal returns the peer's active signal.
5095
func (p *Brontide) ActiveSignal() chan struct{} {
3✔
5096
        return p.activeSignal
3✔
5097
}
3✔
5098

5099
// Conn returns a pointer to the peer's connection struct.
5100
func (p *Brontide) Conn() net.Conn {
3✔
5101
        return p.cfg.Conn
3✔
5102
}
3✔
5103

5104
// BytesReceived returns the number of bytes received from the peer.
5105
func (p *Brontide) BytesReceived() uint64 {
3✔
5106
        return atomic.LoadUint64(&p.bytesReceived)
3✔
5107
}
3✔
5108

5109
// BytesSent returns the number of bytes sent to the peer.
5110
func (p *Brontide) BytesSent() uint64 {
3✔
5111
        return atomic.LoadUint64(&p.bytesSent)
3✔
5112
}
3✔
5113

5114
// LastRemotePingPayload returns the last payload the remote party sent as part
5115
// of their ping.
5116
func (p *Brontide) LastRemotePingPayload() []byte {
3✔
5117
        pingPayload := p.lastPingPayload.Load()
3✔
5118
        if pingPayload == nil {
6✔
5119
                return []byte{}
3✔
5120
        }
3✔
5121

5122
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
5123
        if !ok {
×
5124
                return nil
×
5125
        }
×
5126

5127
        return pingBytes
×
5128
}
5129

5130
// attachChannelEventSubscription creates a channel event subscription and
5131
// attaches to client to Brontide if the reenableTimeout is no greater than 1
5132
// minute.
5133
func (p *Brontide) attachChannelEventSubscription() error {
6✔
5134
        // If the timeout is greater than 1 minute, it's unlikely that the link
6✔
5135
        // hasn't yet finished its reestablishment. Return a nil without
6✔
5136
        // creating the client to specify that we don't want to retry.
6✔
5137
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
9✔
5138
                return nil
3✔
5139
        }
3✔
5140

5141
        // When the reenable timeout is less than 1 minute, it's likely the
5142
        // channel link hasn't finished its reestablishment yet. In that case,
5143
        // we'll give it a second chance by subscribing to the channel update
5144
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
5145
        // enabling the channel again.
5146
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
6✔
5147
        if err != nil {
6✔
5148
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
5149
        }
×
5150

5151
        p.channelEventClient = sub
6✔
5152

6✔
5153
        return nil
6✔
5154
}
5155

5156
// updateNextRevocation updates the existing channel's next revocation if it's
5157
// nil.
5158
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
6✔
5159
        chanPoint := c.FundingOutpoint
6✔
5160
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
6✔
5161

6✔
5162
        // Read the current channel.
6✔
5163
        currentChan, loaded := p.activeChannels.Load(chanID)
6✔
5164

6✔
5165
        // currentChan should exist, but we perform a check anyway to avoid nil
6✔
5166
        // pointer dereference.
6✔
5167
        if !loaded {
7✔
5168
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
5169
                        chanID)
1✔
5170
        }
1✔
5171

5172
        // currentChan should not be nil, but we perform a check anyway to
5173
        // avoid nil pointer dereference.
5174
        if currentChan == nil {
6✔
5175
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
5176
                        chanID)
1✔
5177
        }
1✔
5178

5179
        // If we're being sent a new channel, and our existing channel doesn't
5180
        // have the next revocation, then we need to update the current
5181
        // existing channel.
5182
        if currentChan.RemoteNextRevocation() != nil {
4✔
5183
                return nil
×
5184
        }
×
5185

5186
        p.log.Infof("Processing retransmitted ChannelReady for "+
4✔
5187
                "ChannelPoint(%v)", chanPoint)
4✔
5188

4✔
5189
        nextRevoke := c.RemoteNextRevocation
4✔
5190

4✔
5191
        err := currentChan.InitNextRevocation(nextRevoke)
4✔
5192
        if err != nil {
4✔
5193
                return fmt.Errorf("unable to init next revocation: %w", err)
×
5194
        }
×
5195

5196
        return nil
4✔
5197
}
5198

5199
// addActiveChannel adds a new active channel to the `activeChannels` map. It
5200
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
5201
// it and assembles it with a channel link.
5202
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
3✔
5203
        chanPoint := c.FundingOutpoint
3✔
5204
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5205

3✔
5206
        // If we've reached this point, there are two possible scenarios.  If
3✔
5207
        // the channel was in the active channels map as nil, then it was
3✔
5208
        // loaded from disk and we need to send reestablish. Else, it was not
3✔
5209
        // loaded from disk and we don't need to send reestablish as this is a
3✔
5210
        // fresh channel.
3✔
5211
        shouldReestablish := p.isLoadedFromDisk(chanID)
3✔
5212

3✔
5213
        chanOpts := c.ChanOpts
3✔
5214
        if shouldReestablish {
6✔
5215
                // If we have to do the reestablish dance for this channel,
3✔
5216
                // ensure that we don't try to call InitRemoteMusigNonces twice
3✔
5217
                // by calling SkipNonceInit.
3✔
5218
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
3✔
5219
        }
3✔
5220

5221
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
3✔
5222
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
5223
        })
×
5224
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
3✔
5225
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
5226
        })
×
5227
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
3✔
5228
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
5229
        })
×
5230

5231
        // If not already active, we'll add this channel to the set of active
5232
        // channels, so we can look it up later easily according to its channel
5233
        // ID.
5234
        lnChan, err := lnwallet.NewLightningChannel(
3✔
5235
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
3✔
5236
        )
3✔
5237
        if err != nil {
3✔
5238
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
5239
        }
×
5240

5241
        // Store the channel in the activeChannels map.
5242
        p.activeChannels.Store(chanID, lnChan)
3✔
5243

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

3✔
5246
        // Next, we'll assemble a ChannelLink along with the necessary items it
3✔
5247
        // needs to function.
3✔
5248
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
3✔
5249
        if err != nil {
3✔
5250
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
5251
                        err)
×
5252
        }
×
5253

5254
        // We'll query the channel DB for the new channel's initial forwarding
5255
        // policies to determine the policy we start out with.
5256
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
3✔
5257
        if err != nil {
3✔
5258
                return fmt.Errorf("unable to query for initial forwarding "+
×
5259
                        "policy: %v", err)
×
5260
        }
×
5261

5262
        // Create the link and add it to the switch.
5263
        err = p.addLink(
3✔
5264
                &chanPoint, lnChan, initialPolicy, chainEvents,
3✔
5265
                shouldReestablish, fn.None[lnwire.Shutdown](),
3✔
5266
        )
3✔
5267
        if err != nil {
3✔
5268
                return fmt.Errorf("can't register new channel link(%v) with "+
×
5269
                        "peer", chanPoint)
×
5270
        }
×
5271

5272
        isTaprootChan := c.ChanType.IsTaproot()
3✔
5273

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

5281
        // Now that the link has been added above, we'll also init an RBF chan
5282
        // closer for this channel, but only if the new close feature is
5283
        // negotiated.
5284
        //
5285
        // Creating this here ensures that any shutdown messages sent will be
5286
        // automatically routed by the msg router.
5287
        if _, err := p.initRbfChanCloser(lnChan); err != nil {
3✔
5288
                p.activeChanCloses.Delete(chanID)
×
5289

×
5290
                return fmt.Errorf("unable to init RBF chan closer for new "+
×
5291
                        "chan: %w", err)
×
5292
        }
×
5293

5294
        return nil
3✔
5295
}
5296

5297
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
5298
// know this channel ID or not, we'll either add it to the `activeChannels` map
5299
// or init the next revocation for it.
5300
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
3✔
5301
        newChan := req.channel
3✔
5302
        chanPoint := newChan.FundingOutpoint
3✔
5303
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5304

3✔
5305
        // Only update RemoteNextRevocation if the channel is in the
3✔
5306
        // activeChannels map and if we added the link to the switch. Only
3✔
5307
        // active channels will be added to the switch.
3✔
5308
        if p.isActiveChannel(chanID) {
6✔
5309
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
3✔
5310
                        chanPoint)
3✔
5311

3✔
5312
                // Handle it and close the err chan on the request.
3✔
5313
                close(req.err)
3✔
5314

3✔
5315
                // Update the next revocation point.
3✔
5316
                err := p.updateNextRevocation(newChan.OpenChannel)
3✔
5317
                if err != nil {
3✔
5318
                        p.log.Errorf(err.Error())
×
5319
                }
×
5320

5321
                return
3✔
5322
        }
5323

5324
        // This is a new channel, we now add it to the map.
5325
        if err := p.addActiveChannel(req.channel); err != nil {
3✔
5326
                // Log and send back the error to the request.
×
5327
                p.log.Errorf(err.Error())
×
5328
                req.err <- err
×
5329

×
5330
                return
×
5331
        }
×
5332

5333
        // Close the err chan if everything went fine.
5334
        close(req.err)
3✔
5335
}
5336

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

7✔
5344
        chanID := req.channelID
7✔
5345

7✔
5346
        // If we already have this channel, something is wrong with the funding
7✔
5347
        // flow as it will only be marked as active after `ChannelReady` is
7✔
5348
        // handled. In this case, we will do nothing but log an error, just in
7✔
5349
        // case this is a legit channel.
7✔
5350
        if p.isActiveChannel(chanID) {
8✔
5351
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
5352
                        "pending channel request", chanID)
1✔
5353

1✔
5354
                return
1✔
5355
        }
1✔
5356

5357
        // The channel has already been added, we will do nothing and return.
5358
        if p.isPendingChannel(chanID) {
7✔
5359
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
5360
                        "pending channel request", chanID)
1✔
5361

1✔
5362
                return
1✔
5363
        }
1✔
5364

5365
        // This is a new channel, we now add it to the map `activeChannels`
5366
        // with nil value and mark it as a newly added channel in
5367
        // `addedChannels`.
5368
        p.activeChannels.Store(chanID, nil)
5✔
5369
        p.addedChannels.Store(chanID, struct{}{})
5✔
5370
}
5371

5372
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
5373
// from `activeChannels` map. The request will be ignored if the channel is
5374
// considered active by Brontide. Noop if the channel ID cannot be found.
5375
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
7✔
5376
        defer close(req.err)
7✔
5377

7✔
5378
        chanID := req.channelID
7✔
5379

7✔
5380
        // If we already have this channel, something is wrong with the funding
7✔
5381
        // flow as it will only be marked as active after `ChannelReady` is
7✔
5382
        // handled. In this case, we will log an error and exit.
7✔
5383
        if p.isActiveChannel(chanID) {
8✔
5384
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
5385
                        chanID)
1✔
5386
                return
1✔
5387
        }
1✔
5388

5389
        // The channel has not been added yet, we will log a warning as there
5390
        // is an unexpected call from funding manager.
5391
        if !p.isPendingChannel(chanID) {
10✔
5392
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
4✔
5393
        }
4✔
5394

5395
        // Remove the record of this pending channel.
5396
        p.activeChannels.Delete(chanID)
6✔
5397
        p.addedChannels.Delete(chanID)
6✔
5398
}
5399

5400
// sendLinkUpdateMsg sends a message that updates the channel to the
5401
// channel's message stream.
5402
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
3✔
5403
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
3✔
5404

3✔
5405
        chanStream, ok := p.activeMsgStreams[cid]
3✔
5406
        if !ok {
6✔
5407
                // If a stream hasn't yet been created, then we'll do so, add
3✔
5408
                // it to the map, and finally start it.
3✔
5409
                chanStream = newChanMsgStream(p, cid)
3✔
5410
                p.activeMsgStreams[cid] = chanStream
3✔
5411
                chanStream.Start()
3✔
5412

3✔
5413
                // Stop the stream when quit.
3✔
5414
                go func() {
6✔
5415
                        <-p.cg.Done()
3✔
5416
                        chanStream.Stop()
3✔
5417
                }()
3✔
5418
        }
5419

5420
        // With the stream obtained, add the message to the stream so we can
5421
        // continue processing message.
5422
        chanStream.AddMsg(msg)
3✔
5423
}
5424

5425
// scaleTimeout multiplies the argument duration by a constant factor depending
5426
// on variious heuristics. Currently this is only used to check whether our peer
5427
// appears to be connected over Tor and relaxes the timout deadline. However,
5428
// this is subject to change and should be treated as opaque.
5429
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
70✔
5430
        if p.isTorConnection {
73✔
5431
                return timeout * time.Duration(torTimeoutMultiplier)
3✔
5432
        }
3✔
5433

5434
        return timeout
67✔
5435
}
5436

5437
// CoopCloseUpdates is a struct used to communicate updates for an active close
5438
// to the caller.
5439
type CoopCloseUpdates struct {
5440
        UpdateChan chan interface{}
5441

5442
        ErrChan chan error
5443
}
5444

5445
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5446
// point has an active RBF chan closer.
5447
func (p *Brontide) ChanHasRbfCoopCloser(chanPoint wire.OutPoint) bool {
3✔
5448
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5449
        chanCloser, found := p.activeChanCloses.Load(chanID)
3✔
5450
        if !found {
6✔
5451
                return false
3✔
5452
        }
3✔
5453

5454
        return chanCloser.IsRight()
3✔
5455
}
5456

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

3✔
5465
        // If RBF coop close isn't permitted, then we'll an error.
3✔
5466
        if !p.rbfCoopCloseAllowed() {
3✔
5467
                return nil, fmt.Errorf("rbf coop close not enabled for " +
×
5468
                        "channel")
×
5469
        }
×
5470

5471
        closeUpdates := &CoopCloseUpdates{
3✔
5472
                UpdateChan: make(chan interface{}, 1),
3✔
5473
                ErrChan:    make(chan error, 1),
3✔
5474
        }
3✔
5475

3✔
5476
        // We'll re-use the existing switch struct here, even though we're
3✔
5477
        // bypassing the switch entirely.
3✔
5478
        closeReq := htlcswitch.ChanClose{
3✔
5479
                CloseType:      contractcourt.CloseRegular,
3✔
5480
                ChanPoint:      &chanPoint,
3✔
5481
                TargetFeePerKw: feeRate,
3✔
5482
                DeliveryScript: deliveryScript,
3✔
5483
                Updates:        closeUpdates.UpdateChan,
3✔
5484
                Err:            closeUpdates.ErrChan,
3✔
5485
                Ctx:            ctx,
3✔
5486
        }
3✔
5487

3✔
5488
        err := p.startRbfChanCloser(newRPCShutdownInit(&closeReq), chanPoint)
3✔
5489
        if err != nil {
3✔
5490
                return nil, err
×
5491
        }
×
5492

5493
        return closeUpdates, nil
3✔
5494
}
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