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

lightningnetwork / lnd / 10426952143

16 Aug 2024 10:17PM UTC coverage: 49.856% (+0.01%) from 49.843%
10426952143

Pull #8512

github

Roasbeef
lnwallet/chancloser: add unit tests for new rbf coop close
Pull Request #8512: [3/4] - lnwallet/chancloser: add new protofsm based RBF chan closer

6 of 1064 new or added lines in 6 files covered. (0.56%)

159 existing lines in 21 files now uncovered.

96167 of 192890 relevant lines covered (49.86%)

1.55 hits per line

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

76.73
/peer/brontide.go
1
package peer
2

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

15
        "github.com/btcsuite/btcd/btcec/v2"
16
        "github.com/btcsuite/btcd/chaincfg/chainhash"
17
        "github.com/btcsuite/btcd/connmgr"
18
        "github.com/btcsuite/btcd/txscript"
19
        "github.com/btcsuite/btcd/wire"
20
        "github.com/btcsuite/btclog"
21
        "github.com/davecgh/go-spew/spew"
22
        "github.com/lightningnetwork/lnd/buffer"
23
        "github.com/lightningnetwork/lnd/build"
24
        "github.com/lightningnetwork/lnd/chainntnfs"
25
        "github.com/lightningnetwork/lnd/channeldb"
26
        "github.com/lightningnetwork/lnd/channeldb/models"
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"
32
        "github.com/lightningnetwork/lnd/funding"
33
        "github.com/lightningnetwork/lnd/htlcswitch"
34
        "github.com/lightningnetwork/lnd/htlcswitch/hodl"
35
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
36
        "github.com/lightningnetwork/lnd/input"
37
        "github.com/lightningnetwork/lnd/invoices"
38
        "github.com/lightningnetwork/lnd/lnpeer"
39
        "github.com/lightningnetwork/lnd/lntypes"
40
        "github.com/lightningnetwork/lnd/lnutils"
41
        "github.com/lightningnetwork/lnd/lnwallet"
42
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
43
        "github.com/lightningnetwork/lnd/lnwallet/chancloser"
44
        "github.com/lightningnetwork/lnd/lnwire"
45
        "github.com/lightningnetwork/lnd/msgmux"
46
        "github.com/lightningnetwork/lnd/netann"
47
        "github.com/lightningnetwork/lnd/pool"
48
        "github.com/lightningnetwork/lnd/queue"
49
        "github.com/lightningnetwork/lnd/subscribe"
50
        "github.com/lightningnetwork/lnd/ticker"
51
        "github.com/lightningnetwork/lnd/tlv"
52
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
53
)
54

55
const (
56
        // pingInterval is the interval at which ping messages are sent.
57
        pingInterval = 1 * time.Minute
58

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

65
        // idleTimeout is the duration of inactivity before we time out a peer.
66
        idleTimeout = 5 * time.Minute
67

68
        // writeMessageTimeout is the timeout used when writing a message to the
69
        // peer.
70
        writeMessageTimeout = 5 * time.Second
71

72
        // readMessageTimeout is the timeout used when reading a message from a
73
        // peer.
74
        readMessageTimeout = 5 * time.Second
75

76
        // handshakeTimeout is the timeout used when waiting for the peer's init
77
        // message.
78
        handshakeTimeout = 15 * time.Second
79

80
        // ErrorBufferSize is the number of historic peer errors that we store.
81
        ErrorBufferSize = 10
82

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

89
        // torTimeoutMultiplier is the scaling factor we use on network timeouts
90
        // for Tor peers.
91
        torTimeoutMultiplier = 3
92
)
93

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

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

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

117
        // channelID is used when there's a new pending channel.
118
        channelID lnwire.ChannelID
119

120
        err chan error
121
}
122

123
type customMsg struct {
124
        peer [33]byte
125
        msg  lnwire.Custom
126
}
127

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

136
// PendingUpdate describes the pending state of a closing channel.
137
type PendingUpdate struct {
138
        Txid        []byte
139
        OutputIndex uint32
140
}
141

142
// ChannelCloseUpdate contains the outcome of the close channel operation.
143
type ChannelCloseUpdate struct {
144
        ClosingTxid []byte
145
        Success     bool
146
}
147

148
// TimestampedError is a timestamped error that is used to store the most recent
149
// errors we have experienced with our peers.
150
type TimestampedError struct {
151
        Error     error
152
        Timestamp time.Time
153
}
154

155
// Config defines configuration fields that are necessary for a peer object
156
// to function.
157
type Config struct {
158
        // Conn is the underlying network connection for this peer.
159
        Conn MessageConn
160

161
        // ConnReq stores information related to the persistent connection request
162
        // for this peer.
163
        ConnReq *connmgr.ConnReq
164

165
        // PubKeyBytes is the serialized, compressed public key of this peer.
166
        PubKeyBytes [33]byte
167

168
        // Addr is the network address of the peer.
169
        Addr *lnwire.NetAddress
170

171
        // Inbound indicates whether or not the peer is an inbound peer.
172
        Inbound bool
173

174
        // Features is the set of features that we advertise to the remote party.
175
        Features *lnwire.FeatureVector
176

177
        // LegacyFeatures is the set of features that we advertise to the remote
178
        // peer for backwards compatibility. Nodes that have not implemented
179
        // flat features will still be able to read our feature bits from the
180
        // legacy global field, but we will also advertise everything in the
181
        // default features field.
182
        LegacyFeatures *lnwire.FeatureVector
183

184
        // OutgoingCltvRejectDelta defines the number of blocks before expiry of
185
        // an htlc where we don't offer it anymore.
186
        OutgoingCltvRejectDelta uint32
187

188
        // ChanActiveTimeout specifies the duration the peer will wait to request
189
        // a channel reenable, beginning from the time the peer was started.
190
        ChanActiveTimeout time.Duration
191

192
        // ErrorBuffer stores a set of errors related to a peer. It contains error
193
        // messages that our peer has recently sent us over the wire and records of
194
        // unknown messages that were sent to us so that we can have a full track
195
        // record of the communication errors we have had with our peer. If we
196
        // choose to disconnect from a peer, it also stores the reason we had for
197
        // disconnecting.
198
        ErrorBuffer *queue.CircularBuffer
199

200
        // WritePool is the task pool that manages reuse of write buffers. Write
201
        // tasks are submitted to the pool in order to conserve the total number of
202
        // write buffers allocated at any one time, and decouple write buffer
203
        // allocation from the peer life cycle.
204
        WritePool *pool.Write
205

206
        // ReadPool is the task pool that manages reuse of read buffers.
207
        ReadPool *pool.Read
208

209
        // Switch is a pointer to the htlcswitch. It is used to setup, get, and
210
        // tear-down ChannelLinks.
211
        Switch messageSwitch
212

213
        // InterceptSwitch is a pointer to the InterceptableSwitch, a wrapper around
214
        // the regular Switch. We only export it here to pass ForwardPackets to the
215
        // ChannelLinkConfig.
216
        InterceptSwitch *htlcswitch.InterceptableSwitch
217

218
        // ChannelDB is used to fetch opened channels, and closed channels.
219
        ChannelDB *channeldb.ChannelStateDB
220

221
        // ChannelGraph is a pointer to the channel graph which is used to
222
        // query information about the set of known active channels.
223
        ChannelGraph *channeldb.ChannelGraph
224

225
        // ChainArb is used to subscribe to channel events, update contract signals,
226
        // and force close channels.
227
        ChainArb *contractcourt.ChainArbitrator
228

229
        // AuthGossiper is needed so that the Brontide impl can register with the
230
        // gossiper and process remote channel announcements.
231
        AuthGossiper *discovery.AuthenticatedGossiper
232

233
        // ChanStatusMgr is used to set or un-set the disabled bit in channel
234
        // updates.
235
        ChanStatusMgr *netann.ChanStatusManager
236

237
        // ChainIO is used to retrieve the best block.
238
        ChainIO lnwallet.BlockChainIO
239

240
        // FeeEstimator is used to compute our target ideal fee-per-kw when
241
        // initializing the coop close process.
242
        FeeEstimator chainfee.Estimator
243

244
        // Signer is used when creating *lnwallet.LightningChannel instances.
245
        Signer input.Signer
246

247
        // SigPool is used when creating *lnwallet.LightningChannel instances.
248
        SigPool *lnwallet.SigPool
249

250
        // Wallet is used to publish transactions and generates delivery
251
        // scripts during the coop close process.
252
        Wallet *lnwallet.LightningWallet
253

254
        // ChainNotifier is used to receive confirmations of a coop close
255
        // transaction.
256
        ChainNotifier chainntnfs.ChainNotifier
257

258
        // BestBlockView is used to efficiently query for up-to-date
259
        // blockchain state information
260
        BestBlockView chainntnfs.BestBlockView
261

262
        // RoutingPolicy is used to set the forwarding policy for links created by
263
        // the Brontide.
264
        RoutingPolicy models.ForwardingPolicy
265

266
        // Sphinx is used when setting up ChannelLinks so they can decode sphinx
267
        // onion blobs.
268
        Sphinx *hop.OnionProcessor
269

270
        // WitnessBeacon is used when setting up ChannelLinks so they can add any
271
        // preimages that they learn.
272
        WitnessBeacon contractcourt.WitnessBeacon
273

274
        // Invoices is passed to the ChannelLink on creation and handles all
275
        // invoice-related logic.
276
        Invoices *invoices.InvoiceRegistry
277

278
        // ChannelNotifier is used by the link to notify other sub-systems about
279
        // channel-related events and by the Brontide to subscribe to
280
        // ActiveLinkEvents.
281
        ChannelNotifier *channelnotifier.ChannelNotifier
282

283
        // HtlcNotifier is used when creating a ChannelLink.
284
        HtlcNotifier *htlcswitch.HtlcNotifier
285

286
        // TowerClient is used to backup revoked states.
287
        TowerClient wtclient.ClientManager
288

289
        // DisconnectPeer is used to disconnect this peer if the cooperative close
290
        // process fails.
291
        DisconnectPeer func(*btcec.PublicKey) error
292

293
        // GenNodeAnnouncement is used to send our node announcement to the remote
294
        // on startup.
295
        GenNodeAnnouncement func(...netann.NodeAnnModifier) (
296
                lnwire.NodeAnnouncement, error)
297

298
        // PrunePersistentPeerConnection is used to remove all internal state
299
        // related to this peer in the server.
300
        PrunePersistentPeerConnection func([33]byte)
301

302
        // FetchLastChanUpdate fetches our latest channel update for a target
303
        // channel.
304
        FetchLastChanUpdate func(lnwire.ShortChannelID) (*lnwire.ChannelUpdate,
305
                error)
306

307
        // FundingManager is an implementation of the funding.Controller interface.
308
        FundingManager funding.Controller
309

310
        // Hodl is used when creating ChannelLinks to specify HodlFlags as
311
        // breakpoints in dev builds.
312
        Hodl *hodl.Config
313

314
        // UnsafeReplay is used when creating ChannelLinks to specify whether or
315
        // not to replay adds on its commitment tx.
316
        UnsafeReplay bool
317

318
        // MaxOutgoingCltvExpiry is used when creating ChannelLinks and is the max
319
        // number of blocks that funds could be locked up for when forwarding
320
        // payments.
321
        MaxOutgoingCltvExpiry uint32
322

323
        // MaxChannelFeeAllocation is used when creating ChannelLinks and is the
324
        // maximum percentage of total funds that can be allocated to a channel's
325
        // commitment fee. This only applies for the initiator of the channel.
326
        MaxChannelFeeAllocation float64
327

328
        // MaxAnchorsCommitFeeRate is the maximum fee rate we'll use as an
329
        // initiator for anchor channel commitments.
330
        MaxAnchorsCommitFeeRate chainfee.SatPerKWeight
331

332
        // CoopCloseTargetConfs is the confirmation target that will be used
333
        // to estimate the fee rate to use during a cooperative channel
334
        // closure initiated by the remote peer.
335
        CoopCloseTargetConfs uint32
336

337
        // ServerPubKey is the serialized, compressed public key of our lnd node.
338
        // It is used to determine which policy (channel edge) to pass to the
339
        // ChannelLink.
340
        ServerPubKey [33]byte
341

342
        // ChannelCommitInterval is the maximum time that is allowed to pass between
343
        // receiving a channel state update and signing the next commitment.
344
        // Setting this to a longer duration allows for more efficient channel
345
        // operations at the cost of latency.
346
        ChannelCommitInterval time.Duration
347

348
        // PendingCommitInterval is the maximum time that is allowed to pass
349
        // while waiting for the remote party to revoke a locally initiated
350
        // commitment state. Setting this to a longer duration if a slow
351
        // response is expected from the remote party or large number of
352
        // payments are attempted at the same time.
353
        PendingCommitInterval time.Duration
354

355
        // ChannelCommitBatchSize is the maximum number of channel state updates
356
        // that is accumulated before signing a new commitment.
357
        ChannelCommitBatchSize uint32
358

359
        // HandleCustomMessage is called whenever a custom message is received
360
        // from the peer.
361
        HandleCustomMessage func(peer [33]byte, msg *lnwire.Custom) error
362

363
        // GetAliases is passed to created links so the Switch and link can be
364
        // aware of the channel's aliases.
365
        GetAliases func(base lnwire.ShortChannelID) []lnwire.ShortChannelID
366

367
        // RequestAlias allows the Brontide struct to request an alias to send
368
        // to the peer.
369
        RequestAlias func() (lnwire.ShortChannelID, error)
370

371
        // AddLocalAlias persists an alias to an underlying alias store.
372
        AddLocalAlias func(alias, base lnwire.ShortChannelID,
373
                gossip bool) error
374

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

381
        // Adds the option to disable forwarding payments in blinded routes
382
        // by failing back any blinding-related payloads as if they were
383
        // invalid.
384
        DisallowRouteBlinding bool
385

386
        // MaxFeeExposure limits the number of outstanding fees in a channel.
387
        // This value will be passed to created links.
388
        MaxFeeExposure lnwire.MilliSatoshi
389

390
        // MsgRouter is an optional instance of the main message router that
391
        // the peer will use. If None, then a new default version will be used
392
        // in place.
393
        MsgRouter fn.Option[msgmux.Router]
394

395
        // Quit is the server's quit channel. If this is closed, we halt operation.
396
        Quit chan struct{}
397
}
398

399
// Brontide is an active peer on the Lightning Network. This struct is responsible
400
// for managing any channel state related to this peer. To do so, it has
401
// several helper goroutines to handle events such as HTLC timeouts, new
402
// funding workflow, and detecting an uncooperative closure of any active
403
// channels.
404
// TODO(roasbeef): proper reconnection logic.
405
type Brontide struct {
406
        // MUST be used atomically.
407
        started    int32
408
        disconnect int32
409

410
        // MUST be used atomically.
411
        bytesReceived uint64
412
        bytesSent     uint64
413

414
        // isTorConnection is a flag that indicates whether or not we believe
415
        // the remote peer is a tor connection. It is not always possible to
416
        // know this with certainty but we have heuristics we use that should
417
        // catch most cases.
418
        //
419
        // NOTE: We judge the tor-ness of a connection by if the remote peer has
420
        // ".onion" in the address OR if it's connected over localhost.
421
        // This will miss cases where our peer is connected to our clearnet
422
        // address over the tor network (via exit nodes). It will also misjudge
423
        // actual localhost connections as tor. We need to include this because
424
        // inbound connections to our tor address will appear to come from the
425
        // local socks5 proxy. This heuristic is only used to expand the timeout
426
        // window for peers so it is OK to misjudge this. If you use this field
427
        // for any other purpose you should seriously consider whether or not
428
        // this heuristic is good enough for your use case.
429
        isTorConnection bool
430

431
        pingManager *PingManager
432

433
        // lastPingPayload stores an unsafe pointer wrapped as an atomic
434
        // variable which points to the last payload the remote party sent us
435
        // as their ping.
436
        //
437
        // MUST be used atomically.
438
        lastPingPayload atomic.Value
439

440
        cfg Config
441

442
        // activeSignal when closed signals that the peer is now active and
443
        // ready to process messages.
444
        activeSignal chan struct{}
445

446
        // startTime is the time this peer connection was successfully established.
447
        // It will be zero for peers that did not successfully call Start().
448
        startTime time.Time
449

450
        // sendQueue is the channel which is used to queue outgoing messages to be
451
        // written onto the wire. Note that this channel is unbuffered.
452
        sendQueue chan outgoingMsg
453

454
        // outgoingQueue is a buffered channel which allows second/third party
455
        // objects to queue messages to be sent out on the wire.
456
        outgoingQueue chan outgoingMsg
457

458
        // activeChannels is a map which stores the state machines of all
459
        // active channels. Channels are indexed into the map by the txid of
460
        // the funding transaction which opened the channel.
461
        //
462
        // NOTE: On startup, pending channels are stored as nil in this map.
463
        // Confirmed channels have channel data populated in the map. This means
464
        // that accesses to this map should nil-check the LightningChannel to
465
        // see if this is a pending channel or not. The tradeoff here is either
466
        // having two maps everywhere (one for pending, one for confirmed chans)
467
        // or having an extra nil-check per access.
468
        activeChannels *lnutils.SyncMap[
469
                lnwire.ChannelID, *lnwallet.LightningChannel]
470

471
        // addedChannels tracks any new channels opened during this peer's
472
        // lifecycle. We use this to filter out these new channels when the time
473
        // comes to request a reenable for active channels, since they will have
474
        // waited a shorter duration.
475
        addedChannels *lnutils.SyncMap[lnwire.ChannelID, struct{}]
476

477
        // newActiveChannel is used by the fundingManager to send fully opened
478
        // channels to the source peer which handled the funding workflow.
479
        newActiveChannel chan *newChannelMsg
480

481
        // newPendingChannel is used by the fundingManager to send pending open
482
        // channels to the source peer which handled the funding workflow.
483
        newPendingChannel chan *newChannelMsg
484

485
        // removePendingChannel is used by the fundingManager to cancel pending
486
        // open channels to the source peer when the funding flow is failed.
487
        removePendingChannel chan *newChannelMsg
488

489
        // activeMsgStreams is a map from channel id to the channel streams that
490
        // proxy messages to individual, active links.
491
        activeMsgStreams map[lnwire.ChannelID]*msgStream
492

493
        // activeChanCloses is a map that keeps track of all the active
494
        // cooperative channel closures. Any channel closing messages are directed
495
        // to one of these active state machines. Once the channel has been closed,
496
        // the state machine will be deleted from the map.
497
        activeChanCloses map[lnwire.ChannelID]*chancloser.ChanCloser
498

499
        // localCloseChanReqs is a channel in which any local requests to close
500
        // a particular channel are sent over.
501
        localCloseChanReqs chan *htlcswitch.ChanClose
502

503
        // linkFailures receives all reported channel failures from the switch,
504
        // and instructs the channelManager to clean remaining channel state.
505
        linkFailures chan linkFailureReport
506

507
        // chanCloseMsgs is a channel that any message related to channel
508
        // closures are sent over. This includes lnwire.Shutdown message as
509
        // well as lnwire.ClosingSigned messages.
510
        chanCloseMsgs chan *closeMsg
511

512
        // remoteFeatures is the feature vector received from the peer during
513
        // the connection handshake.
514
        remoteFeatures *lnwire.FeatureVector
515

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

522
        // channelEventClient is the channel event subscription client that's
523
        // used to assist retry enabling the channels. This client is only
524
        // created when the reenableTimeout is no greater than 1 minute. Once
525
        // created, it is canceled once the reenabling has been finished.
526
        //
527
        // NOTE: we choose to create the client conditionally to avoid
528
        // potentially holding lots of un-consumed events.
529
        channelEventClient *subscribe.Client
530

531
        // msgRouter is an instance of the msgmux.Router which is used to send
532
        // off new wire messages for handing.
533
        msgRouter fn.Option[msgmux.Router]
534

535
        // globalMsgRouter is a flag that indicates whether we have a global
536
        // msg router. If so, then we don't worry about stopping the msg router
537
        // when a peer disconnects.
538
        globalMsgRouter bool
539

540
        startReady chan struct{}
541
        quit       chan struct{}
542
        wg         sync.WaitGroup
543

544
        // log is a peer-specific logging instance.
545
        log btclog.Logger
546
}
547

548
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer interface.
549
var _ lnpeer.Peer = (*Brontide)(nil)
550

