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

lightningnetwork / lnd / 11216766535

07 Oct 2024 01:37PM UTC coverage: 57.817% (-1.0%) from 58.817%
11216766535

Pull #9148

github

ProofOfKeags
lnwire: remove kickoff feerate from propose/commit
Pull Request #9148: DynComms [2/n]: lnwire: add authenticated wire messages for Dyn*

571 of 879 new or added lines in 16 files covered. (64.96%)

23253 existing lines in 251 files now uncovered.

99022 of 171268 relevant lines covered (57.82%)

38420.67 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

122
        err chan error
123
}
124

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

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

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

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

149
        // LocalCloseOutput is an optional, additional output on the closing
150
        // transaction that the local party should be paid to. This will only be
151
        // populated if the local balance isn't dust.
152
        LocalCloseOutput fn.Option[chancloser.CloseOutput]
153

154
        // RemoteCloseOutput is an optional, additional output on the closing
155
        // transaction that the remote party should be paid to. This will only
156
        // be populated if the remote balance isn't dust.
157
        RemoteCloseOutput fn.Option[chancloser.CloseOutput]
158

159
        // AuxOutputs is an optional set of additional outputs that might be
160
        // included in the closing transaction. These are used for custom
161
        // channel types.
162
        AuxOutputs fn.Option[chancloser.AuxCloseOutputs]
163
}
164

165
// TimestampedError is a timestamped error that is used to store the most recent
166
// errors we have experienced with our peers.
167
type TimestampedError struct {
168
        Error     error
169
        Timestamp time.Time
170
}
171

172
// Config defines configuration fields that are necessary for a peer object
173
// to function.
174
type Config struct {
175
        // Conn is the underlying network connection for this peer.
176
        Conn MessageConn
177

178
        // ConnReq stores information related to the persistent connection request
179
        // for this peer.
180
        ConnReq *connmgr.ConnReq
181

182
        // PubKeyBytes is the serialized, compressed public key of this peer.
183
        PubKeyBytes [33]byte
184

185
        // Addr is the network address of the peer.
186
        Addr *lnwire.NetAddress
187

188
        // Inbound indicates whether or not the peer is an inbound peer.
189
        Inbound bool
190

191
        // Features is the set of features that we advertise to the remote party.
192
        Features *lnwire.FeatureVector
193

194
        // LegacyFeatures is the set of features that we advertise to the remote
195
        // peer for backwards compatibility. Nodes that have not implemented
196
        // flat features will still be able to read our feature bits from the
197
        // legacy global field, but we will also advertise everything in the
198
        // default features field.
199
        LegacyFeatures *lnwire.FeatureVector
200

201
        // OutgoingCltvRejectDelta defines the number of blocks before expiry of
202
        // an htlc where we don't offer it anymore.
203
        OutgoingCltvRejectDelta uint32
204

205
        // ChanActiveTimeout specifies the duration the peer will wait to request
206
        // a channel reenable, beginning from the time the peer was started.
207
        ChanActiveTimeout time.Duration
208

209
        // ErrorBuffer stores a set of errors related to a peer. It contains error
210
        // messages that our peer has recently sent us over the wire and records of
211
        // unknown messages that were sent to us so that we can have a full track
212
        // record of the communication errors we have had with our peer. If we
213
        // choose to disconnect from a peer, it also stores the reason we had for
214
        // disconnecting.
215
        ErrorBuffer *queue.CircularBuffer
216

217
        // WritePool is the task pool that manages reuse of write buffers. Write
218
        // tasks are submitted to the pool in order to conserve the total number of
219
        // write buffers allocated at any one time, and decouple write buffer
220
        // allocation from the peer life cycle.
221
        WritePool *pool.Write
222

223
        // ReadPool is the task pool that manages reuse of read buffers.
224
        ReadPool *pool.Read
225

226
        // Switch is a pointer to the htlcswitch. It is used to setup, get, and
227
        // tear-down ChannelLinks.
228
        Switch messageSwitch
229

230
        // InterceptSwitch is a pointer to the InterceptableSwitch, a wrapper around
231
        // the regular Switch. We only export it here to pass ForwardPackets to the
232
        // ChannelLinkConfig.
233
        InterceptSwitch *htlcswitch.InterceptableSwitch
234

235
        // ChannelDB is used to fetch opened channels, and closed channels.
236
        ChannelDB *channeldb.ChannelStateDB
237

238
        // ChannelGraph is a pointer to the channel graph which is used to
239
        // query information about the set of known active channels.
240
        ChannelGraph *channeldb.ChannelGraph
241

242
        // ChainArb is used to subscribe to channel events, update contract signals,
243
        // and force close channels.
244
        ChainArb *contractcourt.ChainArbitrator
245

246
        // AuthGossiper is needed so that the Brontide impl can register with the
247
        // gossiper and process remote channel announcements.
248
        AuthGossiper *discovery.AuthenticatedGossiper
249

250
        // ChanStatusMgr is used to set or un-set the disabled bit in channel
251
        // updates.
252
        ChanStatusMgr *netann.ChanStatusManager
253

254
        // ChainIO is used to retrieve the best block.
255
        ChainIO lnwallet.BlockChainIO
256

257
        // FeeEstimator is used to compute our target ideal fee-per-kw when
258
        // initializing the coop close process.
259
        FeeEstimator chainfee.Estimator
260

261
        // Signer is used when creating *lnwallet.LightningChannel instances.
262
        Signer input.Signer
263

264
        // SigPool is used when creating *lnwallet.LightningChannel instances.
265
        SigPool *lnwallet.SigPool
266

267
        // Wallet is used to publish transactions and generates delivery
268
        // scripts during the coop close process.
269
        Wallet *lnwallet.LightningWallet
270

271
        // ChainNotifier is used to receive confirmations of a coop close
272
        // transaction.
273
        ChainNotifier chainntnfs.ChainNotifier
274

275
        // BestBlockView is used to efficiently query for up-to-date
276
        // blockchain state information
277
        BestBlockView chainntnfs.BestBlockView
278

279
        // RoutingPolicy is used to set the forwarding policy for links created by
280
        // the Brontide.
281
        RoutingPolicy models.ForwardingPolicy
282

283
        // Sphinx is used when setting up ChannelLinks so they can decode sphinx
284
        // onion blobs.
285
        Sphinx *hop.OnionProcessor
286

287
        // WitnessBeacon is used when setting up ChannelLinks so they can add any
288
        // preimages that they learn.
289
        WitnessBeacon contractcourt.WitnessBeacon
290

291
        // Invoices is passed to the ChannelLink on creation and handles all
292
        // invoice-related logic.
293
        Invoices *invoices.InvoiceRegistry
294

295
        // ChannelNotifier is used by the link to notify other sub-systems about
296
        // channel-related events and by the Brontide to subscribe to
297
        // ActiveLinkEvents.
298
        ChannelNotifier *channelnotifier.ChannelNotifier
299

300
        // HtlcNotifier is used when creating a ChannelLink.
301
        HtlcNotifier *htlcswitch.HtlcNotifier
302

303
        // TowerClient is used to backup revoked states.
304
        TowerClient wtclient.ClientManager
305

306
        // DisconnectPeer is used to disconnect this peer if the cooperative close
307
        // process fails.
308
        DisconnectPeer func(*btcec.PublicKey) error
309

310
        // GenNodeAnnouncement is used to send our node announcement to the remote
311
        // on startup.
312
        GenNodeAnnouncement func(...netann.NodeAnnModifier) (
313
                lnwire.NodeAnnouncement, error)
314

315
        // PrunePersistentPeerConnection is used to remove all internal state
316
        // related to this peer in the server.
317
        PrunePersistentPeerConnection func([33]byte)
318

319
        // FetchLastChanUpdate fetches our latest channel update for a target
320
        // channel.
321
        FetchLastChanUpdate func(lnwire.ShortChannelID) (*lnwire.ChannelUpdate1,
322
                error)
323

324
        // FundingManager is an implementation of the funding.Controller interface.
325
        FundingManager funding.Controller
326

327
        // Hodl is used when creating ChannelLinks to specify HodlFlags as
328
        // breakpoints in dev builds.
329
        Hodl *hodl.Config
330

331
        // UnsafeReplay is used when creating ChannelLinks to specify whether or
332
        // not to replay adds on its commitment tx.
333
        UnsafeReplay bool
334

335
        // MaxOutgoingCltvExpiry is used when creating ChannelLinks and is the max
336
        // number of blocks that funds could be locked up for when forwarding
337
        // payments.
338
        MaxOutgoingCltvExpiry uint32
339

340
        // MaxChannelFeeAllocation is used when creating ChannelLinks and is the
341
        // maximum percentage of total funds that can be allocated to a channel's
342
        // commitment fee. This only applies for the initiator of the channel.
343
        MaxChannelFeeAllocation float64
344

345
        // MaxAnchorsCommitFeeRate is the maximum fee rate we'll use as an
346
        // initiator for anchor channel commitments.
347
        MaxAnchorsCommitFeeRate chainfee.SatPerKWeight
348

349
        // CoopCloseTargetConfs is the confirmation target that will be used
350
        // to estimate the fee rate to use during a cooperative channel
351
        // closure initiated by the remote peer.
352
        CoopCloseTargetConfs uint32
353

354
        // ServerPubKey is the serialized, compressed public key of our lnd node.
355
        // It is used to determine which policy (channel edge) to pass to the
356
        // ChannelLink.
357
        ServerPubKey [33]byte
358

359
        // ChannelCommitInterval is the maximum time that is allowed to pass between
360
        // receiving a channel state update and signing the next commitment.
361
        // Setting this to a longer duration allows for more efficient channel
362
        // operations at the cost of latency.
363
        ChannelCommitInterval time.Duration
364

365
        // PendingCommitInterval is the maximum time that is allowed to pass
366
        // while waiting for the remote party to revoke a locally initiated
367
        // commitment state. Setting this to a longer duration if a slow
368
        // response is expected from the remote party or large number of
369
        // payments are attempted at the same time.
370
        PendingCommitInterval time.Duration
371

372
        // ChannelCommitBatchSize is the maximum number of channel state updates
373
        // that is accumulated before signing a new commitment.
374
        ChannelCommitBatchSize uint32
375

376
        // HandleCustomMessage is called whenever a custom message is received
377
        // from the peer.
378
        HandleCustomMessage func(peer [33]byte, msg *lnwire.Custom) error
379

380
        // GetAliases is passed to created links so the Switch and link can be
381
        // aware of the channel's aliases.
382
        GetAliases func(base lnwire.ShortChannelID) []lnwire.ShortChannelID
383

384
        // RequestAlias allows the Brontide struct to request an alias to send
385
        // to the peer.
386
        RequestAlias func() (lnwire.ShortChannelID, error)
387

388
        // AddLocalAlias persists an alias to an underlying alias store.
389
        AddLocalAlias func(alias, base lnwire.ShortChannelID,
390
                gossip, liveUpdate bool) error
391

392
        // AuxLeafStore is an optional store that can be used to store auxiliary
393
        // leaves for certain custom channel types.
394
        AuxLeafStore fn.Option[lnwallet.AuxLeafStore]
395

396
        // AuxSigner is an optional signer that can be used to sign auxiliary
397
        // leaves for certain custom channel types.
398
        AuxSigner fn.Option[lnwallet.AuxSigner]
399

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

406
        // Adds the option to disable forwarding payments in blinded routes
407
        // by failing back any blinding-related payloads as if they were
408
        // invalid.
409
        DisallowRouteBlinding bool
410

411
        // DisallowQuiescence is a flag that indicates whether the Brontide
412
        // should have the quiescence feature disabled.
413
        DisallowQuiescence bool
414

415
        // MaxFeeExposure limits the number of outstanding fees in a channel.
416
        // This value will be passed to created links.
417
        MaxFeeExposure lnwire.MilliSatoshi
418

419
        // MsgRouter is an optional instance of the main message router that
420
        // the peer will use. If None, then a new default version will be used
421
        // in place.
422
        MsgRouter fn.Option[msgmux.Router]
423

424
        // AuxChanCloser is an optional instance of an abstraction that can be
425
        // used to modify the way the co-op close transaction is constructed.
426
        AuxChanCloser fn.Option[chancloser.AuxChanCloser]
427

428
        // Quit is the server's quit channel. If this is closed, we halt operation.
429
        Quit chan struct{}
430
}
431

432
// Brontide is an active peer on the Lightning Network. This struct is responsible
433
// for managing any channel state related to this peer. To do so, it has
434
// several helper goroutines to handle events such as HTLC timeouts, new
435
// funding workflow, and detecting an uncooperative closure of any active
436
// channels.
437
// TODO(roasbeef): proper reconnection logic.
438
type Brontide struct {
439
        // MUST be used atomically.
440
        started    int32
441
        disconnect int32
442

443
        // MUST be used atomically.
444
        bytesReceived uint64
445
        bytesSent     uint64
446

447
        // isTorConnection is a flag that indicates whether or not we believe
448
        // the remote peer is a tor connection. It is not always possible to
449
        // know this with certainty but we have heuristics we use that should
450
        // catch most cases.
451
        //
452
        // NOTE: We judge the tor-ness of a connection by if the remote peer has
453
        // ".onion" in the address OR if it's connected over localhost.
454
        // This will miss cases where our peer is connected to our clearnet
455
        // address over the tor network (via exit nodes). It will also misjudge
456
        // actual localhost connections as tor. We need to include this because
457
        // inbound connections to our tor address will appear to come from the
458
        // local socks5 proxy. This heuristic is only used to expand the timeout
459
        // window for peers so it is OK to misjudge this. If you use this field
460
        // for any other purpose you should seriously consider whether or not
461
        // this heuristic is good enough for your use case.
462
        isTorConnection bool
463

464
        pingManager *PingManager
465

466
        // lastPingPayload stores an unsafe pointer wrapped as an atomic
467
        // variable which points to the last payload the remote party sent us
468
        // as their ping.
469
        //
470
        // MUST be used atomically.
471
        lastPingPayload atomic.Value
472

473
        cfg Config
474

475
        // activeSignal when closed signals that the peer is now active and
476
        // ready to process messages.
477
        activeSignal chan struct{}
478

479
        // startTime is the time this peer connection was successfully established.
480
        // It will be zero for peers that did not successfully call Start().
481
        startTime time.Time
482

483
        // sendQueue is the channel which is used to queue outgoing messages to be
484
        // written onto the wire. Note that this channel is unbuffered.
485
        sendQueue chan outgoingMsg
486

487
        // outgoingQueue is a buffered channel which allows second/third party
488
        // objects to queue messages to be sent out on the wire.
489
        outgoingQueue chan outgoingMsg
490

491
        // activeChannels is a map which stores the state machines of all
492
        // active channels. Channels are indexed into the map by the txid of
493
        // the funding transaction which opened the channel.
494
        //
495
        // NOTE: On startup, pending channels are stored as nil in this map.
496
        // Confirmed channels have channel data populated in the map. This means
497
        // that accesses to this map should nil-check the LightningChannel to
498
        // see if this is a pending channel or not. The tradeoff here is either
499
        // having two maps everywhere (one for pending, one for confirmed chans)
500
        // or having an extra nil-check per access.
501
        activeChannels *lnutils.SyncMap[
502
                lnwire.ChannelID, *lnwallet.LightningChannel]
503

504
        // addedChannels tracks any new channels opened during this peer's
505
        // lifecycle. We use this to filter out these new channels when the time
506
        // comes to request a reenable for active channels, since they will have
507
        // waited a shorter duration.
508
        addedChannels *lnutils.SyncMap[lnwire.ChannelID, struct{}]
509

510
        // newActiveChannel is used by the fundingManager to send fully opened
511
        // channels to the source peer which handled the funding workflow.
512
        newActiveChannel chan *newChannelMsg
513

514
        // newPendingChannel is used by the fundingManager to send pending open
515
        // channels to the source peer which handled the funding workflow.
516
        newPendingChannel chan *newChannelMsg
517

518
        // removePendingChannel is used by the fundingManager to cancel pending
519
        // open channels to the source peer when the funding flow is failed.
520
        removePendingChannel chan *newChannelMsg
521

522
        // activeMsgStreams is a map from channel id to the channel streams that
523
        // proxy messages to individual, active links.
524
        activeMsgStreams map[lnwire.ChannelID]*msgStream
525

526
        // activeChanCloses is a map that keeps track of all the active
527
        // cooperative channel closures. Any channel closing messages are directed
528
        // to one of these active state machines. Once the channel has been closed,
529
        // the state machine will be deleted from the map.
530
        activeChanCloses map[lnwire.ChannelID]*chancloser.ChanCloser
531

532
        // localCloseChanReqs is a channel in which any local requests to close
533
        // a particular channel are sent over.
534
        localCloseChanReqs chan *htlcswitch.ChanClose
535

536
        // linkFailures receives all reported channel failures from the switch,
537
        // and instructs the channelManager to clean remaining channel state.
538
        linkFailures chan linkFailureReport
539

540
        // chanCloseMsgs is a channel that any message related to channel
541
        // closures are sent over. This includes lnwire.Shutdown message as
542
        // well as lnwire.ClosingSigned messages.
543
        chanCloseMsgs chan *closeMsg
544

545
        // remoteFeatures is the feature vector received from the peer during
546
        // the connection handshake.
547
        remoteFeatures *lnwire.FeatureVector
548

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

555
        // channelEventClient is the channel event subscription client that's
556
        // used to assist retry enabling the channels. This client is only
557
        // created when the reenableTimeout is no greater than 1 minute. Once
558
        // created, it is canceled once the reenabling has been finished.
559
        //
560
        // NOTE: we choose to create the client conditionally to avoid
561
        // potentially holding lots of un-consumed events.
562
        channelEventClient *subscribe.Client
563

564
        // msgRouter is an instance of the msgmux.Router which is used to send
565
        // off new wire messages for handing.
566
        msgRouter fn.Option[msgmux.Router]
567

568
        // globalMsgRouter is a flag that indicates whether we have a global
569
        // msg router. If so, then we don't worry about stopping the msg router
570
        // when a peer disconnects.
571
        globalMsgRouter bool
572

573
        startReady chan struct{}
574
        quit       chan struct{}
575
        wg         sync.WaitGroup
576

577
        // log is a peer-specific logging instance.
578
        log btclog.Logger
579
}
580

581
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer interface.
582
var _ lnpeer.Peer = (*Brontide)(nil)
583

584
// NewBrontide creates a new Brontide from a peer.Config struct.
585
func NewBrontide(cfg Config) *Brontide {
586
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
587

588
        // We have a global message router if one was passed in via the config.
25✔
589
        // In this case, we don't need to attempt to tear it down when the peer
25✔
590
        // is stopped.
25✔
591
        globalMsgRouter := cfg.MsgRouter.IsSome()
25✔
592

25✔
593
        // We'll either use the msg router instance passed in, or create a new
25✔
594
        // blank instance.
25✔
595
        msgRouter := cfg.MsgRouter.Alt(fn.Some[msgmux.Router](
25✔
596
                msgmux.NewMultiMsgRouter(),
25✔
597
        ))
25✔
598

25✔
599
        p := &Brontide{
25✔
600
                cfg:           cfg,
25✔
601
                activeSignal:  make(chan struct{}),
25✔
602
                sendQueue:     make(chan outgoingMsg),
25✔
603
                outgoingQueue: make(chan outgoingMsg),
25✔
604
                addedChannels: &lnutils.SyncMap[lnwire.ChannelID, struct{}]{},
25✔
605
                activeChannels: &lnutils.SyncMap[
25✔
606
                        lnwire.ChannelID, *lnwallet.LightningChannel,
25✔
607
                ]{},
25✔
608
                newActiveChannel:     make(chan *newChannelMsg, 1),
25✔
609
                newPendingChannel:    make(chan *newChannelMsg, 1),
25✔
610
                removePendingChannel: make(chan *newChannelMsg),
25✔
611

25✔
612
                activeMsgStreams:   make(map[lnwire.ChannelID]*msgStream),
25✔
613
                activeChanCloses:   make(map[lnwire.ChannelID]*chancloser.ChanCloser),
25✔
614
                localCloseChanReqs: make(chan *htlcswitch.ChanClose),
25✔
615
                linkFailures:       make(chan linkFailureReport),
25✔
616
                chanCloseMsgs:      make(chan *closeMsg),
25✔
617
                resentChanSyncMsg:  make(map[lnwire.ChannelID]struct{}),
25✔
618
                startReady:         make(chan struct{}),
25✔
619
                quit:               make(chan struct{}),
25✔
620
                log:                build.NewPrefixLog(logPrefix, peerLog),
25✔
621
                msgRouter:          msgRouter,
25✔
622
                globalMsgRouter:    globalMsgRouter,
25✔
623
        }
25✔
624

25✔
625
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
25✔
626
                remoteAddr := cfg.Conn.RemoteAddr().String()
25✔
627
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
25✔
628
                        strings.Contains(remoteAddr, "127.0.0.1")
25✔
UNCOV
629
        }
×
UNCOV
630

×
UNCOV
631
        var (
×
UNCOV
632
                lastBlockHeader           *wire.BlockHeader
×
633
                lastSerializedBlockHeader [wire.MaxBlockHeaderPayload]byte
634
        )
25✔
635
        newPingPayload := func() []byte {
25✔
636
                // We query the BestBlockHeader from our BestBlockView each time
25✔
637
                // this is called, and update our serialized block header if
25✔
638
                // they differ.  Over time, we'll use this to disseminate the
25✔
UNCOV
639
                // latest block header between all our peers, which can later be
×
UNCOV
640
                // used to cross-check our own view of the network to mitigate
×
UNCOV
641
                // various types of eclipse attacks.
×
UNCOV
642
                header, err := p.cfg.BestBlockView.BestBlockHeader()
×
UNCOV
643
                if err != nil && header == lastBlockHeader {
×
644
                        return lastSerializedBlockHeader[:]
×
645
                }
×
UNCOV
646

×
UNCOV
647
                buf := bytes.NewBuffer(lastSerializedBlockHeader[0:0])
×
UNCOV
648
                err = header.Serialize(buf)
×
649
                if err == nil {
UNCOV
650
                        lastBlockHeader = header
×
UNCOV
651
                } else {
×
652
                        p.log.Warn("unable to serialize current block" +
×
653
                                "header for ping payload generation." +
×
654
                                "This should be impossible and means" +
×
655
                                "there is an implementation bug.")
×
656
                }
×
UNCOV
657

×
UNCOV
658
                return lastSerializedBlockHeader[:]
×
UNCOV
659
        }
×
660

UNCOV
661
        // TODO(roasbeef): make dynamic in order to create fake cover traffic.
×
662
        //
663
        // NOTE(proofofkeags): this was changed to be dynamic to allow better
664
        // pong identification, however, more thought is needed to make this
665
        // actually usable as a traffic decoy.
666
        randPongSize := func() uint16 {
667
                return uint16(
668
                        // We don't need cryptographic randomness here.
669
                        /* #nosec */
25✔
UNCOV
670
                        rand.Intn(pongSizeCeiling) + 1,
×
UNCOV
671
                )
×
UNCOV
672
        }
×
UNCOV
673

×
UNCOV
674
        p.pingManager = NewPingManager(&PingManagerConfig{
×
UNCOV
675
                NewPingPayload:   newPingPayload,
×
676
                NewPongSize:      randPongSize,
677
                IntervalDuration: p.scaleTimeout(pingInterval),
25✔
678
                TimeoutDuration:  p.scaleTimeout(pingTimeout),
25✔
679
                SendPing: func(ping *lnwire.Ping) {
25✔
680
                        p.queueMsg(ping, nil)
25✔
681
                },
25✔
682
                OnPongFailure: func(err error) {
25✔
683
                        eStr := "pong response failure for %s: %v " +
×
684
                                "-- disconnecting"
×
685
                        p.log.Warnf(eStr, p, err)
×
686
                        go p.Disconnect(fmt.Errorf(eStr, p, err))
×
687
                },
×
UNCOV
688
        })
×
UNCOV
689

×
UNCOV
690
        return p
×
691
}
692

693
// Start starts all helper goroutines the peer needs for normal operations.  In
25✔
694
// the case this peer has already been started, then this function is a noop.
695
func (p *Brontide) Start() error {
696
        if atomic.AddInt32(&p.started, 1) != 1 {
697
                return nil
698
        }
3✔
699

3✔
UNCOV
700
        // Once we've finished starting up the peer, we'll signal to other
×
UNCOV
701
        // goroutines that the they can move forward to tear down the peer, or
×
702
        // carry out other relevant changes.
703
        defer close(p.startReady)
704

705
        p.log.Tracef("starting with conn[%v->%v]",
706
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
3✔
707

3✔
708
        // Fetch and then load all the active channels we have with this remote
3✔
709
        // peer from the database.
3✔
710
        activeChans, err := p.cfg.ChannelDB.FetchOpenChannels(
3✔
711
                p.cfg.Addr.IdentityKey,
3✔
712
        )
3✔
713
        if err != nil {
3✔
714
                p.log.Errorf("Unable to fetch active chans "+
3✔
715
                        "for peer: %v", err)
3✔
716
                return err
3✔
717
        }
×
UNCOV
718

×
UNCOV
719
        if len(activeChans) == 0 {
×
UNCOV
720
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
×
721
        }
722

4✔
723
        // Quickly check if we have any existing legacy channels with this
1✔
724
        // peer.
1✔
725
        haveLegacyChan := false
726
        for _, c := range activeChans {
727
                if c.ChanType.IsTweakless() {
728
                        continue
3✔
729
                }
5✔
730

4✔
731
                haveLegacyChan = true
2✔
732
                break
733
        }
UNCOV
734

×
UNCOV
735
        // Exchange local and global features, the init message should be very
×
736
        // first between two nodes.
737
        if err := p.sendInitMsg(haveLegacyChan); err != nil {
738
                return fmt.Errorf("unable to send init msg: %w", err)
739
        }
740

3✔
UNCOV
741
        // Before we launch any of the helper goroutines off the peer struct,
×
UNCOV
742
        // we'll first ensure proper adherence to the p2p protocol. The init
×
743
        // message MUST be sent before any other message.
744
        readErr := make(chan error, 1)
745
        msgChan := make(chan lnwire.Message, 1)
746
        p.wg.Add(1)
747
        go func() {
3✔
748
                defer p.wg.Done()
3✔
749

3✔
750
                msg, err := p.readNextMessage()
6✔
751
                if err != nil {
3✔
752
                        readErr <- err
3✔
753
                        msgChan <- nil
3✔
754
                        return
3✔
UNCOV
755
                }
×
UNCOV
756
                readErr <- nil
×
UNCOV
757
                msgChan <- msg
×
UNCOV
758
        }()
×
759

3✔
760
        select {
3✔
761
        // In order to avoid blocking indefinitely, we'll give the other peer
762
        // an upper timeout to respond before we bail out early.
763
        case <-time.After(handshakeTimeout):
3✔
764
                return fmt.Errorf("peer did not complete handshake within %v",
765
                        handshakeTimeout)
UNCOV
766
        case err := <-readErr:
×
UNCOV
767
                if err != nil {
×
UNCOV
768
                        return fmt.Errorf("unable to read init msg: %w", err)
×
769
                }
3✔
770
        }
3✔
UNCOV
771

×
UNCOV
772
        // Once the init message arrives, we can parse it so we can figure out
×
773
        // the negotiation of features for this session.
774
        msg := <-msgChan
775
        if msg, ok := msg.(*lnwire.Init); ok {
776
                if err := p.handleInitMsg(msg); err != nil {
777
                        p.storeError(err)
3✔
778
                        return err
6✔
779
                }
3✔
780
        } else {
×
781
                return errors.New("very first message between nodes " +
×
782
                        "must be init message")
×
783
        }
×
UNCOV
784

×
UNCOV
785
        // Next, load all the active channels we have with this peer,
×
UNCOV
786
        // registering them with the switch and launching the necessary
×
787
        // goroutines required to operate them.
788
        p.log.Debugf("Loaded %v active channels from database",
789
                len(activeChans))
790

791
        // Conditionally subscribe to channel events before loading channels so
3✔
792
        // we won't miss events. This subscription is used to listen to active
3✔
793
        // channel event when reenabling channels. Once the reenabling process
3✔
794
        // is finished, this subscription will be canceled.
3✔
795
        //
3✔
796
        // NOTE: ChannelNotifier must be started before subscribing events
3✔
797
        // otherwise we'd panic here.
3✔
798
        if err := p.attachChannelEventSubscription(); err != nil {
3✔
799
                return err
3✔
800
        }
3✔
801

3✔
UNCOV
802
        // Register the message router now as we may need to register some
×
UNCOV
803
        // endpoints while loading the channels below.
×
804
        p.msgRouter.WhenSome(func(router msgmux.Router) {
805
                router.Start()
806
        })
807

6✔
808
        msgs, err := p.loadActiveChannels(activeChans)
3✔
809
        if err != nil {
3✔
810
                return fmt.Errorf("unable to load channels: %w", err)
811
        }
3✔
812

3✔
UNCOV
813
        p.startTime = time.Now()
×
UNCOV
814

×
815
        // Before launching the writeHandler goroutine, we send any channel
816
        // sync messages that must be resent for borked channels. We do this to
3✔
817
        // avoid data races with WriteMessage & Flush calls.
3✔
818
        if len(msgs) > 0 {
3✔
819
                p.log.Infof("Sending %d channel sync messages to peer after "+
3✔
820
                        "loading active channels", len(msgs))
3✔
821

5✔
822
                // Send the messages directly via writeMessage and bypass the
2✔
823
                // writeHandler goroutine.
2✔
824
                for _, msg := range msgs {
2✔
825
                        if err := p.writeMessage(msg); err != nil {
2✔
826
                                return fmt.Errorf("unable to send "+
2✔
827
                                        "reestablish msg: %v", err)
4✔
828
                        }
2✔
UNCOV
829
                }
×
UNCOV
830
        }
×
UNCOV
831

×
832
        err = p.pingManager.Start()
833
        if err != nil {
834
                return fmt.Errorf("could not start ping manager %w", err)
835
        }
3✔
836

3✔
UNCOV
837
        p.wg.Add(4)
×
UNCOV
838
        go p.queueHandler()
×
839
        go p.writeHandler()
840
        go p.channelManager()
3✔
841
        go p.readHandler()
3✔
842

3✔
843
        // Signal to any external processes that the peer is now active.
3✔
844
        close(p.activeSignal)
3✔
845

3✔
846
        // Node announcements don't propagate very well throughout the network
3✔
847
        // as there isn't a way to efficiently query for them through their
3✔
848
        // timestamp, mostly affecting nodes that were offline during the time
3✔
849
        // of broadcast. We'll resend our node announcement to the remote peer
3✔
850
        // as a best-effort delivery such that it can also propagate to their
3✔
851
        // peers. To ensure they can successfully process it in most cases,
3✔
852
        // we'll only resend it as long as we have at least one confirmed
3✔
853
        // advertised channel with the remote peer.
3✔
854
        //
3✔
855
        // TODO(wilmer): Remove this once we're able to query for node
3✔
856
        // announcements through their timestamps.
3✔
857
        p.wg.Add(2)
3✔
858
        go p.maybeSendNodeAnn(activeChans)
3✔
859
        go p.maybeSendChannelUpdates()
3✔
860

3✔
861
        return nil
3✔
862
}
3✔
863

3✔
864
// initGossipSync initializes either a gossip syncer or an initial routing
3✔
865
// dump, depending on the negotiated synchronization method.
866
func (p *Brontide) initGossipSync() {
867
        // If the remote peer knows of the new gossip queries feature, then
868
        // we'll create a new gossipSyncer in the AuthenticatedGossiper for it.
869
        if p.remoteFeatures.HasFeature(lnwire.GossipQueriesOptional) {
3✔
870
                p.log.Info("Negotiated chan series queries")
3✔
871

3✔
872
                if p.cfg.AuthGossiper == nil {
6✔
873
                        // This should only ever be hit in the unit tests.
3✔
874
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
3✔
875
                                "gossip sync.")
6✔
876
                        return
3✔
877
                }
3✔
878

3✔
879
                // Register the peer's gossip syncer with the gossiper.
3✔
880
                // This blocks synchronously to ensure the gossip syncer is
3✔
881
                // registered with the gossiper before attempting to read
882
                // messages from the remote peer.
883
                //
884
                // TODO(wilmer): Only sync updates from non-channel peers. This
885
                // requires an improved version of the current network
886
                // bootstrapper to ensure we can find and connect to non-channel
887
                // peers.
888
                p.cfg.AuthGossiper.InitSyncState(p)
889
        }
890
}
UNCOV
891

×
892
// taprootShutdownAllowed returns true if both parties have negotiated the
893
// shutdown-any-segwit feature.
894
func (p *Brontide) taprootShutdownAllowed() bool {
895
        return p.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
896
                p.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
897
}
6✔
898

6✔
899
// QuitSignal is a method that should return a channel which will be sent upon
6✔
900
// or closed once the backing peer exits. This allows callers using the
6✔
901
// interface to cancel any processing in the event the backing implementation
902
// exits.
903
//
904
// NOTE: Part of the lnpeer.Peer interface.
905
func (p *Brontide) QuitSignal() <-chan struct{} {
906
        return p.quit
907
}
UNCOV
908

×
UNCOV
909
// internalKeyForAddr returns the internal key associated with a taproot
×
UNCOV
910
// address.
×
911
func internalKeyForAddr(wallet *lnwallet.LightningWallet,
912
        deliveryScript []byte) (fn.Option[btcec.PublicKey], error) {
913

914
        none := fn.None[btcec.PublicKey]()
915

916
        pkScript, err := txscript.ParsePkScript(deliveryScript)
9✔
917
        if err != nil {
9✔
918
                return none, err
9✔
919
        }
9✔
920
        addr, err := pkScript.Address(&wallet.Cfg.NetParams)
9✔
921
        if err != nil {
9✔
922
                return none, err
9✔
923
        }
9✔
924

9✔
925
        // If it's not a taproot address, we don't require to know the internal
9✔
UNCOV
926
        // key in the first place. So we don't return an error here, but also no
×
UNCOV
927
        // internal key.
×
928
        _, isTaproot := addr.(*btcutil.AddressTaproot)
929
        if !isTaproot {
9✔
930
                return none, nil
9✔
931
        }
9✔
932

9✔
UNCOV
933
        walletAddr, err := wallet.AddressInfo(addr)
×
UNCOV
934
        if err != nil {
×
935
                return none, err
936
        }
937

938
        // If the address isn't known to the wallet, we can't determine the
939
        // internal key.
940
        if walletAddr == nil {
941
                return none, nil
942
        }
943

944
        pubKeyAddr, ok := walletAddr.(waddrmgr.ManagedPubKeyAddress)
3✔
945
        if !ok {
3✔
946
                return none, fmt.Errorf("expected pubkey addr, got %T",
3✔
947
                        pubKeyAddr)
3✔
948
        }
3✔
949

3✔
950
        return fn.Some(*pubKeyAddr.PubKey()), nil
3✔
951
}
3✔
952

5✔
953
// addrWithInternalKey takes a delivery script, then attempts to supplement it
2✔
954
// with information related to the internal key for the addr, but only if it's
2✔
UNCOV
955
// a taproot addr.
×
UNCOV
956
func (p *Brontide) addrWithInternalKey(
×
UNCOV
957
        deliveryScript []byte) fn.Result[chancloser.DeliveryAddrWithKey] {
×
UNCOV
958

×
UNCOV
959
        // TODO(roasbeef): not compatible with external shutdown addr?
×
UNCOV
960
        // Currently, custom channels cannot be created with external upfront
×
UNCOV
961
        // shutdown addresses, so this shouldn't be an issue. We only require
×
UNCOV
962
        // the internal key for taproot addresses to be able to provide a non
×
UNCOV
963
        // inclusion proof of any scripts.
×
UNCOV
964

×
UNCOV
965
        internalKey, err := internalKeyForAddr(p.cfg.Wallet, deliveryScript)
×
UNCOV
966
        if err != nil {
×
967
                return fn.Err[chancloser.DeliveryAddrWithKey](err)
×
968
        }
×
UNCOV
969

×
UNCOV
970
        return fn.Ok(chancloser.DeliveryAddrWithKey{
×
971
                DeliveryAddress: deliveryScript,
UNCOV
972
                InternalKey:     internalKey,
×
UNCOV
973
        })
×
UNCOV
974
}
×
UNCOV
975

×
UNCOV
976
// loadActiveChannels creates indexes within the peer for tracking all active
×
UNCOV
977
// channels returned by the database. It returns a slice of channel reestablish
×
UNCOV
978
// messages that should be sent to the peer immediately, in case we have borked
×
979
// channels that haven't been closed yet.
UNCOV
980
func (p *Brontide) loadActiveChannels(chans []*channeldb.OpenChannel) (
×
UNCOV
981
        []lnwire.Message, error) {
×
UNCOV
982

×
UNCOV
983
        // Return a slice of messages to send to the peers in case the channel
×
UNCOV
984
        // cannot be loaded normally.
×
UNCOV
985
        var msgs []lnwire.Message
×
UNCOV
986

×
UNCOV
987
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
×
UNCOV
988

×
UNCOV
989
        for _, dbChan := range chans {
×
990
                hasScidFeature := dbChan.ChanType.HasScidAliasFeature()
UNCOV
991
                if scidAliasNegotiated && !hasScidFeature {
×
UNCOV
992
                        // We'll request and store an alias, making sure that a
×
UNCOV
993
                        // gossiper mapping is not created for the alias to the
×
UNCOV
994
                        // real SCID. This is done because the peer and funding
×
UNCOV
995
                        // manager are not aware of each other's states and if
×
UNCOV
996
                        // we did not do this, we would accept alias channel
×
997
                        // updates after 6 confirmations, which would be buggy.
998
                        // We'll queue a channel_ready message with the new
999
                        // alias. This should technically be done *after* the
1000
                        // reestablish, but this behavior is pre-existing since
1001
                        // the funding manager may already queue a
1002
                        // channel_ready before the channel_reestablish.
1003
                        if !dbChan.IsPending {
UNCOV
1004
                                aliasScid, err := p.cfg.RequestAlias()
×
UNCOV
1005
                                if err != nil {
×
1006
                                        return nil, err
×
1007
                                }
×
1008

1009
                                err = p.cfg.AddLocalAlias(
1010
                                        aliasScid, dbChan.ShortChanID(), false,
2✔
1011
                                        false,
2✔
UNCOV
1012
                                )
×
UNCOV
1013
                                if err != nil {
×
1014
                                        return nil, err
2✔
1015
                                }
×
UNCOV
1016

×
1017
                                chanID := lnwire.NewChanIDFromOutPoint(
2✔
1018
                                        dbChan.FundingOutpoint,
2✔
UNCOV
1019
                                )
×
UNCOV
1020

×
UNCOV
1021
                                // Fetch the second commitment point to send in
×
UNCOV
1022
                                // the channel_ready message.
×
1023
                                second, err := dbChan.SecondCommitmentPoint()
1024
                                if err != nil {
1025
                                        return nil, err
2✔
1026
                                }
2✔
1027

2✔
1028
                                channelReadyMsg := lnwire.NewChannelReady(
2✔
UNCOV
1029
                                        chanID, second,
×
UNCOV
1030
                                )
×
UNCOV
1031
                                channelReadyMsg.AliasScid = &aliasScid
×
1032

1033
                                msgs = append(msgs, channelReadyMsg)
2✔
1034
                        }
2✔
1035

2✔
1036
                        // If we've negotiated the option-scid-alias feature
2✔
1037
                        // and this channel does not have ScidAliasFeature set
2✔
1038
                        // to true due to an upgrade where the feature bit was
2✔
1039
                        // turned on, we'll update the channel's database
2✔
1040
                        // state.
2✔
1041
                        err := dbChan.MarkScidAliasNegotiated()
2✔
1042
                        if err != nil {
2✔
1043
                                return nil, err
4✔
1044
                        }
2✔
1045
                }
2✔
1046

2✔
1047
                var chanOpts []lnwallet.ChannelOpt
2✔
1048
                p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
2✔
1049
                        chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
2✔
1050
                })
2✔
1051
                p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
2✔
1052
                        chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
2✔
1053
                })
2✔
1054
                lnChan, err := lnwallet.NewLightningChannel(
2✔
1055
                        p.cfg.Signer, dbChan, p.cfg.SigPool, chanOpts...,
2✔
UNCOV
1056
                )
×
UNCOV
1057
                if err != nil {
×
1058
                        return nil, fmt.Errorf("unable to create channel "+
×
1059
                                "state machine: %w", err)
×
1060
                }
1061

1062
                chanPoint := dbChan.FundingOutpoint
2✔
1063

2✔
1064
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
1065

2✔
1066
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
2✔
1067
                        chanPoint, lnChan.IsPending())
2✔
1068

2✔
1069
                // Skip adding any permanently irreconcilable channels to the
2✔
UNCOV
1070
                // htlcswitch.
×
UNCOV
1071
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
×
UNCOV
1072
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
×
UNCOV
1073

×
UNCOV
1074
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
×
UNCOV
1075
                                "start.", chanPoint, dbChan.ChanStatus())
×
UNCOV
1076

×
1077
                        // To help our peer recover from a potential data loss,
1078
                        // we resend our channel reestablish message if the
UNCOV
1079
                        // channel is in a borked state. We won't process any
×
UNCOV
1080
                        // channel reestablish message sent from the peer, but
×
1081
                        // that's okay since the assumption is that we did when
1082
                        // marking the channel borked.
1083
                        chanSync, err := dbChan.ChanSyncMsg()
1084
                        if err != nil {
1085
                                p.log.Errorf("Unable to create channel "+
×
1086
                                        "reestablish message for channel %v: "+
1087
                                        "%v", chanPoint, err)
1088
                                continue
2✔
1089
                        }
1090

1091
                        msgs = append(msgs, chanSync)
1092

1093
                        // Check if this channel needs to have the cooperative
UNCOV
1094
                        // close process restarted. If so, we'll need to send
×
UNCOV
1095
                        // the Shutdown message that is returned.
×
UNCOV
1096
                        if dbChan.HasChanStatus(
×
UNCOV
1097
                                channeldb.ChanStatusCoopBroadcasted,
×
UNCOV
1098
                        ) {
×
1099

×
1100
                                shutdownMsg, err := p.restartCoopClose(lnChan)
×
1101
                                if err != nil {
1102
                                        p.log.Errorf("Unable to restart "+
1103
                                                "coop close for channel: %v",
1104
                                                err)
1105
                                        continue
1106
                                }
1107

1108
                                if shutdownMsg == nil {
1109
                                        continue
×
UNCOV
1110
                                }
×
UNCOV
1111

×
UNCOV
1112
                                // Append the message to the set of messages to
×
UNCOV
1113
                                // send.
×
1114
                                msgs = append(msgs, shutdownMsg)
×
UNCOV
1115
                        }
×
UNCOV
1116

×
1117
                        continue
1118
                }
1119

1120
                // Before we register this new link with the HTLC Switch, we'll
UNCOV
1121
                // need to fetch its current link-layer forwarding policy from
×
UNCOV
1122
                // the database.
×
UNCOV
1123
                graph := p.cfg.ChannelGraph
×
UNCOV
1124
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
×
UNCOV
1125
                        &chanPoint,
×
UNCOV
1126
                )
×
UNCOV
1127
                if err != nil && !errors.Is(err, channeldb.ErrEdgeNotFound) {
×
1128
                        return nil, err
×
1129
                }
×
1130

UNCOV
1131
                // We'll filter out our policy from the directional channel
×
UNCOV
1132
                // edges based whom the edge connects to. If it doesn't connect
×
UNCOV
1133
                // to us, then we know that we were the one that advertised the
×
UNCOV
1134
                // policy.
×
UNCOV
1135
                //
×
UNCOV
1136
                // TODO(roasbeef): can add helper method to get policy for
×
UNCOV
1137
                // particular channel.
×
UNCOV
1138
                var selfPolicy *models.ChannelEdgePolicy
×
UNCOV
1139
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
×
UNCOV
1140
                        p.cfg.ServerPubKey[:]) {
×
UNCOV
1141

×
UNCOV
1142
                        selfPolicy = p1
×
UNCOV
1143
                } else {
×
UNCOV
1144
                        selfPolicy = p2
×
UNCOV
1145
                }
×
UNCOV
1146

×
UNCOV
1147
                // If we don't yet have an advertised routing policy, then
×
UNCOV
1148
                // we'll use the current default, otherwise we'll translate the
×
UNCOV
1149
                // routing policy into a forwarding policy.
×
1150
                var forwardingPolicy *models.ForwardingPolicy
UNCOV
1151
                if selfPolicy != nil {
×
UNCOV
1152
                        var inboundWireFee lnwire.Fee
×
UNCOV
1153
                        _, err := selfPolicy.ExtraOpaqueData.ExtractRecords(
×
UNCOV
1154
                                &inboundWireFee,
×
UNCOV
1155
                        )
×
UNCOV
1156
                        if err != nil {
×
1157
                                return nil, err
×
1158
                        }
×
UNCOV
1159

×
UNCOV
1160
                        inboundFee := models.NewInboundFeeFromWire(
×
UNCOV
1161
                                inboundWireFee,
×
UNCOV
1162
                        )
×
UNCOV
1163

×
1164
                        forwardingPolicy = &models.ForwardingPolicy{
1165
                                MinHTLCOut:    selfPolicy.MinHTLC,
UNCOV
1166
                                MaxHTLC:       selfPolicy.MaxHTLC,
×
UNCOV
1167
                                BaseFee:       selfPolicy.FeeBaseMSat,
×
UNCOV
1168
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
×
UNCOV
1169
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
×
1170

UNCOV
1171
                                InboundFee: inboundFee,
×
UNCOV
1172
                        }
×
UNCOV
1173
                } else {
×
UNCOV
1174
                        p.log.Warnf("Unable to find our forwarding policy "+
×
UNCOV
1175
                                "for channel %v, using default values",
×
UNCOV
1176
                                chanPoint)
×
UNCOV
1177
                        forwardingPolicy = &p.cfg.RoutingPolicy
×
UNCOV
1178
                }
×
UNCOV
1179

×
UNCOV
1180
                p.log.Tracef("Using link policy of: %v",
×
UNCOV
1181
                        spew.Sdump(forwardingPolicy))
×
UNCOV
1182

×
UNCOV
1183
                // If the channel is pending, set the value to nil in the
×
UNCOV
1184
                // activeChannels map. This is done to signify that the channel
×
UNCOV
1185
                // is pending. We don't add the link to the switch here - it's
×
1186
                // the funding manager's responsibility to spin up pending
UNCOV
1187
                // channels. Adding them here would just be extra work as we'll
×
UNCOV
1188
                // tear them down when creating + adding the final link.
×
UNCOV
1189
                if lnChan.IsPending() {
×
UNCOV
1190
                        p.activeChannels.Store(chanID, nil)
×
UNCOV
1191

×
UNCOV
1192
                        continue
×
UNCOV
1193
                }
×
UNCOV
1194

×
UNCOV
1195
                shutdownInfo, err := lnChan.State().ShutdownInfo()
×
UNCOV
1196
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
×
1197
                        return nil, err
×
1198
                }
×
UNCOV
1199

×
UNCOV
1200
                var (
×
UNCOV
1201
                        shutdownMsg     fn.Option[lnwire.Shutdown]
×
UNCOV
1202
                        shutdownInfoErr error
×
UNCOV
1203
                )
×
1204
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
UNCOV
1205
                        // Compute an ideal fee.
×
UNCOV
1206
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
UNCOV
1207
                                p.cfg.CoopCloseTargetConfs,
×
UNCOV
1208
                        )
×
UNCOV
1209
                        if err != nil {
×
1210
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1211
                                        "estimate fee: %w", err)
×
1212

×
1213
                                return
×
1214
                        }
×
UNCOV
1215

×
UNCOV
1216
                        addr, err := p.addrWithInternalKey(
×
UNCOV
1217
                                info.DeliveryScript.Val,
×
UNCOV
1218
                        ).Unpack()
×
1219
                        if err != nil {
1220
                                shutdownInfoErr = fmt.Errorf("unable to make "+
×
1221
                                        "delivery addr: %w", err)
1222
                                return
×
1223
                        }