551
// NewBrontide creates a new Brontide from a peer.Config struct.
552
func NewBrontide(cfg Config) *Brontide {
3✔
553
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
3✔
554

3✔
555
        // We have a global message router if one was passed in via the config.
3✔
556
        // In this case, we don't need to attempt to tear it down when the peer
3✔
557
        // is stopped.
3✔
558
        globalMsgRouter := cfg.MsgRouter.IsSome()
3✔
559

3✔
560
        // We'll either use the msg router instance passed in, or create a new
3✔
561
        // blank instance.
3✔
562
        msgRouter := cfg.MsgRouter.Alt(fn.Some[msgmux.Router](
3✔
563
                msgmux.NewMultiMsgRouter(),
3✔
564
        ))
3✔
565

3✔
566
        p := &Brontide{
3✔
567
                cfg:           cfg,
3✔
568
                activeSignal:  make(chan struct{}),
3✔
569
                sendQueue:     make(chan outgoingMsg),
3✔
570
                outgoingQueue: make(chan outgoingMsg),
3✔
571
                addedChannels: &lnutils.SyncMap[lnwire.ChannelID, struct{}]{},
3✔
572
                activeChannels: &lnutils.SyncMap[
3✔
573
                        lnwire.ChannelID, *lnwallet.LightningChannel,
3✔
574
                ]{},
3✔
575
                newActiveChannel:     make(chan *newChannelMsg, 1),
3✔
576
                newPendingChannel:    make(chan *newChannelMsg, 1),
3✔
577
                removePendingChannel: make(chan *newChannelMsg),
3✔
578

3✔
579
                activeMsgStreams:   make(map[lnwire.ChannelID]*msgStream),
3✔
580
                activeChanCloses:   make(map[lnwire.ChannelID]*chancloser.ChanCloser),
3✔
581
                localCloseChanReqs: make(chan *htlcswitch.ChanClose),
3✔
582
                linkFailures:       make(chan linkFailureReport),
3✔
583
                chanCloseMsgs:      make(chan *closeMsg),
3✔
584
                resentChanSyncMsg:  make(map[lnwire.ChannelID]struct{}),
3✔
585
                startReady:         make(chan struct{}),
3✔
586
                quit:               make(chan struct{}),
3✔
587
                log:                build.NewPrefixLog(logPrefix, peerLog),
3✔
588
                msgRouter:          msgRouter,
3✔
589
                globalMsgRouter:    globalMsgRouter,
3✔
590
        }
3✔
591

3✔
592
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
6✔
593
                remoteAddr := cfg.Conn.RemoteAddr().String()
3✔
594
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
3✔
595
                        strings.Contains(remoteAddr, "127.0.0.1")
3✔
596
        }
3✔
597

598
        var (
3✔
599
                lastBlockHeader           *wire.BlockHeader
3✔
600
                lastSerializedBlockHeader [wire.MaxBlockHeaderPayload]byte
3✔
601
        )
3✔
602
        newPingPayload := func() []byte {
5✔
603
                // We query the BestBlockHeader from our BestBlockView each time
2✔
604
                // this is called, and update our serialized block header if
2✔
605
                // they differ.  Over time, we'll use this to disseminate the
2✔
606
                // latest block header between all our peers, which can later be
2✔
607
                // used to cross-check our own view of the network to mitigate
2✔
608
                // various types of eclipse attacks.
2✔
609
                header, err := p.cfg.BestBlockView.BestBlockHeader()
2✔
610
                if err != nil && header == lastBlockHeader {
2✔
611
                        return lastSerializedBlockHeader[:]
×
612
                }
×
613

614
                buf := bytes.NewBuffer(lastSerializedBlockHeader[0:0])
2✔
615
                err = header.Serialize(buf)
2✔
616
                if err == nil {
4✔
617
                        lastBlockHeader = header
2✔
618
                } else {
2✔
619
                        p.log.Warn("unable to serialize current block" +
×
620
                                "header for ping payload generation." +
×
621
                                "This should be impossible and means" +
×
622
                                "there is an implementation bug.")
×
623
                }
×
624

625
                return lastSerializedBlockHeader[:]
2✔
626
        }
627

628
        // TODO(roasbeef): make dynamic in order to create fake cover traffic.
629
        //
630
        // NOTE(proofofkeags): this was changed to be dynamic to allow better
631
        // pong identification, however, more thought is needed to make this
632
        // actually usable as a traffic decoy.
633
        randPongSize := func() uint16 {
5✔
634
                return uint16(
2✔
635
                        // We don't need cryptographic randomness here.
2✔
636
                        /* #nosec */
2✔
637
                        rand.Intn(pongSizeCeiling) + 1,
2✔
638
                )
2✔
639
        }
2✔
640

641
        p.pingManager = NewPingManager(&PingManagerConfig{
3✔
642
                NewPingPayload:   newPingPayload,
3✔
643
                NewPongSize:      randPongSize,
3✔
644
                IntervalDuration: p.scaleTimeout(pingInterval),
3✔
645
                TimeoutDuration:  p.scaleTimeout(pingTimeout),
3✔
646
                SendPing: func(ping *lnwire.Ping) {
5✔
647
                        p.queueMsg(ping, nil)
2✔
648
                },
2✔
649
                OnPongFailure: func(err error) {
×
650
                        eStr := "pong response failure for %s: %v " +
×
651
                                "-- disconnecting"
×
652
                        p.log.Warnf(eStr, p, err)
×
653
                        go p.Disconnect(fmt.Errorf(eStr, p, err))
×
654
                },
×
655
        })
656

657
        return p
3✔
658
}
659

660
// Start starts all helper goroutines the peer needs for normal operations.  In
661
// the case this peer has already been started, then this function is a noop.
662
func (p *Brontide) Start() error {
3✔
663
        if atomic.AddInt32(&p.started, 1) != 1 {
3✔
664
                return nil
×
665
        }
×
666

667
        // Once we've finished starting up the peer, we'll signal to other
668
        // goroutines that the they can move forward to tear down the peer, or
669
        // carry out other relevant changes.
670
        defer close(p.startReady)
3✔
671

3✔
672
        p.log.Tracef("starting with conn[%v->%v]",
3✔
673
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
3✔
674

3✔
675
        // Fetch and then load all the active channels we have with this remote
3✔
676
        // peer from the database.
3✔
677
        activeChans, err := p.cfg.ChannelDB.FetchOpenChannels(
3✔
678
                p.cfg.Addr.IdentityKey,
3✔
679
        )
3✔
680
        if err != nil {
3✔
681
                p.log.Errorf("Unable to fetch active chans "+
×
682
                        "for peer: %v", err)
×
683
                return err
×
684
        }
×
685

686
        if len(activeChans) == 0 {
6✔
687
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
3✔
688
        }
3✔
689

690
        // Quickly check if we have any existing legacy channels with this
691
        // peer.
692
        haveLegacyChan := false
3✔
693
        for _, c := range activeChans {
6✔
694
                if c.ChanType.IsTweakless() {
6✔
695
                        continue
3✔
696
                }
697

698
                haveLegacyChan = true
3✔
699
                break
3✔
700
        }
701

702
        // Exchange local and global features, the init message should be very
703
        // first between two nodes.
704
        if err := p.sendInitMsg(haveLegacyChan); err != nil {
3✔
705
                return fmt.Errorf("unable to send init msg: %w", err)
×
706
        }
×
707

708
        // Before we launch any of the helper goroutines off the peer struct,
709
        // we'll first ensure proper adherence to the p2p protocol. The init
710
        // message MUST be sent before any other message.
711
        readErr := make(chan error, 1)
3✔
712
        msgChan := make(chan lnwire.Message, 1)
3✔
713
        p.wg.Add(1)
3✔
714
        go func() {
6✔
715
                defer p.wg.Done()
3✔
716

3✔
717
                msg, err := p.readNextMessage()
3✔
718
                if err != nil {
3✔
UNCOV
719
                        readErr <- err
×
UNCOV
720
                        msgChan <- nil
×
UNCOV
721
                        return
×
UNCOV
722
                }
×
723
                readErr <- nil
3✔
724
                msgChan <- msg
3✔
725
        }()
726

727
        select {
3✔
728
        // In order to avoid blocking indefinitely, we'll give the other peer
729
        // an upper timeout to respond before we bail out early.
730
        case <-time.After(handshakeTimeout):
×
731
                return fmt.Errorf("peer did not complete handshake within %v",
×
732
                        handshakeTimeout)
×
733
        case err := <-readErr:
3✔
734
                if err != nil {
3✔
UNCOV
735
                        return fmt.Errorf("unable to read init msg: %w", err)
×
UNCOV
736
                }
×
737
        }
738

739
        // Once the init message arrives, we can parse it so we can figure out
740
        // the negotiation of features for this session.
741
        msg := <-msgChan
3✔
742
        if msg, ok := msg.(*lnwire.Init); ok {
6✔
743
                if err := p.handleInitMsg(msg); err != nil {
3✔
744
                        p.storeError(err)
×
745
                        return err
×
746
                }
×
747
        } else {
×
748
                return errors.New("very first message between nodes " +
×
749
                        "must be init message")
×
750
        }
×
751

752
        // Next, load all the active channels we have with this peer,
753
        // registering them with the switch and launching the necessary
754
        // goroutines required to operate them.
755
        p.log.Debugf("Loaded %v active channels from database",
3✔
756
                len(activeChans))
3✔
757

3✔
758
        // Conditionally subscribe to channel events before loading channels so
3✔
759
        // we won't miss events. This subscription is used to listen to active
3✔
760
        // channel event when reenabling channels. Once the reenabling process
3✔
761
        // is finished, this subscription will be canceled.
3✔
762
        //
3✔
763
        // NOTE: ChannelNotifier must be started before subscribing events
3✔
764
        // otherwise we'd panic here.
3✔
765
        if err := p.attachChannelEventSubscription(); err != nil {
3✔
766
                return err
×
767
        }
×
768

769
        // Register the message router now as we may need to register some
770
        // endpoints while loading the channels below.
771
        p.msgRouter.WhenSome(func(router msgmux.Router) {
6✔
772
                router.Start()
3✔
773
        })
3✔
774

775
        msgs, err := p.loadActiveChannels(activeChans)
3✔
776
        if err != nil {
3✔
777
                return fmt.Errorf("unable to load channels: %w", err)
×
778
        }
×
779

780
        p.startTime = time.Now()
3✔
781

3✔
782
        // Before launching the writeHandler goroutine, we send any channel
3✔
783
        // sync messages that must be resent for borked channels. We do this to
3✔
784
        // avoid data races with WriteMessage & Flush calls.
3✔
785
        if len(msgs) > 0 {
6✔
786
                p.log.Infof("Sending %d channel sync messages to peer after "+
3✔
787
                        "loading active channels", len(msgs))
3✔
788

3✔
789
                // Send the messages directly via writeMessage and bypass the
3✔
790
                // writeHandler goroutine.
3✔
791
                for _, msg := range msgs {
6✔
792
                        if err := p.writeMessage(msg); err != nil {
3✔
793
                                return fmt.Errorf("unable to send "+
×
794
                                        "reestablish msg: %v", err)
×
795
                        }
×
796
                }
797
        }
798

799
        err = p.pingManager.Start()
3✔
800
        if err != nil {
3✔
801
                return fmt.Errorf("could not start ping manager %w", err)
×
802
        }
×
803

804
        p.wg.Add(4)
3✔
805
        go p.queueHandler()
3✔
806
        go p.writeHandler()
3✔
807
        go p.channelManager()
3✔
808
        go p.readHandler()
3✔
809

3✔
810
        // Signal to any external processes that the peer is now active.
3✔
811
        close(p.activeSignal)
3✔
812

3✔
813
        // Node announcements don't propagate very well throughout the network
3✔
814
        // as there isn't a way to efficiently query for them through their
3✔
815
        // timestamp, mostly affecting nodes that were offline during the time
3✔
816
        // of broadcast. We'll resend our node announcement to the remote peer
3✔
817
        // as a best-effort delivery such that it can also propagate to their
3✔
818
        // peers. To ensure they can successfully process it in most cases,
3✔
819
        // we'll only resend it as long as we have at least one confirmed
3✔
820
        // advertised channel with the remote peer.
3✔
821
        //
3✔
822
        // TODO(wilmer): Remove this once we're able to query for node
3✔
823
        // announcements through their timestamps.
3✔
824
        p.wg.Add(2)
3✔
825
        go p.maybeSendNodeAnn(activeChans)
3✔
826
        go p.maybeSendChannelUpdates()
3✔
827

3✔
828
        return nil
3✔
829
}
830

831
// initGossipSync initializes either a gossip syncer or an initial routing
832
// dump, depending on the negotiated synchronization method.
833
func (p *Brontide) initGossipSync() {
3✔
834
        // If the remote peer knows of the new gossip queries feature, then
3✔
835
        // we'll create a new gossipSyncer in the AuthenticatedGossiper for it.
3✔
836
        if p.remoteFeatures.HasFeature(lnwire.GossipQueriesOptional) {
6✔
837
                p.log.Info("Negotiated chan series queries")
3✔
838

3✔
839
                if p.cfg.AuthGossiper == nil {
3✔
840
                        // This should only ever be hit in the unit tests.
×
841
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
×
842
                                "gossip sync.")
×
843
                        return
×
844
                }
×
845

846
                // Register the peer's gossip syncer with the gossiper.
847
                // This blocks synchronously to ensure the gossip syncer is
848
                // registered with the gossiper before attempting to read
849
                // messages from the remote peer.
850
                //
851
                // TODO(wilmer): Only sync updates from non-channel peers. This
852
                // requires an improved version of the current network
853
                // bootstrapper to ensure we can find and connect to non-channel
854
                // peers.
855
                p.cfg.AuthGossiper.InitSyncState(p)
3✔
856
        }
857
}
858

859
// taprootShutdownAllowed returns true if both parties have negotiated the
860
// shutdown-any-segwit feature.
861
func (p *Brontide) taprootShutdownAllowed() bool {
3✔
862
        return p.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
3✔
863
                p.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
3✔
864
}
3✔
865

866
// QuitSignal is a method that should return a channel which will be sent upon
867
// or closed once the backing peer exits. This allows callers using the
868
// interface to cancel any processing in the event the backing implementation
869
// exits.
870
//
871
// NOTE: Part of the lnpeer.Peer interface.
872
func (p *Brontide) QuitSignal() <-chan struct{} {
3✔
873
        return p.quit
3✔
874
}
3✔
875

876
// loadActiveChannels creates indexes within the peer for tracking all active
877
// channels returned by the database. It returns a slice of channel reestablish
878
// messages that should be sent to the peer immediately, in case we have borked
879
// channels that haven't been closed yet.
880
func (p *Brontide) loadActiveChannels(chans []*channeldb.OpenChannel) (
881
        []lnwire.Message, error) {
3✔
882

3✔
883
        // Return a slice of messages to send to the peers in case the channel
3✔
884
        // cannot be loaded normally.
3✔
885
        var msgs []lnwire.Message
3✔
886

3✔
887
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
3✔
888

3✔
889
        for _, dbChan := range chans {
6✔
890
                hasScidFeature := dbChan.ChanType.HasScidAliasFeature()
3✔
891
                if scidAliasNegotiated && !hasScidFeature {
6✔
892
                        // We'll request and store an alias, making sure that a
3✔
893
                        // gossiper mapping is not created for the alias to the
3✔
894
                        // real SCID. This is done because the peer and funding
3✔
895
                        // manager are not aware of each other's states and if
3✔
896
                        // we did not do this, we would accept alias channel
3✔
897
                        // updates after 6 confirmations, which would be buggy.
3✔
898
                        // We'll queue a channel_ready message with the new
3✔
899
                        // alias. This should technically be done *after* the
3✔
900
                        // reestablish, but this behavior is pre-existing since
3✔
901
                        // the funding manager may already queue a
3✔
902
                        // channel_ready before the channel_reestablish.
3✔
903
                        if !dbChan.IsPending {
6✔
904
                                aliasScid, err := p.cfg.RequestAlias()
3✔
905
                                if err != nil {
3✔
906
                                        return nil, err
×
907
                                }
×
908

909
                                err = p.cfg.AddLocalAlias(
3✔
910
                                        aliasScid, dbChan.ShortChanID(), false,
3✔
911
                                )
3✔
912
                                if err != nil {
3✔
913
                                        return nil, err
×
914
                                }
×
915

916
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
917
                                        dbChan.FundingOutpoint,
3✔
918
                                )
3✔
919

3✔
920
                                // Fetch the second commitment point to send in
3✔
921
                                // the channel_ready message.
3✔
922
                                second, err := dbChan.SecondCommitmentPoint()
3✔
923
                                if err != nil {
3✔
924
                                        return nil, err
×
925
                                }
×
926

927
                                channelReadyMsg := lnwire.NewChannelReady(
3✔
928
                                        chanID, second,
3✔
929
                                )
3✔
930
                                channelReadyMsg.AliasScid = &aliasScid
3✔
931

3✔
932
                                msgs = append(msgs, channelReadyMsg)
3✔
933
                        }
934

935
                        // If we've negotiated the option-scid-alias feature
936
                        // and this channel does not have ScidAliasFeature set
937
                        // to true due to an upgrade where the feature bit was
938
                        // turned on, we'll update the channel's database
939
                        // state.
940
                        err := dbChan.MarkScidAliasNegotiated()
3✔
941
                        if err != nil {
3✔
942
                                return nil, err
×
943
                        }
×
944
                }
945

946
                lnChan, err := lnwallet.NewLightningChannel(
3✔
947
                        p.cfg.Signer, dbChan, p.cfg.SigPool,
3✔
948
                )
3✔
949
                if err != nil {
3✔
950
                        return nil, fmt.Errorf("unable to create channel "+
×
951
                                "state machine: %w", err)
×
952
                }
×
953

954
                chanPoint := dbChan.FundingOutpoint
3✔
955

3✔
956
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
957

3✔
958
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
3✔
959
                        chanPoint, lnChan.IsPending())
3✔
960

3✔
961
                // Skip adding any permanently irreconcilable channels to the
3✔
962
                // htlcswitch.
3✔
963
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
3✔
964
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
6✔
965

3✔
966
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
3✔
967
                                "start.", chanPoint, dbChan.ChanStatus())
3✔
968

3✔
969
                        // To help our peer recover from a potential data loss,
3✔
970
                        // we resend our channel reestablish message if the
3✔
971
                        // channel is in a borked state. We won't process any
3✔
972
                        // channel reestablish message sent from the peer, but
3✔
973
                        // that's okay since the assumption is that we did when
3✔
974
                        // marking the channel borked.
3✔
975
                        chanSync, err := dbChan.ChanSyncMsg()
3✔
976
                        if err != nil {
3✔
977
                                p.log.Errorf("Unable to create channel "+
×
978
                                        "reestablish message for channel %v: "+
×
979
                                        "%v", chanPoint, err)
×
980
                                continue
×
981
                        }
982

983
                        msgs = append(msgs, chanSync)
3✔
984

3✔
985
                        // Check if this channel needs to have the cooperative
3✔
986
                        // close process restarted. If so, we'll need to send
3✔
987
                        // the Shutdown message that is returned.
3✔
988
                        if dbChan.HasChanStatus(
3✔
989
                                channeldb.ChanStatusCoopBroadcasted,
3✔
990
                        ) {
3✔
991

×
992
                                shutdownMsg, err := p.restartCoopClose(lnChan)
×
993
                                if err != nil {
×
994
                                        p.log.Errorf("Unable to restart "+
×
995
                                                "coop close for channel: %v",
×
996
                                                err)
×
997
                                        continue
×
998
                                }
999

1000
                                if shutdownMsg == nil {
×
1001
                                        continue
×
1002
                                }
1003

1004
                                // Append the message to the set of messages to
1005
                                // send.
1006
                                msgs = append(msgs, shutdownMsg)
×
1007
                        }
1008

1009
                        continue
3✔
1010
                }
1011

1012
                // Before we register this new link with the HTLC Switch, we'll
1013
                // need to fetch its current link-layer forwarding policy from
1014
                // the database.
1015
                graph := p.cfg.ChannelGraph
3✔
1016
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
3✔
1017
                        &chanPoint,
3✔
1018
                )
3✔
1019
                if err != nil && !errors.Is(err, channeldb.ErrEdgeNotFound) {
3✔
1020
                        return nil, err
×
1021
                }
×
1022

1023
                // We'll filter out our policy from the directional channel
1024
                // edges based whom the edge connects to. If it doesn't connect
1025
                // to us, then we know that we were the one that advertised the
1026
                // policy.
1027
                //
1028
                // TODO(roasbeef): can add helper method to get policy for
1029
                // particular channel.
1030
                var selfPolicy *models.ChannelEdgePolicy
3✔
1031
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
3✔
1032
                        p.cfg.ServerPubKey[:]) {
6✔
1033

3✔
1034
                        selfPolicy = p1
3✔
1035
                } else {
6✔
1036
                        selfPolicy = p2
3✔
1037
                }
3✔
1038

1039
                // If we don't yet have an advertised routing policy, then
1040
                // we'll use the current default, otherwise we'll translate the
1041
                // routing policy into a forwarding policy.
1042
                var forwardingPolicy *models.ForwardingPolicy
3✔
1043
                if selfPolicy != nil {
6✔
1044
                        var inboundWireFee lnwire.Fee
3✔
1045
                        _, err := selfPolicy.ExtraOpaqueData.ExtractRecords(
3✔
1046
                                &inboundWireFee,
3✔
1047
                        )
3✔
1048
                        if err != nil {
3✔
1049
                                return nil, err
×
1050
                        }
×
1051

1052
                        inboundFee := models.NewInboundFeeFromWire(
3✔
1053
                                inboundWireFee,
3✔
1054
                        )
3✔
1055

3✔
1056
                        forwardingPolicy = &models.ForwardingPolicy{
3✔
1057
                                MinHTLCOut:    selfPolicy.MinHTLC,
3✔
1058
                                MaxHTLC:       selfPolicy.MaxHTLC,
3✔
1059
                                BaseFee:       selfPolicy.FeeBaseMSat,
3✔
1060
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
3✔
1061
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
3✔
1062

3✔
1063
                                InboundFee: inboundFee,
3✔
1064
                        }
3✔
1065
                } else {
3✔
1066
                        p.log.Warnf("Unable to find our forwarding policy "+
3✔
1067
                                "for channel %v, using default values",
3✔
1068
                                chanPoint)
3✔
1069
                        forwardingPolicy = &p.cfg.RoutingPolicy
3✔
1070
                }
3✔
1071

1072
                p.log.Tracef("Using link policy of: %v",
3✔
1073
                        spew.Sdump(forwardingPolicy))
3✔
1074

3✔
1075
                // If the channel is pending, set the value to nil in the
3✔
1076
                // activeChannels map. This is done to signify that the channel