×
UNCOV
1224
                        chanCloser, err := p.createChanCloser(
×
1225
                                lnChan, addr, feePerKw, nil, info.Closer(),
1226
                        )
UNCOV
1227
                        if err != nil {
×
1228
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1229
                                        "create chan closer: %w", err)
×
1230

×
1231
                                return
×
1232
                        }
×
1233

UNCOV
1234
                        chanID := lnwire.NewChanIDFromOutPoint(
×
UNCOV
1235
                                lnChan.State().FundingOutpoint,
×
UNCOV
1236
                        )
×
UNCOV
1237

×
UNCOV
1238
                        p.activeChanCloses[chanID] = chanCloser
×
UNCOV
1239

×
UNCOV
1240
                        // Create the Shutdown message.
×
UNCOV
1241
                        shutdown, err := chanCloser.ShutdownChan()
×
1242
                        if err != nil {
1243
                                delete(p.activeChanCloses, chanID)
×
1244
                                shutdownInfoErr = err
1245

1246
                                return
3✔
1247
                        }
1248

1249
                        shutdownMsg = fn.Some(*shutdown)
1250
                })
1251
                if shutdownInfoErr != nil {
1252
                        return nil, shutdownInfoErr
1253
                }
UNCOV
1254

×
UNCOV
1255
                // Subscribe to the set of on-chain events for this channel.
×
UNCOV
1256
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
×
UNCOV
1257
                        chanPoint,
×
UNCOV
1258
                )
×
UNCOV
1259
                if err != nil {
×
1260
                        return nil, err
×
1261
                }
×
UNCOV
1262

×
UNCOV
1263
                err = p.addLink(
×
UNCOV
1264
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
×
UNCOV
1265
                        true, shutdownMsg,
×
UNCOV
1266
                )
×
UNCOV
1267
                if err != nil {
×
1268
                        return nil, fmt.Errorf("unable to add link %v to "+
×
1269
                                "switch: %v", chanPoint, err)
×
1270
                }
×
UNCOV
1271

×
UNCOV
1272
                p.activeChannels.Store(chanID, lnChan)
×
1273
        }
1274

1275
        return msgs, nil
UNCOV
1276
}
×
UNCOV
1277

×
UNCOV
1278
// addLink creates and adds a new ChannelLink from the specified channel.
×
1279
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
UNCOV
1280
        lnChan *lnwallet.LightningChannel,
×
UNCOV
1281
        forwardingPolicy *models.ForwardingPolicy,
×
UNCOV
1282
        chainEvents *contractcourt.ChainEventSubscription,
×
1283
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
1284

UNCOV
1285
        // onChannelFailure will be called by the link in case the channel
×
UNCOV
1286
        // fails for some reason.
×
UNCOV
1287
        onChannelFailure := func(chanID lnwire.ChannelID,
×
UNCOV
1288
                shortChanID lnwire.ShortChannelID,
×
UNCOV
1289
                linkErr htlcswitch.LinkFailureError) {
×
UNCOV
1290

×
UNCOV
1291
                failure := linkFailureReport{
×
UNCOV
1292
                        chanPoint:   *chanPoint,
×
UNCOV
1293
                        chanID:      chanID,
×
UNCOV
1294
                        shortChanID: shortChanID,
×
UNCOV
1295
                        linkErr:     linkErr,
×
UNCOV
1296
                }
×
UNCOV
1297

×
UNCOV
1298
                select {
×
UNCOV
1299
                case p.linkFailures <- failure:
×
1300
                case <-p.quit:
×
1301
                case <-p.cfg.Quit:
×
UNCOV
1302
                }
×
UNCOV
1303
        }
×
UNCOV
1304

×
UNCOV
1305
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
×
UNCOV
1306
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
×
UNCOV
1307
        }
×
UNCOV
1308

×
UNCOV
1309
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
×
UNCOV
1310
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
×
UNCOV
1311
        }
×
UNCOV
1312

×
UNCOV
1313
        //nolint:lll
×
UNCOV
1314
        linkCfg := htlcswitch.ChannelLinkConfig{
×
UNCOV
1315
                Peer:                   p,
×
UNCOV
1316
                DecodeHopIterators:     p.cfg.Sphinx.DecodeHopIterators,
×
UNCOV
1317
                ExtractErrorEncrypter:  p.cfg.Sphinx.ExtractErrorEncrypter,
×
UNCOV
1318
                FetchLastChannelUpdate: p.cfg.FetchLastChanUpdate,
×
UNCOV
1319
                HodlMask:               p.cfg.Hodl.Mask(),
×
UNCOV
1320
                Registry:               p.cfg.Invoices,
×
UNCOV
1321
                BestHeight:             p.cfg.Switch.BestHeight,
×
UNCOV
1322
                Circuits:               p.cfg.Switch.CircuitModifier(),
×
UNCOV
1323
                ForwardPackets:         p.cfg.InterceptSwitch.ForwardPackets,
×
UNCOV
1324
                FwrdingPolicy:          *forwardingPolicy,
×
UNCOV
1325
                FeeEstimator:           p.cfg.FeeEstimator,
×
UNCOV
1326
                PreimageCache:          p.cfg.WitnessBeacon,
×
UNCOV
1327
                ChainEvents:            chainEvents,
×
UNCOV
1328
                UpdateContractSignals:  updateContractSignals,
×
UNCOV
1329
                NotifyContractUpdate:   notifyContractUpdate,
×
UNCOV
1330
                OnChannelFailure:       onChannelFailure,
×
UNCOV
1331
                SyncStates:             syncStates,
×
UNCOV
1332
                BatchTicker:            ticker.New(p.cfg.ChannelCommitInterval),
×
UNCOV
1333
                FwdPkgGCTicker:         ticker.New(time.Hour),
×
UNCOV
1334
                PendingCommitTicker: ticker.New(
×
UNCOV
1335
                        p.cfg.PendingCommitInterval,
×
UNCOV
1336
                ),
×
UNCOV
1337
                BatchSize:               p.cfg.ChannelCommitBatchSize,
×
UNCOV
1338
                UnsafeReplay:            p.cfg.UnsafeReplay,
×
UNCOV
1339
                MinUpdateTimeout:        htlcswitch.DefaultMinLinkFeeUpdateTimeout,
×
UNCOV
1340
                MaxUpdateTimeout:        htlcswitch.DefaultMaxLinkFeeUpdateTimeout,
×
1341
                OutgoingCltvRejectDelta: p.cfg.OutgoingCltvRejectDelta,
1342
                TowerClient:             p.cfg.TowerClient,
1343
                MaxOutgoingCltvExpiry:   p.cfg.MaxOutgoingCltvExpiry,
1344
                MaxFeeAllocation:        p.cfg.MaxChannelFeeAllocation,
1345
                MaxAnchorsCommitFeeRate: p.cfg.MaxAnchorsCommitFeeRate,
3✔
1346
                NotifyActiveLink:        p.cfg.ChannelNotifier.NotifyActiveLinkEvent,
3✔
1347
                NotifyActiveChannel:     p.cfg.ChannelNotifier.NotifyActiveChannelEvent,
3✔
1348
                NotifyInactiveChannel:   p.cfg.ChannelNotifier.NotifyInactiveChannelEvent,
3✔
1349
                NotifyInactiveLinkEvent: p.cfg.ChannelNotifier.NotifyInactiveLinkEvent,
5✔
1350
                HtlcNotifier:            p.cfg.HtlcNotifier,
2✔
UNCOV
1351
                GetAliases:              p.cfg.GetAliases,
×
1352
                PreviouslySentShutdown:  shutdownMsg,
1353
                DisallowRouteBlinding:   p.cfg.DisallowRouteBlinding,
4✔
1354
                DisallowQuiescence: p.cfg.DisallowQuiescence ||
2✔
1355
                        !p.remoteFeatures.HasFeature(lnwire.QuiescenceOptional),
1356
                MaxFeeExposure:          p.cfg.MaxFeeExposure,
UNCOV
1357
        }
×
UNCOV
1358

×
1359
        // Before adding our new link, purge the switch of any pending or live
1360
        // links going by the same channel id. If one is found, we'll shut it
6✔
1361
        // down to ensure that the mailboxes are only ever under the control of
3✔
1362
        // one link.
3✔
1363
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
UNCOV
1364
        p.cfg.Switch.RemoveLink(chanID)
×
UNCOV
1365

×
UNCOV
1366
        // With the channel link created, we'll now notify the htlc switch so
×
UNCOV
1367
        // this channel can be used to dispatch local payments and also
×
UNCOV
1368
        // passively forward payments.
×
1369
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
UNCOV
1370
}
×
UNCOV
1371

×
UNCOV
1372
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
×
1373
// one confirmed public channel exists with them.
1374
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
1375
        defer p.wg.Done()
1376

1377
        hasConfirmedPublicChan := false
3✔
1378
        for _, channel := range channels {
3✔
1379
                if channel.IsPending {
3✔
1380
                        continue
3✔
1381
                }
4✔
1382
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
1✔
1383
                        continue
1✔
1384
                }
1385

2✔
1386
                hasConfirmedPublicChan = true
4✔
1387
                break
2✔
1388
        }
2✔
1389
        if !hasConfirmedPublicChan {
2✔
UNCOV
1390
                return
×
UNCOV
1391
        }
×
1392

1393
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
2✔
1394
        if err != nil {
4✔
1395
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
2✔
1396
                return
1397
        }
UNCOV
1398

×
UNCOV
1399
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
×
1400
                p.log.Debugf("Unable to resend node announcement: %v", err)
1401
        }
1402
}
2✔
1403

2✔
1404
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1405
// have any active channels with them.
1406
func (p *Brontide) maybeSendChannelUpdates() {
1407
        defer p.wg.Done()
1408

1409
        // If we don't have any active channels, then we can exit early.
1410
        if p.activeChannels.Len() == 0 {
1411
                return
2✔
1412
        }
2✔
UNCOV
1413

×
UNCOV
1414
        maybeSendUpd := func(cid lnwire.ChannelID,
×
UNCOV
1415
                lnChan *lnwallet.LightningChannel) error {
×
UNCOV
1416

×
UNCOV
1417
                // Nil channels are pending, so we'll skip them.
×
UNCOV
1418
                if lnChan == nil {
×
1419
                        return nil
1420
                }
2✔
1421

2✔
1422
                dbChan := lnChan.State()
2✔
1423
                scid := func() lnwire.ShortChannelID {
2✔
1424
                        switch {
2✔
1425
                        // Otherwise if it's a zero conf channel and confirmed,
2✔
UNCOV
1426
                        // then we need to use the "real" scid.
×
UNCOV
1427
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
×
UNCOV
1428
                                return dbChan.ZeroConfRealScid()
×
UNCOV
1429

×
UNCOV
1430
                        // Otherwise, we can use the normal scid.
×
UNCOV
1431
                        default:
×
UNCOV
1432
                                return dbChan.ShortChanID()
×
UNCOV
1433
                        }
×
1434
                }()
1435

2✔
1436
                // Now that we know the channel is in a good state, we'll try
1437
                // to fetch the update to send to the remote peer. If the
1438
                // channel is pending, and not a zero conf channel, we'll get
2✔
1439
                // an error here which we'll ignore.
1440
                chanUpd, err := p.cfg.FetchLastChanUpdate(scid)
1441
                if err != nil {
1442
                        p.log.Debugf("Unable to fetch channel update for "+
1443
                                "ChannelPoint(%v), scid=%v: %v",
1444
                                dbChan.FundingOutpoint, dbChan.ShortChanID, err)
1445

1446
                        return nil
1447
                }
1448

UNCOV
1449
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
×
UNCOV
1450
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
×
UNCOV
1451

×
UNCOV
1452
                // We'll send it as a normal message instead of using the lazy
×
UNCOV
1453
                // queue to prioritize transmission of the fresh update.
×
UNCOV
1454
                if err := p.SendMessage(false, chanUpd); err != nil {
×
1455
                        err := fmt.Errorf("unable to send channel update for "+
×
1456
                                "ChannelPoint(%v), scid=%v: %w",
1457
                                dbChan.FundingOutpoint, dbChan.ShortChanID(),
1458
                                err)
×
1459
                        p.log.Errorf(err.Error())
×
1460

×
1461
                        return err
1462
                }
UNCOV
1463

×
1464
                return nil
1465
        }
1466

1467
        p.activeChannels.ForEach(maybeSendUpd)
1468
}
1469

1✔
1470
// WaitForDisconnect waits until the peer has disconnected. A peer may be
1✔
UNCOV
1471
// disconnected if the local or remote side terminates the connection, or an
×
UNCOV
1472
// irrecoverable protocol error has been encountered. This method will only
×
1473
// begin watching the peer's waitgroup after the ready channel or the peer's
1474
// quit channel are signaled. The ready channel should only be signaled if a
1475
// call to Start returns no error. Otherwise, if the peer fails to start,
1476
// calling Disconnect will signal the quit channel and the method will not
1✔
UNCOV
1477
// block, since no goroutines were spawned.
×
UNCOV
1478
func (p *Brontide) WaitForDisconnect(ready chan struct{}) {
×
UNCOV
1479
        // Before we try to call the `Wait` goroutine, we'll make sure the main
×
1480
        // set of goroutines are already active.
1481
        select {
UNCOV
1482
        case <-p.startReady:
×
1483
        case <-p.quit:
×
1484
                return
×
UNCOV
1485
        }
×
UNCOV
1486

×
UNCOV
1487
        select {
×
UNCOV
1488
        case <-ready:
×
UNCOV
1489
        case <-p.quit:
×
UNCOV
1490
        }
×
UNCOV
1491

×
UNCOV
1492
        p.wg.Wait()
×
UNCOV
1493
}
×
UNCOV
1494

×
UNCOV
1495
// Disconnect terminates the connection with the remote peer. Additionally, a
×
UNCOV
1496
// signal is sent to the server and htlcSwitch indicating the resources
×
UNCOV
1497
// allocated to the peer can now be cleaned up.
×
UNCOV
1498
func (p *Brontide) Disconnect(reason error) {
×
UNCOV
1499
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
×
UNCOV
1500
                return
×
1501
        }
1502

1503
        // Make sure initialization has completed before we try to tear things
1504
        // down.
UNCOV
1505
        select {
×
UNCOV
1506
        case <-p.startReady:
×
1507
        case <-p.quit:
×
1508
                return
1509
        }
1510

1511
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
7✔
1512
        p.storeError(err)
7✔
1513

7✔
1514
        p.log.Infof(err.Error())
7✔
UNCOV
1515

×
UNCOV
1516
        // Stop PingManager before closing TCP connection.
×
1517
        p.pingManager.Stop()
1518

7✔
1519
        // Ensure that the TCP connection is properly closed before continuing.
7✔
UNCOV
1520
        p.cfg.Conn.Close()
×
UNCOV
1521

×
1522
        close(p.quit)
1523

1524
        // If our msg router isn't global (local to this instance), then we'll
1525
        // stop it. Otherwise, we'll leave it running.
1526
        if !p.globalMsgRouter {
1527
                p.msgRouter.WhenSome(func(router msgmux.Router) {
4✔
1528
                        router.Stop()
4✔
1529
                })
4✔
1530
        }
4✔
1531
}
8✔
1532

4✔
1533
// String returns the string representation of this peer.
4✔
1534
func (p *Brontide) String() string {
4✔
1535
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
4✔
1536
}
4✔
1537

4✔
1538
// readNextMessage reads, and returns the next message on the wire along with
4✔
1539
// any additional raw payload.
4✔
1540
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
4✔
1541
        noiseConn := p.cfg.Conn
4✔
UNCOV
1542
        err := noiseConn.SetReadDeadline(time.Time{})
×
UNCOV
1543
        if err != nil {
×
1544
                return nil, err
1545
        }
1546

1547
        pktLen, err := noiseConn.ReadNextHeader()
1548
        if err != nil {
1549
                return nil, fmt.Errorf("read next header: %w", err)
4✔
1550
        }
4✔
UNCOV
1551

×
UNCOV
1552
        // First we'll read the next _full_ message. We do this rather than
×
1553
        // reading incrementally from the stream as the Lightning wire protocol
4✔
1554
        // is message oriented and allows nodes to pad on additional data to
4✔
1555
        // the message stream.
4✔
1556
        var (
4✔
1557
                nextMsg lnwire.Message
4✔
1558
                msgLen  uint64
4✔
1559
        )
4✔
UNCOV
1560
        err = p.cfg.ReadPool.Submit(func(buf *buffer.Read) error {
×
UNCOV
1561
                // Before reading the body of the message, set the read timeout
×
1562
                // accordingly to ensure we don't block other readers using the
1563
                // pool. We do so only after the task has been scheduled to
1564
                // ensure the deadline doesn't expire while the message is in
1565
                // the process of being scheduled.
4✔
1566
                readDeadline := time.Now().Add(
1567
                        p.scaleTimeout(readMessageTimeout),
4✔
1568
                )
4✔
UNCOV
1569
                readErr := noiseConn.SetReadDeadline(readDeadline)
×
UNCOV
1570
                if readErr != nil {
×
1571
                        return readErr
1572
                }
4✔
1573

4✔
1574
                // The ReadNextBody method will actually end up re-using the
4✔
1575
                // buffer, so within this closure, we can continue to use
1576
                // rawMsg as it's just a slice into the buf from the buffer
1577
                // pool.
1578
                rawMsg, readErr := noiseConn.ReadNextBody(buf[:pktLen])
1579
                if readErr != nil {
1580
                        return fmt.Errorf("read next body: %w", readErr)
1581
                }
1582
                msgLen = uint64(len(rawMsg))
1583

1584
                // Next, create a new io.Reader implementation from the raw
1585
                // message, and use this to decode the message directly from.
1586
                msgReader := bytes.NewReader(rawMsg)
1587
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
1588
                if err != nil {
1589
                        return err
1590
                }
1591

1592
                // At this point, rawMsg and buf will be returned back to the
1593
                // buffer pool for re-use.
1594
                return nil
1595
        })
1596
        atomic.AddUint64(&p.bytesReceived, msgLen)
1597
        if err != nil {
1598
                return nil, err
1599
        }
1600

1601
        p.logWireMessage(nextMsg, true)
1602

1603
        return nextMsg, nil
1604
}
1605

1606
// msgStream implements a goroutine-safe, in-order stream of messages to be
1607
// delivered via closure to a receiver. These messages MUST be in order due to
1608
// the nature of the lightning channel commitment and gossiper state machines.
1609
// TODO(conner): use stream handler interface to abstract out stream
3✔
1610
// state/logging.
3✔
1611
type msgStream struct {
3✔
1612
        streamShutdown int32 // To be used atomically.
3✔
1613

3✔
1614
        peer *Brontide
3✔
1615

3✔
1616
        apply func(lnwire.Message)
3✔
1617

3✔
1618
        startMsg string
3✔
1619
        stopMsg  string
3✔
1620

3✔
1621
        msgCond *sync.Cond
3✔
1622
        msgs    []lnwire.Message
3✔
1623

3✔
1624
        mtx sync.Mutex
3✔
1625

3,003✔
1626
        producerSema chan struct{}
3,000✔
1627

3,000✔
1628
        wg   sync.WaitGroup
1629
        quit chan struct{}
3✔
1630
}
1631

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

×
UNCOV
1640
        stream := &msgStream{
×
UNCOV
1641
                peer:         p,
×
UNCOV
1642
                apply:        apply,
×
UNCOV
1643
                startMsg:     startMsg,
×
UNCOV
1644
                stopMsg:      stopMsg,
×
UNCOV
1645
                producerSema: make(chan struct{}, bufSize),
×
UNCOV
1646
                quit:         make(chan struct{}),
×
UNCOV
1647
        }
×
UNCOV
1648
        stream.msgCond = sync.NewCond(&stream.mtx)
×
UNCOV
1649

×
1650
        // Before we return the active stream, we'll populate the producer's
UNCOV
1651
        // semaphore channel. We'll use this to ensure that the producer won't
×
1652
        // attempt to allocate memory in the queue for an item until it has
1653
        // sufficient extra space.
1654
        for i := uint32(0); i < bufSize; i++ {
1655
                stream.producerSema <- struct{}{}
1656
        }
3✔
1657

3✔
1658
        return stream
3✔
1659
}
3✔
1660

3✔
1661
// Start starts the chanMsgStream.
3✔
1662
func (ms *msgStream) Start() {
3✔
1663
        ms.wg.Add(1)
6✔
1664
        go ms.msgConsumer()
3✔
1665
}
3✔
1666

3✔
1667
// Stop stops the chanMsgStream.
6✔
1668
func (ms *msgStream) Stop() {
3✔
1669
        // TODO(roasbeef): signal too?
3✔
1670

3✔
1671
        close(ms.quit)
3✔
1672

3✔
1673
        // Now that we've closed the channel, we'll repeatedly signal the msg
3✔
UNCOV
1674
        // consumer until we've detected that it has exited.
×
UNCOV
1675
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
×
UNCOV
1676
                ms.msgCond.Signal()
×
UNCOV
1677
                time.Sleep(time.Millisecond * 100)
×
UNCOV
1678
        }
×
UNCOV
1679

×
UNCOV
1680
        ms.wg.Wait()
×
1681
}
1682

1683
// msgConsumer is the main goroutine that streams messages from the peer's
1684
// readHandler directly to the target channel.
1685
func (ms *msgStream) msgConsumer() {
1686
        defer ms.wg.Done()
UNCOV
1687
        defer peerLog.Tracef(ms.stopMsg)
×
UNCOV
1688
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
×
UNCOV
1689

×
UNCOV
1690
        peerLog.Tracef(ms.startMsg)
×
UNCOV
1691

×
UNCOV
1692
        for {
×
UNCOV
1693
                // First, we'll check our condition. If the queue of messages
×
UNCOV
1694
                // is empty, then we'll wait until a new item is added.
×
UNCOV
1695
                ms.msgCond.L.Lock()
×
UNCOV
1696
                for len(ms.msgs) == 0 {
×
UNCOV
1697
                        ms.msgCond.Wait()
×
UNCOV
1698

×
UNCOV
1699
                        // If we woke up in order to exit, then we'll do so.
×
UNCOV
1700
                        // Otherwise, we'll check the message queue for any new
×
UNCOV
1701
                        // items.
×
UNCOV
1702
                        select {
×
UNCOV
1703
                        case <-ms.peer.quit:
×
UNCOV
1704
                                ms.msgCond.L.Unlock()
×
1705
                                return
1706
                        case <-ms.quit:
1707
                                ms.msgCond.L.Unlock()
1708
                                return
1709
                        default:
1710
                        }
UNCOV
1711
                }
×
UNCOV
1712

×
UNCOV
1713
                // Grab the message off the front of the queue, shifting the
×
UNCOV
1714
                // slice's reference down one in order to remove the message
×
UNCOV
1715
                // from the queue.
×
UNCOV
1716
                msg := ms.msgs[0]
×
UNCOV
1717
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
×
UNCOV
1718
                ms.msgs = ms.msgs[1:]
×
UNCOV
1719

×
UNCOV
1720
                ms.msgCond.L.Unlock()
×
UNCOV
1721

×
UNCOV
1722
                ms.apply(msg)
×
1723

1724
                // We've just successfully processed an item, so we'll signal
1725
                // to the producer that a new slot in the buffer. We'll use
1726
                // this to bound the size of the buffer to avoid allowing it to
UNCOV
1727
                // grow indefinitely.
×
UNCOV
1728
                select {
×
UNCOV
1729
                case ms.producerSema <- struct{}{}:
×
UNCOV
1730
                case <-ms.peer.quit:
×
UNCOV
1731
                        return
×
UNCOV
1732
                case <-ms.quit:
×
UNCOV
1733
                        return
×
1734
                }
1735
        }
1736
}
1737

1738
// AddMsg adds a new message to the msgStream. This function is safe for
1739
// concurrent access.
UNCOV
1740
func (ms *msgStream) AddMsg(msg lnwire.Message) {
×
UNCOV
1741
        // First, we'll attempt to receive from the producerSema struct. This
×
UNCOV
1742
        // acts as a semaphore to prevent us from indefinitely buffering
×
UNCOV
1743
        // incoming items from the wire. Either the msg queue isn't full, and
×
UNCOV
1744
        // we'll not block, or the queue is full, and we'll block until either
×
UNCOV
1745
        // we're signalled to quit, or a slot is freed up.
×
UNCOV
1746
        select {
×
UNCOV
1747
        case <-ms.producerSema:
×
1748
        case <-ms.peer.quit:
×
1749
                return
×
1750
        case <-ms.quit:
×
1751
                return
×
UNCOV
1752
        }
×
UNCOV
1753

×
UNCOV
1754
        // Next, we'll lock the condition, and add the message to the end of
×
UNCOV
1755
        // the message queue.
×
UNCOV
1756
        ms.msgCond.L.Lock()
×
UNCOV
1757
        ms.msgs = append(ms.msgs, msg)
×
UNCOV
1758
        ms.msgCond.L.Unlock()
×
UNCOV
1759

×
UNCOV
1760
        // With the message added, we signal to the msgConsumer that there are
×
UNCOV
1761
        // additional messages to consume.
×
UNCOV
1762
        ms.msgCond.Signal()
×
UNCOV
1763
}
×
UNCOV
1764

×
UNCOV
1765
// waitUntilLinkActive waits until the target link is active and returns a
×
UNCOV
1766
// ChannelLink to pass messages to. It accomplishes this by subscribing to
×
UNCOV
1767
// an ActiveLinkEvent which is emitted by the link when it first starts up.
×
1768
func waitUntilLinkActive(p *Brontide,
1769
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
UNCOV
1770

×
UNCOV
1771
        p.log.Tracef("Waiting for link=%v to be active", cid)
×
1772

1773
        // Subscribe to receive channel events.
1774
        //
1775
        // NOTE: If the link is already active by SubscribeChannelEvents, then
UNCOV
1776
        // GetLink will retrieve the link and we can send messages. If the link
×
UNCOV
1777
        // becomes active between SubscribeChannelEvents and GetLink, then GetLink
×
UNCOV
1778
        // will retrieve the link. If the link becomes active after GetLink, then
×
UNCOV
1779
        // we will get an ActiveLinkEvent notification and retrieve the link. If
×
UNCOV
1780
        // the call to GetLink is before SubscribeChannelEvents, however, there
×
1781
        // will be a race condition.
1782
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
UNCOV
1783
        if err != nil {
×
UNCOV
1784
                // If we have a non-nil error, then the server is shutting down and we
×
UNCOV
1785
                // can exit here and return nil. This means no message will be delivered
×
UNCOV
1786
                // to the link.
×
UNCOV
1787
                return nil
×
UNCOV
1788
        }
×
1789
        defer sub.Cancel()
1790

1791
        // The link may already be active by this point, and we may have missed the
1792
        // ActiveLinkEvent. Check if the link exists.
1793
        link := p.fetchLinkFromKeyAndCid(cid)
UNCOV
1794
        if link != nil {
×
1795
                return link
UNCOV
1796
        }
×
UNCOV
1797

×
1798
        // If the link is nil, we must wait for it to be active.
1799
        for {
1800
                select {
1801
                // A new event has been sent by the ChannelNotifier. We first check
1802
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1803
                // that the event is for this channel. Otherwise, we discard the
1804
                // message.
1805
                case e := <-sub.Updates():
1806
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
1807
                        if !ok {
UNCOV
1808
                                // Ignore this notification.
×
UNCOV
1809
                                continue
×
UNCOV
1810
                        }
×
UNCOV
1811

×
UNCOV
1812
                        chanPoint := event.ChannelPoint
×
UNCOV
1813

×
UNCOV
1814
                        // Check whether the retrieved chanPoint matches the target
×
UNCOV
1815
                        // channel id.
×
UNCOV
1816
                        if !cid.IsChanPoint(chanPoint) {
×
1817
                                continue
×
UNCOV
1818
                        }
×
UNCOV
1819

×
UNCOV
1820
                        // The link shouldn't be nil as we received an
×
UNCOV
1821
                        // ActiveLinkEvent. If it is nil, we return nil and the
×
UNCOV
1822
                        // calling function should catch it.
×
UNCOV
1823
                        return p.fetchLinkFromKeyAndCid(cid)
×
1824

1825
                case <-p.quit:
1826
                        return nil
1827
                }
1828
        }
UNCOV
1829
}
×
UNCOV
1830

×
UNCOV
1831
// newChanMsgStream is used to create a msgStream between the peer and
×
UNCOV
1832
// particular channel link in the htlcswitch. We utilize additional
×
1833
// synchronization with the fundingManager to ensure we don't attempt to
1834
// dispatch a message to a channel before it is fully active. A reference to the
UNCOV
1835
// channel this stream forwards to is held in scope to prevent unnecessary
×
1836
// lookups.
1837
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
UNCOV
1838
        var chanLink htlcswitch.ChannelUpdateHandler
×
UNCOV
1839

×
UNCOV
1840
        apply := func(msg lnwire.Message) {
×
UNCOV
1841
                // This check is fine because if the link no longer exists, it will
×
UNCOV
1842
                // be removed from the activeChannels map and subsequent messages
×
UNCOV
1843
                // shouldn't reach the chan msg stream.
×
1844
                if chanLink == nil {
1845
                        chanLink = waitUntilLinkActive(p, cid)
1846

1847
                        // If the link is still not active and the calling function
1848
                        // errored out, just return.
1849
                        if chanLink == nil {
3✔
1850
                                p.log.Warnf("Link=%v is not active")
3✔
UNCOV
1851
                                return
×
UNCOV
1852
                        }
×
UNCOV
1853
                }
×
UNCOV
1854

×
1855
                // In order to avoid unnecessarily delivering message
1856
                // as the peer is exiting, we'll check quickly to see
3✔
1857
                // if we need to exit.
3✔
1858
                select {
3✔
1859
                case <-p.quit:
3✔
1860
                        return
3✔
1861
                default:
3✔
1862
                }
3✔
1863

1864
                chanLink.HandleChannelUpdate(msg)
1865
        }
1866

1867
        return newMsgStream(p,
1868
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
1869
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
3✔
1870
                1000,
3✔
1871
                apply,
3✔
1872
        )
3✔
1873
}
3✔
1874

3✔
UNCOV
1875
// newDiscMsgStream is used to setup a msgStream between the peer and the
×
UNCOV
1876
// authenticated gossiper. This stream should be used to forward all remote
×
UNCOV
1877
// channel announcements.
×
UNCOV
1878
func newDiscMsgStream(p *Brontide) *msgStream {
×
1879
        apply := func(msg lnwire.Message) {
1880
                // TODO(yy): `ProcessRemoteAnnouncement` returns an error chan
1881
                // and we need to process it.
1882
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(msg, p)
1883
        }
1884

1885
        return newMsgStream(
1886
                p,
3✔
1887
                "Update stream for gossiper created",
3✔
1888
                "Update stream for gossiper exited",
3✔
1889
                1000,
3✔
1890
                apply,
3✔
1891
        )
3✔
1892
}
7✔
1893

4✔
1894
// readHandler is responsible for reading messages off the wire in series, then
4✔
UNCOV
1895
// properly dispatching the handling of the message to the proper subsystem.
×
UNCOV
1896
//
×
UNCOV
1897
// NOTE: This method MUST be run as a goroutine.
×
1898
func (p *Brontide) readHandler() {
1899
        defer p.wg.Done()
1900

1✔
UNCOV
1901
        // We'll stop the timer after a new messages is received, and also
×
UNCOV
1902
        // reset it after we process the next message.
×
UNCOV
1903
        idleTimer := time.AfterFunc(idleTimeout, func() {
×
1904
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
1905
                        p, idleTimeout)
×
1906
                p.Disconnect(err)
×
1907
        })
×
1908

1909
        // Initialize our negotiated gossip sync method before reading messages
1910
        // off the wire. When using gossip queries, this ensures a gossip
1911
        // syncer is active by the time query messages arrive.
UNCOV
1912
        //
×
UNCOV
1913
        // TODO(conner): have peer store gossip syncer directly and bypass
×
UNCOV
1914
        // gossiper?
×
UNCOV
1915
        p.initGossipSync()
×
1916

1917
        discStream := newDiscMsgStream(p)
1918
        discStream.Start()
1919
        defer discStream.Stop()
1920
out:
UNCOV
1921
        for atomic.LoadInt32(&p.disconnect) == 0 {
×
UNCOV
1922
                nextMsg, err := p.readNextMessage()
×
UNCOV
1923
                if !idleTimer.Stop() {
×
1924
                        select {
×
1925
                        case <-idleTimer.C:
1926
                        default:
1927
                        }
1928
                }
1929
                if err != nil {
1930
                        p.log.Infof("unable to read message from peer: %v", err)
UNCOV
1931

×
UNCOV
1932
                        // If we could not read our peer's message due to an
×
UNCOV
1933
                        // unknown type or invalid alias, we continue processing
×
1934
                        // as normal. We store unknown message and address
1935
                        // types, as they may provide debugging insight.
1936
                        switch e := err.(type) {
1937
                        // If this is just a message we don't yet recognize,
UNCOV
1938
                        // we'll continue processing as normal as this allows
×
UNCOV
1939
                        // us to introduce new messages in a forwards
×
1940
                        // compatible manner.
1941
                        case *lnwire.UnknownMessage:
1942
                                p.storeError(e)
1943
                                idleTimer.Reset(idleTimeout)
1944
                                continue
1945

1946
                        // If they sent us an address type that we don't yet
2✔
1947
                        // know of, then this isn't a wire error, so we'll
1✔
1948
                        // simply continue parsing the remainder of their
1✔
1949
                        // messages.
1✔
1950
                        case *lnwire.ErrUnknownAddrType:
1✔
1951
                                p.storeError(e)
1✔
1952
                                idleTimer.Reset(idleTimeout)
1953
                                continue
1954

1955
                        // If the NodeAnnouncement has an invalid alias, then
1✔
UNCOV
1956
                        // we'll log that error above and continue so we can
×
1957
                        // continue to read messages from the peer. We do not
1958
                        // store this error because it is of little debugging
1959
                        // value.
1✔
1960
                        case *lnwire.ErrInvalidNodeAlias:
1✔
1961
                                idleTimer.Reset(idleTimeout)
1✔
1962
                                continue
1✔
1963

1✔
1964
                        // If the error we encountered wasn't just a message we
1✔
UNCOV
1965
                        // didn't recognize, then we'll stop all processing as
×
UNCOV
1966
                        // this is a fatal error.
×
UNCOV
1967
                        default:
×
UNCOV
1968
                                break out
×
1969
                        }
UNCOV
1970
                }
×
UNCOV
1971

×
UNCOV
1972
                // If a message router is active, then we'll try to have it
×
UNCOV
1973
                // handle this message. If it can, then we're able to skip the
×
UNCOV
1974
                // rest of the message handling logic.
×
UNCOV
1975
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
×
UNCOV
1976
                        return r.RouteMsg(msgmux.PeerMsg{
×
UNCOV
1977
                                PeerPub: *p.IdentityKey(),
×
UNCOV
1978
                                Message: nextMsg,
×
1979
                        })
1980
                })
1981

1982
                // No error occurred, and the message was handled by the
1983
                // router.
UNCOV
1984
                if err == nil {
×
1985
                        continue
×
UNCOV
1986
                }
×
1987

UNCOV
1988
                var (
×
UNCOV
1989
                        targetChan   lnwire.ChannelID
×
UNCOV
1990
                        isLinkUpdate bool
×
UNCOV
1991
                )
×
UNCOV
1992

×
1993
                switch msg := nextMsg.(type) {
UNCOV
1994
                case *lnwire.Pong:
×
UNCOV
1995
                        // When we receive a Pong message in response to our
×
UNCOV
1996
                        // last ping message, we send it to the pingManager
×
UNCOV
1997
                        p.pingManager.ReceivedPong(msg)
×
UNCOV
1998

×
1999
                case *lnwire.Ping:
2000
                        // First, we'll store their latest ping payload within
UNCOV
2001
                        // the relevant atomic variable.
×
UNCOV
2002
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
UNCOV
2003

×
2004
                        // Next, we'll send over the amount of specified pong
UNCOV
2005
                        // bytes.
×
UNCOV
2006
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
×
UNCOV
2007
                        p.queueMsg(pong, nil)
×
2008

UNCOV
2009
                case *lnwire.OpenChannel,
×
UNCOV
2010
                        *lnwire.AcceptChannel,
×
UNCOV
2011
                        *lnwire.FundingCreated,
×
UNCOV
2012
                        *lnwire.FundingSigned,
×
UNCOV
2013
                        *lnwire.ChannelReady:
×
UNCOV
2014

×
UNCOV
2015
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
×
UNCOV
2016

×
UNCOV
2017
                case *lnwire.Shutdown:
×
UNCOV
2018
                        select {
×
UNCOV
2019
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
×
2020
                        case <-p.quit:
×
2021
                                break out
×
UNCOV
2022
                        }
×
UNCOV
2023
                case *lnwire.ClosingSigned:
×
UNCOV
2024
                        select {
×
UNCOV
2025
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
×
2026
                        case <-p.quit:
2027
                                break out
2028
                        }
2029

2030
                case *lnwire.Warning:
2031
                        targetChan = msg.ChanID
2032
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
UNCOV
2033

×
UNCOV
2034
                case *lnwire.Error:
×
UNCOV
2035
                        targetChan = msg.ChanID
×
UNCOV
2036
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
UNCOV
2037

×
UNCOV
2038
                case *lnwire.ChannelReestablish:
×
UNCOV
2039
                        targetChan = msg.ChanID
×
UNCOV
2040
                        isLinkUpdate = p.hasChannel(targetChan)
×
UNCOV
2041

×
UNCOV
2042
                        // If we failed to find the link in question, and the
×
UNCOV
2043
                        // message received was a channel sync message, then
×
2044
                        // this might be a peer trying to resync closed channel.
2045
                        // In this case we'll try to resend our last channel
2046
                        // sync message, such that the peer can recover funds
2047
                        // from the closed channel.
2048
                        if !isLinkUpdate {
2049
                                err := p.resendChanSyncMsg(targetChan)
2050
                                if err != nil {
2051
                                        // TODO(halseth): send error to peer?
2052
                                        p.log.Errorf("resend failed: %v",
UNCOV
2053
                                                err)
×
UNCOV
2054
                                }
×
UNCOV
2055
                        }
×
2056

2057
                // For messages that implement the LinkUpdater interface, we
1✔
2058
                // will consider them as link updates and send them to
1✔
2059
                // chanStream. These messages will be queued inside chanStream
1✔
UNCOV
2060
                // if the channel is not active yet.
×
UNCOV
2061
                case lnwire.LinkUpdater:
×
UNCOV
2062
                        targetChan = msg.TargetChanID()
×
2063
                        isLinkUpdate = p.hasChannel(targetChan)
UNCOV
2064

×
UNCOV
2065
                        // Log an error if we don't have this channel. This
×
UNCOV
2066
                        // means the peer has sent us a message with unknown
×
UNCOV
2067
                        // channel ID.
×
UNCOV
2068
                        if !isLinkUpdate {
×
UNCOV
2069
                                p.log.Errorf("Unknown channel ID: %v found "+
×
UNCOV
2070
                                        "in received msg=%s", targetChan,
×
UNCOV
2071
                                        nextMsg.MsgType())
×
2072
                        }
2073

2074
                case *lnwire.ChannelUpdate1,
1✔
UNCOV
2075
                        *lnwire.ChannelAnnouncement1,
×
UNCOV
2076
                        *lnwire.NodeAnnouncement,
×
UNCOV
2077
                        *lnwire.AnnounceSignatures1,
×
UNCOV
2078
                        *lnwire.GossipTimestampRange,
×
2079
                        *lnwire.QueryShortChanIDs,
2080
                        *lnwire.QueryChannelRange,
1✔
2081
                        *lnwire.ReplyChannelRange,
2082
                        *lnwire.ReplyShortChanIDsEnd:
UNCOV
2083

×
UNCOV
2084
                        discStream.AddMsg(msg)
×
UNCOV
2085

×
2086
                case *lnwire.Custom:
2087
                        err := p.handleCustomMessage(msg)
2088
                        if err != nil {
2089
                                p.storeError(err)
2090
                                p.log.Errorf("%v", err)
1✔
2091
                        }
1✔
UNCOV
2092

×
2093
                default:
×
2094
                        // If the message we received is unknown to us, store
×
2095
                        // the type to track the failure.
2096
                        err := fmt.Errorf("unknown message type %v received",
1✔
2097
                                uint16(msg.MsgType()))
2098
                        p.storeError(err)
2099

2100
                        p.log.Errorf("%v", err)
2101
                }
2102

UNCOV
2103
                if isLinkUpdate {
×
UNCOV
2104
                        // If this is a channel update, then we need to feed it
×
UNCOV
2105
                        // into the channel's in-order message stream.
×
UNCOV
2106
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
×
UNCOV
2107
                }
×
UNCOV
2108

×
2109
                idleTimer.Reset(idleTimeout)
2110
        }
UNCOV
2111

×
UNCOV
2112
        p.Disconnect(errors.New("read handler closed"))
×
UNCOV
2113

×
UNCOV
2114
        p.log.Trace("readHandler for peer done")
×
2115
}
2116

2117
// handleCustomMessage handles the given custom message if a handler is
UNCOV
2118
// registered.
×
2119
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
2120
        if p.cfg.HandleCustomMessage == nil {
2121
                return fmt.Errorf("no custom message handler for "+
2122
                        "message type %v", uint16(msg.MsgType()))
2123
        }
8✔
2124

8✔
2125
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
8✔
2126
}
8✔
2127

8✔
2128
// isLoadedFromDisk returns true if the provided channel ID is loaded from
8✔
2129
// disk.
8✔
2130
//
8✔
2131
// NOTE: only returns true for pending channels.
8✔
2132
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
2133
        // If this is a newly added channel, no need to reestablish.
2134
        _, added := p.addedChannels.Load(chanID)
2135
        if added {
6✔
2136
                return false
6✔
2137
        }
6✔
2138

9✔
2139
        // Return false if the channel is unknown.
3✔
2140
        channel, ok := p.activeChannels.Load(chanID)
3✔
2141
        if !ok {
2142
                return false
3✔
2143
        }
2144

2145
        // During startup, we will use a nil value to mark a pending channel
2146
        // that's loaded from disk.
UNCOV
2147
        return channel == nil
×
UNCOV
2148
}
×
UNCOV
2149

×
UNCOV
2150
// isActiveChannel returns true if the provided channel id is active, otherwise
×
2151
// returns false.
2152
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
2153
        // The channel would be nil if,
2154
        // - the channel doesn't exist, or,
2155
        // - the channel exists, but is pending. In this case, we don't
UNCOV
2156
        //   consider this channel active.
×
UNCOV
2157
        channel, _ := p.activeChannels.Load(chanID)
×
UNCOV
2158

×
UNCOV
2159
        return channel != nil
×
UNCOV
2160
}
×
UNCOV
2161

×
UNCOV
2162
// isPendingChannel returns true if the provided channel ID is pending, and
×
UNCOV
2163
// returns false if the channel is active or unknown.
×
UNCOV
2164
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
×
UNCOV
2165
        // Return false if the channel is unknown.
×
UNCOV
2166
        channel, ok := p.activeChannels.Load(chanID)
×
2167
        if !ok {
UNCOV
2168
                return false
×
UNCOV
2169
        }
×
UNCOV
2170

×
UNCOV
2171
        return channel == nil
×
2172
}
2173

2174
// hasChannel returns true if the peer has a pending/active channel specified
2175
// by the channel ID.
UNCOV
2176
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
×
UNCOV
2177
        _, ok := p.activeChannels.Load(chanID)
×
UNCOV
2178
        return ok
×
UNCOV
2179
}
×
2180

UNCOV
2181
// storeError stores an error in our peer's buffer of recent errors with the
×
UNCOV
2182
// current timestamp. Errors are only stored if we have at least one active
×
UNCOV
2183
// channel with the peer to mitigate a dos vector where a peer costlessly
×
2184
// connects to us and spams us with errors.
2185
func (p *Brontide) storeError(err error) {
2186
        var haveChannels bool
2187

2188
        p.activeChannels.Range(func(_ lnwire.ChannelID,
2189
                channel *lnwallet.LightningChannel) bool {
2190

2191
                // Pending channels will be nil in the activeChannels map.
2192
                if channel == nil {
UNCOV
2193
                        // Return true to continue the iteration.
×
UNCOV
2194
                        return true
×
UNCOV
2195
                }
×
UNCOV
2196

×
UNCOV
2197
                haveChannels = true
×
2198

UNCOV
2199
                // Return false to break the iteration.
×
2200
                return false
2201
        })
UNCOV
2202

×
UNCOV
2203
        // If we do not have any active channels with the peer, we do not store
×
UNCOV
2204
        // errors as a dos mitigation.
×
UNCOV
2205
        if !haveChannels {
×
2206
                p.log.Trace("no channels with peer, not storing err")
UNCOV
2207
                return
×
2208
        }
2209

2210
        p.cfg.ErrorBuffer.Add(
UNCOV
2211
                &TimestampedError{Timestamp: time.Now(), Error: err},
×
UNCOV
2212
        )
×
UNCOV
2213
}
×
2214

2215
// handleWarningOrError processes a warning or error msg and returns true if
UNCOV
2216
// msg should be forwarded to the associated channel link. False is returned if
×
UNCOV
2217
// any necessary forwarding of msg was already handled by this method. If msg is
×
2218
// an error from a peer with an active channel, we'll store it in memory.
UNCOV
2219
//
×
UNCOV
2220
// NOTE: This method should only be called from within the readHandler.
×
2221
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
2222
        msg lnwire.Message) bool {
2223

2224
        if errMsg, ok := msg.(*lnwire.Error); ok {
2225
                p.storeError(errMsg)
2226
        }
UNCOV
2227

×
UNCOV
2228
        switch {
×
UNCOV
2229
        // Connection wide messages should be forwarded to all channel links
×
UNCOV
2230
        // with this peer.
×
2231
        case chanID == lnwire.ConnectionWideID:
×
2232
                for _, chanStream := range p.activeMsgStreams {
2233
                        chanStream.AddMsg(msg)
×
2234
                }
×
UNCOV
2235

×
2236
                return false
×
UNCOV
2237

×
UNCOV
2238
        // If the channel ID for the message corresponds to a pending channel,
×
2239
        // then the funding manager will handle it.
UNCOV
2240
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
×
UNCOV
2241
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
×
UNCOV
2242
                return false
×
UNCOV
2243

×
2244
        // If not we hand the message to the channel link for this channel.
UNCOV
2245
        case p.isActiveChannel(chanID):
×
UNCOV
2246
                return true
×
UNCOV
2247

×
2248
        default:
UNCOV
2249
                return false
×
UNCOV
2250
        }
×
2251
}
UNCOV
2252

×
UNCOV
2253
// messageSummary returns a human-readable string that summarizes a
×
UNCOV
2254
// incoming/outgoing message. Not all messages will have a summary, only those
×
2255
// which have additional data that can be informative at a glance.
UNCOV
2256
func messageSummary(msg lnwire.Message) string {
×
UNCOV
2257
        switch msg := msg.(type) {
×
UNCOV
2258
        case *lnwire.Init:
×
2259
                // No summary.
UNCOV
2260
                return ""
×
UNCOV
2261

×
UNCOV
2262
        case *lnwire.OpenChannel:
×
2263
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
UNCOV
2264
                        "push_amt=%v, reserve=%v, flags=%v",
×
UNCOV
2265
                        msg.PendingChannelID[:], msg.ChainHash,
×
UNCOV
2266
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
×
UNCOV
2267
                        msg.ChannelReserve, msg.ChannelFlags)
×
UNCOV
2268

×
UNCOV
2269
        case *lnwire.AcceptChannel:
×
UNCOV
2270
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
×
UNCOV
2271
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
×
2272
                        msg.MinAcceptDepth)
2273

UNCOV
2274
        case *lnwire.FundingCreated:
×
UNCOV
2275
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
×
UNCOV
2276
                        msg.PendingChannelID[:], msg.FundingPoint)