3✔
1077
                // is pending. We don't add the link to the switch here - it's
3✔
1078
                // the funding manager's responsibility to spin up pending
3✔
1079
                // channels. Adding them here would just be extra work as we'll
3✔
1080
                // tear them down when creating + adding the final link.
3✔
1081
                if lnChan.IsPending() {
6✔
1082
                        p.activeChannels.Store(chanID, nil)
3✔
1083

3✔
1084
                        continue
3✔
1085
                }
1086

1087
                shutdownInfo, err := lnChan.State().ShutdownInfo()
3✔
1088
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
3✔
1089
                        return nil, err
×
1090
                }
×
1091

1092
                var (
3✔
1093
                        shutdownMsg     fn.Option[lnwire.Shutdown]
3✔
1094
                        shutdownInfoErr error
3✔
1095
                )
3✔
1096
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
6✔
1097
                        // Compute an ideal fee.
3✔
1098
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
1099
                                p.cfg.CoopCloseTargetConfs,
3✔
1100
                        )
3✔
1101
                        if err != nil {
3✔
1102
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1103
                                        "estimate fee: %w", err)
×
1104

×
1105
                                return
×
1106
                        }
×
1107

1108
                        chanCloser, err := p.createChanCloser(
3✔
1109
                                lnChan, info.DeliveryScript.Val, feePerKw, nil,
3✔
1110
                                info.Closer(),
3✔
1111
                        )
3✔
1112
                        if err != nil {
3✔
1113
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1114
                                        "create chan closer: %w", err)
×
1115

×
1116
                                return
×
1117
                        }
×
1118

1119
                        chanID := lnwire.NewChanIDFromOutPoint(
3✔
1120
                                lnChan.State().FundingOutpoint,
3✔
1121
                        )
3✔
1122

3✔
1123
                        p.activeChanCloses[chanID] = chanCloser
3✔
1124

3✔
1125
                        // Create the Shutdown message.
3✔
1126
                        shutdown, err := chanCloser.ShutdownChan()
3✔
1127
                        if err != nil {
3✔
1128
                                delete(p.activeChanCloses, chanID)
×
1129
                                shutdownInfoErr = err
×
1130

×
1131
                                return
×
1132
                        }
×
1133

1134
                        shutdownMsg = fn.Some(*shutdown)
3✔
1135
                })
1136
                if shutdownInfoErr != nil {
3✔
1137
                        return nil, shutdownInfoErr
×
1138
                }
×
1139

1140
                // Subscribe to the set of on-chain events for this channel.
1141
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
3✔
1142
                        chanPoint,
3✔
1143
                )
3✔
1144
                if err != nil {
3✔
1145
                        return nil, err
×
1146
                }
×
1147

1148
                err = p.addLink(
3✔
1149
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
3✔
1150
                        true, shutdownMsg,
3✔
1151
                )
3✔
1152
                if err != nil {
3✔
1153
                        return nil, fmt.Errorf("unable to add link %v to "+
×
1154
                                "switch: %v", chanPoint, err)
×
1155
                }
×
1156

1157
                p.activeChannels.Store(chanID, lnChan)
3✔
1158
        }
1159

1160
        return msgs, nil
3✔
1161
}
1162

1163
// addLink creates and adds a new ChannelLink from the specified channel.
1164
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1165
        lnChan *lnwallet.LightningChannel,
1166
        forwardingPolicy *models.ForwardingPolicy,
1167
        chainEvents *contractcourt.ChainEventSubscription,
1168
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
3✔
1169

3✔
1170
        // onChannelFailure will be called by the link in case the channel
3✔
1171
        // fails for some reason.
3✔
1172
        onChannelFailure := func(chanID lnwire.ChannelID,
3✔
1173
                shortChanID lnwire.ShortChannelID,
3✔
1174
                linkErr htlcswitch.LinkFailureError) {
6✔
1175

3✔
1176
                failure := linkFailureReport{
3✔
1177
                        chanPoint:   *chanPoint,
3✔
1178
                        chanID:      chanID,
3✔
1179
                        shortChanID: shortChanID,
3✔
1180
                        linkErr:     linkErr,
3✔
1181
                }
3✔
1182

3✔
1183
                select {
3✔
1184
                case p.linkFailures <- failure:
3✔
1185
                case <-p.quit:
×
1186
                case <-p.cfg.Quit:
×
1187
                }
1188
        }
1189

1190
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
6✔
1191
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
3✔
1192
        }
3✔
1193

1194
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
6✔
1195
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
3✔
1196
        }
3✔
1197

1198
        //nolint:lll
1199
        linkCfg := htlcswitch.ChannelLinkConfig{
3✔
1200
                Peer:                   p,
3✔
1201
                DecodeHopIterators:     p.cfg.Sphinx.DecodeHopIterators,
3✔
1202
                ExtractErrorEncrypter:  p.cfg.Sphinx.ExtractErrorEncrypter,
3✔
1203
                FetchLastChannelUpdate: p.cfg.FetchLastChanUpdate,
3✔
1204
                HodlMask:               p.cfg.Hodl.Mask(),
3✔
1205
                Registry:               p.cfg.Invoices,
3✔
1206
                BestHeight:             p.cfg.Switch.BestHeight,
3✔
1207
                Circuits:               p.cfg.Switch.CircuitModifier(),
3✔
1208
                ForwardPackets:         p.cfg.InterceptSwitch.ForwardPackets,
3✔
1209
                FwrdingPolicy:          *forwardingPolicy,
3✔
1210
                FeeEstimator:           p.cfg.FeeEstimator,
3✔
1211
                PreimageCache:          p.cfg.WitnessBeacon,
3✔
1212
                ChainEvents:            chainEvents,
3✔
1213
                UpdateContractSignals:  updateContractSignals,
3✔
1214
                NotifyContractUpdate:   notifyContractUpdate,
3✔
1215
                OnChannelFailure:       onChannelFailure,
3✔
1216
                SyncStates:             syncStates,
3✔
1217
                BatchTicker:            ticker.New(p.cfg.ChannelCommitInterval),
3✔
1218
                FwdPkgGCTicker:         ticker.New(time.Hour),
3✔
1219
                PendingCommitTicker: ticker.New(
3✔
1220
                        p.cfg.PendingCommitInterval,
3✔
1221
                ),
3✔
1222
                BatchSize:               p.cfg.ChannelCommitBatchSize,
3✔
1223
                UnsafeReplay:            p.cfg.UnsafeReplay,
3✔
1224
                MinUpdateTimeout:        htlcswitch.DefaultMinLinkFeeUpdateTimeout,
3✔
1225
                MaxUpdateTimeout:        htlcswitch.DefaultMaxLinkFeeUpdateTimeout,
3✔
1226
                OutgoingCltvRejectDelta: p.cfg.OutgoingCltvRejectDelta,
3✔
1227
                TowerClient:             p.cfg.TowerClient,
3✔
1228
                MaxOutgoingCltvExpiry:   p.cfg.MaxOutgoingCltvExpiry,
3✔
1229
                MaxFeeAllocation:        p.cfg.MaxChannelFeeAllocation,
3✔
1230
                MaxAnchorsCommitFeeRate: p.cfg.MaxAnchorsCommitFeeRate,
3✔
1231
                NotifyActiveLink:        p.cfg.ChannelNotifier.NotifyActiveLinkEvent,
3✔
1232
                NotifyActiveChannel:     p.cfg.ChannelNotifier.NotifyActiveChannelEvent,
3✔
1233
                NotifyInactiveChannel:   p.cfg.ChannelNotifier.NotifyInactiveChannelEvent,
3✔
1234
                NotifyInactiveLinkEvent: p.cfg.ChannelNotifier.NotifyInactiveLinkEvent,
3✔
1235
                HtlcNotifier:            p.cfg.HtlcNotifier,
3✔
1236
                GetAliases:              p.cfg.GetAliases,
3✔
1237
                PreviouslySentShutdown:  shutdownMsg,
3✔
1238
                DisallowRouteBlinding:   p.cfg.DisallowRouteBlinding,
3✔
1239
                MaxFeeExposure:          p.cfg.MaxFeeExposure,
3✔
1240
        }
3✔
1241

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

3✔
1249
        // With the channel link created, we'll now notify the htlc switch so
3✔
1250
        // this channel can be used to dispatch local payments and also
3✔
1251
        // passively forward payments.
3✔
1252
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
3✔
1253
}
1254

1255
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1256
// one confirmed public channel exists with them.
1257
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
3✔
1258
        defer p.wg.Done()
3✔
1259

3✔
1260
        hasConfirmedPublicChan := false
3✔
1261
        for _, channel := range channels {
6✔
1262
                if channel.IsPending {
6✔
1263
                        continue
3✔
1264
                }
1265
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
6✔
1266
                        continue
3✔
1267
                }
1268

1269
                hasConfirmedPublicChan = true
3✔
1270
                break
3✔
1271
        }
1272
        if !hasConfirmedPublicChan {
6✔
1273
                return
3✔
1274
        }
3✔
1275

1276
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
3✔
1277
        if err != nil {
3✔
1278
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1279
                return
×
1280
        }
×
1281

1282
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
3✔
1283
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1284
        }
×
1285
}
1286

1287
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1288
// have any active channels with them.
1289
func (p *Brontide) maybeSendChannelUpdates() {
3✔
1290
        defer p.wg.Done()
3✔
1291

3✔
1292
        // If we don't have any active channels, then we can exit early.
3✔
1293
        if p.activeChannels.Len() == 0 {
6✔
1294
                return
3✔
1295
        }
3✔
1296

1297
        maybeSendUpd := func(cid lnwire.ChannelID,
3✔
1298
                lnChan *lnwallet.LightningChannel) error {
6✔
1299

3✔
1300
                // Nil channels are pending, so we'll skip them.
3✔
1301
                if lnChan == nil {
6✔
1302
                        return nil
3✔
1303
                }
3✔
1304

1305
                dbChan := lnChan.State()
3✔
1306
                scid := func() lnwire.ShortChannelID {
6✔
1307
                        switch {
3✔
1308
                        // Otherwise if it's a zero conf channel and confirmed,
1309
                        // then we need to use the "real" scid.
1310
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
3✔
1311
                                return dbChan.ZeroConfRealScid()
3✔
1312

1313
                        // Otherwise, we can use the normal scid.
1314
                        default:
3✔
1315
                                return dbChan.ShortChanID()
3✔
1316
                        }
1317
                }()
1318

1319
                // Now that we know the channel is in a good state, we'll try
1320
                // to fetch the update to send to the remote peer. If the
1321
                // channel is pending, and not a zero conf channel, we'll get
1322
                // an error here which we'll ignore.
1323
                chanUpd, err := p.cfg.FetchLastChanUpdate(scid)
3✔
1324
                if err != nil {
6✔
1325
                        p.log.Debugf("Unable to fetch channel update for "+
3✔
1326
                                "ChannelPoint(%v), scid=%v: %v",
3✔
1327
                                dbChan.FundingOutpoint, dbChan.ShortChanID, err)
3✔
1328

3✔
1329
                        return nil
3✔
1330
                }
3✔
1331

1332
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
3✔
1333
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
3✔
1334

3✔
1335
                // We'll send it as a normal message instead of using the lazy
3✔
1336
                // queue to prioritize transmission of the fresh update.
3✔
1337
                if err := p.SendMessage(false, chanUpd); err != nil {
3✔
1338
                        err := fmt.Errorf("unable to send channel update for "+
×
1339
                                "ChannelPoint(%v), scid=%v: %w",
×
1340
                                dbChan.FundingOutpoint, dbChan.ShortChanID(),
×
1341
                                err)
×
1342
                        p.log.Errorf(err.Error())
×
1343

×
1344
                        return err
×
1345
                }
×
1346

1347
                return nil
3✔
1348
        }
1349

1350
        p.activeChannels.ForEach(maybeSendUpd)
3✔
1351
}
1352

1353
// WaitForDisconnect waits until the peer has disconnected. A peer may be
1354
// disconnected if the local or remote side terminates the connection, or an
1355
// irrecoverable protocol error has been encountered. This method will only
1356
// begin watching the peer's waitgroup after the ready channel or the peer's
1357
// quit channel are signaled. The ready channel should only be signaled if a
1358
// call to Start returns no error. Otherwise, if the peer fails to start,
1359
// calling Disconnect will signal the quit channel and the method will not
1360
// block, since no goroutines were spawned.
1361
func (p *Brontide) WaitForDisconnect(ready chan struct{}) {
3✔
1362
        // Before we try to call the `Wait` goroutine, we'll make sure the main
3✔
1363
        // set of goroutines are already active.
3✔
1364
        select {
3✔
1365
        case <-p.startReady:
3✔
1366
        case <-p.quit:
×
1367
                return
×
1368
        }
1369

1370
        select {
3✔
1371
        case <-ready:
3✔
UNCOV
1372
        case <-p.quit:
×
1373
        }
1374

1375
        p.wg.Wait()
3✔
1376
}
1377

1378
// Disconnect terminates the connection with the remote peer. Additionally, a
1379
// signal is sent to the server and htlcSwitch indicating the resources
1380
// allocated to the peer can now be cleaned up.
1381
func (p *Brontide) Disconnect(reason error) {
3✔
1382
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
6✔
1383
                return
3✔
1384
        }
3✔
1385

1386
        // Make sure initialization has completed before we try to tear things
1387
        // down.
1388
        select {
3✔
1389
        case <-p.startReady:
3✔
1390
        case <-p.quit:
×
1391
                return
×
1392
        }
1393

1394
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
3✔
1395
        p.storeError(err)
3✔
1396

3✔
1397
        p.log.Infof(err.Error())
3✔
1398

3✔
1399
        // Stop PingManager before closing TCP connection.
3✔
1400
        p.pingManager.Stop()
3✔
1401

3✔
1402
        // Ensure that the TCP connection is properly closed before continuing.
3✔
1403
        p.cfg.Conn.Close()
3✔
1404

3✔
1405
        close(p.quit)
3✔
1406

3✔
1407
        // If our msg router isn't global (local to this instance), then we'll
3✔
1408
        // stop it. Otherwise, we'll leave it running.
3✔
1409
        if !p.globalMsgRouter {
6✔
1410
                p.msgRouter.WhenSome(func(router msgmux.Router) {
6✔
1411
                        router.Stop()
3✔
1412
                })
3✔
1413
        }
1414
}
1415

1416
// String returns the string representation of this peer.
1417
func (p *Brontide) String() string {
3✔
1418
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
3✔
1419
}
3✔
1420

1421
// readNextMessage reads, and returns the next message on the wire along with
1422
// any additional raw payload.
1423
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
3✔
1424
        noiseConn := p.cfg.Conn
3✔
1425
        err := noiseConn.SetReadDeadline(time.Time{})
3✔
1426
        if err != nil {
3✔
1427
                return nil, err
×
1428
        }
×
1429

1430
        pktLen, err := noiseConn.ReadNextHeader()
3✔
1431
        if err != nil {
6✔
1432
                return nil, fmt.Errorf("read next header: %w", err)
3✔
1433
        }
3✔
1434

1435
        // First we'll read the next _full_ message. We do this rather than
1436
        // reading incrementally from the stream as the Lightning wire protocol
1437
        // is message oriented and allows nodes to pad on additional data to
1438
        // the message stream.
1439
        var (
3✔
1440
                nextMsg lnwire.Message
3✔
1441
                msgLen  uint64
3✔
1442
        )
3✔
1443
        err = p.cfg.ReadPool.Submit(func(buf *buffer.Read) error {
6✔
1444
                // Before reading the body of the message, set the read timeout
3✔
1445
                // accordingly to ensure we don't block other readers using the
3✔
1446
                // pool. We do so only after the task has been scheduled to
3✔
1447
                // ensure the deadline doesn't expire while the message is in
3✔
1448
                // the process of being scheduled.
3✔
1449
                readDeadline := time.Now().Add(
3✔
1450
                        p.scaleTimeout(readMessageTimeout),
3✔
1451
                )
3✔
1452
                readErr := noiseConn.SetReadDeadline(readDeadline)
3✔
1453
                if readErr != nil {
3✔
1454
                        return readErr
×
1455
                }
×
1456

1457
                // The ReadNextBody method will actually end up re-using the
1458
                // buffer, so within this closure, we can continue to use
1459
                // rawMsg as it's just a slice into the buf from the buffer
1460
                // pool.
1461
                rawMsg, readErr := noiseConn.ReadNextBody(buf[:pktLen])
3✔
1462
                if readErr != nil {
3✔
1463
                        return fmt.Errorf("read next body: %w", readErr)
×
1464
                }
×
1465
                msgLen = uint64(len(rawMsg))
3✔
1466

3✔
1467
                // Next, create a new io.Reader implementation from the raw
3✔
1468
                // message, and use this to decode the message directly from.
3✔
1469
                msgReader := bytes.NewReader(rawMsg)
3✔
1470
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
3✔
1471
                if err != nil {
6✔
1472
                        return err
3✔
1473
                }
3✔
1474

1475
                // At this point, rawMsg and buf will be returned back to the
1476
                // buffer pool for re-use.
1477
                return nil
3✔
1478
        })
1479
        atomic.AddUint64(&p.bytesReceived, msgLen)
3✔
1480
        if err != nil {
6✔
1481
                return nil, err
3✔
1482
        }
3✔
1483

1484
        p.logWireMessage(nextMsg, true)
3✔
1485

3✔
1486
        return nextMsg, nil
3✔
1487
}
1488

1489
// msgStream implements a goroutine-safe, in-order stream of messages to be
1490
// delivered via closure to a receiver. These messages MUST be in order due to
1491
// the nature of the lightning channel commitment and gossiper state machines.
1492
// TODO(conner): use stream handler interface to abstract out stream
1493
// state/logging.
1494
type msgStream struct {
1495
        streamShutdown int32 // To be used atomically.
1496

1497
        peer *Brontide
1498

1499
        apply func(lnwire.Message)
1500

1501
        startMsg string
1502
        stopMsg  string
1503

1504
        msgCond *sync.Cond
1505
        msgs    []lnwire.Message
1506

1507
        mtx sync.Mutex
1508

1509
        producerSema chan struct{}
1510

1511
        wg   sync.WaitGroup
1512
        quit chan struct{}
1513
}
1514

1515
// newMsgStream creates a new instance of a chanMsgStream for a particular
1516
// channel identified by its channel ID. bufSize is the max number of messages
1517
// that should be buffered in the internal queue. Callers should set this to a
1518
// sane value that avoids blocking unnecessarily, but doesn't allow an
1519
// unbounded amount of memory to be allocated to buffer incoming messages.
1520
func newMsgStream(p *Brontide, startMsg, stopMsg string, bufSize uint32,
1521
        apply func(lnwire.Message)) *msgStream {
3✔
1522

3✔
1523
        stream := &msgStream{
3✔
1524
                peer:         p,
3✔
1525
                apply:        apply,
3✔
1526
                startMsg:     startMsg,
3✔
1527
                stopMsg:      stopMsg,
3✔
1528
                producerSema: make(chan struct{}, bufSize),
3✔
1529
                quit:         make(chan struct{}),
3✔
1530
        }
3✔
1531
        stream.msgCond = sync.NewCond(&stream.mtx)
3✔
1532

3✔
1533
        // Before we return the active stream, we'll populate the producer's
3✔
1534
        // semaphore channel. We'll use this to ensure that the producer won't
3✔
1535
        // attempt to allocate memory in the queue for an item until it has
3✔
1536
        // sufficient extra space.
3✔
1537
        for i := uint32(0); i < bufSize; i++ {
6✔
1538
                stream.producerSema <- struct{}{}
3✔
1539
        }
3✔
1540

1541
        return stream
3✔
1542
}
1543

1544
// Start starts the chanMsgStream.
1545
func (ms *msgStream) Start() {
3✔
1546
        ms.wg.Add(1)
3✔
1547
        go ms.msgConsumer()
3✔
1548
}
3✔
1549

1550
// Stop stops the chanMsgStream.
1551
func (ms *msgStream) Stop() {
3✔
1552
        // TODO(roasbeef): signal too?
3✔
1553

3✔
1554
        close(ms.quit)
3✔
1555

3✔
1556
        // Now that we've closed the channel, we'll repeatedly signal the msg
3✔
1557
        // consumer until we've detected that it has exited.
3✔
1558
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
6✔
1559
                ms.msgCond.Signal()
3✔
1560
                time.Sleep(time.Millisecond * 100)
3✔
1561
        }
3✔
1562

1563
        ms.wg.Wait()
3✔
1564
}
1565