×
UNCOV
2277

×
2278
        case *lnwire.FundingSigned:
UNCOV
2279
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
×
UNCOV
2280

×
UNCOV
2281
        case *lnwire.ChannelReady:
×
2282
                return fmt.Sprintf("chan_id=%v, next_point=%x",
UNCOV
2283
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
×
UNCOV
2284

×
UNCOV
2285
        case *lnwire.Shutdown:
×
UNCOV
2286
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
×
2287
                        msg.Address[:])
UNCOV
2288

×
UNCOV
2289
        case *lnwire.ClosingSigned:
×
UNCOV
2290
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
×
2291
                        msg.FeeSatoshis)
UNCOV
2292

×
UNCOV
2293
        case *lnwire.UpdateAddHTLC:
×
UNCOV
2294
                var blindingPoint []byte
×
UNCOV
2295
                msg.BlindingPoint.WhenSome(
×
2296
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
UNCOV
2297
                                *btcec.PublicKey]) {
×
UNCOV
2298

×
UNCOV
2299
                                blindingPoint = b.Val.SerializeCompressed()
×
2300
                        },
UNCOV
2301
                )
×
UNCOV
2302

×
2303
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
UNCOV
2304
                        "hash=%x, blinding_point=%x, custom_records=%v",
×
UNCOV
2305
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
×
2306
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
UNCOV
2307

×
UNCOV
2308
        case *lnwire.UpdateFailHTLC:
×
UNCOV
2309
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
×
2310
                        msg.ID, msg.Reason)
UNCOV
2311

×
UNCOV
2312
        case *lnwire.UpdateFulfillHTLC:
×
UNCOV
2313
                return fmt.Sprintf("chan_id=%v, id=%v, pre_image=%x, "+
×
2314
                        "custom_records=%v", msg.ChanID, msg.ID,
UNCOV
2315
                        msg.PaymentPreimage[:], msg.CustomRecords)
×
UNCOV
2316

×
UNCOV
2317
        case *lnwire.CommitSig:
×
UNCOV
2318
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
×
UNCOV
2319
                        len(msg.HtlcSigs))
×
2320

UNCOV
2321
        case *lnwire.RevokeAndAck:
×
UNCOV
2322
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
×
UNCOV
2323
                        msg.ChanID, msg.Revocation[:],
×
2324
                        msg.NextRevocationKey.SerializeCompressed())
UNCOV
2325

×
UNCOV
2326
        case *lnwire.UpdateFailMalformedHTLC:
×
2327
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
UNCOV
2328
                        msg.ChanID, msg.ID, msg.FailureCode)
×
UNCOV
2329

×
2330
        case *lnwire.Warning:
2331
                return fmt.Sprintf("%v", msg.Warning())
×
UNCOV
2332

×
UNCOV
2333
        case *lnwire.Error:
×
2334
                return fmt.Sprintf("%v", msg.Error())
UNCOV
2335

×
UNCOV
2336
        case *lnwire.AnnounceSignatures1:
×
UNCOV
2337
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
×
UNCOV
2338
                        msg.ShortChannelID.ToUint64())
×
2339

UNCOV
2340
        case *lnwire.ChannelAnnouncement1:
×
UNCOV
2341
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
×
UNCOV
2342
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
×
2343

UNCOV
2344
        case *lnwire.ChannelUpdate1:
×
UNCOV
2345
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
×
UNCOV
2346
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
×
UNCOV
2347
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
×
UNCOV
2348
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
×
2349

UNCOV
2350
        case *lnwire.NodeAnnouncement:
×
UNCOV
2351
                return fmt.Sprintf("node=%x, update_time=%v",
×
UNCOV
2352
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
×
2353

UNCOV
2354
        case *lnwire.Ping:
×
UNCOV
2355
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
UNCOV
2356

×
UNCOV
2357
        case *lnwire.Pong:
×
2358
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
UNCOV
2359

×
2360
        case *lnwire.UpdateFee:
×
2361
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2362
                        msg.ChanID, int64(msg.FeePerKw))
×
UNCOV
2363

×
2364
        case *lnwire.ChannelReestablish:
UNCOV
2365
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
×
UNCOV
2366
                        "remote_tail_height=%v", msg.ChanID,
×
UNCOV
2367
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
×
2368

UNCOV
2369
        case *lnwire.ReplyShortChanIDsEnd:
×
UNCOV
2370
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
×
2371
                        msg.Complete)
2372

UNCOV
2373
        case *lnwire.ReplyChannelRange:
×
2374
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
2375
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
2376
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
2377
                        msg.EncodingType)
2378

2379
        case *lnwire.QueryShortChanIDs:
2380
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
2381
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
17✔
2382

17✔
2383
        case *lnwire.QueryChannelRange:
30✔
2384
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
13✔
2385
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
13✔
2386
                        msg.LastBlockHeight())
2387

17✔
UNCOV
2388
        case *lnwire.GossipTimestampRange:
×
UNCOV
2389
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
×
UNCOV
2390
                        "stamp_range=%v", msg.ChainHash,
×
UNCOV
2391
                        time.Unix(int64(msg.FirstTimestamp), 0),
×
UNCOV
2392
                        msg.TimestampRange)
×
2393

2394
        case *lnwire.Stfu:
×
2395
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
×
2396
                        msg.Initiator)
×
UNCOV
2397

×
2398
        case *lnwire.Custom:
UNCOV
2399
                return fmt.Sprintf("type=%d", msg.Type)
×
UNCOV
2400
        }
×
UNCOV
2401

×
2402
        return fmt.Sprintf("unknown msg type=%T", msg)
×
UNCOV
2403
}
×
UNCOV
2404

×
2405
// logWireMessage logs the receipt or sending of particular wire message. This
UNCOV
2406
// function is used rather than just logging the message in order to produce
×
UNCOV
2407
// less spammy log messages in trace mode by setting the 'Curve" parameter to
×
2408
// nil. Doing this avoids printing out each of the field elements in the curve
2409
// parameters for secp256k1.
2410
func (p *Brontide) logWireMessage(msg lnwire.Message, read bool) {
17✔
2411
        summaryPrefix := "Received"
30✔
2412
        if !read {
13✔
2413
                summaryPrefix = "Sending"
13✔
2414
        }
2415

17✔
2416
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
2417
                // Debug summary of message.
2418
                summary := messageSummary(msg)
2419
                if len(summary) > 0 {
2420
                        summary = "(" + summary + ")"
2421
                }
2422

2423
                preposition := "to"
2424
                if read {
2425
                        preposition = "from"
2426
                }
2427

2428
                var msgType string
2429
                if msg.MsgType() < lnwire.CustomTypeStart {
13✔
2430
                        msgType = msg.MsgType().String()
13✔
2431
                } else {
26✔
2432
                        msgType = "custom"
13✔
2433
                }
13✔
2434

2435
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
13✔
2436
                        msgType, summary, preposition, p)
13✔
2437
        }))
26✔
2438

13✔
2439
        prefix := "readMessage from peer"
13✔
2440
        if !read {
13✔
2441
                prefix = "writeMessage to peer"
13✔
2442
        }
13✔
2443

13✔
2444
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
13✔
UNCOV
2445
}
×
UNCOV
2446

×
2447
// writeMessage writes and flushes the target lnwire.Message to the remote peer.
2448
// If the passed message is nil, this method will only try to flush an existing
2449
// message buffered on the connection. It is safe to call this method again
2450
// with a nil message iff a timeout error is returned. This will continue to
2451
// flush the pending message to the wire.
13✔
2452
//
13✔
2453
// NOTE:
13✔
2454
// Besides its usage in Start, this function should not be used elsewhere
13✔
UNCOV
2455
// except in writeHandler. If multiple goroutines call writeMessage at the same
×
UNCOV
2456
// time, panics can occur because WriteMessage and Flush don't use any locking
×
2457
// internally.
2458
func (p *Brontide) writeMessage(msg lnwire.Message) error {
13✔
2459
        // Only log the message on the first attempt.
2460
        if msg != nil {
2461
                p.logWireMessage(msg, false)
2462
        }
2463

2464
        noiseConn := p.cfg.Conn
13✔
UNCOV
2465

×
UNCOV
2466
        flushMsg := func() error {
×
2467
                // Ensure the write deadline is set before we attempt to send
2468
                // the message.
2469
                writeDeadline := time.Now().Add(
2470
                        p.scaleTimeout(writeMessageTimeout),
26✔
2471
                )
13✔
2472
                err := noiseConn.SetWriteDeadline(writeDeadline)
13✔
2473
                if err != nil {
13✔
2474
                        return err
13✔
2475
                }
×
UNCOV
2476

×
2477
                // Flush the pending message to the wire. If an error is
2478
                // encountered, e.g. write timeout, the number of bytes written
2479
                // so far will be returned.
2480
                n, err := noiseConn.Flush()
2481

2482
                // Record the number of bytes written on the wire, if any.
13✔
2483
                if n > 0 {
2484
                        atomic.AddUint64(&p.bytesSent, uint64(n))
13✔
UNCOV
2485
                }
×
UNCOV
2486

×
2487
                return err
2488
        }
13✔
2489

2490
        // If the current message has already been serialized, encrypted, and
2491
        // buffered on the underlying connection we will skip straight to
2492
        // flushing it to the wire.
2493
        if msg == nil {
2494
                return flushMsg()
2495
        }
2496

2497
        // Otherwise, this is a new message. We'll acquire a write buffer to
3✔
2498
        // serialize the message and buffer the ciphertext on the connection.
3✔
2499
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
3✔
2500
                // Using a buffer allocated by the write pool, encode the
3✔
UNCOV
2501
                // message directly into the buffer.
×
UNCOV
2502
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
×
UNCOV
2503
                if writeErr != nil {
×
2504
                        return writeErr
×
2505
                }
2506

3✔
2507
                // Finally, write the message itself in a single swoop. This
3✔
2508
                // will buffer the ciphertext on the underlying connection. We
3✔
2509
                // will defer flushing the message until the write pool has been
10✔
2510
                // released.
7✔
2511
                return noiseConn.WriteMessage(buf.Bytes())
4✔
2512
        })
4✔
2513
        if err != nil {
4✔
2514
                return err
4✔
2515
        }
4✔
2516

4✔
2517
        return flushMsg()
2518
}
2519

2520
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2521
// queue, and writing them out to the wire. This goroutine coordinates with the
4✔
2522
// queueHandler in order to ensure the incoming message queue is quickly
4✔
UNCOV
2523
// drained.
×
UNCOV
2524
//
×
UNCOV
2525
// NOTE: This method MUST be run as a goroutine.
×
UNCOV
2526
func (p *Brontide) writeHandler() {
×
UNCOV
2527
        // We'll stop the timer after a new messages is sent, and also reset it
×
UNCOV
2528
        // after we process the next message.
×
UNCOV
2529
        idleTimer := time.AfterFunc(idleTimeout, func() {
×
UNCOV
2530
                err := fmt.Errorf("peer %s no write for %s -- disconnecting",
×
UNCOV
2531
                        p, idleTimeout)
×
UNCOV
2532
                p.Disconnect(err)
×
UNCOV
2533
        })
×
UNCOV
2534

×
UNCOV
2535
        var exitErr error
×
UNCOV
2536

×
UNCOV
2537
out:
×
2538
        for {
2539
                select {
2540
                case outMsg := <-p.sendQueue:
2541
                        // Record the time at which we first attempt to send the
2542
                        // message.
4✔
UNCOV
2543
                        startTime := time.Now()
×
UNCOV
2544

×
UNCOV
2545
                retry:
×
2546
                        // Write out the message to the socket. If a timeout
2547
                        // error is encountered, we will catch this and retry
2548
                        // after backing off in case the remote peer is just
4✔
2549
                        // slow to process messages from the wire.
4✔
2550
                        err := p.writeMessage(outMsg.msg)
4✔
2551
                        if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
4✔
2552
                                p.log.Debugf("Write timeout detected for "+
5✔
2553
                                        "peer, first write for message "+
1✔
2554
                                        "attempted %v ago",
1✔
2555
                                        time.Since(startTime))
2556

4✔
2557
                                // If we received a timeout error, this implies
×
2558
                                // that the message was buffered on the
×
2559
                                // connection successfully and that a flush was
×
2560
                                // attempted. We'll set the message to nil so
2561
                                // that on a subsequent pass we only try to
2562
                                // flush the buffered message, and forgo
×
2563
                                // reserializing or reencrypting it.
×
2564
                                outMsg.msg = nil
×
2565

2566
                                goto retry
2567
                        }
2568

2569
                        // The write succeeded, reset the idle timer to prevent
UNCOV
2570
                        // us from disconnecting the peer.
×
UNCOV
2571
                        if !idleTimer.Stop() {
×
2572
                                select {
×
2573
                                case <-idleTimer.C:
×
2574
                                default:
×
2575
                                }
2576
                        }
2577
                        idleTimer.Reset(idleTimeout)
2578

2579
                        // If the peer requested a synchronous write, respond
2580
                        // with the error.
2581
                        if outMsg.errChan != nil {
3✔
2582
                                outMsg.errChan <- err
3✔
2583
                        }
3✔
2584

3✔
2585
                        if err != nil {
3✔
2586
                                exitErr = fmt.Errorf("unable to write "+
3✔
2587
                                        "message: %v", err)
3✔
2588
                                break out
3✔
2589
                        }
3✔
2590

3✔
2591
                case <-p.quit:
3✔
2592
                        exitErr = lnpeer.ErrPeerExiting
3✔
2593
                        break out
3✔
2594
                }
14✔
2595
        }
11✔
2596

11✔
2597
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
11✔
2598
        // disconnect.
19✔
2599
        p.wg.Done()
8✔
2600

8✔
2601
        p.Disconnect(exitErr)
2602

15✔
2603
        p.log.Trace("writeHandler for peer done")
4✔
2604
}
4✔
2605

4✔
2606
// queueHandler is responsible for accepting messages from outside subsystems
4✔
2607
// to be eventually sent out on the wire by the writeHandler.
4✔
2608
//
4✔
2609
// NOTE: This method MUST be run as a goroutine.
4✔
2610
func (p *Brontide) queueHandler() {
4✔
2611
        defer p.wg.Done()
4✔
2612

7✔
2613
        // priorityMsgs holds an in order list of messages deemed high-priority
3✔
2614
        // to be added to the sendQueue. This predominately includes messages
4✔
2615
        // from the funding manager and htlcswitch.
1✔
2616
        priorityMsgs := list.New()
1✔
UNCOV
2617

×
UNCOV
2618
        // lazyMsgs holds an in order list of messages deemed low-priority to be
×
UNCOV
2619
        // added to the sendQueue only after all high-priority messages have
×
UNCOV
2620
        // been queued. This predominately includes messages from the gossiper.
×
UNCOV
2621
        lazyMsgs := list.New()
×
UNCOV
2622

×
UNCOV
2623
        for {
×
UNCOV
2624
                // Examine the front of the priority queue, if it is empty check
×
2625
                // the low priority queue.
2626
                elem := priorityMsgs.Front()
7✔
2627
                if elem == nil {
7✔
2628
                        elem = lazyMsgs.Front()
7✔
2629
                }
7✔
2630

7✔
2631
                if elem != nil {
4✔
2632
                        front := elem.Value.(outgoingMsg)
7✔
2633

3✔
2634
                        // There's an element on the queue, try adding
4✔
2635
                        // it to the sendQueue. We also watch for
1✔
2636
                        // messages on the outgoingQueue, in case the
1✔
UNCOV
2637
                        // writeHandler cannot accept messages on the
×
UNCOV
2638
                        // sendQueue.
×
2639
                        select {
2640
                        case p.sendQueue <- front:
2641
                                if front.priority {
2642
                                        priorityMsgs.Remove(elem)
2643
                                } else {
2644
                                        lazyMsgs.Remove(elem)
UNCOV
2645
                                }
×
UNCOV
2646
                        case msg := <-p.outgoingQueue:
×
UNCOV
2647
                                if msg.priority {
×
2648
                                        priorityMsgs.PushBack(msg)
2649
                                } else {
2650
                                        lazyMsgs.PushBack(msg)
2651
                                }
2652
                        case <-p.quit:
24✔
2653
                                return
24✔
2654
                        }
24✔
2655
                } else {
2656
                        // If there weren't any messages to send to the
2657
                        // writeHandler, then we'll accept a new message
2658
                        // into the queue from outside sub-systems.
2659
                        select {
1✔
2660
                        case msg := <-p.outgoingQueue:
1✔
2661
                                if msg.priority {
1✔
2662
                                        priorityMsgs.PushBack(msg)
2663
                                } else {
2664
                                        lazyMsgs.PushBack(msg)
2665
                                }
2666
                        case <-p.quit:
2667
                                return
25✔
2668
                        }
25✔
2669
                }
25✔
2670
        }
25✔
UNCOV
2671
}
×
UNCOV
2672

×
UNCOV
2673
// PingTime returns the estimated ping time to the peer in microseconds.
×
UNCOV
2674
func (p *Brontide) PingTime() int64 {
×
UNCOV
2675
        return p.pingManager.GetPingTimeMicroSeconds()
×
UNCOV
2676
}
×
2677

2678
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2679
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2680
// or failed to write, and nil otherwise.
2681
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
UNCOV
2682
        p.queue(true, msg, errChan)
×
UNCOV
2683
}
×
UNCOV
2684

×
UNCOV
2685
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
×
UNCOV
2686
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
×
UNCOV
2687
// queue or failed to write, and nil otherwise.
×
UNCOV
2688
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
×
UNCOV
2689
        p.queue(false, msg, errChan)
×
UNCOV
2690
}
×
UNCOV
2691

×
UNCOV
2692
// queue sends a given message to the queueHandler using the passed priority. If
×
UNCOV
2693
// the errChan is non-nil, an error is sent back if the msg failed to queue or
×
UNCOV
2694
// failed to write, and nil otherwise.
×
2695
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2696
        errChan chan error) {
2697

UNCOV
2698
        select {
×
UNCOV
2699
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
×
UNCOV
2700
        case <-p.quit:
×
2701
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
UNCOV
2702
                        spew.Sdump(msg))
×
UNCOV
2703
                if errChan != nil {
×
2704
                        errChan <- lnpeer.ErrPeerExiting
×
2705
                }
×
2706
        }
2707
}
UNCOV
2708

×
2709
// ChannelSnapshots returns a slice of channel snapshots detailing all
2710
// currently active channels maintained with the remote peer.
2711
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
2712
        snapshots := make(
2713
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
6✔
2714
        )
6✔
2715

6✔
2716
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
6✔
2717
                activeChan *lnwallet.LightningChannel) error {
6✔
UNCOV
2718

×
UNCOV
2719
                // If the activeChan is nil, then we skip it as the channel is
×
2720
                // pending.
2721
                if activeChan == nil {
6✔
2722
                        return nil
6✔
2723
                }
6✔
2724

6✔
UNCOV
2725
                // We'll only return a snapshot for channels that are
×
UNCOV
2726
                // *immediately* available for routing payments over.
×
2727
                if activeChan.RemoteNextRevocation() == nil {
6✔
2728
                        return nil
6✔
2729
                }
6✔
2730

6✔
2731
                snapshot := activeChan.StateSnapshot()
2732
                snapshots = append(snapshots, snapshot)
2733

2734
                return nil
2735
        })
2736

2737
        return snapshots
2738
}
17✔
2739

17✔
2740
// genDeliveryScript returns a new script to be used to send our funds to in
17✔
2741
// the case of a cooperative channel close negotiation.
17✔
2742
func (p *Brontide) genDeliveryScript() ([]byte, error) {
17✔
2743
        // We'll send a normal p2wkh address unless we've negotiated the
17✔
2744
        // shutdown-any-segwit feature.
17✔
2745
        addrType := lnwallet.WitnessPubKey
17✔
2746
        if p.taprootShutdownAllowed() {
17✔
2747
                addrType = lnwallet.TaprootPubkey
55✔
2748
        }
38✔
2749

2750
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
2751
                addrType, false, lnwallet.DefaultAccountName,
2752
        )
2753
        if err != nil {
2754
                return nil, err
1✔
2755
        }
1✔
2756
        p.log.Infof("Delivery addr for channel close: %v",
2757
                deliveryAddr)
2758

2759
        return txscript.PayToAddrScript(deliveryAddr)
UNCOV
2760
}
×
UNCOV
2761

×
2762
// channelManager is goroutine dedicated to handling all requests/signals
2763
// pertaining to the opening, cooperative closing, and force closing of all
2764
// channels maintained with the remote peer.
2765
//
1✔
2766
// NOTE: This method MUST be run as a goroutine.
1✔
2767
func (p *Brontide) channelManager() {
2768
        defer p.wg.Done()
2769

2770
        // reenableTimeout will fire once after the configured channel status
2771
        // interval has elapsed. This will trigger us to sign new channel
2772
        // updates and broadcast them with the "disabled" flag unset.
7✔
2773
        reenableTimeout := time.After(p.cfg.ChanActiveTimeout)
7✔
2774

2775
out:
2776
        for {
2777
                select {
UNCOV
2778
                // A new pending channel has arrived which means we are about
×
UNCOV
2779
                // to complete a funding workflow and is waiting for the final
×
2780
                // `ChannelReady` messages to be exchanged. We will add this
2781
                // channel to the `activeChannels` with a nil value to indicate
2782
                // this is a pending channel.
2783
                case req := <-p.newPendingChannel:
2784
                        p.handleNewPendingChannel(req)
13✔
2785

13✔
2786
                // A new channel has arrived which means we've just completed a
2787
                // funding workflow. We'll initialize the necessary local
2788
                // state, and notify the htlc switch of a new link.
2789
                case req := <-p.newActiveChannel:
2790
                        p.handleNewActiveChannel(req)
2791

2792
                // The funding flow for a pending channel is failed, we will
2793
                // remove it from Brontide.
UNCOV
2794
                case req := <-p.removePendingChannel:
×
UNCOV
2795
                        p.handleRemovePendingChannel(req)
×
UNCOV
2796

×
UNCOV
2797
                // We've just received a local request to close an active
×
UNCOV
2798
                // channel. It will either kick of a cooperative channel
×
UNCOV
2799
                // closure negotiation, or be a notification of a breached
×
UNCOV
2800
                // contract that should be abandoned.
×
UNCOV
2801
                case req := <-p.localCloseChanReqs:
×
UNCOV
2802
                        p.handleLocalCloseReq(req)
×
UNCOV
2803

×
UNCOV
2804
                // We've received a link failure from a link that was added to
×
UNCOV
2805
                // the switch. This will initiate the teardown of the link, and
×
UNCOV
2806
                // initiate any on-chain closures if necessary.
×
UNCOV
2807
                case failure := <-p.linkFailures:
×
UNCOV
2808
                        p.handleLinkFailure(failure)
×
UNCOV
2809

×
UNCOV
2810
                // We've received a new cooperative channel closure related
×
UNCOV
2811
                // message from the remote peer, we'll use this message to
×
UNCOV
2812
                // advance the chan closer state machine.
×
UNCOV
2813
                case closeMsg := <-p.chanCloseMsgs:
×
2814
                        p.handleCloseMsg(closeMsg)
UNCOV
2815

×
UNCOV
2816
                // The channel reannounce delay has elapsed, broadcast the
×
UNCOV
2817
                // reenabled channel updates to the network. This should only
×
UNCOV
2818
                // fire once, so we set the reenableTimeout channel to nil to
×
UNCOV
2819
                // mark it for garbage collection. If the peer is torn down
×
UNCOV
2820
                // before firing, reenabling will not be attempted.
×
UNCOV
2821
                // TODO(conner): consolidate reenables timers inside chan status
×
UNCOV
2822
                // manager
×
UNCOV
2823
                case <-reenableTimeout:
×
UNCOV
2824
                        p.reenableActiveChannels()
×
UNCOV
2825

×
2826
                        // Since this channel will never fire again during the
UNCOV
2827
                        // lifecycle of the peer, we nil the channel to mark it
×
UNCOV
2828
                        // eligible for garbage collection, and make this
×
UNCOV
2829
                        // explicitly ineligible to receive in future calls to
×
2830
                        // select. This also shaves a few CPU cycles since the
2831
                        // select will ignore this case entirely.
UNCOV
2832
                        reenableTimeout = nil
×
2833

2834
                        // Once the reenabling is attempted, we also cancel the
2835
                        // channel event subscription to free up the overflow
2836
                        // queue used in channel notifier.
2837
                        //
2838
                        // NOTE: channelEventClient will be nil if the
2839
                        // reenableTimeout is greater than 1 minute.
2840
                        if p.channelEventClient != nil {
UNCOV
2841
                                p.channelEventClient.Cancel()
×
UNCOV
2842
                        }
×
UNCOV
2843

×
UNCOV
2844
                case <-p.quit:
×
UNCOV
2845
                        // As, we've been signalled to exit, we'll reset all
×
UNCOV
2846
                        // our active channel back to their default state.
×
UNCOV
2847
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
×
UNCOV
2848
                                lc *lnwallet.LightningChannel) error {
×
UNCOV
2849

×
UNCOV
2850
                                // Exit if the channel is nil as it's a pending
×
UNCOV
2851
                                // channel.
×
UNCOV
2852
                                if lc == nil {
×
UNCOV
2853
                                        return nil
×
UNCOV
2854
                                }
×
UNCOV
2855

×
2856
                                lc.ResetState()
UNCOV
2857

×
UNCOV
2858
                                return nil
×
2859
                        })
2860

2861
                        break out
UNCOV
2862
                }
×
UNCOV
2863
        }
×
UNCOV
2864
}
×
UNCOV
2865

×
UNCOV
2866
// reenableActiveChannels searches the index of channels maintained with this
×
2867
// peer, and reenables each public, non-pending channel. This is done at the
2868
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
2869
// No message will be sent if the channel is already enabled.
2870
func (p *Brontide) reenableActiveChannels() {
2871
        // First, filter all known channels with this peer for ones that are
2872
        // both public and not pending.
2873
        activePublicChans := p.filterChannelsToEnable()
2874

2875
        // Create a map to hold channels that needs to be retried.
2876
        retryChans := make(map[wire.OutPoint]struct{}, len(activePublicChans))
UNCOV
2877

×
UNCOV
2878
        // For each of the public, non-pending channels, set the channel
×
UNCOV
2879
        // disabled bit to false and send out a new ChannelUpdate. If this
×
UNCOV
2880
        // channel is already active, the update won't be sent.
×
UNCOV
2881
        for _, chanPoint := range activePublicChans {
×
UNCOV
2882
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
UNCOV
2883

×
UNCOV
2884
                switch {
×
UNCOV
2885
                // No error occurred, continue to request the next channel.
×
2886
                case err == nil:
2887
                        continue
UNCOV
2888

×
UNCOV
2889
                // Cannot auto enable a manually disabled channel so we do
×
UNCOV
2890
                // nothing but proceed to the next channel.
×
UNCOV
2891
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
×
UNCOV
2892
                        p.log.Debugf("Channel(%v) was manually disabled, "+
×
2893
                                "ignoring automatic enable request", chanPoint)
2894

2895
                        continue
2896

UNCOV
2897
                // If the channel is reported as inactive, we will give it
×
UNCOV
2898
                // another chance. When handling the request, ChanStatusManager
×
UNCOV
2899
                // will check whether the link is active or not. One of the
×
2900
                // conditions is whether the link has been marked as
2901
                // reestablished, which happens inside a goroutine(htlcManager)
2902
                // after the link is started. And we may get a false negative
2903
                // saying the link is not active because that goroutine hasn't
2904
                // reached the line to mark the reestablishment. Thus we give
2905
                // it a second chance to send the request.
2906
                case errors.Is(err, netann.ErrEnableInactiveChan):
2907
                        // If we don't have a client created, it means we
13✔
2908
                        // shouldn't retry enabling the channel.
13✔
2909
                        if p.channelEventClient == nil {
13✔
2910
                                p.log.Errorf("Channel(%v) request enabling "+
23✔
2911
                                        "failed due to inactive link",
10✔
2912
                                        chanPoint)
10✔
2913

10✔
2914
                                continue
10✔
2915
                        }
10✔
2916

10✔
2917
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
2918
                                "ChanStatusManager reported inactive, retrying")
2919

2920
                        // Add the channel to the retry map.
3✔
2921
                        retryChans[chanPoint] = struct{}{}
3✔
2922
                }
3✔
2923
        }
3✔
2924

3✔
UNCOV
2925
        // Retry the channels if we have any.
×
UNCOV
2926
        if len(retryChans) != 0 {
×
2927
                p.retryRequestEnable(retryChans)
2928
        }
2929
}
2930

2931
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
2932
// for the target channel ID. If the channel isn't active an error is returned.
2933
// Otherwise, either an existing state machine will be returned, or a new one
2934
// will be created.
2935
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
2936
        *chancloser.ChanCloser, error) {
3✔
2937

6✔
2938
        chanCloser, found := p.activeChanCloses[chanID]
3✔
2939
        if found {
3✔
2940
                // An entry will only be found if the closer has already been
3✔
UNCOV
2941
                // created for a non-pending channel or for a channel that had
×
UNCOV
2942
                // previously started the shutdown process but the connection
×
UNCOV
2943
                // was restarted.
×
UNCOV
2944
                return chanCloser, nil
×
2945
        }
2946

2947
        // First, we'll ensure that we actually know of the target channel. If
2948
        // not, we'll ignore this message.
2949
        channel, ok := p.activeChannels.Load(chanID)
3✔
2950

3✔
2951
        // If the channel isn't in the map or the channel is nil, return
3✔
2952
        // ErrChannelNotFound as the channel is pending.
3✔
UNCOV
2953
        if !ok || channel == nil {
×
UNCOV
2954
                return nil, ErrChannelNotFound
×
UNCOV
2955
        }
×
2956

2957
        // We'll create a valid closing state machine in order to respond to
3✔
2958
        // the initiated cooperative channel closure. First, we set the
3✔
UNCOV
2959
        // delivery script that our funds will be paid out to. If an upfront
×
UNCOV
2960
        // shutdown script was set, we will use it. Otherwise, we get a fresh
×
2961
        // delivery script.
3✔
2962
        //
3✔
2963
        // TODO: Expose option to allow upfront shutdown script from watch-only
3✔
2964
        // accounts.
3✔
UNCOV
2965
        deliveryScript := channel.LocalUpfrontShutdownScript()
×
UNCOV
2966
        if len(deliveryScript) == 0 {
×
UNCOV
2967
                var err error
×
2968
                deliveryScript, err = p.genDeliveryScript()
2969
                if err != nil {
3✔
2970
                        p.log.Errorf("unable to gen delivery script: %v",
3✔
2971
                                err)
3✔
2972
                        return nil, fmt.Errorf("close addr unavailable")
2973
                }
2974
        }
2975

2976
        // In order to begin fee negotiations, we'll first compute our target
UNCOV
2977
        // ideal fee-per-kw.
×
UNCOV
2978
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
UNCOV
2979
                p.cfg.CoopCloseTargetConfs,
×
UNCOV
2980
        )
×
UNCOV
2981
        if err != nil {
×
2982
                p.log.Errorf("unable to query fee estimator: %v", err)
×
2983
                return nil, fmt.Errorf("unable to estimate fee")
×
2984
        }
×
UNCOV
2985

×
UNCOV
2986
        addr, err := p.addrWithInternalKey(deliveryScript).Unpack()
×
2987
        if err != nil {
2988
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
2989
        }
×
UNCOV
2990
        chanCloser, err = p.createChanCloser(
×
UNCOV
2991
                channel, addr, feePerKw, nil, lntypes.Remote,
×
UNCOV
2992
        )
×
2993
        if err != nil {
2994
                p.log.Errorf("unable to create chan closer: %v", err)
2995
                return nil, fmt.Errorf("unable to create chan closer")
2996
        }
2997

2998
        p.activeChanCloses[chanID] = chanCloser
UNCOV
2999

×
UNCOV
3000
        return chanCloser, nil
×
UNCOV
3001
}
×
3002

UNCOV
3003
// filterChannelsToEnable filters a list of channels to be enabled upon start.
×
UNCOV
3004
// The filtered channels are active channels that's neither private nor
×
UNCOV
3005
// pending.
×
UNCOV
3006
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
×
UNCOV
3007
        var activePublicChans []wire.OutPoint
×
3008

3009
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
UNCOV
3010
                lnChan *lnwallet.LightningChannel) bool {
×
3011

3012
                // If the lnChan is nil, continue as this is a pending channel.
3013
                if lnChan == nil {
3014
                        return true
3015
                }
3016

UNCOV
3017
                dbChan := lnChan.State()
×
UNCOV
3018
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
×
UNCOV
3019
                if !isPublic || dbChan.IsPending {
×
3020
                        return true
×
3021
                }
×
UNCOV
3022

×
UNCOV
3023
                // We'll also skip any channels added during this peer's
×
UNCOV
3024
                // lifecycle since they haven't waited out the timeout. Their
×
UNCOV
3025
                // first announcement will be enabled, and the chan status
×
UNCOV
3026
                // manager will begin monitoring them passively since they exist
×
UNCOV
3027
                // in the database.
×
UNCOV
3028
                if _, ok := p.addedChannels.Load(chanID); ok {
×
UNCOV
3029
                        return true
×
UNCOV
3030
                }
×
UNCOV
3031

×
3032
                activePublicChans = append(
3033
                        activePublicChans, dbChan.FundingOutpoint,
3034
                )
3035

3036
                return true
3037
        })
3038

UNCOV
3039
        return activePublicChans
×
UNCOV
3040
}
×
UNCOV
3041

×
UNCOV
3042
// retryRequestEnable takes a map of channel outpoints and a channel event
×
UNCOV
3043
// client. It listens to the channel events and removes a channel from the map
×
UNCOV
3044
// if it's matched to the event. Upon receiving an active channel event, it
×
UNCOV
3045
// will send the enabling request again.
×
3046
func (p *Brontide) retryRequestEnable(activeChans map[wire.OutPoint]struct{}) {
×
3047
        p.log.Debugf("Retry enabling %v channels", len(activeChans))
3048

×
3049
        // retryEnable is a helper closure that sends an enable request and
3050
        // removes the channel from the map if it's matched.
3051
        retryEnable := func(chanPoint wire.OutPoint) error {
×
3052
                // If this is an active channel event, check whether it's in
×
3053
                // our targeted channels map.
×
3054
                _, found := activeChans[chanPoint]
×
3055

×
3056
                // If this channel is irrelevant, return nil so the loop can
×
3057
                // jump to next iteration.
×
3058
                if !found {
3059
                        return nil
×
3060
                }
3061

UNCOV
3062
                // Otherwise we've just received an active signal for a channel
×
UNCOV
3063
                // that's previously failed to be enabled, we send the request
×
UNCOV
3064
                // again.
×
UNCOV
3065
                //
×
UNCOV
3066
                // We only give the channel one more shot, so we delete it from
×
UNCOV
3067
                // our map first to keep it from being attempted again.
×
3068
                delete(activeChans, chanPoint)
×
3069

×
3070
                // Send the request.
×
3071
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3072
                if err != nil {
×
3073
                        return fmt.Errorf("request enabling channel %v "+
×
3074
                                "failed: %w", chanPoint, err)
×
3075
                }
UNCOV
3076

×
3077
                return nil
3078
        }
3079

3080
        for {
3081
                // If activeChans is empty, we've done processing all the
×
3082
                // channels.
×
3083
                if len(activeChans) == 0 {
×
3084
                        p.log.Debug("Finished retry enabling channels")
3085
                        return
3086
                }
3087

3088
                select {
×
UNCOV
3089
                // A new event has been sent by the ChannelNotifier. We now
×
UNCOV
3090
                // check whether it's an active or inactive channel event.
×
3091
                case e := <-p.channelEventClient.Updates():
×
3092
                        // If this is an active channel event, try enable the
3093
                        // channel then jump to the next iteration.
3094
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
3095
                        if ok {
×
3096
                                chanPoint := *active.ChannelPoint
×
3097

3098
                                // If we received an error for this particular
×
3099
                                // channel, we log an error and won't quit as
×
3100
                                // we still want to retry other channels.
×
3101
                                if err := retryEnable(chanPoint); err != nil {
3102
                                        p.log.Errorf("Retry failed: %v", err)
3103
                                }
3104

3105
                                continue
3106
                        }
3107

3108
                        // Otherwise check for inactive link event, and jump to
3109
                        // next iteration if it's not.
12✔
3110
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
12✔
3111
                        if !ok {
12✔
3112
                                continue
12✔
3113
                        }
18✔
3114

6✔
3115
                        // Found an inactive link event, if this is our
6✔
3116
                        // targeted channel, remove it from our map.
3117
                        chanPoint := *inactive.ChannelPoint
3118
                        _, found := activeChans[chanPoint]
3119
                        if !found {
8✔
3120
                                continue
2✔
3121
                        }
2✔
3122

3123
                        delete(activeChans, chanPoint)
3124
                        p.log.Warnf("Re-enable channel %v failed, received "+
3125
                                "inactive link event", chanPoint)
3126

3127
                case <-p.quit:
6✔
3128
                        p.log.Debugf("Peer shutdown during retry enabling")
2✔
3129
                        return
2✔
3130
                }
3131
        }
3132
}
3133

2✔
3134
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3135
// a suitable script to close out to. This may be nil if neither script is
3136
// set. If both scripts are set, this function will error if they do not match.
3137
func chooseDeliveryScript(upfront,
3138
        requested lnwire.DeliveryAddress) (lnwire.DeliveryAddress, error) {
UNCOV
3139

×
UNCOV
3140
        // If no upfront shutdown script was provided, return the user
×
UNCOV
3141
        // requested address (which may be nil).
×
UNCOV
3142
        if len(upfront) == 0 {
×
UNCOV
3143
                return requested, nil
×
UNCOV
3144
        }
×
UNCOV
3145

×
UNCOV
3146
        // If an upfront shutdown script was provided, and the user did not
×
UNCOV
3147
        // request a custom shutdown script, return the upfront address.
×
UNCOV
3148
        if len(requested) == 0 {
×
UNCOV
3149
                return upfront, nil
×
UNCOV
3150
        }
×
UNCOV
3151

×
UNCOV
3152
        // If both an upfront shutdown script and a custom close script were
×
UNCOV
3153
        // provided, error if the user provided shutdown script does not match
×
UNCOV
3154
        // the upfront shutdown script (because closing out to a different
×
UNCOV
3155
        // script would violate upfront shutdown).
×
UNCOV
3156
        if !bytes.Equal(upfront, requested) {
×
UNCOV
3157
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
×
3158
        }
UNCOV
3159

×
UNCOV
3160
        // The user requested script matches the upfront shutdown script, so we
×
UNCOV
3161
        // can return it without error.
×
UNCOV
3162
        return upfront, nil
×
3163
}
3164

UNCOV
3165
// restartCoopClose checks whether we need to restart the cooperative close
×
UNCOV
3166
// process for a given channel.
×
UNCOV
3167
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
×
3168
        *lnwire.Shutdown, error) {
×
3169

3170
        // If this channel has status ChanStatusCoopBroadcasted and does not
3171
        // have a closing transaction, then the cooperative close process was
×
3172
        // started but never finished. We'll re-create the chanCloser state
×
3173
        // machine and resend Shutdown. BOLT#2 requires that we retransmit
3174
        // Shutdown exactly, but doing so would mean persisting the RPC
×
3175
        // provided close script. Instead use the LocalUpfrontShutdownScript
×
3176
        // or generate a script.
×
3177
        c := lnChan.State()
×
3178
        _, err := c.BroadcastedCooperative()
×
3179
        if err != nil && err != channeldb.ErrNoCloseTx {
×
3180
                // An error other than ErrNoCloseTx was encountered.
×
3181
                return nil, err
×
3182
        } else if err == nil {
×
3183
                // This channel has already completed the coop close
×
3184
                // negotiation.
×
3185
                return nil, nil
3186
        }
3187

3188
        var deliveryScript []byte
3189

×
3190
        shutdownInfo, err := c.ShutdownInfo()
×
3191
        switch {
×
UNCOV
3192
        // We have previously stored the delivery script that we need to use
×
UNCOV
3193
        // in the shutdown message. Re-use this script.
×
3194
        case err == nil:
×
3195
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
×
3196
                        deliveryScript = info.DeliveryScript.Val
3197
                })
3198

UNCOV
3199
        // An error other than ErrNoShutdownInfo was returned
×
3200
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3201
                return nil, err
×
UNCOV
3202

×
3203
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
3204
                deliveryScript = c.LocalShutdownScript
×
3205
                if len(deliveryScript) == 0 {
×
3206
                        var err error
×
3207
                        deliveryScript, err = p.genDeliveryScript()
×
3208
                        if err != nil {
×
3209
                                p.log.Errorf("unable to gen delivery script: "+
×
3210
                                        "%v", err)
×
3211

×
3212
                                return nil, fmt.Errorf("close addr unavailable")
×
3213
                        }
×
UNCOV
3214
                }
×
3215
        }
3216

3217
        // Compute an ideal fee.
3218
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3219
                p.cfg.CoopCloseTargetConfs,
×
3220
        )
×
3221
        if err != nil {
×
3222
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3223
                return nil, fmt.Errorf("unable to estimate fee")
×
3224
        }
×
UNCOV
3225

×
UNCOV
3226
        // Determine whether we or the peer are the initiator of the coop
×
UNCOV
3227
        // close attempt by looking at the channel's status.
×
3228
        closingParty := lntypes.Remote
×
3229
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
3230
                closingParty = lntypes.Local
×
3231
        }
3232

3233
        addr, err := p.addrWithInternalKey(deliveryScript).Unpack()
3234
        if err != nil {
3235
                return nil, fmt.Errorf("unable to parse addr: %w", err)
3236
        }
3237
        chanCloser, err := p.createChanCloser(
3238
                lnChan, addr, feePerKw, nil, closingParty,
9✔
3239
        )
9✔
3240
        if err != nil {
9✔
3241
                p.log.Errorf("unable to create chan closer: %v", err)
9✔
3242
                return nil, fmt.Errorf("unable to create chan closer")
×
3243
        }
×
UNCOV
3244

×
3245
        // This does not need a mutex even though it is in a different
3246
        // goroutine since this is done before the channelManager goroutine is
3247
        // created.
9✔
3248
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
15✔
3249
        p.activeChanCloses[chanID] = chanCloser
6✔
3250

6✔
3251
        // Create the Shutdown message.
3252
        shutdownMsg, err := chanCloser.ShutdownChan()
9✔
3253
        if err != nil {
9✔
3254
                p.log.Errorf("unable to create shutdown message: %v", err)
9✔
3255
                delete(p.activeChanCloses, chanID)
9✔
3256
                return nil, err
9✔
3257
        }
9✔
3258

9✔
3259
        return shutdownMsg, nil
18✔
3260
}
9✔
3261

9✔
3262
// createChanCloser constructs a ChanCloser from the passed parameters and is
9✔
3263
// used to de-duplicate code.
9✔
3264
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
UNCOV
3265
        deliveryScript chancloser.DeliveryAddrWithKey,
×
UNCOV
3266
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
×
UNCOV
3267
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
×
3268

3269
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
3270
        if err != nil {
3271
                p.log.Errorf("unable to obtain best block: %v", err)
3272
                return nil, fmt.Errorf("cannot obtain best block")
3273
        }
3274

3275
        // The req will only be set if we initiated the co-op closing flow.
3276
        var maxFee chainfee.SatPerKWeight
3277
        if req != nil {
3278
                maxFee = req.MaxFee
9✔
3279
        }
3280

3281
        chanCloser := chancloser.NewChanCloser(
3282
                chancloser.ChanCloseCfg{
3283
                        Channel:      channel,
7✔
3284
                        MusigSession: NewMusigChanCloser(channel),
7✔
3285
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
7✔
3286
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
7✔
3287
                        AuxCloser:    p.cfg.AuxChanCloser,
7✔
3288
                        DisableChannel: func(op wire.OutPoint) error {
7✔
3289
                                return p.cfg.ChanStatusMgr.RequestDisable(
7✔
3290
                                        op, false,
7✔
UNCOV
3291
                                )
×
UNCOV
3292
                        },
×
UNCOV
3293
                        MaxFee: maxFee,
×
3294
                        Disconnect: func() error {
×
3295
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
3296
                        },
×
3297
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3298
                        Quit:        p.quit,
7✔
3299
                },
3300
                deliveryScript,
3301
                fee,
3302
                uint32(startingHeight),
7✔
3303
                req,
7✔
3304
                closer,
7✔
3305
        )
7✔
3306

7✔
3307
        return chanCloser, nil
7✔
3308
}
7✔
3309

7✔
3310
// handleLocalCloseReq kicks-off the workflow to execute a cooperative or
7✔
3311
// forced unilateral closure of the channel initiated by a local subsystem.
7✔
3312
func (p *Brontide) handleLocalCloseReq(req *htlcswitch.ChanClose) {
7✔
3313
        chanID := lnwire.NewChanIDFromOutPoint(*req.ChanPoint)
7✔
3314

8✔
3315
        channel, ok := p.activeChannels.Load(chanID)
1✔
3316

1✔
3317
        // Though this function can't be called for pending channels, we still
1✔
3318
        // check whether channel is nil for safety.
1✔
3319
        if !ok || channel == nil {
3320
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
3321
                        "unknown", chanID)
3322
                p.log.Errorf(err.Error())
9✔
3323
                req.Err <- err
3✔
3324
                return
3✔
3325
        }
×
UNCOV
3326

×
UNCOV
3327
        switch req.CloseType {
×
UNCOV
3328
        // A type of CloseRegular indicates that the user has opted to close
×
3329
        // out this channel on-chain, so we execute the cooperative channel
3330
        // closure workflow.
6✔
3331
        case contractcourt.CloseRegular:
6✔
UNCOV
3332
                // First, we'll choose a delivery address that we'll use to send the
×
UNCOV
3333
                // funds to in the case of a successful negotiation.
×
UNCOV
3334

×
UNCOV
3335
                // An upfront shutdown and user provided script are both optional,
×
UNCOV
3336
                // but must be equal if both set  (because we cannot serve a request
×
UNCOV
3337
                // to close out to a script which violates upfront shutdown). Get the
×
UNCOV
3338
                // appropriate address to close out to (which may be nil if neither
×
3339
                // are set) and error if they are both set and do not match.
6✔
3340
                deliveryScript, err := chooseDeliveryScript(
6✔
3341
                        channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
6✔
3342
                )
6✔
UNCOV
3343
                if err != nil {
×
UNCOV
3344
                        p.log.Errorf("cannot close channel %v: %v", req.ChanPoint, err)
×
UNCOV
3345
                        req.Err <- err
×
UNCOV
3346
                        return
×
3347
                }
3348

6✔
3349
                // If neither an upfront address or a user set address was
6✔
3350
                // provided, generate a fresh script.
6✔
3351
                if len(deliveryScript) == 0 {
6✔
3352
                        deliveryScript, err = p.genDeliveryScript()
6✔
3353
                        if err != nil {
6✔
3354
                                p.log.Errorf(err.Error())
6✔
3355
                                req.Err <- err
×
3356
                                return
×
3357
                        }
×
UNCOV
3358
                }
×
UNCOV
3359
                addr, err := p.addrWithInternalKey(deliveryScript).Unpack()
×
UNCOV
3360
                if err != nil {
×
3361
                        err = fmt.Errorf("unable to parse addr for channel "+
×
3362
                                "%v: %w", req.ChanPoint, err)
×
3363
                        p.log.Errorf(err.Error())
×
3364
                        req.Err <- err
3365

6✔
3366
                        return
6✔
3367
                }
×
UNCOV
3368
                chanCloser, err := p.createChanCloser(
×
UNCOV
3369
                        channel, addr, req.TargetFeePerKw, req, lntypes.Local,
×
UNCOV
3370
                )
×
UNCOV
3371
                if err != nil {
×
3372
                        p.log.Errorf(err.Error())
×
3373
                        req.Err <- err
×
3374
                        return
×
3375
                }
×
UNCOV
3376

×
3377
                p.activeChanCloses[chanID] = chanCloser
3378

6✔
UNCOV
3379
                // Finally, we'll initiate the channel shutdown within the
×
UNCOV
3380
                // chanCloser, and send the shutdown message to the remote
×
UNCOV
3381
                // party to kick things off.
×
3382
                shutdownMsg, err := chanCloser.ShutdownChan()
3383
                if err != nil {
12✔
3384
                        p.log.Errorf(err.Error())
6✔
3385
                        req.Err <- err
6✔
3386
                        delete(p.activeChanCloses, chanID)
3387

3388
                        // As we were unable to shutdown the channel, we'll
3389
                        // return it back to its normal state.
×
3390
                        channel.ResetState()
×
3391
                        return
×
3392
                }
×
UNCOV
3393

×
3394
                link := p.fetchLinkFromKeyAndCid(chanID)
3395
                if link == nil {
3396
                        // If the link is nil then it means it was already
3397
                        // removed from the switch or it never existed in the
3398
                        // first place. The latter case is handled at the
3399
                        // beginning of this function, so in the case where it
3400
                        // has already been removed, we can skip adding the
3401
                        // commit hook to queue a Shutdown message.
3402
                        p.log.Warnf("link not found during attempted closure: "+
3403
                                "%v", chanID)
3404
                        return
3405
                }
3406

3407
                if !link.DisableAdds(htlcswitch.Outgoing) {
3408
                        p.log.Warnf("Outgoing link adds already "+
3409
                                "disabled: %v", link.ChanID())
3410
                }
3411

UNCOV
3412
                link.OnCommitOnce(htlcswitch.Outgoing, func() {
×
UNCOV
3413
                        p.queueMsg(shutdownMsg, nil)
×
UNCOV
3414
                })
×
UNCOV
3415

×
UNCOV
3416
        // A type of CloseBreach indicates that the counterparty has breached
×
UNCOV
3417
        // the channel therefore we need to clean up our local state.
×
3418
        case contractcourt.CloseBreach:
×
3419
                // TODO(roasbeef): no longer need with newer beach logic?
×
3420
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
×
3421
                        "channel", req.ChanPoint)