1566
// msgConsumer is the main goroutine that streams messages from the peer's
1567
// readHandler directly to the target channel.
1568
func (ms *msgStream) msgConsumer() {
3✔
1569
        defer ms.wg.Done()
3✔
1570
        defer peerLog.Tracef(ms.stopMsg)
3✔
1571
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
3✔
1572

3✔
1573
        peerLog.Tracef(ms.startMsg)
3✔
1574

3✔
1575
        for {
6✔
1576
                // First, we'll check our condition. If the queue of messages
3✔
1577
                // is empty, then we'll wait until a new item is added.
3✔
1578
                ms.msgCond.L.Lock()
3✔
1579
                for len(ms.msgs) == 0 {
6✔
1580
                        ms.msgCond.Wait()
3✔
1581

3✔
1582
                        // If we woke up in order to exit, then we'll do so.
3✔
1583
                        // Otherwise, we'll check the message queue for any new
3✔
1584
                        // items.
3✔
1585
                        select {
3✔
1586
                        case <-ms.peer.quit:
3✔
1587
                                ms.msgCond.L.Unlock()
3✔
1588
                                return
3✔
1589
                        case <-ms.quit:
3✔
1590
                                ms.msgCond.L.Unlock()
3✔
1591
                                return
3✔
1592
                        default:
3✔
1593
                        }
1594
                }
1595

1596
                // Grab the message off the front of the queue, shifting the
1597
                // slice's reference down one in order to remove the message
1598
                // from the queue.
1599
                msg := ms.msgs[0]
3✔
1600
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
3✔
1601
                ms.msgs = ms.msgs[1:]
3✔
1602

3✔
1603
                ms.msgCond.L.Unlock()
3✔
1604

3✔
1605
                ms.apply(msg)
3✔
1606

3✔
1607
                // We've just successfully processed an item, so we'll signal
3✔
1608
                // to the producer that a new slot in the buffer. We'll use
3✔
1609
                // this to bound the size of the buffer to avoid allowing it to
3✔
1610
                // grow indefinitely.
3✔
1611
                select {
3✔
1612
                case ms.producerSema <- struct{}{}:
3✔
1613
                case <-ms.peer.quit:
3✔
1614
                        return
3✔
1615
                case <-ms.quit:
3✔
1616
                        return
3✔
1617
                }
1618
        }
1619
}
1620

1621
// AddMsg adds a new message to the msgStream. This function is safe for
1622
// concurrent access.
1623
func (ms *msgStream) AddMsg(msg lnwire.Message) {
3✔
1624
        // First, we'll attempt to receive from the producerSema struct. This
3✔
1625
        // acts as a semaphore to prevent us from indefinitely buffering
3✔
1626
        // incoming items from the wire. Either the msg queue isn't full, and
3✔
1627
        // we'll not block, or the queue is full, and we'll block until either
3✔
1628
        // we're signalled to quit, or a slot is freed up.
3✔
1629
        select {
3✔
1630
        case <-ms.producerSema:
3✔
1631
        case <-ms.peer.quit:
×
1632
                return
×
1633
        case <-ms.quit:
×
1634
                return
×
1635
        }
1636

1637
        // Next, we'll lock the condition, and add the message to the end of
1638
        // the message queue.
1639
        ms.msgCond.L.Lock()
3✔
1640
        ms.msgs = append(ms.msgs, msg)
3✔
1641
        ms.msgCond.L.Unlock()
3✔
1642

3✔
1643
        // With the message added, we signal to the msgConsumer that there are
3✔
1644
        // additional messages to consume.
3✔
1645
        ms.msgCond.Signal()
3✔
1646
}
1647

1648
// waitUntilLinkActive waits until the target link is active and returns a
1649
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1650
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1651
func waitUntilLinkActive(p *Brontide,
1652
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
3✔
1653

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

3✔
1656
        // Subscribe to receive channel events.
3✔
1657
        //
3✔
1658
        // NOTE: If the link is already active by SubscribeChannelEvents, then
3✔
1659
        // GetLink will retrieve the link and we can send messages. If the link
3✔
1660
        // becomes active between SubscribeChannelEvents and GetLink, then GetLink
3✔
1661
        // will retrieve the link. If the link becomes active after GetLink, then
3✔
1662
        // we will get an ActiveLinkEvent notification and retrieve the link. If
3✔
1663
        // the call to GetLink is before SubscribeChannelEvents, however, there
3✔
1664
        // will be a race condition.
3✔
1665
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
3✔
1666
        if err != nil {
6✔
1667
                // If we have a non-nil error, then the server is shutting down and we
3✔
1668
                // can exit here and return nil. This means no message will be delivered
3✔
1669
                // to the link.
3✔
1670
                return nil
3✔
1671
        }
3✔
1672
        defer sub.Cancel()
3✔
1673

3✔
1674
        // The link may already be active by this point, and we may have missed the
3✔
1675
        // ActiveLinkEvent. Check if the link exists.
3✔
1676
        link := p.fetchLinkFromKeyAndCid(cid)
3✔
1677
        if link != nil {
6✔
1678
                return link
3✔
1679
        }
3✔
1680

1681
        // If the link is nil, we must wait for it to be active.
1682
        for {
6✔
1683
                select {
3✔
1684
                // A new event has been sent by the ChannelNotifier. We first check
1685
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1686
                // that the event is for this channel. Otherwise, we discard the
1687
                // message.
1688
                case e := <-sub.Updates():
3✔
1689
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
3✔
1690
                        if !ok {
6✔
1691
                                // Ignore this notification.
3✔
1692
                                continue
3✔
1693
                        }
1694

1695
                        chanPoint := event.ChannelPoint
3✔
1696

3✔
1697
                        // Check whether the retrieved chanPoint matches the target
3✔
1698
                        // channel id.
3✔
1699
                        if !cid.IsChanPoint(chanPoint) {
3✔
1700
                                continue
×
1701
                        }
1702

1703
                        // The link shouldn't be nil as we received an
1704
                        // ActiveLinkEvent. If it is nil, we return nil and the
1705
                        // calling function should catch it.
1706
                        return p.fetchLinkFromKeyAndCid(cid)
3✔
1707

1708
                case <-p.quit:
3✔
1709
                        return nil
3✔
1710
                }
1711
        }
1712
}
1713

1714
// newChanMsgStream is used to create a msgStream between the peer and
1715
// particular channel link in the htlcswitch. We utilize additional
1716
// synchronization with the fundingManager to ensure we don't attempt to
1717
// dispatch a message to a channel before it is fully active. A reference to the
1718
// channel this stream forwards to is held in scope to prevent unnecessary
1719
// lookups.
1720
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
3✔
1721
        var chanLink htlcswitch.ChannelUpdateHandler
3✔
1722

3✔
1723
        apply := func(msg lnwire.Message) {
6✔
1724
                // This check is fine because if the link no longer exists, it will
3✔
1725
                // be removed from the activeChannels map and subsequent messages
3✔
1726
                // shouldn't reach the chan msg stream.
3✔
1727
                if chanLink == nil {
6✔
1728
                        chanLink = waitUntilLinkActive(p, cid)
3✔
1729

3✔
1730
                        // If the link is still not active and the calling function
3✔
1731
                        // errored out, just return.
3✔
1732
                        if chanLink == nil {
6✔
1733
                                p.log.Warnf("Link=%v is not active")
3✔
1734
                                return
3✔
1735
                        }
3✔
1736
                }
1737

1738
                // In order to avoid unnecessarily delivering message
1739
                // as the peer is exiting, we'll check quickly to see
1740
                // if we need to exit.
1741
                select {
3✔
1742
                case <-p.quit:
×
1743
                        return
×
1744
                default:
3✔
1745
                }
1746

1747
                chanLink.HandleChannelUpdate(msg)
3✔
1748
        }
1749

1750
        return newMsgStream(p,
3✔
1751
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
3✔
1752
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
3✔
1753
                1000,
3✔
1754
                apply,
3✔
1755
        )
3✔
1756
}
1757

1758
// newDiscMsgStream is used to setup a msgStream between the peer and the
1759
// authenticated gossiper. This stream should be used to forward all remote
1760
// channel announcements.
1761
func newDiscMsgStream(p *Brontide) *msgStream {
3✔
1762
        apply := func(msg lnwire.Message) {
6✔
1763
                // TODO(yy): `ProcessRemoteAnnouncement` returns an error chan
3✔
1764
                // and we need to process it.
3✔
1765
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(msg, p)
3✔
1766
        }
3✔
1767

1768
        return newMsgStream(
3✔
1769
                p,
3✔
1770
                "Update stream for gossiper created",
3✔
1771
                "Update stream for gossiper exited",
3✔
1772
                1000,
3✔
1773
                apply,
3✔
1774
        )
3✔
1775
}
1776

1777
// readHandler is responsible for reading messages off the wire in series, then
1778
// properly dispatching the handling of the message to the proper subsystem.
1779
//
1780
// NOTE: This method MUST be run as a goroutine.
1781
func (p *Brontide) readHandler() {
3✔
1782
        defer p.wg.Done()
3✔
1783

3✔
1784
        // We'll stop the timer after a new messages is received, and also
3✔
1785
        // reset it after we process the next message.
3✔
1786
        idleTimer := time.AfterFunc(idleTimeout, func() {
3✔
1787
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
1788
                        p, idleTimeout)
×
1789
                p.Disconnect(err)
×
1790
        })
×
1791

1792
        // Initialize our negotiated gossip sync method before reading messages
1793
        // off the wire. When using gossip queries, this ensures a gossip
1794
        // syncer is active by the time query messages arrive.
1795
        //
1796
        // TODO(conner): have peer store gossip syncer directly and bypass
1797
        // gossiper?
1798
        p.initGossipSync()
3✔
1799

3✔
1800
        discStream := newDiscMsgStream(p)
3✔
1801
        discStream.Start()
3✔
1802
        defer discStream.Stop()
3✔
1803
out:
3✔
1804
        for atomic.LoadInt32(&p.disconnect) == 0 {
6✔
1805
                nextMsg, err := p.readNextMessage()
3✔
1806
                if !idleTimer.Stop() {
3✔
1807
                        select {
×
1808
                        case <-idleTimer.C:
×
1809
                        default:
×
1810
                        }
1811
                }
1812
                if err != nil {
6✔
1813
                        p.log.Infof("unable to read message from peer: %v", err)
3✔
1814

3✔
1815
                        // If we could not read our peer's message due to an
3✔
1816
                        // unknown type or invalid alias, we continue processing
3✔
1817
                        // as normal. We store unknown message and address
3✔
1818
                        // types, as they may provide debugging insight.
3✔
1819
                        switch e := err.(type) {
3✔
1820
                        // If this is just a message we don't yet recognize,
1821
                        // we'll continue processing as normal as this allows
1822
                        // us to introduce new messages in a forwards
1823
                        // compatible manner.
1824
                        case *lnwire.UnknownMessage:
3✔
1825
                                p.storeError(e)
3✔
1826
                                idleTimer.Reset(idleTimeout)
3✔
1827
                                continue
3✔
1828

1829
                        // If they sent us an address type that we don't yet
1830
                        // know of, then this isn't a wire error, so we'll
1831
                        // simply continue parsing the remainder of their
1832
                        // messages.
1833
                        case *lnwire.ErrUnknownAddrType:
×
1834
                                p.storeError(e)
×
1835
                                idleTimer.Reset(idleTimeout)
×
1836
                                continue
×
1837

1838
                        // If the NodeAnnouncement has an invalid alias, then
1839
                        // we'll log that error above and continue so we can
1840
                        // continue to read messages from the peer. We do not
1841
                        // store this error because it is of little debugging
1842
                        // value.
1843
                        case *lnwire.ErrInvalidNodeAlias:
×
1844
                                idleTimer.Reset(idleTimeout)
×
1845
                                continue
×
1846

1847
                        // If the error we encountered wasn't just a message we
1848
                        // didn't recognize, then we'll stop all processing as
1849
                        // this is a fatal error.
1850
                        default:
3✔
1851
                                break out
3✔
1852
                        }
1853
                }
1854

1855
                // If a message router is active, then we'll try to have it
1856
                // handle this message. If it can, then we're able to skip the
1857
                // rest of the message handling logic.
1858
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
6✔
1859
                        return r.RouteMsg(msgmux.PeerMsg{
3✔
1860
                                PeerPub: *p.IdentityKey(),
3✔
1861
                                Message: nextMsg,
3✔
1862
                        })
3✔
1863
                })
3✔
1864

1865
                // No error occurred, and the message was handled by the
1866
                // router.
1867
                if err == nil {
3✔
1868
                        continue
×
1869
                }
1870

1871
                var (
3✔
1872
                        targetChan   lnwire.ChannelID
3✔
1873
                        isLinkUpdate bool
3✔
1874
                )
3✔
1875

3✔
1876
                switch msg := nextMsg.(type) {
3✔
1877
                case *lnwire.Pong:
2✔
1878
                        // When we receive a Pong message in response to our
2✔
1879
                        // last ping message, we send it to the pingManager
2✔
1880
                        p.pingManager.ReceivedPong(msg)
2✔
1881

1882
                case *lnwire.Ping:
2✔
1883
                        // First, we'll store their latest ping payload within
2✔
1884
                        // the relevant atomic variable.
2✔
1885
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
2✔
1886

2✔
1887
                        // Next, we'll send over the amount of specified pong
2✔
1888
                        // bytes.
2✔
1889
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
2✔
1890
                        p.queueMsg(pong, nil)
2✔
1891

1892
                case *lnwire.OpenChannel,
1893
                        *lnwire.AcceptChannel,
1894
                        *lnwire.FundingCreated,
1895
                        *lnwire.FundingSigned,
1896
                        *lnwire.ChannelReady:
3✔
1897

3✔
1898
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
1899

1900
                case *lnwire.Shutdown:
3✔
1901
                        select {
3✔
1902
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
1903
                        case <-p.quit:
×
1904
                                break out
×
1905
                        }
1906
                case *lnwire.ClosingSigned:
3✔
1907
                        select {
3✔
1908
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
1909
                        case <-p.quit:
×
1910
                                break out
×
1911
                        }
1912

1913
                case *lnwire.Warning:
×
1914
                        targetChan = msg.ChanID
×
1915
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
1916

1917
                case *lnwire.Error:
3✔
1918
                        targetChan = msg.ChanID
3✔
1919
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
3✔
1920

1921
                case *lnwire.ChannelReestablish:
3✔
1922
                        targetChan = msg.ChanID
3✔
1923
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
1924

3✔
1925
                        // If we failed to find the link in question, and the
3✔
1926
                        // message received was a channel sync message, then
3✔
1927
                        // this might be a peer trying to resync closed channel.
3✔
1928
                        // In this case we'll try to resend our last channel
3✔
1929
                        // sync message, such that the peer can recover funds
3✔
1930
                        // from the closed channel.
3✔
1931
                        if !isLinkUpdate {
6✔
1932
                                err := p.resendChanSyncMsg(targetChan)
3✔
1933
                                if err != nil {
6✔
1934
                                        // TODO(halseth): send error to peer?
3✔
1935
                                        p.log.Errorf("resend failed: %v",
3✔
1936
                                                err)
3✔
1937
                                }
3✔
1938
                        }
1939

1940
                // For messages that implement the LinkUpdater interface, we
1941
                // will consider them as link updates and send them to
1942
                // chanStream. These messages will be queued inside chanStream
1943
                // if the channel is not active yet.
1944
                case lnwire.LinkUpdater:
3✔
1945
                        targetChan = msg.TargetChanID()
3✔
1946
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
1947

3✔
1948
                        // Log an error if we don't have this channel. This
3✔
1949
                        // means the peer has sent us a message with unknown
3✔
1950
                        // channel ID.
3✔
1951
                        if !isLinkUpdate {
6✔
1952
                                p.log.Errorf("Unknown channel ID: %v found "+
3✔
1953
                                        "in received msg=%s", targetChan,
3✔
1954
                                        nextMsg.MsgType())
3✔
1955
                        }
3✔
1956

1957
                case *lnwire.ChannelUpdate,
1958
                        *lnwire.ChannelAnnouncement,
1959
                        *lnwire.NodeAnnouncement,
1960
                        *lnwire.AnnounceSignatures,
1961
                        *lnwire.GossipTimestampRange,
1962
                        *lnwire.QueryShortChanIDs,
1963
                        *lnwire.QueryChannelRange,
1964
                        *lnwire.ReplyChannelRange,
1965
                        *lnwire.ReplyShortChanIDsEnd:
3✔
1966

3✔
1967
                        discStream.AddMsg(msg)
3✔
1968

1969
                case *lnwire.Custom:
3✔
1970
                        err := p.handleCustomMessage(msg)
3✔
1971
                        if err != nil {
3✔
1972
                                p.storeError(err)
×
1973
                                p.log.Errorf("%v", err)
×
1974
                        }
×
1975

1976
                default:
×
1977
                        // If the message we received is unknown to us, store
×
1978
                        // the type to track the failure.
×
1979
                        err := fmt.Errorf("unknown message type %v received",
×
1980
                                uint16(msg.MsgType()))
×
1981
                        p.storeError(err)
×
1982

×
1983
                        p.log.Errorf("%v", err)
×
1984
                }
1985

1986
                if isLinkUpdate {
6✔
1987
                        // If this is a channel update, then we need to feed it
3✔
1988
                        // into the channel's in-order message stream.
3✔
1989
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
3✔
1990
                }
3✔
1991

1992
                idleTimer.Reset(idleTimeout)
3✔
1993
        }
1994

1995
        p.Disconnect(errors.New("read handler closed"))
3✔
1996

3✔
1997
        p.log.Trace("readHandler for peer done")
3✔
1998
}
1999

2000
// handleCustomMessage handles the given custom message if a handler is
2001
// registered.
2002
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
3✔
2003
        if p.cfg.HandleCustomMessage == nil {
3✔
2004
                return fmt.Errorf("no custom message handler for "+
×
2005
                        "message type %v", uint16(msg.MsgType()))
×
2006
        }
×
2007

2008
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
3✔
2009
}
2010

2011
// isLoadedFromDisk returns true if the provided channel ID is loaded from
2012
// disk.
2013
//
2014
// NOTE: only returns true for pending channels.
2015
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
3✔
2016
        // If this is a newly added channel, no need to reestablish.
3✔
2017
        _, added := p.addedChannels.Load(chanID)
3✔
2018
        if added {
6✔
2019
                return false
3✔
2020
        }
3✔
2021

2022
        // Return false if the channel is unknown.
2023
        channel, ok := p.activeChannels.Load(chanID)
3✔
2024
        if !ok {
3✔
2025
                return false
×
2026
        }
×
2027

2028
        // During startup, we will use a nil value to mark a pending channel
2029
        // that's loaded from disk.
2030
        return channel == nil
3✔
2031
}
2032

2033
// isActiveChannel returns true if the provided channel id is active, otherwise
2034
// returns false.
2035
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
3✔
2036
        // The channel would be nil if,
3✔
2037
        // - the channel doesn't exist, or,
3✔
2038
        // - the channel exists, but is pending. In this case, we don't
3✔
2039
        //   consider this channel active.
3✔
2040
        channel, _ := p.activeChannels.Load(chanID)
3✔
2041

3✔
2042
        return channel != nil
3✔
2043
}
3✔
2044

2045
// isPendingChannel returns true if the provided channel ID is pending, and
2046
// returns false if the channel is active or unknown.
2047
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
3✔
2048
        // Return false if the channel is unknown.
3✔
2049
        channel, ok := p.activeChannels.Load(chanID)
3✔
2050
        if !ok {
6✔
2051
                return false
3✔
2052
        }
3✔
2053

2054
        return channel == nil
×
2055
}
2056

2057
// hasChannel returns true if the peer has a pending/active channel specified
2058
// by the channel ID.
2059
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
3✔
2060
        _, ok := p.activeChannels.Load(chanID)
3✔
2061
        return ok
3✔
2062
}
3✔
2063

2064
// storeError stores an error in our peer's buffer of recent errors with the
2065
// current timestamp. Errors are only stored if we have at least one active
2066
// channel with the peer to mitigate a dos vector where a peer costlessly
2067
// connects to us and spams us with errors.
2068
func (p *Brontide) storeError(err error) {
3✔
2069
        var haveChannels bool
3✔
2070

3✔
2071
        p.activeChannels.Range(func(_ lnwire.ChannelID,
3✔
2072
                channel *lnwallet.LightningChannel) bool {
6✔
2073

3✔
2074
                // Pending channels will be nil in the activeChannels map.
3✔
2075
                if channel == nil {
6✔
2076
                        // Return true to continue the iteration.
3✔
2077
                        return true
3✔
2078
                }
3✔
2079

2080
                haveChannels = true
3✔
2081

3✔
2082
                // Return false to break the iteration.
3✔
2083
                return false
3✔
2084
        })
2085

2086
        // If we do not have any active channels with the peer, we do not store
2087
        // errors as a dos mitigation.
2088
        if !haveChannels {
6✔
2089
                p.log.Trace("no channels with peer, not storing err")
3✔
2090
                return
3✔
2091
        }
3✔
2092

2093
        p.cfg.ErrorBuffer.Add(
3✔
2094
                &TimestampedError{Timestamp: time.Now(), Error: err},
3✔
2095
        )
3✔
2096
}
2097

2098
// handleWarningOrError processes a warning or error msg and returns true if
2099
// msg should be forwarded to the associated channel link. False is returned if
2100
// any necessary forwarding of msg was already handled by this method. If msg is
2101
// an error from a peer with an active channel, we'll store it in memory.
2102
//
2103
// NOTE: This method should only be called from within the readHandler.
2104
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
2105
        msg lnwire.Message) bool {
3✔
2106

3✔
2107
        if errMsg, ok := msg.(*lnwire.Error); ok {
6✔
2108
                p.storeError(errMsg)
3✔
2109
        }
3✔
2110

2111
        switch {
3✔
2112
        // Connection wide messages should be forwarded to all channel links
2113
        // with this peer.
2114
        case chanID == lnwire.ConnectionWideID:
×
2115
                for _, chanStream := range p.activeMsgStreams {
×
2116
                        chanStream.AddMsg(msg)
×
2117
                }
×
2118

2119
                return false
×
2120

2121
        // If the channel ID for the message corresponds to a pending channel,
2122
        // then the funding manager will handle it.
2123
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
3✔
2124
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2125
                return false
3✔
2126

2127
        // If not we hand the message to the channel link for this channel.
2128
        case p.isActiveChannel(chanID):
3✔
2129
                return true
3✔
2130

2131
        default:
3✔
2132
                return false
3✔
2133
        }
2134
}
2135