×
3422
                p.WipeChannel(req.ChanPoint)
×
UNCOV
3423
        }
×
UNCOV
3424
}
×
UNCOV
3425

×
UNCOV
3426
// linkFailureReport is sent to the channelManager whenever a link reports a
×
UNCOV
3427
// link failure, and is forced to exit. The report houses the necessary
×
UNCOV
3428
// information to clean up the channel state, send back the error message, and
×
UNCOV
3429
// force close if necessary.
×
UNCOV
3430
type linkFailureReport struct {
×
UNCOV
3431
        chanPoint   wire.OutPoint
×
UNCOV
3432
        chanID      lnwire.ChannelID
×
UNCOV
3433
        shortChanID lnwire.ShortChannelID
×
UNCOV
3434
        linkErr     htlcswitch.LinkFailureError
×
UNCOV
3435
}
×
UNCOV
3436

×
UNCOV
3437
// handleLinkFailure processes a link failure report when a link in the switch
×
UNCOV
3438
// fails. It facilitates the removal of all channel state within the peer,
×
UNCOV
3439
// force closing the channel depending on severity, and sending the error
×
UNCOV
3440
// message back to the remote party.
×
UNCOV
3441
func (p *Brontide) handleLinkFailure(failure linkFailureReport) {
×
UNCOV
3442
        // Retrieve the channel from the map of active channels. We do this to
×
3443
        // have access to it even after WipeChannel remove it from the map.
3444
        chanID := lnwire.NewChanIDFromOutPoint(failure.chanPoint)
3445
        lnChan, _ := p.activeChannels.Load(chanID)
UNCOV
3446

×
UNCOV
3447
        // We begin by wiping the link, which will remove it from the switch,
×
UNCOV
3448
        // such that it won't be attempted used for any more updates.
×
UNCOV
3449
        //
×
UNCOV
3450
        // TODO(halseth): should introduce a way to atomically stop/pause the
×
UNCOV
3451
        // link and cancel back any adds in its mailboxes such that we can
×
UNCOV
3452
        // safely force close without the link being added again and updates
×
UNCOV
3453
        // being applied.
×
3454
        p.WipeChannel(&failure.chanPoint)
3455

3456
        // If the error encountered was severe enough, we'll now force close
UNCOV
3457
        // the channel to prevent reading it to the switch in the future.
×
UNCOV
3458
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureForceClose {
×
UNCOV
3459
                p.log.Warnf("Force closing link(%v)", failure.shortChanID)
×
UNCOV
3460

×
UNCOV
3461
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
×
UNCOV
3462
                        failure.chanPoint,
×
UNCOV
3463
                )
×
UNCOV
3464
                if err != nil {
×
UNCOV
3465
                        p.log.Errorf("unable to force close "+
×
3466
                                "link(%v): %v", failure.shortChanID, err)
UNCOV
3467
                } else {
×
UNCOV
3468
                        p.log.Infof("channel(%v) force "+
×
UNCOV
3469
                                "closed with txid %v",
×
UNCOV
3470
                                failure.shortChanID, closeTx.TxHash())
×
UNCOV
3471
                }
×
UNCOV
3472
        }
×
UNCOV
3473

×
UNCOV
3474
        // If this is a permanent failure, we will mark the channel borked.
×
UNCOV
3475
        if failure.linkErr.PermanentFailure && lnChan != nil {
×
3476
                p.log.Warnf("Marking link(%v) borked due to permanent "+
×
3477
                        "failure", failure.shortChanID)
×
3478

×
3479
                if err := lnChan.State().MarkBorked(); err != nil {
3480
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
3481
                                failure.shortChanID, err)
×
3482
                }
×
UNCOV
3483
        }
×
UNCOV
3484

×
3485
        // Send an error to the peer, why we failed the channel.
3486
        if failure.linkErr.ShouldSendToPeer() {
3487
                // If SendData is set, send it to the peer. If not, we'll use
3488
                // the standard error messages in the payload. We only include
3489
                // sendData in the cases where the error data does not contain
UNCOV
3490
                // sensitive information.
×
UNCOV
3491
                data := []byte(failure.linkErr.Error())
×
UNCOV
3492
                if failure.linkErr.SendData != nil {
×
3493
                        data = failure.linkErr.SendData
3494
                }
3495

3496
                var networkMsg lnwire.Message
3497
                if failure.linkErr.Warning {
3498
                        networkMsg = &lnwire.Warning{
19✔
3499
                                ChanID: failure.chanID,
19✔
3500
                                Data:   data,
19✔
3501
                        }
19✔
3502
                } else {
19✔
3503
                        networkMsg = &lnwire.Error{
19✔
3504
                                ChanID: failure.chanID,
19✔
3505
                                Data:   data,
37✔
3506
                        }
36✔
3507
                }
18✔
3508

18✔
3509
                err := p.SendMessage(true, networkMsg)
3510
                if err != nil {
3511
                        p.log.Errorf("unable to send msg to "+
3512
                                "remote peer: %v", err)
19✔
3513
                }
3514
        }
3515

3516
        // If the failure action is disconnect, then we'll execute that now. If
3517
        // we had to send an error above, it was a sync call, so we expect the
3518
        // message to be flushed on the wire by now.
3519
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
3520
                p.Disconnect(fmt.Errorf("link requested disconnect"))
4✔
3521
        }
4✔
3522
}
4✔
3523

4✔
3524
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
4✔
3525
// public key and the channel id.
4✔
3526
func (p *Brontide) fetchLinkFromKeyAndCid(
4✔
3527
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
4✔
3528

4✔
3529
        var chanLink htlcswitch.ChannelUpdateHandler
4✔
3530

4✔
3531
        // We don't need to check the error here, and can instead just loop
4✔
3532
        // over the slice and return nil.
4✔
3533
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
4✔
3534
        for _, link := range links {
4✔
3535
                if link.ChanID() == cid {
4✔
3536
                        chanLink = link
4✔
3537
                        break
4✔
3538
                }
4✔
3539
        }
4✔
3540

6✔
3541
        return chanLink
2✔
3542
}
2✔
3543

3544
// finalizeChanClosure performs the final clean up steps once the cooperative
4✔
3545
// closure transaction has been fully broadcast. The finalized closing state
4✔
UNCOV
3546
// machine should be passed in. Once the transaction has been sufficiently
×
UNCOV
3547
// confirmed, the channel will be marked as fully closed within the database,
×
UNCOV
3548
// and any clients will be notified of updates to the closing state.
×
UNCOV
3549
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
×
3550
        closeReq := chanCloser.CloseRequest()
3551

3552
        // First, we'll clear all indexes related to the channel in question.
4✔
3553
        chanPoint := chanCloser.Channel().ChannelPoint()
4✔
3554
        p.WipeChannel(&chanPoint)
4✔
3555

4✔
3556
        // Also clear the activeChanCloses map of this channel.
6✔
3557
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
3558
        delete(p.activeChanCloses, cid)
2✔
3559

2✔
3560
        // Next, we'll launch a goroutine which will request to be notified by
2✔
3561
        // the ChainNotifier once the closure transaction obtains a single
3562
        // confirmation.
4✔
3563
        notifier := p.cfg.ChainNotifier
4✔
3564

4✔
3565
        // If any error happens during waitForChanToClose, forward it to
4✔
3566
        // closeReq. If this channel closure is not locally initiated, closeReq
4✔
3567
        // will be nil, so just ignore the error.
8✔
3568
        errChan := make(chan error, 1)
4✔
3569
        if closeReq != nil {
4✔
3570
                errChan = closeReq.Err
6✔
3571
        }
2✔
3572

2✔
3573
        closingTx, err := chanCloser.ClosingTx()
2✔
3574
        if err != nil {
2✔
3575
                if closeReq != nil {
2✔
3576
                        p.log.Error(err)
2✔
3577
                        closeReq.Err <- err
2✔
3578
                }
2✔
3579
        }
3580

3581
        closingTxid := closingTx.TxHash()
3582

3583
        // If this is a locally requested shutdown, update the caller with a
3584
        // new event detailing the current pending state of this request.
3585
        if closeReq != nil {
3586
                closeReq.Updates <- &PendingUpdate{
3587
                        Txid: closingTxid[:],
3588
                }
3589
        }
3590

4✔
3591
        localOut := chanCloser.LocalCloseOutput()
4✔
3592
        remoteOut := chanCloser.RemoteCloseOutput()
4✔
3593
        auxOut := chanCloser.AuxOutputs()
4✔
3594
        go WaitForChanToClose(
4✔
3595
                chanCloser.NegotiationHeight(), notifier, errChan,
4✔
3596
                &chanPoint, &closingTxid, closingTx.TxOut[0].PkScript, func() {
4✔
3597
                        // Respond to the local subsystem which requested the
4✔
3598
                        // channel closure.
4✔
3599
                        if closeReq != nil {
4✔
UNCOV
3600
                                closeReq.Updates <- &ChannelCloseUpdate{
×
UNCOV
3601
                                        ClosingTxid:       closingTxid[:],
×
UNCOV
3602
                                        Success:           true,
×
UNCOV
3603
                                        LocalCloseOutput:  localOut,
×
3604
                                        RemoteCloseOutput: remoteOut,
3605
                                        AuxOutputs:        auxOut,
3606
                                }
3607
                        }
3608
                },
4✔
3609
        )
4✔
UNCOV
3610
}
×
UNCOV
3611

×
3612
// WaitForChanToClose uses the passed notifier to wait until the channel has
3613
// been detected as closed on chain and then concludes by executing the
3614
// following actions: the channel point will be sent over the settleChan, and
3615
// finally the callback will be executed. If any error is encountered within
4✔
3616
// the function, then it will be sent over the errChan.
4✔
3617
func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
4✔
3618
        errChan chan error, chanPoint *wire.OutPoint,
4✔
3619
        closingTxID *chainhash.Hash, closeScript []byte, cb func()) {
4✔
3620

4✔
3621
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
3622
                "with txid: %v", chanPoint, closingTxID)
3623

3624
        // TODO(roasbeef): add param for num needed confs
3625
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
4✔
3626
                closingTxID, closeScript, 1, bestHeight,
4✔
3627
        )
4✔
3628
        if err != nil {
4✔
3629
                if errChan != nil {
4✔
3630
                        errChan <- err
4✔
3631
                }
4✔
3632
                return
4✔
3633
        }
4✔
3634

3635
        // In the case that the ChainNotifier is shutting down, all subscriber
3636
        // notification channels will be closed, generating a nil receive.
3637
        height, ok := <-confNtfn.Confirmed
3✔
3638
        if !ok {
3✔
3639
                return
3✔
3640
        }
3✔
3641

3✔
UNCOV
3642
        // The channel has been closed, remove it from any active indexes, and
×
UNCOV
3643
        // the database state.
×
UNCOV
3644
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
×
3645
                "height %v", chanPoint, height.BlockHeight)
3646

3647
        // Finally, execute the closure call back to mark the confirmation of
3648
        // the transaction closing the contract.
3✔
3649
        cb()
3✔
3650
}
3✔
3651

3✔
3652
// WipeChannel removes the passed channel point from all indexes associated with
3✔
3653
// the peer and the switch.
3✔
3654
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
3✔
3655
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
3✔
UNCOV
3656

×
UNCOV
3657
        p.activeChannels.Delete(chanID)
×
3658

3659
        // Instruct the HtlcSwitch to close this link as the channel is no
3660
        // longer active.
3661
        p.cfg.Switch.RemoveLink(chanID)
3662
}
3✔
3663

3✔
UNCOV
3664
// handleInitMsg handles the incoming init message which contains global and
×
UNCOV
3665
// local feature vectors. If feature vectors are incompatible then disconnect.
×
3666
func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
3667
        // First, merge any features from the legacy global features field into
3668
        // those presented in the local features fields.
3669
        err := msg.Features.Merge(msg.GlobalFeatures)
3✔
UNCOV
3670
        if err != nil {
×
3671
                return fmt.Errorf("unable to merge legacy global features: %w",
×
3672
                        err)
3673
        }
3✔
3674

3675
        // Then, finalize the remote feature vector providing the flattened
3676
        // feature bit namespace.
3677
        p.remoteFeatures = lnwire.NewFeatureVector(
3678
                msg.Features, lnwire.Features,
3679
        )
3680

UNCOV
3681
        // Now that we have their features loaded, we'll ensure that they
×
UNCOV
3682
        // didn't set any required bits that we don't know of.
×
UNCOV
3683
        err = feature.ValidateRequired(p.remoteFeatures)
×
3684
        if err != nil {
3685
                return fmt.Errorf("invalid remote features: %w", err)
3686
        }
3687

3688
        // Ensure the remote party's feature vector contains all transitive
3689
        // dependencies. We know ours are correct since they are validated
3690
        // during the feature manager's instantiation.
6✔
3691
        err = feature.ValidateDeps(p.remoteFeatures)
6✔
3692
        if err != nil {
6✔
3693
                return fmt.Errorf("invalid remote features: %w", err)
3694
        }
3695

3696
        // Now that we know we understand their requirements, we'll check to
3✔
3697
        // see if they don't support anything that we deem to be mandatory.
3✔
3698
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
3✔
3699
                return fmt.Errorf("data loss protection required")
3✔
3700
        }
3✔
3701

3702
        return nil
3703
}
3704

7✔
3705
// LocalFeatures returns the set of global features that has been advertised by
7✔
3706
// the local node. This allows sub-systems that use this interface to gate their
7✔
3707
// behavior off the set of negotiated feature bits.
7✔
3708
//
7✔
3709
// NOTE: Part of the lnpeer.Peer interface.
7✔
3710
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
7✔
3711
        return p.cfg.Features
7✔
3712
}
7✔
3713

8✔
3714
// RemoteFeatures returns the set of global features that has been advertised by
1✔
3715
// the remote node. This allows sub-systems that use this interface to gate
1✔
3716
// their behavior off the set of negotiated feature bits.
1✔
3717
//
1✔
3718
// NOTE: Part of the lnpeer.Peer interface.
1✔
3719
func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector {
1✔
3720
        return p.remoteFeatures
1✔
3721
}
1✔
3722

1✔
3723
// hasNegotiatedScidAlias returns true if we've negotiated the
1✔
3724
// option-scid-alias feature bit with the peer.
1✔
3725
func (p *Brontide) hasNegotiatedScidAlias() bool {
1✔
3726
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
1✔
3727
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
3728
        return peerHas && localHas
7✔
3729
}
7✔
3730

7✔
3731
// sendInitMsg sends the Init message to the remote peer. This message contains
7✔
3732
// our currently supported local and global features.
7✔
3733
func (p *Brontide) sendInitMsg(legacyChan bool) error {
7✔
3734
        features := p.cfg.Features.Clone()
3735
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
3736

3737
        // If we have a legacy channel open with a peer, we downgrade static
UNCOV
3738
        // remote required to optional in case the peer does not understand the
×
UNCOV
3739
        // required feature bit. If we do not do this, the peer will reject our
×
UNCOV
3740
        // connection because it does not understand a required feature bit, and
×
UNCOV
3741
        // our channel will be unusable.
×
UNCOV
3742
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
×
UNCOV
3743
                p.log.Infof("Legacy channel open with peer, " +
×
3744
                        "downgrading static remote required feature bit to " +
3745
                        "optional")
UNCOV
3746

×
UNCOV
3747
                // Unset and set in both the local and global features to
×
UNCOV
3748
                // ensure both sets are consistent and merge able by old and
×
UNCOV
3749
                // new nodes.
×
UNCOV
3750
                features.Unset(lnwire.StaticRemoteKeyRequired)
×
3751
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
UNCOV
3752

×
UNCOV
3753
                features.Set(lnwire.StaticRemoteKeyOptional)
×
UNCOV
3754
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
×
UNCOV
3755
        }
×
3756

UNCOV
3757
        msg := lnwire.NewInitMessage(
×
UNCOV
3758
                legacyFeatures.RawFeatureVector,
×
UNCOV
3759
                features.RawFeatureVector,
×
UNCOV
3760
        )
×
3761

UNCOV
3762
        return p.writeMessage(msg)
×
UNCOV
3763
}
×
UNCOV
3764

×
UNCOV
3765
// resendChanSyncMsg will attempt to find a channel sync message for the closed
×
UNCOV
3766
// channel and resend it to our peer.
×
UNCOV
3767
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
×
UNCOV
3768
        // If we already re-sent the mssage for this channel, we won't do it
×
3769
        // again.
UNCOV
3770
        if _, ok := p.resentChanSyncMsg[cid]; ok {
×
UNCOV
3771
                return nil
×
UNCOV
3772
        }
×
UNCOV
3773

×
UNCOV
3774
        // Check if we have any channel sync messages stored for this channel.
×
UNCOV
3775
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
×
UNCOV
3776
        if err != nil {
×
UNCOV
3777
                return fmt.Errorf("unable to fetch channel sync messages for "+
×
3778
                        "peer %v: %v", p, err)
3779
        }
3780

3781
        if c.LastChanSyncMsg == nil {
3782
                return fmt.Errorf("no chan sync message stored for channel %v",
3783
                        cid)
3784
        }
3785

3786
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
3✔
3787
                return fmt.Errorf("ignoring channel reestablish from "+
3✔
3788
                        "peer=%x", p.IdentityKey().SerializeCompressed())
3✔
3789
        }
3790

3791
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
3792
                "peer", cid)
3793

3794
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
3795
                return fmt.Errorf("failed resending channel sync "+
3796
                        "message to peer %v: %v", p, err)
1✔
3797
        }
1✔
3798

1✔
3799
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
3800
                cid)
3801

3802
        // Note down that we sent the message, so we won't resend it again for
3803
        // this connection.
3804
        p.resentChanSyncMsg[cid] = struct{}{}
4✔
3805

4✔
3806
        return nil
4✔
3807
}
4✔
3808

4✔
3809
// SendMessage sends a variadic number of high-priority messages to the remote
5✔
3810
// peer. The first argument denotes if the method should block until the
1✔
3811
// messages have been sent to the remote peer or an error is returned,
1✔
3812
// otherwise it returns immediately after queuing.
8✔
3813
//
4✔
3814
// NOTE: Part of the lnpeer.Peer interface.
4✔
3815
func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error {
4✔
3816
        return p.sendMessage(sync, true, msgs...)
5✔
3817
}
1✔
3818

1✔
3819
// SendMessageLazy sends a variadic number of low-priority messages to the
1✔
3820
// remote peer. The first argument denotes if the method should block until
3821
// the messages have been sent to the remote peer or an error is returned,
7✔
3822
// otherwise it returns immediately after queueing.
3✔
3823
//
4✔
3824
// NOTE: Part of the lnpeer.Peer interface.
1✔
3825
func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
1✔
3826
        return p.sendMessage(sync, false, msgs...)
3827
}
3828

3829
// sendMessage queues a variadic number of messages using the passed priority
3830
// to the remote peer. If sync is true, this method will block until the
5✔
3831
// messages have been sent to the remote peer or an error is returned, otherwise
1✔
3832
// it returns immediately after queueing.
1✔
3833
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
1✔
UNCOV
3834
        // Add all incoming messages to the outgoing queue. A list of error
×
UNCOV
3835
        // chans is populated for each message if the caller requested a sync
×
UNCOV
3836
        // send.
×
UNCOV
3837
        var errChans []chan error
×
3838
        if sync {
3839
                errChans = make([]chan error, 0, len(msgs))
3840
        }
3841
        for _, msg := range msgs {
3✔
3842
                // If a sync send was requested, create an error chan to listen
3843
                // for an ack from the writeHandler.
3844
                var errChan chan error
3845
                if sync {
3846
                        errChan = make(chan error, 1)
3847
                        errChans = append(errChans, errChan)
2✔
3848
                }
2✔
3849

2✔
3850
                if priority {
3851
                        p.queueMsg(msg, errChan)
3852
                } else {
3853
                        p.queueMsgLazy(msg, errChan)
3854
                }
15✔
3855
        }
15✔
3856

15✔
3857
        // Wait for all replies from the writeHandler. For async sends, this
3858
        // will be a NOP as the list of error chans is nil.
3859
        for _, errChan := range errChans {
3860
                select {
UNCOV
3861
                case err := <-errChan:
×
UNCOV
3862
                        return err
×
3863
                case <-p.quit:
×
3864
                        return lnpeer.ErrPeerExiting
3865
                case <-p.cfg.Quit:
3866
                        return lnpeer.ErrPeerExiting
3867
                }
3868
        }
3869

UNCOV
3870
        return nil
×
UNCOV
3871
}
×
UNCOV
3872

×
UNCOV
3873
// PubKey returns the pubkey of the peer in compressed serialized format.
×
UNCOV
3874
//
×
UNCOV
3875
// NOTE: Part of the lnpeer.Peer interface.
×
UNCOV
3876
func (p *Brontide) PubKey() [33]byte {
×
UNCOV
3877
        return p.cfg.PubKeyBytes
×
UNCOV
3878
}
×
UNCOV
3879

×
UNCOV
3880
// IdentityKey returns the public key of the remote peer.
×
UNCOV
3881
//
×
UNCOV
3882
// NOTE: Part of the lnpeer.Peer interface.
×
UNCOV
3883
func (p *Brontide) IdentityKey() *btcec.PublicKey {
×
3884
        return p.cfg.Addr.IdentityKey
3885
}
3886

3887
// Address returns the network address of the remote peer.
UNCOV
3888
//
×
UNCOV
3889
// NOTE: Part of the lnpeer.Peer interface.
×
UNCOV
3890
func (p *Brontide) Address() net.Addr {
×
UNCOV
3891
        return p.cfg.Addr.Address
×
UNCOV
3892
}
×
3893