2136
// messageSummary returns a human-readable string that summarizes a
2137
// incoming/outgoing message. Not all messages will have a summary, only those
2138
// which have additional data that can be informative at a glance.
2139
func messageSummary(msg lnwire.Message) string {
3✔
2140
        switch msg := msg.(type) {
3✔
2141
        case *lnwire.Init:
3✔
2142
                // No summary.
3✔
2143
                return ""
3✔
2144

2145
        case *lnwire.OpenChannel:
3✔
2146
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
3✔
2147
                        "push_amt=%v, reserve=%v, flags=%v",
3✔
2148
                        msg.PendingChannelID[:], msg.ChainHash,
3✔
2149
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
3✔
2150
                        msg.ChannelReserve, msg.ChannelFlags)
3✔
2151

2152
        case *lnwire.AcceptChannel:
3✔
2153
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
3✔
2154
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
3✔
2155
                        msg.MinAcceptDepth)
3✔
2156

2157
        case *lnwire.FundingCreated:
3✔
2158
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
3✔
2159
                        msg.PendingChannelID[:], msg.FundingPoint)
3✔
2160

2161
        case *lnwire.FundingSigned:
3✔
2162
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
3✔
2163

2164
        case *lnwire.ChannelReady:
3✔
2165
                return fmt.Sprintf("chan_id=%v, next_point=%x",
3✔
2166
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
3✔
2167

2168
        case *lnwire.Shutdown:
3✔
2169
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
3✔
2170
                        msg.Address[:])
3✔
2171

2172
        case *lnwire.ClosingSigned:
3✔
2173
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
3✔
2174
                        msg.FeeSatoshis)
3✔
2175

2176
        case *lnwire.UpdateAddHTLC:
3✔
2177
                var blindingPoint []byte
3✔
2178
                msg.BlindingPoint.WhenSome(
3✔
2179
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
3✔
2180
                                *btcec.PublicKey]) {
6✔
2181

3✔
2182
                                blindingPoint = b.Val.SerializeCompressed()
3✔
2183
                        },
3✔
2184
                )
2185

2186
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
3✔
2187
                        "hash=%x, blinding_point=%x", msg.ChanID, msg.ID,
3✔
2188
                        msg.Amount, msg.Expiry, msg.PaymentHash[:],
3✔
2189
                        blindingPoint)
3✔
2190

2191
        case *lnwire.UpdateFailHTLC:
3✔
2192
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
3✔
2193
                        msg.ID, msg.Reason)
3✔
2194

2195
        case *lnwire.UpdateFulfillHTLC:
3✔
2196
                return fmt.Sprintf("chan_id=%v, id=%v, pre_image=%x",
3✔
2197
                        msg.ChanID, msg.ID, msg.PaymentPreimage[:])
3✔
2198

2199
        case *lnwire.CommitSig:
3✔
2200
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
3✔
2201
                        len(msg.HtlcSigs))
3✔
2202

2203
        case *lnwire.RevokeAndAck:
3✔
2204
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
3✔
2205
                        msg.ChanID, msg.Revocation[:],
3✔
2206
                        msg.NextRevocationKey.SerializeCompressed())
3✔
2207

2208
        case *lnwire.UpdateFailMalformedHTLC:
3✔
2209
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
3✔
2210
                        msg.ChanID, msg.ID, msg.FailureCode)
3✔
2211

2212
        case *lnwire.Warning:
×
2213
                return fmt.Sprintf("%v", msg.Warning())
×
2214

2215
        case *lnwire.Error:
3✔
2216
                return fmt.Sprintf("%v", msg.Error())
3✔
2217

2218
        case *lnwire.AnnounceSignatures:
3✔
2219
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
3✔
2220
                        msg.ShortChannelID.ToUint64())
3✔
2221

2222
        case *lnwire.ChannelAnnouncement:
3✔
2223
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
3✔
2224
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
3✔
2225

2226
        case *lnwire.ChannelUpdate:
3✔
2227
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
3✔
2228
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
3✔
2229
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
3✔
2230
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
3✔
2231

2232
        case *lnwire.NodeAnnouncement:
3✔
2233
                return fmt.Sprintf("node=%x, update_time=%v",
3✔
2234
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
3✔
2235

2236
        case *lnwire.Ping:
2✔
2237
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
2✔
2238

2239
        case *lnwire.Pong:
2✔
2240
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
2✔
2241

2242
        case *lnwire.UpdateFee:
×
2243
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2244
                        msg.ChanID, int64(msg.FeePerKw))
×
2245

2246
        case *lnwire.ChannelReestablish:
3✔
2247
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
3✔
2248
                        "remote_tail_height=%v", msg.ChanID,
3✔
2249
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
3✔
2250

2251
        case *lnwire.ReplyShortChanIDsEnd:
3✔
2252
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
3✔
2253
                        msg.Complete)
3✔
2254

2255
        case *lnwire.ReplyChannelRange:
3✔
2256
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
3✔
2257
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
3✔
2258
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
3✔
2259
                        msg.EncodingType)
3✔
2260

2261
        case *lnwire.QueryShortChanIDs:
3✔
2262
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
3✔
2263
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
3✔
2264

2265
        case *lnwire.QueryChannelRange:
3✔
2266
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
3✔
2267
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
3✔
2268
                        msg.LastBlockHeight())
3✔
2269

2270
        case *lnwire.GossipTimestampRange:
3✔
2271
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
3✔
2272
                        "stamp_range=%v", msg.ChainHash,
3✔
2273
                        time.Unix(int64(msg.FirstTimestamp), 0),
3✔
2274
                        msg.TimestampRange)
3✔
2275

2276
        case *lnwire.Stfu:
×
2277
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
×
2278
                        msg.Initiator)
×
2279

2280
        case *lnwire.Custom:
3✔
2281
                return fmt.Sprintf("type=%d", msg.Type)
3✔
2282
        }
2283

2284
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2285
}
2286

2287
// logWireMessage logs the receipt or sending of particular wire message. This
2288
// function is used rather than just logging the message in order to produce
2289
// less spammy log messages in trace mode by setting the 'Curve" parameter to
2290
// nil. Doing this avoids printing out each of the field elements in the curve
2291
// parameters for secp256k1.
2292
func (p *Brontide) logWireMessage(msg lnwire.Message, read bool) {
3✔
2293
        summaryPrefix := "Received"
3✔
2294
        if !read {
6✔
2295
                summaryPrefix = "Sending"
3✔
2296
        }
3✔
2297

2298
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
6✔
2299
                // Debug summary of message.
3✔
2300
                summary := messageSummary(msg)
3✔
2301
                if len(summary) > 0 {
6✔
2302
                        summary = "(" + summary + ")"
3✔
2303
                }
3✔
2304

2305
                preposition := "to"
3✔
2306
                if read {
6✔
2307
                        preposition = "from"
3✔
2308
                }
3✔
2309

2310
                var msgType string
3✔
2311
                if msg.MsgType() < lnwire.CustomTypeStart {
6✔
2312
                        msgType = msg.MsgType().String()
3✔
2313
                } else {
6✔
2314
                        msgType = "custom"
3✔
2315
                }
3✔
2316

2317
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
3✔
2318
                        msgType, summary, preposition, p)
3✔
2319
        }))
2320

2321
        prefix := "readMessage from peer"
3✔
2322
        if !read {
6✔
2323
                prefix = "writeMessage to peer"
3✔
2324
        }
3✔
2325

2326
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
3✔
2327
}
2328

2329
// writeMessage writes and flushes the target lnwire.Message to the remote peer.
2330
// If the passed message is nil, this method will only try to flush an existing
2331
// message buffered on the connection. It is safe to call this method again
2332
// with a nil message iff a timeout error is returned. This will continue to
2333
// flush the pending message to the wire.
2334
//
2335
// NOTE:
2336
// Besides its usage in Start, this function should not be used elsewhere
2337
// except in writeHandler. If multiple goroutines call writeMessage at the same
2338
// time, panics can occur because WriteMessage and Flush don't use any locking
2339
// internally.
2340
func (p *Brontide) writeMessage(msg lnwire.Message) error {
3✔
2341
        // Only log the message on the first attempt.
3✔
2342
        if msg != nil {
6✔
2343
                p.logWireMessage(msg, false)
3✔
2344
        }
3✔
2345

2346
        noiseConn := p.cfg.Conn
3✔
2347

3✔
2348
        flushMsg := func() error {
6✔
2349
                // Ensure the write deadline is set before we attempt to send
3✔
2350
                // the message.
3✔
2351
                writeDeadline := time.Now().Add(
3✔
2352
                        p.scaleTimeout(writeMessageTimeout),
3✔
2353
                )
3✔
2354
                err := noiseConn.SetWriteDeadline(writeDeadline)
3✔
2355
                if err != nil {
3✔
2356
                        return err
×
2357
                }
×
2358

2359
                // Flush the pending message to the wire. If an error is
2360
                // encountered, e.g. write timeout, the number of bytes written
2361
                // so far will be returned.
2362
                n, err := noiseConn.Flush()
3✔
2363

3✔
2364
                // Record the number of bytes written on the wire, if any.
3✔
2365
                if n > 0 {
6✔
2366
                        atomic.AddUint64(&p.bytesSent, uint64(n))
3✔
2367
                }
3✔
2368

2369
                return err
3✔
2370
        }
2371

2372
        // If the current message has already been serialized, encrypted, and
2373
        // buffered on the underlying connection we will skip straight to
2374
        // flushing it to the wire.
2375
        if msg == nil {
3✔
2376
                return flushMsg()
×
2377
        }
×
2378

2379
        // Otherwise, this is a new message. We'll acquire a write buffer to
2380
        // serialize the message and buffer the ciphertext on the connection.
2381
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
6✔
2382
                // Using a buffer allocated by the write pool, encode the
3✔
2383
                // message directly into the buffer.
3✔
2384
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
3✔
2385
                if writeErr != nil {
3✔
2386
                        return writeErr
×
2387
                }
×
2388

2389
                // Finally, write the message itself in a single swoop. This
2390
                // will buffer the ciphertext on the underlying connection. We
2391
                // will defer flushing the message until the write pool has been
2392
                // released.
2393
                return noiseConn.WriteMessage(buf.Bytes())
3✔
2394
        })
2395
        if err != nil {
3✔
2396
                return err
×
2397
        }
×
2398

2399
        return flushMsg()
3✔
2400
}
2401

2402
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2403
// queue, and writing them out to the wire. This goroutine coordinates with the
2404
// queueHandler in order to ensure the incoming message queue is quickly
2405
// drained.
2406
//
2407
// NOTE: This method MUST be run as a goroutine.
2408
func (p *Brontide) writeHandler() {
3✔
2409
        // We'll stop the timer after a new messages is sent, and also reset it
3✔
2410
        // after we process the next message.
3✔
2411
        idleTimer := time.AfterFunc(idleTimeout, func() {
5✔
2412
                err := fmt.Errorf("peer %s no write for %s -- disconnecting",
2✔
2413
                        p, idleTimeout)
2✔
2414
                p.Disconnect(err)
2✔
2415
        })
2✔
2416

2417
        var exitErr error
3✔
2418

3✔
2419
out:
3✔
2420
        for {
6✔
2421
                select {
3✔
2422
                case outMsg := <-p.sendQueue:
3✔
2423
                        // Record the time at which we first attempt to send the
3✔
2424
                        // message.
3✔
2425
                        startTime := time.Now()
3✔
2426

3✔
2427
                retry:
3✔
2428
                        // Write out the message to the socket. If a timeout
2429
                        // error is encountered, we will catch this and retry
2430
                        // after backing off in case the remote peer is just
2431
                        // slow to process messages from the wire.
2432
                        err := p.writeMessage(outMsg.msg)
3✔
2433
                        if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
3✔
2434
                                p.log.Debugf("Write timeout detected for "+
×
2435
                                        "peer, first write for message "+
×
2436
                                        "attempted %v ago",
×
2437
                                        time.Since(startTime))
×
2438

×
2439
                                // If we received a timeout error, this implies
×
2440
                                // that the message was buffered on the
×
2441
                                // connection successfully and that a flush was
×
2442
                                // attempted. We'll set the message to nil so
×
2443
                                // that on a subsequent pass we only try to
×
2444
                                // flush the buffered message, and forgo
×
2445
                                // reserializing or reencrypting it.
×
2446
                                outMsg.msg = nil
×
2447

×
2448
                                goto retry
×
2449
                        }
2450

2451
                        // The write succeeded, reset the idle timer to prevent
2452
                        // us from disconnecting the peer.
2453
                        if !idleTimer.Stop() {
3✔
2454
                                select {
×
2455
                                case <-idleTimer.C:
×
2456
                                default:
×
2457
                                }
2458
                        }
2459
                        idleTimer.Reset(idleTimeout)
3✔
2460

3✔
2461
                        // If the peer requested a synchronous write, respond
3✔
2462
                        // with the error.
3✔
2463
                        if outMsg.errChan != nil {
6✔
2464
                                outMsg.errChan <- err
3✔
2465
                        }
3✔
2466

2467
                        if err != nil {
3✔
2468
                                exitErr = fmt.Errorf("unable to write "+
×
2469
                                        "message: %v", err)
×
2470
                                break out
×
2471
                        }
2472

2473
                case <-p.quit:
3✔
2474
                        exitErr = lnpeer.ErrPeerExiting
3✔
2475
                        break out
3✔
2476
                }
2477
        }
2478

2479
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2480
        // disconnect.
2481
        p.wg.Done()
3✔
2482

3✔
2483
        p.Disconnect(exitErr)
3✔
2484

3✔
2485
        p.log.Trace("writeHandler for peer done")
3✔
2486
}
2487

2488
// queueHandler is responsible for accepting messages from outside subsystems
2489
// to be eventually sent out on the wire by the writeHandler.
2490
//
2491
// NOTE: This method MUST be run as a goroutine.
2492
func (p *Brontide) queueHandler() {
3✔
2493
        defer p.wg.Done()
3✔
2494

3✔
2495
        // priorityMsgs holds an in order list of messages deemed high-priority
3✔
2496
        // to be added to the sendQueue. This predominately includes messages
3✔
2497
        // from the funding manager and htlcswitch.
3✔
2498
        priorityMsgs := list.New()
3✔
2499

3✔
2500
        // lazyMsgs holds an in order list of messages deemed low-priority to be
3✔
2501
        // added to the sendQueue only after all high-priority messages have
3✔
2502
        // been queued. This predominately includes messages from the gossiper.
3✔
2503
        lazyMsgs := list.New()
3✔
2504

3✔
2505
        for {
6✔
2506
                // Examine the front of the priority queue, if it is empty check
3✔
2507
                // the low priority queue.
3✔
2508
                elem := priorityMsgs.Front()
3✔
2509
                if elem == nil {
6✔
2510
                        elem = lazyMsgs.Front()
3✔
2511
                }
3✔
2512

2513
                if elem != nil {
6✔
2514
                        front := elem.Value.(outgoingMsg)
3✔
2515

3✔
2516
                        // There's an element on the queue, try adding
3✔
2517
                        // it to the sendQueue. We also watch for
3✔
2518
                        // messages on the outgoingQueue, in case the
3✔
2519
                        // writeHandler cannot accept messages on the
3✔
2520
                        // sendQueue.
3✔
2521
                        select {
3✔
2522
                        case p.sendQueue <- front:
3✔
2523
                                if front.priority {
6✔
2524
                                        priorityMsgs.Remove(elem)
3✔
2525
                                } else {
6✔
2526
                                        lazyMsgs.Remove(elem)
3✔
2527
                                }
3✔
2528
                        case msg := <-p.outgoingQueue:
3✔
2529
                                if msg.priority {
6✔
2530
                                        priorityMsgs.PushBack(msg)
3✔
2531
                                } else {
6✔
2532
                                        lazyMsgs.PushBack(msg)
3✔
2533
                                }
3✔
2534
                        case <-p.quit:
×
2535
                                return
×
2536
                        }
2537
                } else {
3✔
2538
                        // If there weren't any messages to send to the
3✔
2539
                        // writeHandler, then we'll accept a new message
3✔
2540
                        // into the queue from outside sub-systems.
3✔
2541
                        select {
3✔
2542
                        case msg := <-p.outgoingQueue:
3✔
2543
                                if msg.priority {
6✔
2544
                                        priorityMsgs.PushBack(msg)
3✔
2545
                                } else {
6✔
2546
                                        lazyMsgs.PushBack(msg)
3✔
2547
                                }
3✔
2548
                        case <-p.quit:
3✔
2549
                                return
3✔
2550
                        }
2551
                }
2552
        }
2553
}
2554

2555
// PingTime returns the estimated ping time to the peer in microseconds.
2556
func (p *Brontide) PingTime() int64 {
3✔
2557
        return p.pingManager.GetPingTimeMicroSeconds()
3✔
2558
}
3✔
2559

2560
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2561
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2562
// or failed to write, and nil otherwise.
2563
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
3✔
2564
        p.queue(true, msg, errChan)
3✔
2565
}
3✔
2566

2567
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2568
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2569
// queue or failed to write, and nil otherwise.
2570
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
3✔
2571
        p.queue(false, msg, errChan)
3✔
2572
}
3✔
2573

2574
// queue sends a given message to the queueHandler using the passed priority. If
2575
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2576
// failed to write, and nil otherwise.
2577
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2578
        errChan chan error) {
3✔
2579

3✔
2580
        select {
3✔
2581
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
3✔
2582
        case <-p.quit:
3✔
2583
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
3✔
2584
                        spew.Sdump(msg))
3✔
2585
                if errChan != nil {
3✔
2586
                        errChan <- lnpeer.ErrPeerExiting
×
2587
                }
×
2588
        }
2589
}
2590

2591
// ChannelSnapshots returns a slice of channel snapshots detailing all
2592
// currently active channels maintained with the remote peer.
2593
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
3✔
2594
        snapshots := make(
3✔
2595
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
3✔
2596
        )
3✔
2597

3✔
2598
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2599
                activeChan *lnwallet.LightningChannel) error {
6✔
2600

3✔
2601
                // If the activeChan is nil, then we skip it as the channel is
3✔
2602
                // pending.
3✔
2603
                if activeChan == nil {
6✔
2604
                        return nil
3✔
2605
                }
3✔
2606

2607
                // We'll only return a snapshot for channels that are
2608
                // *immediately* available for routing payments over.
2609
                if activeChan.RemoteNextRevocation() == nil {
6✔
2610
                        return nil
3✔
2611
                }
3✔
2612

2613
                snapshot := activeChan.StateSnapshot()
3✔
2614
                snapshots = append(snapshots, snapshot)
3✔
2615

3✔
2616
                return nil
3✔
2617
        })
2618

2619
        return snapshots
3✔
2620
}
2621

2622
// genDeliveryScript returns a new script to be used to send our funds to in
2623
// the case of a cooperative channel close negotiation.
2624
func (p *Brontide) genDeliveryScript() ([]byte, error) {
3✔
2625
        // We'll send a normal p2wkh address unless we've negotiated the
3✔
2626
        // shutdown-any-segwit feature.
3✔
2627
        addrType := lnwallet.WitnessPubKey
3✔
2628
        if p.taprootShutdownAllowed() {
6✔
2629
                addrType = lnwallet.TaprootPubkey
3✔
2630
        }
3✔
2631

2632
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
3✔
2633
                addrType, false, lnwallet.DefaultAccountName,
3✔
2634
        )
3✔
2635
        if err != nil {
3✔
2636
                return nil, err
×
2637
        }
×
2638
        p.log.Infof("Delivery addr for channel close: %v",
3✔
2639
                deliveryAddr)
3✔
2640

3✔
2641
        return txscript.PayToAddrScript(deliveryAddr)
3✔
2642
}
2643

2644
// channelManager is goroutine dedicated to handling all requests/signals
2645
// pertaining to the opening, cooperative closing, and force closing of all
2646
// channels maintained with the remote peer.
2647
//
2648
// NOTE: This method MUST be run as a goroutine.
2649
func (p *Brontide) channelManager() {
3✔
2650
        defer p.wg.Done()
3✔
2651

3✔
2652
        // reenableTimeout will fire once after the configured channel status
3✔
2653
        // interval has elapsed. This will trigger us to sign new channel
3✔
2654
        // updates and broadcast them with the "disabled" flag unset.
3✔
2655
        reenableTimeout := time.After(p.cfg.ChanActiveTimeout)
3✔
2656

3✔
2657
out:
3✔
2658
        for {
6✔
2659
                select {
3✔
2660
                // A new pending channel has arrived which means we are about
2661
                // to complete a funding workflow and is waiting for the final
2662
                // `ChannelReady` messages to be exchanged. We will add this
2663
                // channel to the `activeChannels` with a nil value to indicate
2664
                // this is a pending channel.
2665
                case req := <-p.newPendingChannel:
3✔
2666
                        p.handleNewPendingChannel(req)
3✔
2667

2668
                // A new channel has arrived which means we've just completed a
2669
                // funding workflow. We'll initialize the necessary local
2670
                // state, and notify the htlc switch of a new link.
2671
                case req := <-p.newActiveChannel:
3✔
2672
                        p.handleNewActiveChannel(req)
3✔
2673

2674
                // The funding flow for a pending channel is failed, we will
2675
                // remove it from Brontide.
2676
                case req := <-p.removePendingChannel:
3✔
2677
                        p.handleRemovePendingChannel(req)
3✔
2678

2679
                // We've just received a local request to close an active
2680
                // channel. It will either kick of a cooperative channel
2681
                // closure negotiation, or be a notification of a breached
2682
                // contract that should be abandoned.
2683
                case req := <-p.localCloseChanReqs:
3✔
2684
                        p.handleLocalCloseReq(req)
3✔
2685

2686
                // We've received a link failure from a link that was added to
2687
                // the switch. This will initiate the teardown of the link, and
2688
                // initiate any on-chain closures if necessary.
2689
                case failure := <-p.linkFailures:
3✔
2690
                        p.handleLinkFailure(failure)
3✔
2691

2692
                // We've received a new cooperative channel closure related
2693
                // message from the remote peer, we'll use this message to
2694
                // advance the chan closer state machine.
2695
                case closeMsg := <-p.chanCloseMsgs:
3✔
2696
                        p.handleCloseMsg(closeMsg)
3✔
2697

2698
                // The channel reannounce delay has elapsed, broadcast the
2699
                // reenabled channel updates to the network. This should only
2700
                // fire once, so we set the reenableTimeout channel to nil to
2701
                // mark it for garbage collection. If the peer is torn down
2702
                // before firing, reenabling will not be attempted.
2703
                // TODO(conner): consolidate reenables timers inside chan status
2704
                // manager
2705
                case <-reenableTimeout:
3✔
2706
                        p.reenableActiveChannels()
3✔
2707

3✔
2708
                        // Since this channel will never fire again during the
3✔
2709
                        // lifecycle of the peer, we nil the channel to mark it
3✔
2710
                        // eligible for garbage collection, and make this
3✔
2711
                        // explicitly ineligible to receive in future calls to
3✔
2712
                        // select. This also shaves a few CPU cycles since the
3✔
2713
                        // select will ignore this case entirely.
3✔
2714
                        reenableTimeout = nil
3✔
2715

3✔
2716
                        // Once the reenabling is attempted, we also cancel the
3✔
2717
                        // channel event subscription to free up the overflow
3✔
2718
                        // queue used in channel notifier.
3✔
2719
                        //
3✔
2720
                        // NOTE: channelEventClient will be nil if the
3✔
2721
                        // reenableTimeout is greater than 1 minute.
3✔
2722
                        if p.channelEventClient != nil {
6✔
2723
                                p.channelEventClient.Cancel()
3✔
2724
                        }
3✔
2725

2726
                case <-p.quit:
3✔
2727
                        // As, we've been signalled to exit, we'll reset all
3✔
2728
                        // our active channel back to their default state.
3✔
2729
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2730
                                lc *lnwallet.LightningChannel) error {
6✔
2731

3✔
2732
                                // Exit if the channel is nil as it's a pending
3✔
2733
                                // channel.
3✔
2734
                                if lc == nil {
6✔
2735
                                        return nil
3✔
2736
                                }
3✔
2737

2738
                                lc.ResetState()
3✔
2739

3✔
2740
                                return nil
3✔
2741
                        })
2742

2743
                        break out
3✔
2744
                }
2745
        }
2746
}
2747

2748
// reenableActiveChannels searches the index of channels maintained with this
2749
// peer, and reenables each public, non-pending channel. This is done at the
2750
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
2751
// No message will be sent if the channel is already enabled.
2752
func (p *Brontide) reenableActiveChannels() {
3✔
2753
        // First, filter all known channels with this peer for ones that are
3✔
2754
        // both public and not pending.
3✔
2755
        activePublicChans := p.filterChannelsToEnable()
3✔
2756

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

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

3✔
2766
                switch {
3✔
2767
                // No error occurred, continue to request the next channel.
2768
                case err == nil:
3✔
2769
                        continue
3✔
2770

2771
                // Cannot auto enable a manually disabled channel so we do
2772
                // nothing but proceed to the next channel.
2773
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
3✔
2774
                        p.log.Debugf("Channel(%v) was manually disabled, "+
3✔
2775
                                "ignoring automatic enable request", chanPoint)
3✔
2776

3✔
2777
                        continue
3✔
2778

2779
                // If the channel is reported as inactive, we will give it
2780
                // another chance. When handling the request, ChanStatusManager
2781
                // will check whether the link is active or not. One of the
2782
                // conditions is whether the link has been marked as
2783
                // reestablished, which happens inside a goroutine(htlcManager)
2784
                // after the link is started. And we may get a false negative
2785
                // saying the link is not active because that goroutine hasn't
2786
                // reached the line to mark the reestablishment. Thus we give
2787
                // it a second chance to send the request.
2788
                case errors.Is(err, netann.ErrEnableInactiveChan):
×
2789
                        // If we don't have a client created, it means we
×
2790
                        // shouldn't retry enabling the channel.
×
2791
                        if p.channelEventClient == nil {
×
2792
                                p.log.Errorf("Channel(%v) request enabling "+
×
2793
                                        "failed due to inactive link",
×
2794
                                        chanPoint)
×
2795

×
2796
                                continue
×
2797
                        }
2798

2799
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
2800
                                "ChanStatusManager reported inactive, retrying")
×
2801

×
2802
                        // Add the channel to the retry map.
×
2803
                        retryChans[chanPoint] = struct{}{}
×
2804
                }
2805
        }
2806

2807
        // Retry the channels if we have any.
2808
        if len(retryChans) != 0 {
3✔
2809
                p.retryRequestEnable(retryChans)
×
2810
        }
×
2811
}
2812

2813
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
2814
// for the target channel ID. If the channel isn't active an error is returned.
2815
// Otherwise, either an existing state machine will be returned, or a new one
2816
// will be created.
2817
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
2818
        *chancloser.ChanCloser, error) {
3✔
2819

3✔
2820
        chanCloser, found := p.activeChanCloses[chanID]
3✔
2821
        if found {
6✔
2822
                // An entry will only be found if the closer has already been
3✔
2823
                // created for a non-pending channel or for a channel that had
3✔
2824
                // previously started the shutdown process but the connection
3✔
2825
                // was restarted.
3✔
2826
                return chanCloser, nil
3✔
2827
        }
3✔
2828

2829
        // First, we'll ensure that we actually know of the target channel. If
2830
        // not, we'll ignore this message.
2831
        channel, ok := p.activeChannels.Load(chanID)
3✔
2832

3✔
2833
        // If the channel isn't in the map or the channel is nil, return
3✔
2834
        // ErrChannelNotFound as the channel is pending.
3✔
2835
        if !ok || channel == nil {
6✔
2836
                return nil, ErrChannelNotFound
3✔
2837
        }
3✔
2838

2839
        // We'll create a valid closing state machine in order to respond to
2840
        // the initiated cooperative channel closure. First, we set the
2841
        // delivery script that our funds will be paid out to. If an upfront
2842
        // shutdown script was set, we will use it. Otherwise, we get a fresh
2843
        // delivery script.
2844
        //
2845
        // TODO: Expose option to allow upfront shutdown script from watch-only
2846
        // accounts.
2847
        deliveryScript := channel.LocalUpfrontShutdownScript()
3✔
2848
        if len(deliveryScript) == 0 {
6✔
2849
                var err error
3✔
2850
                deliveryScript, err = p.genDeliveryScript()
3✔
2851
                if err != nil {
3✔
2852
                        p.log.Errorf("unable to gen delivery script: %v",
×
2853
                                err)
×
2854
                        return nil, fmt.Errorf("close addr unavailable")
×
2855
                }
×
2856
        }
2857

2858
        // In order to begin fee negotiations, we'll first compute our target
2859
        // ideal fee-per-kw.
2860
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
2861
                p.cfg.CoopCloseTargetConfs,
3✔
2862
        )
3✔
2863
        if err != nil {
3✔
2864
                p.log.Errorf("unable to query fee estimator: %v", err)
×
2865
                return nil, fmt.Errorf("unable to estimate fee")
×
2866
        }
×
2867

2868
        chanCloser, err = p.createChanCloser(
3✔
2869
                channel, deliveryScript, feePerKw, nil, lntypes.Remote,
3✔
2870
        )
3✔
2871
        if err != nil {
3✔
2872
                p.log.Errorf("unable to create chan closer: %v", err)
×
2873
                return nil, fmt.Errorf("unable to create chan closer")
×
2874
        }
×
2875

2876
        p.activeChanCloses[chanID] = chanCloser
3✔
2877

3✔
2878
        return chanCloser, nil
3✔
2879
}
2880

2881
// filterChannelsToEnable filters a list of channels to be enabled upon start.
2882
// The filtered channels are active channels that's neither private nor
2883
// pending.
2884
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
3✔
2885
        var activePublicChans []wire.OutPoint
3✔
2886

3✔
2887
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
3✔
2888
                lnChan *lnwallet.LightningChannel) bool {
6✔
2889

3✔
2890
                // If the lnChan is nil, continue as this is a pending channel.
3✔
2891
                if lnChan == nil {
4✔
2892
                        return true
1✔
2893
                }
1✔
2894

2895
                dbChan := lnChan.State()
3✔
2896
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
2897
                if !isPublic || dbChan.IsPending {
3✔
2898
                        return true
×
2899
                }
×
2900

2901
                // We'll also skip any channels added during this peer's
2902
                // lifecycle since they haven't waited out the timeout. Their
2903
                // first announcement will be enabled, and the chan status
2904
                // manager will begin monitoring them passively since they exist
2905
                // in the database.
2906
                if _, ok := p.addedChannels.Load(chanID); ok {
5✔
2907
                        return true
2✔
2908
                }
2✔
2909

2910
                activePublicChans = append(
3✔
2911
                        activePublicChans, dbChan.FundingOutpoint,
3✔
2912
                )
3✔
2913

3✔
2914
                return true
3✔
2915
        })
2916

2917
        return activePublicChans
3✔
2918
}
2919

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

×
2927
        // retryEnable is a helper closure that sends an enable request and
×
2928
        // removes the channel from the map if it's matched.
×
2929
        retryEnable := func(chanPoint wire.OutPoint) error {
×
2930
                // If this is an active channel event, check whether it's in
×
2931
                // our targeted channels map.
×
2932
                _, found := activeChans[chanPoint]
×
2933

×
2934
                // If this channel is irrelevant, return nil so the loop can
×
2935
                // jump to next iteration.
×
2936
                if !found {
×
2937
                        return nil
×
2938
                }
×
2939

2940
                // Otherwise we've just received an active signal for a channel
2941
                // that's previously failed to be enabled, we send the request
2942
                // again.
2943
                //
2944
                // We only give the channel one more shot, so we delete it from
2945
                // our map first to keep it from being attempted again.
2946
                delete(activeChans, chanPoint)
×
2947

×
2948
                // Send the request.
×
2949
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
2950
                if err != nil {
×
2951
                        return fmt.Errorf("request enabling channel %v "+
×
2952
                                "failed: %w", chanPoint, err)
×
2953
                }
×
2954

2955
                return nil
×
2956
        }
2957

2958
        for {
×
2959
                // If activeChans is empty, we've done processing all the
×
2960
                // channels.
×
2961
                if len(activeChans) == 0 {
×
2962
                        p.log.Debug("Finished retry enabling channels")
×
2963
                        return
×
2964
                }
×
2965

2966
                select {
×
2967
                // A new event has been sent by the ChannelNotifier. We now
2968
                // check whether it's an active or inactive channel event.
2969
                case e := <-p.channelEventClient.Updates():
×
2970
                        // If this is an active channel event, try enable the
×
2971
                        // channel then jump to the next iteration.
×
2972
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
2973
                        if ok {
×
2974
                                chanPoint := *active.ChannelPoint
×
2975

×
2976
                                // If we received an error for this particular
×
2977
                                // channel, we log an error and won't quit as
×
2978
                                // we still want to retry other channels.
×
2979
                                if err := retryEnable(chanPoint); err != nil {
×
2980
                                        p.log.Errorf("Retry failed: %v", err)
×
2981
                                }
×
2982

2983
                                continue
×
2984
                        }
2985

2986
                        // Otherwise check for inactive link event, and jump to
2987
                        // next iteration if it's not.
2988
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
2989
                        if !ok {
×
2990
                                continue
×
2991
                        }
2992

2993
                        // Found an inactive link event, if this is our
2994
                        // targeted channel, remove it from our map.
2995
                        chanPoint := *inactive.ChannelPoint
×
2996
                        _, found := activeChans[chanPoint]
×
2997
                        if !found {
×
2998
                                continue
×
2999
                        }
3000

3001
                        delete(activeChans, chanPoint)
×
3002
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3003
                                "inactive link event", chanPoint)
×
3004

3005
                case <-p.quit:
×
3006
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3007
                        return
×
3008
                }
3009
        }
3010
}
3011

3012
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3013
// a suitable script to close out to. This may be nil if neither script is
3014
// set. If both scripts are set, this function will error if they do not match.
3015
func chooseDeliveryScript(upfront,
3016
        requested lnwire.DeliveryAddress) (lnwire.DeliveryAddress, error) {
3✔
3017

3✔
3018
        // If no upfront shutdown script was provided, return the user
3✔
3019
        // requested address (which may be nil).
3✔
3020
        if len(upfront) == 0 {
6✔
3021
                return requested, nil
3✔
3022
        }
3✔
3023

3024
        // If an upfront shutdown script was provided, and the user did not
3025
        // request a custom shutdown script, return the upfront address.
3026
        if len(requested) == 0 {
6✔
3027
                return upfront, nil
3✔
3028
        }
3✔
3029

3030
        // If both an upfront shutdown script and a custom close script were
3031
        // provided, error if the user provided shutdown script does not match
3032
        // the upfront shutdown script (because closing out to a different
3033
        // script would violate upfront shutdown).
3034
        if !bytes.Equal(upfront, requested) {
×
3035
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
×
3036
        }
×
3037

3038
        // The user requested script matches the upfront shutdown script, so we
3039
        // can return it without error.
3040
        return upfront, nil
×
3041
}
3042

3043
// restartCoopClose checks whether we need to restart the cooperative close
3044
// process for a given channel.
3045
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3046
        *lnwire.Shutdown, error) {
×
3047

×
3048
        // If this channel has status ChanStatusCoopBroadcasted and does not
×
3049
        // have a closing transaction, then the cooperative close process was
×
3050
        // started but never finished. We'll re-create the chanCloser state
×
3051
        // machine and resend Shutdown. BOLT#2 requires that we retransmit
×
3052
        // Shutdown exactly, but doing so would mean persisting the RPC
×
3053
        // provided close script. Instead use the LocalUpfrontShutdownScript
×
3054
        // or generate a script.
×
3055
        c := lnChan.State()
×
3056
        _, err := c.BroadcastedCooperative()
×
3057
        if err != nil && err != channeldb.ErrNoCloseTx {
×
3058
                // An error other than ErrNoCloseTx was encountered.
×
3059
                return nil, err
×
3060
        } else if err == nil {
×
3061
                // This channel has already completed the coop close
×
3062
                // negotiation.
×
3063
                return nil, nil
×
3064
        }
×
3065

3066
        var deliveryScript []byte
×
3067

×
3068
        shutdownInfo, err := c.ShutdownInfo()
×
3069
        switch {
×
3070
        // We have previously stored the delivery script that we need to use
3071
        // in the shutdown message. Re-use this script.
3072
        case err == nil:
×
3073
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
×
3074
                        deliveryScript = info.DeliveryScript.Val
×
3075
                })
×
3076

3077
        // An error other than ErrNoShutdownInfo was returned
3078
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3079
                return nil, err
×
3080

3081
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3082
                deliveryScript = c.LocalShutdownScript
×
3083
                if len(deliveryScript) == 0 {
×
3084
                        var err error
×
3085
                        deliveryScript, err = p.genDeliveryScript()
×
3086
                        if err != nil {
×
3087
                                p.log.Errorf("unable to gen delivery script: "+
×
3088
                                        "%v", err)
×
3089

×
3090
                                return nil, fmt.Errorf("close addr unavailable")
×
3091
                        }
×
3092
                }
3093
        }
3094

3095
        // Compute an ideal fee.
3096
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
3097
                p.cfg.CoopCloseTargetConfs,
×
3098
        )
×
3099
        if err != nil {
×
3100
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3101
                return nil, fmt.Errorf("unable to estimate fee")
×
3102
        }
×
3103

3104
        // Determine whether we or the peer are the initiator of the coop
3105
        // close attempt by looking at the channel's status.
3106
        closingParty := lntypes.Remote
×
3107
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3108
                closingParty = lntypes.Local
×
3109
        }
×
3110

3111
        chanCloser, err := p.createChanCloser(
×
3112
                lnChan, deliveryScript, feePerKw, nil, closingParty,
×
3113
        )
×
3114
        if err != nil {
×
3115
                p.log.Errorf("unable to create chan closer: %v", err)
×
3116
                return nil, fmt.Errorf("unable to create chan closer")
×
3117
        }
×
3118

3119
        // This does not need a mutex even though it is in a different
3120
        // goroutine since this is done before the channelManager goroutine is
3121
        // created.
3122
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
×
3123
        p.activeChanCloses[chanID] = chanCloser
×
3124

×
3125
        // Create the Shutdown message.
×
3126
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3127
        if err != nil {
×
3128
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3129
                delete(p.activeChanCloses, chanID)
×
3130
                return nil, err
×
3131
        }
×
3132

3133
        return shutdownMsg, nil
×
3134
}
3135

3136
// createChanCloser constructs a ChanCloser from the passed parameters and is
3137
// used to de-duplicate code.
3138
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3139
        deliveryScript lnwire.DeliveryAddress, fee chainfee.SatPerKWeight,
3140
        req *htlcswitch.ChanClose,
3141
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
3✔
3142

3✔
3143
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
3✔
3144
        if err != nil {
3✔
3145
                p.log.Errorf("unable to obtain best block: %v", err)
×
3146
                return nil, fmt.Errorf("cannot obtain best block")
×
3147
        }
×
3148

3149
        // The req will only be set if we initiated the co-op closing flow.
3150
        var maxFee chainfee.SatPerKWeight
3✔
3151
        if req != nil {
6✔
3152
                maxFee = req.MaxFee
3✔
3153
        }
3✔
3154

3155
        chanCloser := chancloser.NewChanCloser(
3✔
3156
                chancloser.ChanCloseCfg{
3✔
3157
                        Channel:      channel,
3✔
3158
                        MusigSession: NewMusigChanCloser(channel),
3✔
3159
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
3✔
3160
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
3✔
3161
                        DisableChannel: func(op wire.OutPoint) error {
6✔
3162
                                return p.cfg.ChanStatusMgr.RequestDisable(
3✔
3163
                                        op, false,
3✔
3164
                                )
3✔
3165
                        },
3✔
3166
                        MaxFee: maxFee,
3167
                        Disconnect: func() error {
×
3168
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
3169
                        },
×
3170
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3171
                        Quit:        p.quit,
3172
                },
3173
                deliveryScript,
3174
                fee,
3175
                uint32(startingHeight),
3176
                req,
3177
                closer,
3178
        )
3179

3180
        return chanCloser, nil
3✔
3181
}
3182

3183
// handleLocalCloseReq kicks-off the workflow to execute a cooperative or
3184
// forced unilateral closure of the channel initiated by a local subsystem.
3185
func (p *Brontide) handleLocalCloseReq(req *htlcswitch.ChanClose) {
3✔
3186
        chanID := lnwire.NewChanIDFromOutPoint(*req.ChanPoint)
3✔
3187

3✔
3188
        channel, ok := p.activeChannels.Load(chanID)
3✔
3189

3✔
3190
        // Though this function can't be called for pending channels, we still
3✔
3191
        // check whether channel is nil for safety.
3✔
3192
        if !ok || channel == nil {
3✔
3193
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
×
3194
                        "unknown", chanID)
×
3195
                p.log.Errorf(err.Error())
×
3196
                req.Err <- err
×
3197
                return
×
3198
        }
×
3199

3200
        switch req.CloseType {
3✔
3201
        // A type of CloseRegular indicates that the user has opted to close
3202
        // out this channel on-chain, so we execute the cooperative channel
3203
        // closure workflow.
3204
        case contractcourt.CloseRegular:
3✔
3205
                // First, we'll choose a delivery address that we'll use to send the
3✔
3206
                // funds to in the case of a successful negotiation.
3✔
3207

3✔
3208
                // An upfront shutdown and user provided script are both optional,
3✔
3209
                // but must be equal if both set  (because we cannot serve a request
3✔
3210
                // to close out to a script which violates upfront shutdown). Get the
3✔
3211
                // appropriate address to close out to (which may be nil if neither
3✔
3212
                // are set) and error if they are both set and do not match.
3✔
3213
                deliveryScript, err := chooseDeliveryScript(
3✔
3214
                        channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
3✔
3215
                )
3✔
3216
                if err != nil {
3✔
3217
                        p.log.Errorf("cannot close channel %v: %v", req.ChanPoint, err)
×
3218
                        req.Err <- err
×
3219
                        return
×
3220
                }
×
3221

3222
                // If neither an upfront address or a user set address was
3223
                // provided, generate a fresh script.
3224
                if len(deliveryScript) == 0 {
6✔
3225
                        deliveryScript, err = p.genDeliveryScript()
3✔
3226
                        if err != nil {
3✔
3227
                                p.log.Errorf(err.Error())
×
3228
                                req.Err <- err
×
3229
                                return
×
3230
                        }
×
3231
                }
3232

3233
                chanCloser, err := p.createChanCloser(
3✔
3234
                        channel, deliveryScript, req.TargetFeePerKw, req,
3✔
3235
                        lntypes.Local,
3✔
3236
                )
3✔
3237
                if err != nil {
3✔
3238
                        p.log.Errorf(err.Error())
×
3239
                        req.Err <- err
×
3240
                        return
×
3241
                }
×
3242

3243
                p.activeChanCloses[chanID] = chanCloser
3✔
3244

3✔
3245
                // Finally, we'll initiate the channel shutdown within the
3✔
3246
                // chanCloser, and send the shutdown message to the remote
3✔
3247
                // party to kick things off.
3✔
3248
                shutdownMsg, err := chanCloser.ShutdownChan()
3✔
3249
                if err != nil {
3✔
3250
                        p.log.Errorf(err.Error())
×
3251
                        req.Err <- err
×
3252
                        delete(p.activeChanCloses, chanID)
×
3253

×
3254
                        // As we were unable to shutdown the channel, we'll
×
3255
                        // return it back to its normal state.
×
3256
                        channel.ResetState()
×
3257
                        return
×
3258
                }
×
3259

3260
                link := p.fetchLinkFromKeyAndCid(chanID)
3✔
3261
                if link == nil {
3✔
3262
                        // If the link is nil then it means it was already
×
3263
                        // removed from the switch or it never existed in the
×
3264
                        // first place. The latter case is handled at the
×
3265
                        // beginning of this function, so in the case where it
×
3266
                        // has already been removed, we can skip adding the
×
3267
                        // commit hook to queue a Shutdown message.
×
3268
                        p.log.Warnf("link not found during attempted closure: "+
×
3269
                                "%v", chanID)
×
3270
                        return
×
3271
                }
×
3272

3273
                if !link.DisableAdds(htlcswitch.Outgoing) {
3✔
3274
                        p.log.Warnf("Outgoing link adds already "+
×
3275
                                "disabled: %v", link.ChanID())
×
3276
                }
×
3277

3278
                link.OnCommitOnce(htlcswitch.Outgoing, func() {
6✔
3279
                        p.queueMsg(shutdownMsg, nil)
3✔
3280
                })
3✔
3281

3282
        // A type of CloseBreach indicates that the counterparty has breached
3283
        // the channel therefore we need to clean up our local state.
3284
        case contractcourt.CloseBreach:
×
3285
                // TODO(roasbeef): no longer need with newer beach logic?
×
3286
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
×
3287
                        "channel", req.ChanPoint)