3894
// AddNewChannel adds a new channel to the peer. The channel should fail to be
3895
// added if the cancel channel is closed.
3896
//
3897
// NOTE: Part of the lnpeer.Peer interface.
3898
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
3899
        cancel <-chan struct{}) error {
3900

UNCOV
3901
        errChan := make(chan error, 1)
×
UNCOV
3902
        newChanMsg := &newChannelMsg{
×
UNCOV
3903
                channel: newChan,
×
UNCOV
3904
                err:     errChan,
×
UNCOV
3905
        }
×
UNCOV
3906

×
UNCOV
3907
        select {
×
UNCOV
3908
        case p.newActiveChannel <- newChanMsg:
×
3909
        case <-cancel:
×
3910
                return errors.New("canceled adding new channel")
×
3911
        case <-p.quit:
3912
                return lnpeer.ErrPeerExiting
×
UNCOV
3913
        }
×
3914

UNCOV
3915
        // We pause here to wait for the peer to recognize the new channel
×
UNCOV
3916
        // before we close the channel barrier corresponding to the channel.
×
3917
        select {
3918
        case err := <-errChan:
3919
                return err
3920
        case <-p.quit:
3921
                return lnpeer.ErrPeerExiting
UNCOV
3922
        }
×
UNCOV
3923
}
×
UNCOV
3924

×
3925
// AddPendingChannel adds a pending open channel to the peer. The channel
UNCOV
3926
// should fail to be added if the cancel channel is closed.
×
UNCOV
3927
//
×
3928
// NOTE: Part of the lnpeer.Peer interface.
UNCOV
3929
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
×
UNCOV
3930
        cancel <-chan struct{}) error {
×
3931

3932
        errChan := make(chan error, 1)
3933
        newChanMsg := &newChannelMsg{
3934
                channelID: cid,
3935
                err:       errChan,
3936
        }
UNCOV
3937

×
UNCOV
3938
        select {
×
UNCOV
3939
        case p.newPendingChannel <- newChanMsg:
×
UNCOV
3940

×
3941
        case <-cancel:
×
3942
                return errors.New("canceled adding pending channel")
×
UNCOV
3943

×
3944
        case <-p.quit:
×
3945
                return lnpeer.ErrPeerExiting
×
UNCOV
3946
        }
×
UNCOV
3947

×
3948
        // We pause here to wait for the peer to recognize the new pending
3949
        // channel before we close the channel barrier corresponding to the
3950
        // channel.
3951
        select {
3952
        case err := <-errChan:
UNCOV
3953
                return err
×
UNCOV
3954

×
3955
        case <-cancel:
×
3956
                return errors.New("canceled adding pending channel")
UNCOV
3957

×
3958
        case <-p.quit:
×
3959
                return lnpeer.ErrPeerExiting
3960
        }
3961
}
3962

3963
// RemovePendingChannel removes a pending open channel from the peer.
UNCOV
3964
//
×
UNCOV
3965
// NOTE: Part of the lnpeer.Peer interface.
×
UNCOV
3966
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
×
3967
        errChan := make(chan error, 1)
3968
        newChanMsg := &newChannelMsg{
3969
                channelID: cid,
3970
                err:       errChan,
3971
        }
13✔
3972

13✔
3973
        select {
13✔
3974
        case p.removePendingChannel <- newChanMsg:
13✔
3975
        case <-p.quit:
13✔
3976
                return lnpeer.ErrPeerExiting
13✔
3977
        }
13✔
UNCOV
3978

×
UNCOV
3979
        // We pause here to wait for the peer to respond to the cancellation of
×
UNCOV
3980
        // the pending channel before we close the channel barrier
×
UNCOV
3981
        // corresponding to the channel.
×
3982
        select {
UNCOV
3983
        case err := <-errChan:
×
UNCOV
3984
                return err
×
UNCOV
3985

×
3986
        case <-p.quit:
×
3987
                return lnpeer.ErrPeerExiting
×
UNCOV
3988
        }
×
UNCOV
3989
}
×
UNCOV
3990

×
3991
// StartTime returns the time at which the connection was established if the
3992
// peer started successfully, and zero otherwise.
3993
func (p *Brontide) StartTime() time.Time {
14✔
3994
        return p.startTime
1✔
3995
}
1✔
3996

1✔
3997
// handleCloseMsg is called when a new cooperative channel closure related
1✔
3998
// message is received from the remote peer. We'll use this message to advance
1✔
3999
// the chan closer state machine.
1✔
4000
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
1✔
4001
        link := p.fetchLinkFromKeyAndCid(msg.cid)
1✔
UNCOV
4002

×
UNCOV
4003
        // We'll now fetch the matching closing state machine in order to continue,
×
4004
        // or finalize the channel closure process.
1✔
4005
        chanCloser, err := p.fetchActiveChanCloser(msg.cid)
1✔
4006
        if err != nil {
1✔
4007
                // If the channel is not known to us, we'll simply ignore this message.
4008
                if err == ErrChannelNotFound {
4009
                        return
4010
                }
4011

13✔
4012
                p.log.Errorf("Unable to respond to remote close msg: %v", err)
5✔
4013

5✔
4014
                errMsg := &lnwire.Error{
5✔
4015
                        ChanID: msg.cid,
×
4016
                        Data:   lnwire.ErrorData(err.Error()),
×
4017
                }
×
4018
                p.queueMsg(errMsg, nil)
4019
                return
5✔
4020
        }
5✔
UNCOV
4021

×
UNCOV
4022
        handleErr := func(err error) {
×
4023
                err = fmt.Errorf("unable to process close msg: %w", err)
×
4024
                p.log.Error(err)
4025

8✔
4026
                // As the negotiations failed, we'll reset the channel state machine to
3✔
4027
                // ensure we act to on-chain events as normal.
3✔
4028
                chanCloser.Channel().ResetState()
3✔
4029

4✔
4030
                if chanCloser.CloseRequest() != nil {
1✔
4031
                        chanCloser.CloseRequest().Err <- err
1✔
4032
                }
1✔
4033
                delete(p.activeChanCloses, msg.cid)
4034

4035
                p.Disconnect(err)
4036
        }
2✔
UNCOV
4037

×
UNCOV
4038
        // Next, we'll process the next message using the target state machine.
×
UNCOV
4039
        // We'll either continue negotiation, or halt.
×
4040
        switch typed := msg.msg.(type) {
4041
        case *lnwire.Shutdown:
4042
                // Disable incoming adds immediately.
4043
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
4044
                        p.log.Warnf("Incoming link adds already disabled: %v",
4✔
4045
                                link.ChanID())
2✔
4046
                }
2✔
4047

4048
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
4049
                if err != nil {
10✔
4050
                        handleErr(err)
5✔
4051
                        return
6✔
4052
                }
1✔
4053

1✔
4054
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
1✔
4055
                        // If the link is nil it means we can immediately queue
4056
                        // the Shutdown message since we don't have to wait for
8✔
4057
                        // commitment transaction synchronization.
4✔
4058
                        if link == nil {
4✔
4059
                                p.queueMsg(&msg, nil)
4060
                                return
4061
                        }
6✔
4062

1✔
4063
                        // Immediately disallow any new HTLC's from being added
5✔
4064
                        // in the outgoing direction.
4✔
4065
                        if !link.DisableAdds(htlcswitch.Outgoing) {
4✔
4066
                                p.log.Warnf("Outgoing link adds already "+
4✔
4067
                                        "disabled: %v", link.ChanID())
8✔
4068
                        }
4✔
4069

4✔
4070
                        // When we have a Shutdown to send, we defer it till the
4✔
4071
                        // next time we send a CommitSig to remain spec
4✔
4072
                        // compliant.
4073
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
4074
                                p.queueMsg(&msg, nil)
8✔
4075
                        })
8✔
4076
                })
8✔
UNCOV
4077

×
UNCOV
4078
                beginNegotiation := func() {
×
UNCOV
4079
                        oClosingSigned, err := chanCloser.BeginNegotiation()
×
4080
                        if err != nil {
4081
                                handleErr(err)
16✔
4082
                                return
8✔
4083
                        }
8✔
4084

UNCOV
4085
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
×
UNCOV
4086
                                p.queueMsg(&msg, nil)
×
4087
                        })
4088
                }
4089

4090
                if link == nil {
4091
                        beginNegotiation()
20✔
4092
                } else {
8✔
4093
                        // Now we register a flush hook to advance the
8✔
4094
                        // ChanCloser and possibly send out a ClosingSigned
4095
                        // when the link finishes draining.
4096
                        link.OnFlushedOnce(func() {
4097
                                // Remove link in goroutine to prevent deadlock.
4098
                                go p.cfg.Switch.RemoveLink(msg.cid)
4✔
4099
                                beginNegotiation()
4100
                        })
4101
                }
4102

4103
        case *lnwire.ClosingSigned:
UNCOV
4104
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
×
UNCOV
4105
                if err != nil {
×
4106
                        handleErr(err)
×
4107
                        return
×
4108
                }
×
UNCOV
4109

×
UNCOV
4110
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
×
UNCOV
4111
                        p.queueMsg(&msg, nil)
×
4112
                })
4113

4114
        default:
4115
                panic("impossible closeMsg type")
UNCOV
4116
        }
×
UNCOV
4117

×
UNCOV
4118
        // If we haven't finished close negotiations, then we'll continue as we
×
4119
        // can't yet finalize the closure.
4120
        if _, err := chanCloser.ClosingTx(); err != nil {
UNCOV
4121
                return
×
UNCOV
4122
        }
×
UNCOV
4123

×
4124
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
4125
        // the channel closure by notifying relevant sub-systems and launching a
UNCOV
4126
        // goroutine to wait for close tx conf.
×
UNCOV
4127
        p.finalizeChanClosure(chanCloser)
×
UNCOV
4128
}
×
4129

4130
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
UNCOV
4131
// the channelManager goroutine, which will shut down the link and possibly
×
UNCOV
4132
// close the channel.
×
UNCOV
4133
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
×
4134
        select {
4135
        case p.localCloseChanReqs <- req:
UNCOV
4136
                p.log.Info("Local close channel request is going to be " +
×
UNCOV
4137
                        "delivered to the peer")
×
4138
        case <-p.quit:
×
4139
                p.log.Info("Unable to deliver local close channel request " +
4140
                        "to peer")
UNCOV
4141
        }
×
UNCOV
4142
}
×
UNCOV
4143

×
4144
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
4145
func (p *Brontide) NetAddress() *lnwire.NetAddress {
UNCOV
4146
        return p.cfg.Addr
×
UNCOV
4147
}
×
UNCOV
4148

×
4149
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
4150
func (p *Brontide) Inbound() bool {
UNCOV
4151
        return p.cfg.Inbound
×
UNCOV
4152
}
×
UNCOV
4153

×
4154
// ConnReq is a getter for the Brontide's connReq in cfg.
4155
func (p *Brontide) ConnReq() *connmgr.ConnReq {
UNCOV
4156
        return p.cfg.ConnReq
×
UNCOV
4157
}
×
UNCOV
4158

×
4159
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
4160
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
4161
        return p.cfg.ErrorBuffer
UNCOV
4162
}
×
UNCOV
4163

×
UNCOV
4164
// SetAddress sets the remote peer's address given an address.
×
4165
func (p *Brontide) SetAddress(address net.Addr) {
×
4166
        p.cfg.Addr.Address = address
×
4167
}
UNCOV
4168

×
UNCOV
4169
// ActiveSignal returns the peer's active signal.
×
UNCOV
4170
func (p *Brontide) ActiveSignal() chan struct{} {
×
UNCOV
4171
        return p.activeSignal
×
4172
}
UNCOV
4173

×
4174
// Conn returns a pointer to the peer's connection struct.
4175
func (p *Brontide) Conn() net.Conn {
4176
        return p.cfg.Conn
4177
}
4178

4179
// BytesReceived returns the number of bytes received from the peer.
3✔
4180
func (p *Brontide) BytesReceived() uint64 {
3✔
4181
        return atomic.LoadUint64(&p.bytesReceived)
3✔
4182
}
3✔
4183

3✔
UNCOV
4184
// BytesSent returns the number of bytes sent to the peer.
×
UNCOV
4185
func (p *Brontide) BytesSent() uint64 {
×
4186
        return atomic.LoadUint64(&p.bytesSent)
4187
}
4188

4189
// LastRemotePingPayload returns the last payload the remote party sent as part
4190
// of their ping.
4191
func (p *Brontide) LastRemotePingPayload() []byte {
4192
        pingPayload := p.lastPingPayload.Load()
3✔
4193
        if pingPayload == nil {
3✔
UNCOV
4194
                return []byte{}
×
UNCOV
4195
        }
×
4196

4197
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
3✔
4198
        if !ok {
3✔
4199
                return nil
3✔
4200
        }
4201

4202
        return pingBytes
4203
}
4204

3✔
4205
// attachChannelEventSubscription creates a channel event subscription and
3✔
4206
// attaches to client to Brontide if the reenableTimeout is no greater than 1
3✔
4207
// minute.
3✔
4208
func (p *Brontide) attachChannelEventSubscription() error {
3✔
4209
        // If the timeout is greater than 1 minute, it's unlikely that the link
3✔
4210
        // hasn't yet finished its reestablishment. Return a nil without
3✔
4211
        // creating the client to specify that we don't want to retry.
3✔
4212
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
3✔
4213
                return nil
4✔
4214
        }
1✔
4215

1✔
4216
        // When the reenable timeout is less than 1 minute, it's likely the
1✔
4217
        // channel link hasn't finished its reestablishment yet. In that case,
4218
        // we'll give it a second chance by subscribing to the channel update
4219
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
4220
        // enabling the channel again.
3✔
4221
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
1✔
4222
        if err != nil {
1✔
4223
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
1✔
4224
        }
4225

4226
        p.channelEventClient = sub
4227

4228
        return nil
1✔
UNCOV
4229
}
×
UNCOV
4230

×
4231
// updateNextRevocation updates the existing channel's next revocation if it's
4232
// nil.
1✔
4233
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
1✔
4234
        chanPoint := c.FundingOutpoint
1✔
4235
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
1✔
4236

1✔
4237
        // Read the current channel.
1✔
4238
        currentChan, loaded := p.activeChannels.Load(chanID)
1✔
UNCOV
4239

×
UNCOV
4240
        // currentChan should exist, but we perform a check anyway to avoid nil
×
4241
        // pointer dereference.
4242
        if !loaded {
1✔
4243
                return fmt.Errorf("missing active channel with chanID=%v",
4244
                        chanID)
4245
        }
4246

4247
        // currentChan should not be nil, but we perform a check anyway to
UNCOV
4248
        // avoid nil pointer dereference.
×
UNCOV
4249
        if currentChan == nil {
×
UNCOV
4250
                return fmt.Errorf("found nil active channel with chanID=%v",
×
UNCOV
4251
                        chanID)
×
UNCOV
4252
        }
×
UNCOV
4253

×
UNCOV
4254
        // If we're being sent a new channel, and our existing channel doesn't
×
UNCOV
4255
        // have the next revocation, then we need to update the current
×
UNCOV
4256
        // existing channel.
×
UNCOV
4257
        if currentChan.RemoteNextRevocation() != nil {
×
4258
                return nil
×
4259
        }
×
UNCOV
4260

×
UNCOV
4261
        p.log.Infof("Processing retransmitted ChannelReady for "+
×
UNCOV
4262
                "ChannelPoint(%v)", chanPoint)
×
UNCOV
4263

×
UNCOV
4264
        nextRevoke := c.RemoteNextRevocation
×
UNCOV
4265

×
4266
        err := currentChan.InitNextRevocation(nextRevoke)
UNCOV
4267
        if err != nil {
×
4268
                return fmt.Errorf("unable to init next revocation: %w", err)
×
4269
        }
×
UNCOV
4270

×
UNCOV
4271
        return nil
×
UNCOV
4272
}
×
UNCOV
4273

×
UNCOV
4274
// addActiveChannel adds a new active channel to the `activeChannels` map. It
×
UNCOV
4275
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
×
4276
// it and assembles it with a channel link.
4277
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
4278
        chanPoint := c.FundingOutpoint
4279
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
UNCOV
4280

×
UNCOV
4281
        // If we've reached this point, there are two possible scenarios.  If
×
UNCOV
4282
        // the channel was in the active channels map as nil, then it was
×
UNCOV
4283
        // loaded from disk and we need to send reestablish. Else, it was not
×
UNCOV
4284
        // loaded from disk and we don't need to send reestablish as this is a
×
UNCOV
4285
        // fresh channel.
×
4286
        shouldReestablish := p.isLoadedFromDisk(chanID)
4287

UNCOV
4288
        chanOpts := c.ChanOpts
×
UNCOV
4289
        if shouldReestablish {
×
UNCOV
4290
                // If we have to do the reestablish dance for this channel,
×
UNCOV
4291
                // ensure that we don't try to call InitRemoteMusigNonces twice
×
UNCOV
4292
                // by calling SkipNonceInit.
×
UNCOV
4293
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
×
UNCOV
4294
        }
×
UNCOV
4295

×
UNCOV
4296
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
×
4297
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
4298
        })
×
4299
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
4300
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
4301
        })
UNCOV
4302

×
UNCOV
4303
        // If not already active, we'll add this channel to the set of active
×
UNCOV
4304
        // channels, so we can look it up later easily according to its channel
×
UNCOV
4305
        // ID.
×
UNCOV
4306
        lnChan, err := lnwallet.NewLightningChannel(
×
4307
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
4308
        )
UNCOV
4309
        if err != nil {
×
4310
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
4311
        }
×
UNCOV
4312

×
UNCOV
4313
        // Store the channel in the activeChannels map.
×
UNCOV
4314
        p.activeChannels.Store(chanID, lnChan)
×
UNCOV
4315

×
UNCOV
4316
        p.log.Infof("New channel active ChannelPoint(%v) with peer", chanPoint)
×
4317

UNCOV
4318
        // Next, we'll assemble a ChannelLink along with the necessary items it
×
4319
        // needs to function.
4320
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
4321
        if err != nil {
4322
                return fmt.Errorf("unable to subscribe to chain events: %w",
4323
                        err)
4324
        }
×
UNCOV
4325

×
UNCOV
4326
        // We'll query the channel DB for the new channel's initial forwarding
×
UNCOV
4327
        // policies to determine the policy we start out with.
×
UNCOV
4328
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
×
UNCOV
4329
        if err != nil {
×
4330
                return fmt.Errorf("unable to query for initial forwarding "+
×
4331
                        "policy: %v", err)
×
4332
        }
×
UNCOV
4333

×
UNCOV
4334
        // Create the link and add it to the switch.
×
UNCOV
4335
        err = p.addLink(
×
UNCOV
4336
                &chanPoint, lnChan, initialPolicy, chainEvents,
×
UNCOV
4337
                shouldReestablish, fn.None[lnwire.Shutdown](),
×
UNCOV
4338
        )
×
UNCOV
4339
        if err != nil {
×
4340
                return fmt.Errorf("can't register new channel link(%v) with "+
×
4341
                        "peer", chanPoint)
×
4342
        }
×
UNCOV
4343

×
4344
        return nil
UNCOV
4345
}
×
4346

4347
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
4348
// know this channel ID or not, we'll either add it to the `activeChannels` map
UNCOV
4349
// or init the next revocation for it.
×
UNCOV
4350
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
×
UNCOV
4351
        newChan := req.channel
×
UNCOV
4352
        chanPoint := newChan.FundingOutpoint
×
UNCOV
4353
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
4354

×
UNCOV
4355
        // Only update RemoteNextRevocation if the channel is in the
×
4356
        // activeChannels map and if we added the link to the switch. Only
4357
        // active channels will be added to the switch.
UNCOV
4358
        if p.isActiveChannel(chanID) {
×
4359
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
4360
                        chanPoint)
4361

4362
                // Handle it and close the err chan on the request.
4363
                close(req.err)
4364

4365
                // Update the next revocation point.
4✔
4366
                err := p.updateNextRevocation(newChan.OpenChannel)
4✔
4367
                if err != nil {
4✔
4368
                        p.log.Errorf(err.Error())
4✔
4369
                }
4✔
4370

4✔
4371
                return
4✔
4372
        }
4✔
4373

4✔
4374
        // This is a new channel, we now add it to the map.
5✔
4375
        if err := p.addActiveChannel(req.channel); err != nil {
1✔
4376
                // Log and send back the error to the request.
1✔
4377
                p.log.Errorf(err.Error())
1✔
4378
                req.err <- err
1✔
4379

1✔
4380
                return
4381
        }
4382

4✔
4383
        // Close the err chan if everything went fine.
1✔
4384
        close(req.err)
1✔
4385
}
1✔
4386

1✔
4387
// handleNewPendingChannel takes a `newChannelMsg` request and add it to
1✔
4388
// `activeChannels` map with nil value. This pending channel will be saved as
4389
// it may become active in the future. Once active, the funding manager will
4390
// send it again via `AddNewChannel`, and we'd handle the link creation there.
4391
func (p *Brontide) handleNewPendingChannel(req *newChannelMsg) {
4392
        defer close(req.err)
2✔
4393

2✔
4394
        chanID := req.channelID
4395

4396
        // If we already have this channel, something is wrong with the funding
4397
        // flow as it will only be marked as active after `ChannelReady` is
4398
        // handled. In this case, we will do nothing but log an error, just in
4399
        // case this is a legit channel.
4✔
4400
        if p.isActiveChannel(chanID) {
4✔
4401
                p.log.Errorf("Channel(%v) is already active, ignoring "+
4✔
4402
                        "pending channel request", chanID)
4✔
4403

4✔
4404
                return
4✔
4405
        }
4✔
4406

4✔
4407
        // The channel has already been added, we will do nothing and return.
5✔
4408
        if p.isPendingChannel(chanID) {
1✔
4409
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
4410
                        "pending channel request", chanID)
1✔
4411

1✔
4412
                return
4413
        }
4414

4415
        // This is a new channel, we now add it to the map `activeChannels`
4✔
4416
        // with nil value and mark it as a newly added channel in
1✔
4417
        // `addedChannels`.
1✔
4418
        p.activeChannels.Store(chanID, nil)
4419
        p.addedChannels.Store(chanID, struct{}{})
4420
}
3✔
4421

3✔
4422
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
4423
// from `activeChannels` map. The request will be ignored if the channel is
4424
// considered active by Brontide. Noop if the channel ID cannot be found.
4425
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
UNCOV
4426
        defer close(req.err)
×
UNCOV
4427

×
UNCOV
4428
        chanID := req.channelID
×
UNCOV
4429

×
UNCOV
4430
        // If we already have this channel, something is wrong with the funding
×
UNCOV
4431
        // flow as it will only be marked as active after `ChannelReady` is
×
UNCOV
4432
        // handled. In this case, we will log an error and exit.
×
UNCOV
4433
        if p.isActiveChannel(chanID) {
×
UNCOV
4434
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
×
UNCOV
4435
                        chanID)
×
UNCOV
4436
                return
×
UNCOV
4437
        }
×
UNCOV
4438

×
UNCOV
4439
        // The channel has not been added yet, we will log a warning as there
×
UNCOV
4440
        // is an unexpected call from funding manager.
×
UNCOV
4441
        if !p.isPendingChannel(chanID) {
×
4442
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
4443
        }
4444

4445
        // Remove the record of this pending channel.
UNCOV
4446
        p.activeChannels.Delete(chanID)
×
4447
        p.addedChannels.Delete(chanID)
4448
}
4449

4450
// sendLinkUpdateMsg sends a message that updates the channel to the
4451
// channel's message stream.
4452
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
4453
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
67✔
4454

67✔
UNCOV
4455
        chanStream, ok := p.activeMsgStreams[cid]
×
UNCOV
4456
        if !ok {
×
4457
                // If a stream hasn't yet been created, then we'll do so, add
4458
                // it to the map, and finally start it.
67✔
4459
                chanStream = newChanMsgStream(p, cid)
4460
                p.activeMsgStreams[cid] = chanStream
4461
                chanStream.Start()
4462

4463
                // Stop the stream when quit.
4464
                go func() {
4465
                        <-p.quit
4466
                        chanStream.Stop()
4467
                }()
4468
        }
4469

4470
        // With the stream obtained, add the message to the stream so we can
4471
        // continue processing message.
4472
        chanStream.AddMsg(msg)
4473
}
4474

4475
// scaleTimeout multiplies the argument duration by a constant factor depending
4476
// on variious heuristics. Currently this is only used to check whether our peer
4477
// appears to be connected over Tor and relaxes the timout deadline. However,
4478
// this is subject to change and should be treated as opaque.
4479
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
4480
        if p.isTorConnection {
4481
                return timeout * time.Duration(torTimeoutMultiplier)
4482
        }
4483

4484
        return timeout
4485
}
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