×
3288
                p.WipeChannel(req.ChanPoint)
×
3289
        }
3290
}
3291

3292
// linkFailureReport is sent to the channelManager whenever a link reports a
3293
// link failure, and is forced to exit. The report houses the necessary
3294
// information to clean up the channel state, send back the error message, and
3295
// force close if necessary.
3296
type linkFailureReport struct {
3297
        chanPoint   wire.OutPoint
3298
        chanID      lnwire.ChannelID
3299
        shortChanID lnwire.ShortChannelID
3300
        linkErr     htlcswitch.LinkFailureError
3301
}
3302

3303
// handleLinkFailure processes a link failure report when a link in the switch
3304
// fails. It facilitates the removal of all channel state within the peer,
3305
// force closing the channel depending on severity, and sending the error
3306
// message back to the remote party.
3307
func (p *Brontide) handleLinkFailure(failure linkFailureReport) {
3✔
3308
        // Retrieve the channel from the map of active channels. We do this to
3✔
3309
        // have access to it even after WipeChannel remove it from the map.
3✔
3310
        chanID := lnwire.NewChanIDFromOutPoint(failure.chanPoint)
3✔
3311
        lnChan, _ := p.activeChannels.Load(chanID)
3✔
3312

3✔
3313
        // We begin by wiping the link, which will remove it from the switch,
3✔
3314
        // such that it won't be attempted used for any more updates.
3✔
3315
        //
3✔
3316
        // TODO(halseth): should introduce a way to atomically stop/pause the
3✔
3317
        // link and cancel back any adds in its mailboxes such that we can
3✔
3318
        // safely force close without the link being added again and updates
3✔
3319
        // being applied.
3✔
3320
        p.WipeChannel(&failure.chanPoint)
3✔
3321

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

3✔
3327
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
3✔
3328
                        failure.chanPoint,
3✔
3329
                )
3✔
3330
                if err != nil {
6✔
3331
                        p.log.Errorf("unable to force close "+
3✔
3332
                                "link(%v): %v", failure.shortChanID, err)
3✔
3333
                } else {
6✔
3334
                        p.log.Infof("channel(%v) force "+
3✔
3335
                                "closed with txid %v",
3✔
3336
                                failure.shortChanID, closeTx.TxHash())
3✔
3337
                }
3✔
3338
        }
3339

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

×
3345
                if err := lnChan.State().MarkBorked(); err != nil {
×
3346
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
3347
                                failure.shortChanID, err)
×
3348
                }
×
3349
        }
3350

3351
        // Send an error to the peer, why we failed the channel.
3352
        if failure.linkErr.ShouldSendToPeer() {
6✔
3353
                // If SendData is set, send it to the peer. If not, we'll use
3✔
3354
                // the standard error messages in the payload. We only include
3✔
3355
                // sendData in the cases where the error data does not contain
3✔
3356
                // sensitive information.
3✔
3357
                data := []byte(failure.linkErr.Error())
3✔
3358
                if failure.linkErr.SendData != nil {
3✔
3359
                        data = failure.linkErr.SendData
×
3360
                }
×
3361

3362
                var networkMsg lnwire.Message
3✔
3363
                if failure.linkErr.Warning {
3✔
3364
                        networkMsg = &lnwire.Warning{
×
3365
                                ChanID: failure.chanID,
×
3366
                                Data:   data,
×
3367
                        }
×
3368
                } else {
3✔
3369
                        networkMsg = &lnwire.Error{
3✔
3370
                                ChanID: failure.chanID,
3✔
3371
                                Data:   data,
3✔
3372
                        }
3✔
3373
                }
3✔
3374

3375
                err := p.SendMessage(true, networkMsg)
3✔
3376
                if err != nil {
3✔
3377
                        p.log.Errorf("unable to send msg to "+
×
3378
                                "remote peer: %v", err)
×
3379
                }
×
3380
        }
3381

3382
        // If the failure action is disconnect, then we'll execute that now. If
3383
        // we had to send an error above, it was a sync call, so we expect the
3384
        // message to be flushed on the wire by now.
3385
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
3✔
3386
                p.Disconnect(fmt.Errorf("link requested disconnect"))
×
3387
        }
×
3388
}
3389

3390
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
3391
// public key and the channel id.
3392
func (p *Brontide) fetchLinkFromKeyAndCid(
3393
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
3✔
3394

3✔
3395
        var chanLink htlcswitch.ChannelUpdateHandler
3✔
3396

3✔
3397
        // We don't need to check the error here, and can instead just loop
3✔
3398
        // over the slice and return nil.
3✔
3399
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
3✔
3400
        for _, link := range links {
6✔
3401
                if link.ChanID() == cid {
6✔
3402
                        chanLink = link
3✔
3403
                        break
3✔
3404
                }
3405
        }
3406

3407
        return chanLink
3✔
3408
}
3409

3410
// finalizeChanClosure performs the final clean up steps once the cooperative
3411
// closure transaction has been fully broadcast. The finalized closing state
3412
// machine should be passed in. Once the transaction has been sufficiently
3413
// confirmed, the channel will be marked as fully closed within the database,
3414
// and any clients will be notified of updates to the closing state.
3415
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
3✔
3416
        closeReq := chanCloser.CloseRequest()
3✔
3417

3✔
3418
        // First, we'll clear all indexes related to the channel in question.
3✔
3419
        chanPoint := chanCloser.Channel().ChannelPoint()
3✔
3420
        p.WipeChannel(&chanPoint)
3✔
3421

3✔
3422
        // Also clear the activeChanCloses map of this channel.
3✔
3423
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
3424
        delete(p.activeChanCloses, cid)
3✔
3425

3✔
3426
        // Next, we'll launch a goroutine which will request to be notified by
3✔
3427
        // the ChainNotifier once the closure transaction obtains a single
3✔
3428
        // confirmation.
3✔
3429
        notifier := p.cfg.ChainNotifier
3✔
3430

3✔
3431
        // If any error happens during waitForChanToClose, forward it to
3✔
3432
        // closeReq. If this channel closure is not locally initiated, closeReq
3✔
3433
        // will be nil, so just ignore the error.
3✔
3434
        errChan := make(chan error, 1)
3✔
3435
        if closeReq != nil {
6✔
3436
                errChan = closeReq.Err
3✔
3437
        }
3✔
3438

3439
        closingTx, err := chanCloser.ClosingTx()
3✔
3440
        if err != nil {
3✔
3441
                if closeReq != nil {
×
3442
                        p.log.Error(err)
×
3443
                        closeReq.Err <- err
×
3444
                }
×
3445
        }
3446

3447
        closingTxid := closingTx.TxHash()
3✔
3448

3✔
3449
        // If this is a locally requested shutdown, update the caller with a
3✔
3450
        // new event detailing the current pending state of this request.
3✔
3451
        if closeReq != nil {
6✔
3452
                closeReq.Updates <- &PendingUpdate{
3✔
3453
                        Txid: closingTxid[:],
3✔
3454
                }
3✔
3455
        }
3✔
3456

3457
        go WaitForChanToClose(chanCloser.NegotiationHeight(), notifier, errChan,
3✔
3458
                &chanPoint, &closingTxid, closingTx.TxOut[0].PkScript, func() {
6✔
3459
                        // Respond to the local subsystem which requested the
3✔
3460
                        // channel closure.
3✔
3461
                        if closeReq != nil {
6✔
3462
                                closeReq.Updates <- &ChannelCloseUpdate{
3✔
3463
                                        ClosingTxid: closingTxid[:],
3✔
3464
                                        Success:     true,
3✔
3465
                                }
3✔
3466
                        }
3✔
3467
                })
3468
}
3469

3470
// WaitForChanToClose uses the passed notifier to wait until the channel has
3471
// been detected as closed on chain and then concludes by executing the
3472
// following actions: the channel point will be sent over the settleChan, and
3473
// finally the callback will be executed. If any error is encountered within
3474
// the function, then it will be sent over the errChan.
3475
func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
3476
        errChan chan error, chanPoint *wire.OutPoint,
3477
        closingTxID *chainhash.Hash, closeScript []byte, cb func()) {
3✔
3478

3✔
3479
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
3✔
3480
                "with txid: %v", chanPoint, closingTxID)
3✔
3481

3✔
3482
        // TODO(roasbeef): add param for num needed confs
3✔
3483
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
3✔
3484
                closingTxID, closeScript, 1, bestHeight,
3✔
3485
        )
3✔
3486
        if err != nil {
3✔
3487
                if errChan != nil {
×
3488
                        errChan <- err
×
3489
                }
×
3490
                return
×
3491
        }
3492

3493
        // In the case that the ChainNotifier is shutting down, all subscriber
3494
        // notification channels will be closed, generating a nil receive.
3495
        height, ok := <-confNtfn.Confirmed
3✔
3496
        if !ok {
6✔
3497
                return
3✔
3498
        }
3✔
3499

3500
        // The channel has been closed, remove it from any active indexes, and
3501
        // the database state.
3502
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
3✔
3503
                "height %v", chanPoint, height.BlockHeight)
3✔
3504

3✔
3505
        // Finally, execute the closure call back to mark the confirmation of
3✔
3506
        // the transaction closing the contract.
3✔
3507
        cb()
3✔
3508
}
3509

3510
// WipeChannel removes the passed channel point from all indexes associated with
3511
// the peer and the switch.
3512
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
3✔
3513
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
3✔
3514

3✔
3515
        p.activeChannels.Delete(chanID)
3✔
3516

3✔
3517
        // Instruct the HtlcSwitch to close this link as the channel is no
3✔
3518
        // longer active.
3✔
3519
        p.cfg.Switch.RemoveLink(chanID)
3✔
3520
}
3✔
3521

3522
// handleInitMsg handles the incoming init message which contains global and
3523
// local feature vectors. If feature vectors are incompatible then disconnect.
3524
func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
3✔
3525
        // First, merge any features from the legacy global features field into
3✔
3526
        // those presented in the local features fields.
3✔
3527
        err := msg.Features.Merge(msg.GlobalFeatures)
3✔
3528
        if err != nil {
3✔
3529
                return fmt.Errorf("unable to merge legacy global features: %w",
×
3530
                        err)
×
3531
        }
×
3532

3533
        // Then, finalize the remote feature vector providing the flattened
3534
        // feature bit namespace.
3535
        p.remoteFeatures = lnwire.NewFeatureVector(
3✔
3536
                msg.Features, lnwire.Features,
3✔
3537
        )
3✔
3538

3✔
3539
        // Now that we have their features loaded, we'll ensure that they
3✔
3540
        // didn't set any required bits that we don't know of.
3✔
3541
        err = feature.ValidateRequired(p.remoteFeatures)
3✔
3542
        if err != nil {
3✔
3543
                return fmt.Errorf("invalid remote features: %w", err)
×
3544
        }
×
3545

3546
        // Ensure the remote party's feature vector contains all transitive
3547
        // dependencies. We know ours are correct since they are validated
3548
        // during the feature manager's instantiation.
3549
        err = feature.ValidateDeps(p.remoteFeatures)
3✔
3550
        if err != nil {
3✔
3551
                return fmt.Errorf("invalid remote features: %w", err)
×
3552
        }
×
3553

3554
        // Now that we know we understand their requirements, we'll check to
3555
        // see if they don't support anything that we deem to be mandatory.
3556
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
3✔
3557
                return fmt.Errorf("data loss protection required")
×
3558
        }
×
3559

3560
        return nil
3✔
3561
}
3562

3563
// LocalFeatures returns the set of global features that has been advertised by
3564
// the local node. This allows sub-systems that use this interface to gate their
3565
// behavior off the set of negotiated feature bits.
3566
//
3567
// NOTE: Part of the lnpeer.Peer interface.
3568
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
3✔
3569
        return p.cfg.Features
3✔
3570
}
3✔
3571

3572
// RemoteFeatures returns the set of global features that has been advertised by
3573
// the remote node. This allows sub-systems that use this interface to gate
3574
// their behavior off the set of negotiated feature bits.
3575
//
3576
// NOTE: Part of the lnpeer.Peer interface.
3577
func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector {
3✔
3578
        return p.remoteFeatures
3✔
3579
}
3✔
3580

3581
// hasNegotiatedScidAlias returns true if we've negotiated the
3582
// option-scid-alias feature bit with the peer.
3583
func (p *Brontide) hasNegotiatedScidAlias() bool {
3✔
3584
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
3✔
3585
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
3✔
3586
        return peerHas && localHas
3✔
3587
}
3✔
3588

3589
// sendInitMsg sends the Init message to the remote peer. This message contains
3590
// our currently supported local and global features.
3591
func (p *Brontide) sendInitMsg(legacyChan bool) error {
3✔
3592
        features := p.cfg.Features.Clone()
3✔
3593
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
3✔
3594

3✔
3595
        // If we have a legacy channel open with a peer, we downgrade static
3✔
3596
        // remote required to optional in case the peer does not understand the
3✔
3597
        // required feature bit. If we do not do this, the peer will reject our
3✔
3598
        // connection because it does not understand a required feature bit, and
3✔
3599
        // our channel will be unusable.
3✔
3600
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
3✔
3601
                p.log.Infof("Legacy channel open with peer, " +
×
3602
                        "downgrading static remote required feature bit to " +
×
3603
                        "optional")
×
3604

×
3605
                // Unset and set in both the local and global features to
×
3606
                // ensure both sets are consistent and merge able by old and
×
3607
                // new nodes.
×
3608
                features.Unset(lnwire.StaticRemoteKeyRequired)
×
3609
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
×
3610

×
3611
                features.Set(lnwire.StaticRemoteKeyOptional)
×
3612
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
×
3613
        }
×
3614

3615
        msg := lnwire.NewInitMessage(
3✔
3616
                legacyFeatures.RawFeatureVector,
3✔
3617
                features.RawFeatureVector,
3✔
3618
        )
3✔
3619

3✔
3620
        return p.writeMessage(msg)
3✔
3621
}
3622

3623
// resendChanSyncMsg will attempt to find a channel sync message for the closed
3624
// channel and resend it to our peer.
3625
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
3✔
3626
        // If we already re-sent the mssage for this channel, we won't do it
3✔
3627
        // again.
3✔
3628
        if _, ok := p.resentChanSyncMsg[cid]; ok {
4✔
3629
                return nil
1✔
3630
        }
1✔
3631

3632
        // Check if we have any channel sync messages stored for this channel.
3633
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
3✔
3634
        if err != nil {
6✔
3635
                return fmt.Errorf("unable to fetch channel sync messages for "+
3✔
3636
                        "peer %v: %v", p, err)
3✔
3637
        }
3✔
3638

3639
        if c.LastChanSyncMsg == nil {
3✔
3640
                return fmt.Errorf("no chan sync message stored for channel %v",
×
3641
                        cid)
×
3642
        }
×
3643

3644
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
3✔
3645
                return fmt.Errorf("ignoring channel reestablish from "+
×
3646
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
3647
        }
×
3648

3649
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
3✔
3650
                "peer", cid)
3✔
3651

3✔
3652
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
3✔
3653
                return fmt.Errorf("failed resending channel sync "+
×
3654
                        "message to peer %v: %v", p, err)
×
3655
        }
×
3656

3657
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
3✔
3658
                cid)
3✔
3659

3✔
3660
        // Note down that we sent the message, so we won't resend it again for
3✔
3661
        // this connection.
3✔
3662
        p.resentChanSyncMsg[cid] = struct{}{}
3✔
3663

3✔
3664
        return nil
3✔
3665
}
3666

3667
// SendMessage sends a variadic number of high-priority messages to the remote
3668
// peer. The first argument denotes if the method should block until the
3669
// messages have been sent to the remote peer or an error is returned,
3670
// otherwise it returns immediately after queuing.
3671
//
3672
// NOTE: Part of the lnpeer.Peer interface.
3673
func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error {
3✔
3674
        return p.sendMessage(sync, true, msgs...)
3✔
3675
}
3✔
3676

3677
// SendMessageLazy sends a variadic number of low-priority messages to the
3678
// remote peer. The first argument denotes if the method should block until
3679
// the messages have been sent to the remote peer or an error is returned,
3680
// otherwise it returns immediately after queueing.
3681
//
3682
// NOTE: Part of the lnpeer.Peer interface.
3683
func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
3✔
3684
        return p.sendMessage(sync, false, msgs...)
3✔
3685
}
3✔
3686

3687
// sendMessage queues a variadic number of messages using the passed priority
3688
// to the remote peer. If sync is true, this method will block until the
3689
// messages have been sent to the remote peer or an error is returned, otherwise
3690
// it returns immediately after queueing.
3691
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
3✔
3692
        // Add all incoming messages to the outgoing queue. A list of error
3✔
3693
        // chans is populated for each message if the caller requested a sync
3✔
3694
        // send.
3✔
3695
        var errChans []chan error
3✔
3696
        if sync {
6✔
3697
                errChans = make([]chan error, 0, len(msgs))
3✔
3698
        }
3✔
3699
        for _, msg := range msgs {
6✔
3700
                // If a sync send was requested, create an error chan to listen
3✔
3701
                // for an ack from the writeHandler.
3✔
3702
                var errChan chan error
3✔
3703
                if sync {
6✔
3704
                        errChan = make(chan error, 1)
3✔
3705
                        errChans = append(errChans, errChan)
3✔
3706
                }
3✔
3707

3708
                if priority {
6✔
3709
                        p.queueMsg(msg, errChan)
3✔
3710
                } else {
6✔
3711
                        p.queueMsgLazy(msg, errChan)
3✔
3712
                }
3✔
3713
        }
3714

3715
        // Wait for all replies from the writeHandler. For async sends, this
3716
        // will be a NOP as the list of error chans is nil.
3717
        for _, errChan := range errChans {
6✔
3718
                select {
3✔
3719
                case err := <-errChan:
3✔
3720
                        return err
3✔
3721
                case <-p.quit:
×
3722
                        return lnpeer.ErrPeerExiting
×
3723
                case <-p.cfg.Quit:
×
3724
                        return lnpeer.ErrPeerExiting
×
3725
                }
3726
        }
3727

3728
        return nil
3✔
3729
}
3730

3731
// PubKey returns the pubkey of the peer in compressed serialized format.
3732
//
3733
// NOTE: Part of the lnpeer.Peer interface.
3734
func (p *Brontide) PubKey() [33]byte {
3✔
3735
        return p.cfg.PubKeyBytes
3✔
3736
}
3✔
3737

3738
// IdentityKey returns the public key of the remote peer.
3739
//
3740
// NOTE: Part of the lnpeer.Peer interface.
3741
func (p *Brontide) IdentityKey() *btcec.PublicKey {
3✔
3742
        return p.cfg.Addr.IdentityKey
3✔
3743
}
3✔
3744

3745
// Address returns the network address of the remote peer.
3746
//
3747
// NOTE: Part of the lnpeer.Peer interface.
3748
func (p *Brontide) Address() net.Addr {
3✔
3749
        return p.cfg.Addr.Address
3✔
3750
}
3✔
3751

3752
// AddNewChannel adds a new channel to the peer. The channel should fail to be
3753
// added if the cancel channel is closed.
3754
//
3755
// NOTE: Part of the lnpeer.Peer interface.
3756
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
3757
        cancel <-chan struct{}) error {
3✔
3758

3✔
3759
        errChan := make(chan error, 1)
3✔
3760
        newChanMsg := &newChannelMsg{
3✔
3761
                channel: newChan,
3✔
3762
                err:     errChan,
3✔
3763
        }
3✔
3764

3✔
3765
        select {
3✔
3766
        case p.newActiveChannel <- newChanMsg:
3✔
3767
        case <-cancel:
×
3768
                return errors.New("canceled adding new channel")
×
3769
        case <-p.quit:
×
3770
                return lnpeer.ErrPeerExiting
×
3771
        }
3772

3773
        // We pause here to wait for the peer to recognize the new channel
3774
        // before we close the channel barrier corresponding to the channel.
3775
        select {
3✔
3776
        case err := <-errChan:
3✔
3777
                return err
3✔
3778
        case <-p.quit:
×
3779
                return lnpeer.ErrPeerExiting
×
3780
        }
3781
}
3782

3783
// AddPendingChannel adds a pending open channel to the peer. The channel
3784
// should fail to be added if the cancel channel is closed.
3785
//
3786
// NOTE: Part of the lnpeer.Peer interface.
3787
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
3788
        cancel <-chan struct{}) error {
3✔
3789

3✔
3790
        errChan := make(chan error, 1)
3✔
3791
        newChanMsg := &newChannelMsg{
3✔
3792
                channelID: cid,
3✔
3793
                err:       errChan,
3✔
3794
        }
3✔
3795

3✔
3796
        select {
3✔
3797
        case p.newPendingChannel <- newChanMsg:
3✔
3798

3799
        case <-cancel:
×
3800
                return errors.New("canceled adding pending channel")
×
3801

3802
        case <-p.quit:
×
3803
                return lnpeer.ErrPeerExiting
×
3804
        }
3805

3806
        // We pause here to wait for the peer to recognize the new pending
3807
        // channel before we close the channel barrier corresponding to the
3808
        // channel.
3809
        select {
3✔
3810
        case err := <-errChan:
3✔
3811
                return err
3✔
3812

3813
        case <-cancel:
×
3814
                return errors.New("canceled adding pending channel")
×
3815

3816
        case <-p.quit:
×
3817
                return lnpeer.ErrPeerExiting
×
3818
        }
3819
}
3820

3821
// RemovePendingChannel removes a pending open channel from the peer.
3822
//
3823
// NOTE: Part of the lnpeer.Peer interface.
3824
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
3✔
3825
        errChan := make(chan error, 1)
3✔
3826
        newChanMsg := &newChannelMsg{
3✔
3827
                channelID: cid,
3✔
3828
                err:       errChan,
3✔
3829
        }
3✔
3830

3✔
3831
        select {
3✔
3832
        case p.removePendingChannel <- newChanMsg:
3✔
3833
        case <-p.quit:
×
3834
                return lnpeer.ErrPeerExiting
×
3835
        }
3836

3837
        // We pause here to wait for the peer to respond to the cancellation of
3838
        // the pending channel before we close the channel barrier
3839
        // corresponding to the channel.
3840
        select {
3✔
3841
        case err := <-errChan:
3✔
3842
                return err
3✔
3843

3844
        case <-p.quit:
×
3845
                return lnpeer.ErrPeerExiting
×
3846
        }
3847
}
3848

3849
// StartTime returns the time at which the connection was established if the
3850
// peer started successfully, and zero otherwise.
3851
func (p *Brontide) StartTime() time.Time {
3✔
3852
        return p.startTime
3✔
3853
}
3✔
3854

3855
// handleCloseMsg is called when a new cooperative channel closure related
3856
// message is received from the remote peer. We'll use this message to advance
3857
// the chan closer state machine.
3858
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
3✔
3859
        link := p.fetchLinkFromKeyAndCid(msg.cid)
3✔
3860

3✔
3861
        // We'll now fetch the matching closing state machine in order to continue,
3✔
3862
        // or finalize the channel closure process.
3✔
3863
        chanCloser, err := p.fetchActiveChanCloser(msg.cid)
3✔
3864
        if err != nil {
6✔
3865
                // If the channel is not known to us, we'll simply ignore this message.
3✔
3866
                if err == ErrChannelNotFound {
6✔
3867
                        return
3✔
3868
                }
3✔
3869

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

×
3872
                errMsg := &lnwire.Error{
×
3873
                        ChanID: msg.cid,
×
3874
                        Data:   lnwire.ErrorData(err.Error()),
×
3875
                }
×
3876
                p.queueMsg(errMsg, nil)
×
3877
                return
×
3878
        }
3879

3880
        handleErr := func(err error) {
4✔
3881
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
3882
                p.log.Error(err)
1✔
3883

1✔
3884
                // As the negotiations failed, we'll reset the channel state machine to
1✔
3885
                // ensure we act to on-chain events as normal.
1✔
3886
                chanCloser.Channel().ResetState()
1✔
3887

1✔
3888
                if chanCloser.CloseRequest() != nil {
1✔
3889
                        chanCloser.CloseRequest().Err <- err
×
3890
                }
×
3891
                delete(p.activeChanCloses, msg.cid)
1✔
3892

1✔
3893
                p.Disconnect(err)
1✔
3894
        }
3895

3896
        // Next, we'll process the next message using the target state machine.
3897
        // We'll either continue negotiation, or halt.
3898
        switch typed := msg.msg.(type) {
3✔
3899
        case *lnwire.Shutdown:
3✔
3900
                // Disable incoming adds immediately.
3✔
3901
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
3✔
3902
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
3903
                                link.ChanID())
×
3904
                }
×
3905

3906
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
3✔
3907
                if err != nil {
3✔
3908
                        handleErr(err)
×
3909
                        return
×
3910
                }
×
3911

3912
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
6✔
3913
                        // If the link is nil it means we can immediately queue
3✔
3914
                        // the Shutdown message since we don't have to wait for
3✔
3915
                        // commitment transaction synchronization.
3✔
3916
                        if link == nil {
3✔
3917
                                p.queueMsg(&msg, nil)
×
3918
                                return
×
3919
                        }
×
3920

3921
                        // Immediately disallow any new HTLC's from being added
3922
                        // in the outgoing direction.
3923
                        if !link.DisableAdds(htlcswitch.Outgoing) {
3✔
3924
                                p.log.Warnf("Outgoing link adds already "+
×
3925
                                        "disabled: %v", link.ChanID())
×
3926
                        }
×
3927

3928
                        // When we have a Shutdown to send, we defer it till the
3929
                        // next time we send a CommitSig to remain spec
3930
                        // compliant.
3931
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
6✔
3932
                                p.queueMsg(&msg, nil)
3✔
3933
                        })
3✔
3934
                })
3935

3936
                beginNegotiation := func() {
6✔
3937
                        oClosingSigned, err := chanCloser.BeginNegotiation()
3✔
3938
                        if err != nil {
3✔
3939
                                handleErr(err)
×
3940
                                return
×
3941
                        }
×
3942

3943
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
6✔
3944
                                p.queueMsg(&msg, nil)
3✔
3945
                        })
3✔
3946
                }
3947

3948
                if link == nil {
3✔
3949
                        beginNegotiation()
×
3950
                } else {
3✔
3951
                        // Now we register a flush hook to advance the
3✔
3952
                        // ChanCloser and possibly send out a ClosingSigned
3✔
3953
                        // when the link finishes draining.
3✔
3954
                        link.OnFlushedOnce(func() {
6✔
3955
                                // Remove link in goroutine to prevent deadlock.
3✔
3956
                                go p.cfg.Switch.RemoveLink(msg.cid)
3✔
3957
                                beginNegotiation()
3✔
3958
                        })
3✔
3959
                }
3960

3961
        case *lnwire.ClosingSigned:
3✔
3962
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
3✔
3963
                if err != nil {
4✔
3964
                        handleErr(err)
1✔
3965
                        return
1✔
3966
                }
1✔
3967

3968
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
6✔
3969
                        p.queueMsg(&msg, nil)
3✔
3970
                })
3✔
3971

3972
        default:
×
3973
                panic("impossible closeMsg type")
×
3974
        }
3975

3976
        // If we haven't finished close negotiations, then we'll continue as we
3977
        // can't yet finalize the closure.
3978
        if _, err := chanCloser.ClosingTx(); err != nil {
6✔
3979
                return
3✔
3980
        }
3✔
3981

3982
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
3983
        // the channel closure by notifying relevant sub-systems and launching a
3984
        // goroutine to wait for close tx conf.
3985
        p.finalizeChanClosure(chanCloser)
3✔
3986
}
3987

3988
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
3989
// the channelManager goroutine, which will shut down the link and possibly
3990
// close the channel.
3991
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
3✔
3992
        select {
3✔
3993
        case p.localCloseChanReqs <- req:
3✔
3994
                p.log.Info("Local close channel request is going to be " +
3✔
3995
                        "delivered to the peer")
3✔
3996
        case <-p.quit:
×
3997
                p.log.Info("Unable to deliver local close channel request " +
×
3998
                        "to peer")
×
3999
        }
4000
}
4001

4002
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
4003
func (p *Brontide) NetAddress() *lnwire.NetAddress {
3✔
4004
        return p.cfg.Addr
3✔
4005
}
3✔
4006

4007
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
4008
func (p *Brontide) Inbound() bool {
3✔
4009
        return p.cfg.Inbound
3✔
4010
}
3✔
4011

4012
// ConnReq is a getter for the Brontide's connReq in cfg.
4013
func (p *Brontide) ConnReq() *connmgr.ConnReq {
3✔
4014
        return p.cfg.ConnReq
3✔
4015
}
3✔
4016

4017
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
4018
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
3✔
4019
        return p.cfg.ErrorBuffer
3✔
4020
}
3✔
4021

4022
// SetAddress sets the remote peer's address given an address.
4023
func (p *Brontide) SetAddress(address net.Addr) {
×
4024
        p.cfg.Addr.Address = address
×
4025
}
×
4026

4027
// ActiveSignal returns the peer's active signal.
4028
func (p *Brontide) ActiveSignal() chan struct{} {
3✔
4029
        return p.activeSignal
3✔
4030
}
3✔
4031

4032
// Conn returns a pointer to the peer's connection struct.
4033
func (p *Brontide) Conn() net.Conn {
3✔
4034
        return p.cfg.Conn
3✔
4035
}
3✔
4036

4037
// BytesReceived returns the number of bytes received from the peer.
4038
func (p *Brontide) BytesReceived() uint64 {
3✔
4039
        return atomic.LoadUint64(&p.bytesReceived)
3✔
4040
}
3✔
4041

4042
// BytesSent returns the number of bytes sent to the peer.
4043
func (p *Brontide) BytesSent() uint64 {
3✔
4044
        return atomic.LoadUint64(&p.bytesSent)
3✔
4045
}
3✔
4046

4047
// LastRemotePingPayload returns the last payload the remote party sent as part
4048
// of their ping.
4049
func (p *Brontide) LastRemotePingPayload() []byte {
3✔
4050
        pingPayload := p.lastPingPayload.Load()
3✔
4051
        if pingPayload == nil {
6✔
4052
                return []byte{}
3✔
4053
        }
3✔
4054

4055
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
1✔
4056
        if !ok {
1✔
4057
                return nil
×
4058
        }
×
4059

4060
        return pingBytes
1✔
4061
}
4062

4063
// attachChannelEventSubscription creates a channel event subscription and
4064
// attaches to client to Brontide if the reenableTimeout is no greater than 1
4065
// minute.
4066
func (p *Brontide) attachChannelEventSubscription() error {
3✔
4067
        // If the timeout is greater than 1 minute, it's unlikely that the link
3✔
4068
        // hasn't yet finished its reestablishment. Return a nil without
3✔
4069
        // creating the client to specify that we don't want to retry.
3✔
4070
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
6✔
4071
                return nil
3✔
4072
        }
3✔
4073

4074
        // When the reenable timeout is less than 1 minute, it's likely the
4075
        // channel link hasn't finished its reestablishment yet. In that case,
4076
        // we'll give it a second chance by subscribing to the channel update
4077
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
4078
        // enabling the channel again.
4079
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
3✔
4080
        if err != nil {
3✔
4081
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
4082
        }
×
4083

4084
        p.channelEventClient = sub
3✔
4085

3✔
4086
        return nil
3✔
4087
}
4088

4089
// updateNextRevocation updates the existing channel's next revocation if it's
4090
// nil.
4091
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
3✔
4092
        chanPoint := c.FundingOutpoint
3✔
4093
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4094

3✔
4095
        // Read the current channel.
3✔
4096
        currentChan, loaded := p.activeChannels.Load(chanID)
3✔
4097

3✔
4098
        // currentChan should exist, but we perform a check anyway to avoid nil
3✔
4099
        // pointer dereference.
3✔
4100
        if !loaded {
3✔
4101
                return fmt.Errorf("missing active channel with chanID=%v",
×
4102
                        chanID)
×
4103
        }
×
4104

4105
        // currentChan should not be nil, but we perform a check anyway to
4106
        // avoid nil pointer dereference.
4107
        if currentChan == nil {
3✔
4108
                return fmt.Errorf("found nil active channel with chanID=%v",
×
4109
                        chanID)
×
4110
        }
×
4111

4112
        // If we're being sent a new channel, and our existing channel doesn't
4113
        // have the next revocation, then we need to update the current
4114
        // existing channel.
4115
        if currentChan.RemoteNextRevocation() != nil {
3✔
4116
                return nil
×
4117
        }
×
4118

4119
        p.log.Infof("Processing retransmitted ChannelReady for "+
3✔
4120
                "ChannelPoint(%v)", chanPoint)
3✔
4121

3✔
4122
        nextRevoke := c.RemoteNextRevocation
3✔
4123

3✔
4124
        err := currentChan.InitNextRevocation(nextRevoke)
3✔
4125
        if err != nil {
3✔
4126
                return fmt.Errorf("unable to init next revocation: %w", err)
×
4127
        }
×
4128

4129
        return nil
3✔
4130
}
4131

4132
// addActiveChannel adds a new active channel to the `activeChannels` map. It
4133
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
4134
// it and assembles it with a channel link.
4135
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
3✔
4136
        chanPoint := c.FundingOutpoint
3✔
4137
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4138

3✔
4139
        // If we've reached this point, there are two possible scenarios.  If
3✔
4140
        // the channel was in the active channels map as nil, then it was
3✔
4141
        // loaded from disk and we need to send reestablish. Else, it was not
3✔
4142
        // loaded from disk and we don't need to send reestablish as this is a
3✔
4143
        // fresh channel.
3✔
4144
        shouldReestablish := p.isLoadedFromDisk(chanID)
3✔
4145

3✔
4146
        chanOpts := c.ChanOpts
3✔
4147
        if shouldReestablish {
6✔
4148
                // If we have to do the reestablish dance for this channel,
3✔
4149
                // ensure that we don't try to call InitRemoteMusigNonces twice
3✔
4150
                // by calling SkipNonceInit.
3✔
4151
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
3✔
4152
        }
3✔
4153

4154
        // If not already active, we'll add this channel to the set of active
4155
        // channels, so we can look it up later easily according to its channel
4156
        // ID.
4157
        lnChan, err := lnwallet.NewLightningChannel(
3✔
4158
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
3✔
4159
        )
3✔
4160
        if err != nil {
3✔
4161
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
4162
        }
×
4163

4164
        // Store the channel in the activeChannels map.
4165
        p.activeChannels.Store(chanID, lnChan)
3✔
4166

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

3✔
4169
        // Next, we'll assemble a ChannelLink along with the necessary items it
3✔
4170
        // needs to function.
3✔
4171
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
3✔
4172
        if err != nil {
3✔
4173
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
4174
                        err)
×
4175
        }
×
4176

4177
        // We'll query the channel DB for the new channel's initial forwarding
4178
        // policies to determine the policy we start out with.
4179
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
3✔
4180
        if err != nil {
3✔
4181
                return fmt.Errorf("unable to query for initial forwarding "+
×
4182
                        "policy: %v", err)
×
4183
        }
×
4184

4185
        // Create the link and add it to the switch.
4186
        err = p.addLink(
3✔
4187
                &chanPoint, lnChan, initialPolicy, chainEvents,
3✔
4188
                shouldReestablish, fn.None[lnwire.Shutdown](),
3✔
4189
        )
3✔
4190
        if err != nil {
3✔
4191
                return fmt.Errorf("can't register new channel link(%v) with "+
×
4192
                        "peer", chanPoint)
×
4193
        }
×
4194

4195
        return nil
3✔
4196
}
4197

4198
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
4199
// know this channel ID or not, we'll either add it to the `activeChannels` map
4200
// or init the next revocation for it.
4201
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
3✔
4202
        newChan := req.channel
3✔
4203
        chanPoint := newChan.FundingOutpoint
3✔
4204
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4205

3✔
4206
        // Only update RemoteNextRevocation if the channel is in the
3✔
4207
        // activeChannels map and if we added the link to the switch. Only
3✔
4208
        // active channels will be added to the switch.
3✔
4209
        if p.isActiveChannel(chanID) {
6✔
4210
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
3✔
4211
                        chanPoint)
3✔
4212

3✔
4213
                // Handle it and close the err chan on the request.
3✔
4214
                close(req.err)
3✔
4215

3✔
4216
                // Update the next revocation point.
3✔
4217
                err := p.updateNextRevocation(newChan.OpenChannel)
3✔
4218
                if err != nil {
3✔
4219
                        p.log.Errorf(err.Error())
×
4220
                }
×
4221

4222
                return
3✔
4223
        }
4224

4225
        // This is a new channel, we now add it to the map.
4226
        if err := p.addActiveChannel(req.channel); err != nil {
3✔
4227
                // Log and send back the error to the request.
×
4228
                p.log.Errorf(err.Error())
×
4229
                req.err <- err
×
4230

×
4231
                return
×
4232
        }
×
4233

4234
        // Close the err chan if everything went fine.
4235
        close(req.err)
3✔
4236
}
4237

4238
// handleNewPendingChannel takes a `newChannelMsg` request and add it to
4239
// `activeChannels` map with nil value. This pending channel will be saved as
4240
// it may become active in the future. Once active, the funding manager will
4241
// send it again via `AddNewChannel`, and we'd handle the link creation there.
4242
func (p *Brontide) handleNewPendingChannel(req *newChannelMsg) {
3✔
4243
        defer close(req.err)
3✔
4244

3✔
4245
        chanID := req.channelID
3✔
4246

3✔
4247
        // If we already have this channel, something is wrong with the funding
3✔
4248
        // flow as it will only be marked as active after `ChannelReady` is
3✔
4249
        // handled. In this case, we will do nothing but log an error, just in
3✔
4250
        // case this is a legit channel.
3✔
4251
        if p.isActiveChannel(chanID) {
3✔
4252
                p.log.Errorf("Channel(%v) is already active, ignoring "+
×
4253
                        "pending channel request", chanID)
×
4254

×
4255
                return
×
4256
        }
×
4257

4258
        // The channel has already been added, we will do nothing and return.
4259
        if p.isPendingChannel(chanID) {
3✔
4260
                p.log.Infof("Channel(%v) is already added, ignoring "+
×
4261
                        "pending channel request", chanID)
×
4262

×
4263
                return
×
4264
        }
×
4265

4266
        // This is a new channel, we now add it to the map `activeChannels`
4267
        // with nil value and mark it as a newly added channel in
4268
        // `addedChannels`.
4269
        p.activeChannels.Store(chanID, nil)
3✔
4270
        p.addedChannels.Store(chanID, struct{}{})
3✔
4271
}
4272

4273
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
4274
// from `activeChannels` map. The request will be ignored if the channel is
4275
// considered active by Brontide. Noop if the channel ID cannot be found.
4276
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
3✔
4277
        defer close(req.err)
3✔
4278

3✔
4279
        chanID := req.channelID
3✔
4280

3✔
4281
        // If we already have this channel, something is wrong with the funding
3✔
4282
        // flow as it will only be marked as active after `ChannelReady` is
3✔
4283
        // handled. In this case, we will log an error and exit.
3✔
4284
        if p.isActiveChannel(chanID) {
3✔
4285
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
×
4286
                        chanID)
×
4287
                return
×
4288
        }
×
4289

4290
        // The channel has not been added yet, we will log a warning as there
4291
        // is an unexpected call from funding manager.
4292
        if !p.isPendingChannel(chanID) {
6✔
4293
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
3✔
4294
        }
3✔
4295

4296
        // Remove the record of this pending channel.
4297
        p.activeChannels.Delete(chanID)
3✔
4298
        p.addedChannels.Delete(chanID)
3✔
4299
}
4300

4301
// sendLinkUpdateMsg sends a message that updates the channel to the
4302
// channel's message stream.
4303
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
3✔
4304
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
3✔
4305

3✔
4306
        chanStream, ok := p.activeMsgStreams[cid]
3✔
4307
        if !ok {
6✔
4308
                // If a stream hasn't yet been created, then we'll do so, add
3✔
4309
                // it to the map, and finally start it.
3✔
4310
                chanStream = newChanMsgStream(p, cid)
3✔
4311
                p.activeMsgStreams[cid] = chanStream
3✔
4312
                chanStream.Start()
3✔
4313

3✔
4314
                // Stop the stream when quit.
3✔
4315
                go func() {
6✔
4316
                        <-p.quit
3✔
4317
                        chanStream.Stop()
3✔
4318
                }()
3✔
4319
        }
4320

4321
        // With the stream obtained, add the message to the stream so we can
4322
        // continue processing message.
4323
        chanStream.AddMsg(msg)
3✔
4324
}
4325

4326
// scaleTimeout multiplies the argument duration by a constant factor depending
4327
// on variious heuristics. Currently this is only used to check whether our peer
4328
// appears to be connected over Tor and relaxes the timout deadline. However,
4329
// this is subject to change and should be treated as opaque.
4330
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
3✔
4331
        if p.isTorConnection {
6✔
4332
                return timeout * time.Duration(torTimeoutMultiplier)
3✔
4333
        }
3✔
4334

4335
        return timeout
×
4336
}
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