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

lightningnetwork / lnd / 11333802987

14 Oct 2024 07:26PM UTC coverage: 57.859% (-0.9%) from 58.779%
11333802987

Pull #9148

github

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

351 of 627 new or added lines in 12 files covered. (55.98%)

19006 existing lines in 242 files now uncovered.

99279 of 171588 relevant lines covered (57.86%)

36687.28 hits per line

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

37.61
/peer/brontide.go
1
package peer
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

121
        err chan error
122
}
123

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

399
        // AuxResolver is an optional interface that can be used to modify the
400
        // way contracts are resolved.
401
        AuxResolver fn.Option[lnwallet.AuxContractResolver]
402

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

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

414
        // DisallowQuiescence is a flag that indicates whether the Brontide
415
        // should have the quiescence feature disabled.
416
        DisallowQuiescence bool
417

418
        // MaxFeeExposure limits the number of outstanding fees in a channel.
419
        // This value will be passed to created links.
420
        MaxFeeExposure lnwire.MilliSatoshi
421

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

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

431
        // Quit is the server's quit channel. If this is closed, we halt operation.
432
        Quit chan struct{}
433
}
434

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

446
        // MUST be used atomically.
447
        bytesReceived uint64
448
        bytesSent     uint64
449

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

467
        pingManager *PingManager
468

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

476
        cfg Config
477

478
        // activeSignal when closed signals that the peer is now active and
479
        // ready to process messages.
480
        activeSignal chan struct{}
481

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

486
        // sendQueue is the channel which is used to queue outgoing messages to be
487
        // written onto the wire. Note that this channel is unbuffered.
488
        sendQueue chan outgoingMsg
489

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

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

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

513
        // newActiveChannel is used by the fundingManager to send fully opened
514
        // channels to the source peer which handled the funding workflow.
515
        newActiveChannel chan *newChannelMsg
516

517
        // newPendingChannel is used by the fundingManager to send pending open
518
        // channels to the source peer which handled the funding workflow.
519
        newPendingChannel chan *newChannelMsg
520

521
        // removePendingChannel is used by the fundingManager to cancel pending
522
        // open channels to the source peer when the funding flow is failed.
523
        removePendingChannel chan *newChannelMsg
524

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

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

535
        // localCloseChanReqs is a channel in which any local requests to close
536
        // a particular channel are sent over.
537
        localCloseChanReqs chan *htlcswitch.ChanClose
538

539
        // linkFailures receives all reported channel failures from the switch,
540
        // and instructs the channelManager to clean remaining channel state.
541
        linkFailures chan linkFailureReport
542

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

548
        // remoteFeatures is the feature vector received from the peer during
549
        // the connection handshake.
550
        remoteFeatures *lnwire.FeatureVector
551

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

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

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

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

576
        startReady chan struct{}
577
        quit       chan struct{}
578
        wg         sync.WaitGroup
579

580
        // log is a peer-specific logging instance.
581
        log btclog.Logger
582
}
583

584
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer interface.
585
var _ lnpeer.Peer = (*Brontide)(nil)
586

587
// NewBrontide creates a new Brontide from a peer.Config struct.
588
func NewBrontide(cfg Config) *Brontide {
25✔
589
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
25✔
590

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

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

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

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

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

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

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

UNCOV
661
                return lastSerializedBlockHeader[:]
×
662
        }
663

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

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

693
        return p
25✔
694
}
695

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

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

3✔
708
        p.log.Tracef("starting with conn[%v->%v]",
3✔
709
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
3✔
710

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

722
        if len(activeChans) == 0 {
4✔
723
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
1✔
724
        }
1✔
725

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

UNCOV
734
                haveLegacyChan = true
×
UNCOV
735
                break
×
736
        }
737

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

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

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

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

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

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

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

805
        // Register the message router now as we may need to register some
806
        // endpoints while loading the channels below.
807
        p.msgRouter.WhenSome(func(router msgmux.Router) {
6✔
808
                router.Start()
3✔
809
        })
3✔
810

811
        msgs, err := p.loadActiveChannels(activeChans)
3✔
812
        if err != nil {
3✔
813
                return fmt.Errorf("unable to load channels: %w", err)
×
814
        }
×
815

816
        p.startTime = time.Now()
3✔
817

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

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

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

840
        p.wg.Add(4)
3✔
841
        go p.queueHandler()
3✔
842
        go p.writeHandler()
3✔
843
        go p.channelManager()
3✔
844
        go p.readHandler()
3✔
845

3✔
846
        // Signal to any external processes that the peer is now active.
3✔
847
        close(p.activeSignal)
3✔
848

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

3✔
864
        return nil
3✔
865
}
866

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

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

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

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

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

912
// addrWithInternalKey takes a delivery script, then attempts to supplement it
913
// with information related to the internal key for the addr, but only if it's
914
// a taproot addr.
915
func (p *Brontide) addrWithInternalKey(
916
        deliveryScript []byte) (*chancloser.DeliveryAddrWithKey, error) {
9✔
917

9✔
918
        // Currently, custom channels cannot be created with external upfront
9✔
919
        // shutdown addresses, so this shouldn't be an issue. We only require
9✔
920
        // the internal key for taproot addresses to be able to provide a non
9✔
921
        // inclusion proof of any scripts.
9✔
922
        internalKeyDesc, err := lnwallet.InternalKeyForAddr(
9✔
923
                p.cfg.Wallet, &p.cfg.Wallet.Cfg.NetParams, deliveryScript,
9✔
924
        )
9✔
925
        if err != nil {
9✔
926
                return nil, fmt.Errorf("unable to fetch internal key: %w", err)
×
927
        }
×
928

929
        return &chancloser.DeliveryAddrWithKey{
9✔
930
                DeliveryAddress: deliveryScript,
9✔
931
                InternalKey: fn.MapOption(
9✔
932
                        func(desc keychain.KeyDescriptor) btcec.PublicKey {
9✔
UNCOV
933
                                return *desc.PubKey
×
UNCOV
934
                        },
×
935
                )(internalKeyDesc),
936
        }, nil
937
}
938

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

3✔
946
        // Return a slice of messages to send to the peers in case the channel
3✔
947
        // cannot be loaded normally.
3✔
948
        var msgs []lnwire.Message
3✔
949

3✔
950
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
3✔
951

3✔
952
        for _, dbChan := range chans {
5✔
953
                hasScidFeature := dbChan.ChanType.HasScidAliasFeature()
2✔
954
                if scidAliasNegotiated && !hasScidFeature {
2✔
UNCOV
955
                        // We'll request and store an alias, making sure that a
×
UNCOV
956
                        // gossiper mapping is not created for the alias to the
×
UNCOV
957
                        // real SCID. This is done because the peer and funding
×
UNCOV
958
                        // manager are not aware of each other's states and if
×
UNCOV
959
                        // we did not do this, we would accept alias channel
×
UNCOV
960
                        // updates after 6 confirmations, which would be buggy.
×
UNCOV
961
                        // We'll queue a channel_ready message with the new
×
UNCOV
962
                        // alias. This should technically be done *after* the
×
UNCOV
963
                        // reestablish, but this behavior is pre-existing since
×
UNCOV
964
                        // the funding manager may already queue a
×
UNCOV
965
                        // channel_ready before the channel_reestablish.
×
UNCOV
966
                        if !dbChan.IsPending {
×
UNCOV
967
                                aliasScid, err := p.cfg.RequestAlias()
×
UNCOV
968
                                if err != nil {
×
969
                                        return nil, err
×
970
                                }
×
971

UNCOV
972
                                err = p.cfg.AddLocalAlias(
×
UNCOV
973
                                        aliasScid, dbChan.ShortChanID(), false,
×
UNCOV
974
                                        false,
×
UNCOV
975
                                )
×
UNCOV
976
                                if err != nil {
×
977
                                        return nil, err
×
978
                                }
×
979

UNCOV
980
                                chanID := lnwire.NewChanIDFromOutPoint(
×
UNCOV
981
                                        dbChan.FundingOutpoint,
×
UNCOV
982
                                )
×
UNCOV
983

×
UNCOV
984
                                // Fetch the second commitment point to send in
×
UNCOV
985
                                // the channel_ready message.
×
UNCOV
986
                                second, err := dbChan.SecondCommitmentPoint()
×
UNCOV
987
                                if err != nil {
×
988
                                        return nil, err
×
989
                                }
×
990

UNCOV
991
                                channelReadyMsg := lnwire.NewChannelReady(
×
UNCOV
992
                                        chanID, second,
×
UNCOV
993
                                )
×
UNCOV
994
                                channelReadyMsg.AliasScid = &aliasScid
×
UNCOV
995

×
UNCOV
996
                                msgs = append(msgs, channelReadyMsg)
×
997
                        }
998

999
                        // If we've negotiated the option-scid-alias feature
1000
                        // and this channel does not have ScidAliasFeature set
1001
                        // to true due to an upgrade where the feature bit was
1002
                        // turned on, we'll update the channel's database
1003
                        // state.
UNCOV
1004
                        err := dbChan.MarkScidAliasNegotiated()
×
UNCOV
1005
                        if err != nil {
×
1006
                                return nil, err
×
1007
                        }
×
1008
                }
1009

1010
                var chanOpts []lnwallet.ChannelOpt
2✔
1011
                p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
2✔
1012
                        chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
1013
                })
×
1014
                p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
2✔
1015
                        chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
1016
                })
×
1017
                p.cfg.AuxResolver.WhenSome(
2✔
1018
                        func(s lnwallet.AuxContractResolver) {
2✔
1019
                                chanOpts = append(
×
1020
                                        chanOpts, lnwallet.WithAuxResolver(s),
×
1021
                                )
×
1022
                        },
×
1023
                )
1024

1025
                lnChan, err := lnwallet.NewLightningChannel(
2✔
1026
                        p.cfg.Signer, dbChan, p.cfg.SigPool, chanOpts...,
2✔
1027
                )
2✔
1028
                if err != nil {
2✔
1029
                        return nil, fmt.Errorf("unable to create channel "+
×
1030
                                "state machine: %w", err)
×
1031
                }
×
1032

1033
                chanPoint := dbChan.FundingOutpoint
2✔
1034

2✔
1035
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
1036

2✔
1037
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
2✔
1038
                        chanPoint, lnChan.IsPending())
2✔
1039

2✔
1040
                // Skip adding any permanently irreconcilable channels to the
2✔
1041
                // htlcswitch.
2✔
1042
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
2✔
1043
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
4✔
1044

2✔
1045
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
2✔
1046
                                "start.", chanPoint, dbChan.ChanStatus())
2✔
1047

2✔
1048
                        // To help our peer recover from a potential data loss,
2✔
1049
                        // we resend our channel reestablish message if the
2✔
1050
                        // channel is in a borked state. We won't process any
2✔
1051
                        // channel reestablish message sent from the peer, but
2✔
1052
                        // that's okay since the assumption is that we did when
2✔
1053
                        // marking the channel borked.
2✔
1054
                        chanSync, err := dbChan.ChanSyncMsg()
2✔
1055
                        if err != nil {
2✔
1056
                                p.log.Errorf("Unable to create channel "+
×
1057
                                        "reestablish message for channel %v: "+
×
1058
                                        "%v", chanPoint, err)
×
1059
                                continue
×
1060
                        }
1061

1062
                        msgs = append(msgs, chanSync)
2✔
1063

2✔
1064
                        // Check if this channel needs to have the cooperative
2✔
1065
                        // close process restarted. If so, we'll need to send
2✔
1066
                        // the Shutdown message that is returned.
2✔
1067
                        if dbChan.HasChanStatus(
2✔
1068
                                channeldb.ChanStatusCoopBroadcasted,
2✔
1069
                        ) {
2✔
1070

×
1071
                                shutdownMsg, err := p.restartCoopClose(lnChan)
×
1072
                                if err != nil {
×
1073
                                        p.log.Errorf("Unable to restart "+
×
1074
                                                "coop close for channel: %v",
×
1075
                                                err)
×
1076
                                        continue
×
1077
                                }
1078

1079
                                if shutdownMsg == nil {
×
1080
                                        continue
×
1081
                                }
1082

1083
                                // Append the message to the set of messages to
1084
                                // send.
1085
                                msgs = append(msgs, shutdownMsg)
×
1086
                        }
1087

1088
                        continue
2✔
1089
                }
1090

1091
                // Before we register this new link with the HTLC Switch, we'll
1092
                // need to fetch its current link-layer forwarding policy from
1093
                // the database.
UNCOV
1094
                graph := p.cfg.ChannelGraph
×
UNCOV
1095
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
×
UNCOV
1096
                        &chanPoint,
×
UNCOV
1097
                )
×
UNCOV
1098
                if err != nil && !errors.Is(err, channeldb.ErrEdgeNotFound) {
×
1099
                        return nil, err
×
1100
                }
×
1101

1102
                // We'll filter out our policy from the directional channel
1103
                // edges based whom the edge connects to. If it doesn't connect
1104
                // to us, then we know that we were the one that advertised the
1105
                // policy.
1106
                //
1107
                // TODO(roasbeef): can add helper method to get policy for
1108
                // particular channel.
UNCOV
1109
                var selfPolicy *models.ChannelEdgePolicy
×
UNCOV
1110
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
×
UNCOV
1111
                        p.cfg.ServerPubKey[:]) {
×
UNCOV
1112

×
UNCOV
1113
                        selfPolicy = p1
×
UNCOV
1114
                } else {
×
UNCOV
1115
                        selfPolicy = p2
×
UNCOV
1116
                }
×
1117

1118
                // If we don't yet have an advertised routing policy, then
1119
                // we'll use the current default, otherwise we'll translate the
1120
                // routing policy into a forwarding policy.
UNCOV
1121
                var forwardingPolicy *models.ForwardingPolicy
×
UNCOV
1122
                if selfPolicy != nil {
×
UNCOV
1123
                        var inboundWireFee lnwire.Fee
×
UNCOV
1124
                        _, err := selfPolicy.ExtraOpaqueData.ExtractRecords(
×
UNCOV
1125
                                &inboundWireFee,
×
UNCOV
1126
                        )
×
UNCOV
1127
                        if err != nil {
×
1128
                                return nil, err
×
1129
                        }
×
1130

UNCOV
1131
                        inboundFee := models.NewInboundFeeFromWire(
×
UNCOV
1132
                                inboundWireFee,
×
UNCOV
1133
                        )
×
UNCOV
1134

×
UNCOV
1135
                        forwardingPolicy = &models.ForwardingPolicy{
×
UNCOV
1136
                                MinHTLCOut:    selfPolicy.MinHTLC,
×
UNCOV
1137
                                MaxHTLC:       selfPolicy.MaxHTLC,
×
UNCOV
1138
                                BaseFee:       selfPolicy.FeeBaseMSat,
×
UNCOV
1139
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
×
UNCOV
1140
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
×
UNCOV
1141

×
UNCOV
1142
                                InboundFee: inboundFee,
×
UNCOV
1143
                        }
×
UNCOV
1144
                } else {
×
UNCOV
1145
                        p.log.Warnf("Unable to find our forwarding policy "+
×
UNCOV
1146
                                "for channel %v, using default values",
×
UNCOV
1147
                                chanPoint)
×
UNCOV
1148
                        forwardingPolicy = &p.cfg.RoutingPolicy
×
UNCOV
1149
                }
×
1150

UNCOV
1151
                p.log.Tracef("Using link policy of: %v",
×
UNCOV
1152
                        spew.Sdump(forwardingPolicy))
×
UNCOV
1153

×
UNCOV
1154
                // If the channel is pending, set the value to nil in the
×
UNCOV
1155
                // activeChannels map. This is done to signify that the channel
×
UNCOV
1156
                // is pending. We don't add the link to the switch here - it's
×
UNCOV
1157
                // the funding manager's responsibility to spin up pending
×
UNCOV
1158
                // channels. Adding them here would just be extra work as we'll
×
UNCOV
1159
                // tear them down when creating + adding the final link.
×
UNCOV
1160
                if lnChan.IsPending() {
×
UNCOV
1161
                        p.activeChannels.Store(chanID, nil)
×
UNCOV
1162

×
UNCOV
1163
                        continue
×
1164
                }
1165

UNCOV
1166
                shutdownInfo, err := lnChan.State().ShutdownInfo()
×
UNCOV
1167
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
×
1168
                        return nil, err
×
1169
                }
×
1170

UNCOV
1171
                var (
×
UNCOV
1172
                        shutdownMsg     fn.Option[lnwire.Shutdown]
×
UNCOV
1173
                        shutdownInfoErr error
×
UNCOV
1174
                )
×
UNCOV
1175
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
×
UNCOV
1176
                        // Compute an ideal fee.
×
UNCOV
1177
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
UNCOV
1178
                                p.cfg.CoopCloseTargetConfs,
×
UNCOV
1179
                        )
×
UNCOV
1180
                        if err != nil {
×
1181
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1182
                                        "estimate fee: %w", err)
×
1183

×
1184
                                return
×
1185
                        }
×
1186

UNCOV
1187
                        addr, err := p.addrWithInternalKey(
×
UNCOV
1188
                                info.DeliveryScript.Val,
×
UNCOV
1189
                        )
×
UNCOV
1190
                        if err != nil {
×
1191
                                shutdownInfoErr = fmt.Errorf("unable to make "+
×
1192
                                        "delivery addr: %w", err)
×
1193
                                return
×
1194
                        }
×
UNCOV
1195
                        chanCloser, err := p.createChanCloser(
×
UNCOV
1196
                                lnChan, addr, feePerKw, nil, info.Closer(),
×
UNCOV
1197
                        )
×
UNCOV
1198
                        if err != nil {
×
1199
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1200
                                        "create chan closer: %w", err)
×
1201

×
1202
                                return
×
1203
                        }
×
1204

UNCOV
1205
                        chanID := lnwire.NewChanIDFromOutPoint(
×
UNCOV
1206
                                lnChan.State().FundingOutpoint,
×
UNCOV
1207
                        )
×
UNCOV
1208

×
UNCOV
1209
                        p.activeChanCloses[chanID] = chanCloser
×
UNCOV
1210

×
UNCOV
1211
                        // Create the Shutdown message.
×
UNCOV
1212
                        shutdown, err := chanCloser.ShutdownChan()
×
UNCOV
1213
                        if err != nil {
×
1214
                                delete(p.activeChanCloses, chanID)
×
1215
                                shutdownInfoErr = err
×
1216

×
1217
                                return
×
1218
                        }
×
1219

UNCOV
1220
                        shutdownMsg = fn.Some(*shutdown)
×
1221
                })
UNCOV
1222
                if shutdownInfoErr != nil {
×
1223
                        return nil, shutdownInfoErr
×
1224
                }
×
1225

1226
                // Subscribe to the set of on-chain events for this channel.
UNCOV
1227
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
×
UNCOV
1228
                        chanPoint,
×
UNCOV
1229
                )
×
UNCOV
1230
                if err != nil {
×
1231
                        return nil, err
×
1232
                }
×
1233

UNCOV
1234
                err = p.addLink(
×
UNCOV
1235
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
×
UNCOV
1236
                        true, shutdownMsg,
×
UNCOV
1237
                )
×
UNCOV
1238
                if err != nil {
×
1239
                        return nil, fmt.Errorf("unable to add link %v to "+
×
1240
                                "switch: %v", chanPoint, err)
×
1241
                }
×
1242

UNCOV
1243
                p.activeChannels.Store(chanID, lnChan)
×
1244
        }
1245

1246
        return msgs, nil
3✔
1247
}
1248

1249
// addLink creates and adds a new ChannelLink from the specified channel.
1250
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1251
        lnChan *lnwallet.LightningChannel,
1252
        forwardingPolicy *models.ForwardingPolicy,
1253
        chainEvents *contractcourt.ChainEventSubscription,
UNCOV
1254
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
×
UNCOV
1255

×
UNCOV
1256
        // onChannelFailure will be called by the link in case the channel
×
UNCOV
1257
        // fails for some reason.
×
UNCOV
1258
        onChannelFailure := func(chanID lnwire.ChannelID,
×
UNCOV
1259
                shortChanID lnwire.ShortChannelID,
×
UNCOV
1260
                linkErr htlcswitch.LinkFailureError) {
×
UNCOV
1261

×
UNCOV
1262
                failure := linkFailureReport{
×
UNCOV
1263
                        chanPoint:   *chanPoint,
×
UNCOV
1264
                        chanID:      chanID,
×
UNCOV
1265
                        shortChanID: shortChanID,
×
UNCOV
1266
                        linkErr:     linkErr,
×
UNCOV
1267
                }
×
UNCOV
1268

×
UNCOV
1269
                select {
×
UNCOV
1270
                case p.linkFailures <- failure:
×
1271
                case <-p.quit:
×
1272
                case <-p.cfg.Quit:
×
1273
                }
1274
        }
1275

UNCOV
1276
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
×
UNCOV
1277
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
×
UNCOV
1278
        }
×
1279

UNCOV
1280
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
×
UNCOV
1281
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
×
UNCOV
1282
        }
×
1283

1284
        //nolint:lll
UNCOV
1285
        linkCfg := htlcswitch.ChannelLinkConfig{
×
UNCOV
1286
                Peer:                   p,
×
UNCOV
1287
                DecodeHopIterators:     p.cfg.Sphinx.DecodeHopIterators,
×
UNCOV
1288
                ExtractErrorEncrypter:  p.cfg.Sphinx.ExtractErrorEncrypter,
×
UNCOV
1289
                FetchLastChannelUpdate: p.cfg.FetchLastChanUpdate,
×
UNCOV
1290
                HodlMask:               p.cfg.Hodl.Mask(),
×
UNCOV
1291
                Registry:               p.cfg.Invoices,
×
UNCOV
1292
                BestHeight:             p.cfg.Switch.BestHeight,
×
UNCOV
1293
                Circuits:               p.cfg.Switch.CircuitModifier(),
×
UNCOV
1294
                ForwardPackets:         p.cfg.InterceptSwitch.ForwardPackets,
×
UNCOV
1295
                FwrdingPolicy:          *forwardingPolicy,
×
UNCOV
1296
                FeeEstimator:           p.cfg.FeeEstimator,
×
UNCOV
1297
                PreimageCache:          p.cfg.WitnessBeacon,
×
UNCOV
1298
                ChainEvents:            chainEvents,
×
UNCOV
1299
                UpdateContractSignals:  updateContractSignals,
×
UNCOV
1300
                NotifyContractUpdate:   notifyContractUpdate,
×
UNCOV
1301
                OnChannelFailure:       onChannelFailure,
×
UNCOV
1302
                SyncStates:             syncStates,
×
UNCOV
1303
                BatchTicker:            ticker.New(p.cfg.ChannelCommitInterval),
×
UNCOV
1304
                FwdPkgGCTicker:         ticker.New(time.Hour),
×
UNCOV
1305
                PendingCommitTicker: ticker.New(
×
UNCOV
1306
                        p.cfg.PendingCommitInterval,
×
UNCOV
1307
                ),
×
UNCOV
1308
                BatchSize:               p.cfg.ChannelCommitBatchSize,
×
UNCOV
1309
                UnsafeReplay:            p.cfg.UnsafeReplay,
×
UNCOV
1310
                MinUpdateTimeout:        htlcswitch.DefaultMinLinkFeeUpdateTimeout,
×
UNCOV
1311
                MaxUpdateTimeout:        htlcswitch.DefaultMaxLinkFeeUpdateTimeout,
×
UNCOV
1312
                OutgoingCltvRejectDelta: p.cfg.OutgoingCltvRejectDelta,
×
UNCOV
1313
                TowerClient:             p.cfg.TowerClient,
×
UNCOV
1314
                MaxOutgoingCltvExpiry:   p.cfg.MaxOutgoingCltvExpiry,
×
UNCOV
1315
                MaxFeeAllocation:        p.cfg.MaxChannelFeeAllocation,
×
UNCOV
1316
                MaxAnchorsCommitFeeRate: p.cfg.MaxAnchorsCommitFeeRate,
×
UNCOV
1317
                NotifyActiveLink:        p.cfg.ChannelNotifier.NotifyActiveLinkEvent,
×
UNCOV
1318
                NotifyActiveChannel:     p.cfg.ChannelNotifier.NotifyActiveChannelEvent,
×
UNCOV
1319
                NotifyInactiveChannel:   p.cfg.ChannelNotifier.NotifyInactiveChannelEvent,
×
UNCOV
1320
                NotifyInactiveLinkEvent: p.cfg.ChannelNotifier.NotifyInactiveLinkEvent,
×
UNCOV
1321
                HtlcNotifier:            p.cfg.HtlcNotifier,
×
UNCOV
1322
                GetAliases:              p.cfg.GetAliases,
×
UNCOV
1323
                PreviouslySentShutdown:  shutdownMsg,
×
UNCOV
1324
                DisallowRouteBlinding:   p.cfg.DisallowRouteBlinding,
×
NEW
1325
                DisallowQuiescence: p.cfg.DisallowQuiescence ||
×
NEW
1326
                        !p.remoteFeatures.HasFeature(lnwire.QuiescenceOptional),
×
UNCOV
1327
                MaxFeeExposure:          p.cfg.MaxFeeExposure,
×
UNCOV
1328
        }
×
UNCOV
1329

×
UNCOV
1330
        // Before adding our new link, purge the switch of any pending or live
×
UNCOV
1331
        // links going by the same channel id. If one is found, we'll shut it
×
UNCOV
1332
        // down to ensure that the mailboxes are only ever under the control of
×
UNCOV
1333
        // one link.
×
UNCOV
1334
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
×
UNCOV
1335
        p.cfg.Switch.RemoveLink(chanID)
×
UNCOV
1336

×
UNCOV
1337
        // With the channel link created, we'll now notify the htlc switch so
×
UNCOV
1338
        // this channel can be used to dispatch local payments and also
×
UNCOV
1339
        // passively forward payments.
×
UNCOV
1340
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
×
1341
}
1342

1343
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1344
// one confirmed public channel exists with them.
1345
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
3✔
1346
        defer p.wg.Done()
3✔
1347

3✔
1348
        hasConfirmedPublicChan := false
3✔
1349
        for _, channel := range channels {
5✔
1350
                if channel.IsPending {
2✔
UNCOV
1351
                        continue
×
1352
                }
1353
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
4✔
1354
                        continue
2✔
1355
                }
1356

UNCOV
1357
                hasConfirmedPublicChan = true
×
UNCOV
1358
                break
×
1359
        }
1360
        if !hasConfirmedPublicChan {
6✔
1361
                return
3✔
1362
        }
3✔
1363

UNCOV
1364
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
×
UNCOV
1365
        if err != nil {
×
1366
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1367
                return
×
1368
        }
×
1369

UNCOV
1370
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
×
1371
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1372
        }
×
1373
}
1374

1375
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1376
// have any active channels with them.
1377
func (p *Brontide) maybeSendChannelUpdates() {
3✔
1378
        defer p.wg.Done()
3✔
1379

3✔
1380
        // If we don't have any active channels, then we can exit early.
3✔
1381
        if p.activeChannels.Len() == 0 {
4✔
1382
                return
1✔
1383
        }
1✔
1384

1385
        maybeSendUpd := func(cid lnwire.ChannelID,
2✔
1386
                lnChan *lnwallet.LightningChannel) error {
4✔
1387

2✔
1388
                // Nil channels are pending, so we'll skip them.
2✔
1389
                if lnChan == nil {
2✔
UNCOV
1390
                        return nil
×
UNCOV
1391
                }
×
1392

1393
                dbChan := lnChan.State()
2✔
1394
                scid := func() lnwire.ShortChannelID {
4✔
1395
                        switch {
2✔
1396
                        // Otherwise if it's a zero conf channel and confirmed,
1397
                        // then we need to use the "real" scid.
UNCOV
1398
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
×
UNCOV
1399
                                return dbChan.ZeroConfRealScid()
×
1400

1401
                        // Otherwise, we can use the normal scid.
1402
                        default:
2✔
1403
                                return dbChan.ShortChanID()
2✔
1404
                        }
1405
                }()
1406

1407
                // Now that we know the channel is in a good state, we'll try
1408
                // to fetch the update to send to the remote peer. If the
1409
                // channel is pending, and not a zero conf channel, we'll get
1410
                // an error here which we'll ignore.
1411
                chanUpd, err := p.cfg.FetchLastChanUpdate(scid)
2✔
1412
                if err != nil {
2✔
UNCOV
1413
                        p.log.Debugf("Unable to fetch channel update for "+
×
UNCOV
1414
                                "ChannelPoint(%v), scid=%v: %v",
×
UNCOV
1415
                                dbChan.FundingOutpoint, dbChan.ShortChanID, err)
×
UNCOV
1416

×
UNCOV
1417
                        return nil
×
UNCOV
1418
                }
×
1419

1420
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
2✔
1421
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
2✔
1422

2✔
1423
                // We'll send it as a normal message instead of using the lazy
2✔
1424
                // queue to prioritize transmission of the fresh update.
2✔
1425
                if err := p.SendMessage(false, chanUpd); err != nil {
2✔
1426
                        err := fmt.Errorf("unable to send channel update for "+
×
1427
                                "ChannelPoint(%v), scid=%v: %w",
×
1428
                                dbChan.FundingOutpoint, dbChan.ShortChanID(),
×
1429
                                err)
×
1430
                        p.log.Errorf(err.Error())
×
1431

×
1432
                        return err
×
1433
                }
×
1434

1435
                return nil
2✔
1436
        }
1437

1438
        p.activeChannels.ForEach(maybeSendUpd)
2✔
1439
}
1440

1441
// WaitForDisconnect waits until the peer has disconnected. A peer may be
1442
// disconnected if the local or remote side terminates the connection, or an
1443
// irrecoverable protocol error has been encountered. This method will only
1444
// begin watching the peer's waitgroup after the ready channel or the peer's
1445
// quit channel are signaled. The ready channel should only be signaled if a
1446
// call to Start returns no error. Otherwise, if the peer fails to start,
1447
// calling Disconnect will signal the quit channel and the method will not
1448
// block, since no goroutines were spawned.
UNCOV
1449
func (p *Brontide) WaitForDisconnect(ready chan struct{}) {
×
UNCOV
1450
        // Before we try to call the `Wait` goroutine, we'll make sure the main
×
UNCOV
1451
        // set of goroutines are already active.
×
UNCOV
1452
        select {
×
UNCOV
1453
        case <-p.startReady:
×
1454
        case <-p.quit:
×
1455
                return
×
1456
        }
1457

UNCOV
1458
        select {
×
UNCOV
1459
        case <-ready:
×
UNCOV
1460
        case <-p.quit:
×
1461
        }
1462

UNCOV
1463
        p.wg.Wait()
×
1464
}
1465

1466
// Disconnect terminates the connection with the remote peer. Additionally, a
1467
// signal is sent to the server and htlcSwitch indicating the resources
1468
// allocated to the peer can now be cleaned up.
UNCOV
1469
func (p *Brontide) Disconnect(reason error) {
×
UNCOV
1470
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
×
UNCOV
1471
                return
×
UNCOV
1472
        }
×
1473

1474
        // Make sure initialization has completed before we try to tear things
1475
        // down.
UNCOV
1476
        select {
×
UNCOV
1477
        case <-p.startReady:
×
1478
        case <-p.quit:
×
1479
                return
×
1480
        }
1481

UNCOV
1482
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
×
UNCOV
1483
        p.storeError(err)
×
UNCOV
1484

×
UNCOV
1485
        p.log.Infof(err.Error())
×
UNCOV
1486

×
UNCOV
1487
        // Stop PingManager before closing TCP connection.
×
UNCOV
1488
        p.pingManager.Stop()
×
UNCOV
1489

×
UNCOV
1490
        // Ensure that the TCP connection is properly closed before continuing.
×
UNCOV
1491
        p.cfg.Conn.Close()
×
UNCOV
1492

×
UNCOV
1493
        close(p.quit)
×
UNCOV
1494

×
UNCOV
1495
        // If our msg router isn't global (local to this instance), then we'll
×
UNCOV
1496
        // stop it. Otherwise, we'll leave it running.
×
UNCOV
1497
        if !p.globalMsgRouter {
×
UNCOV
1498
                p.msgRouter.WhenSome(func(router msgmux.Router) {
×
UNCOV
1499
                        router.Stop()
×
UNCOV
1500
                })
×
1501
        }
1502
}
1503

1504
// String returns the string representation of this peer.
UNCOV
1505
func (p *Brontide) String() string {
×
UNCOV
1506
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
×
UNCOV
1507
}
×
1508

1509
// readNextMessage reads, and returns the next message on the wire along with
1510
// any additional raw payload.
1511
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
7✔
1512
        noiseConn := p.cfg.Conn
7✔
1513
        err := noiseConn.SetReadDeadline(time.Time{})
7✔
1514
        if err != nil {
7✔
1515
                return nil, err
×
1516
        }
×
1517

1518
        pktLen, err := noiseConn.ReadNextHeader()
7✔
1519
        if err != nil {
7✔
UNCOV
1520
                return nil, fmt.Errorf("read next header: %w", err)
×
UNCOV
1521
        }
×
1522

1523
        // First we'll read the next _full_ message. We do this rather than
1524
        // reading incrementally from the stream as the Lightning wire protocol
1525
        // is message oriented and allows nodes to pad on additional data to
1526
        // the message stream.
1527
        var (
4✔
1528
                nextMsg lnwire.Message
4✔
1529
                msgLen  uint64
4✔
1530
        )
4✔
1531
        err = p.cfg.ReadPool.Submit(func(buf *buffer.Read) error {
8✔
1532
                // Before reading the body of the message, set the read timeout
4✔
1533
                // accordingly to ensure we don't block other readers using the
4✔
1534
                // pool. We do so only after the task has been scheduled to
4✔
1535
                // ensure the deadline doesn't expire while the message is in
4✔
1536
                // the process of being scheduled.
4✔
1537
                readDeadline := time.Now().Add(
4✔
1538
                        p.scaleTimeout(readMessageTimeout),
4✔
1539
                )
4✔
1540
                readErr := noiseConn.SetReadDeadline(readDeadline)
4✔
1541
                if readErr != nil {
4✔
1542
                        return readErr
×
1543
                }
×
1544

1545
                // The ReadNextBody method will actually end up re-using the
1546
                // buffer, so within this closure, we can continue to use
1547
                // rawMsg as it's just a slice into the buf from the buffer
1548
                // pool.
1549
                rawMsg, readErr := noiseConn.ReadNextBody(buf[:pktLen])
4✔
1550
                if readErr != nil {
4✔
1551
                        return fmt.Errorf("read next body: %w", readErr)
×
1552
                }
×
1553
                msgLen = uint64(len(rawMsg))
4✔
1554

4✔
1555
                // Next, create a new io.Reader implementation from the raw
4✔
1556
                // message, and use this to decode the message directly from.
4✔
1557
                msgReader := bytes.NewReader(rawMsg)
4✔
1558
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
4✔
1559
                if err != nil {
4✔
UNCOV
1560
                        return err
×
UNCOV
1561
                }
×
1562

1563
                // At this point, rawMsg and buf will be returned back to the
1564
                // buffer pool for re-use.
1565
                return nil
4✔
1566
        })
1567
        atomic.AddUint64(&p.bytesReceived, msgLen)
4✔
1568
        if err != nil {
4✔
UNCOV
1569
                return nil, err
×
UNCOV
1570
        }
×
1571

1572
        p.logWireMessage(nextMsg, true)
4✔
1573

4✔
1574
        return nextMsg, nil
4✔
1575
}
1576

1577
// msgStream implements a goroutine-safe, in-order stream of messages to be
1578
// delivered via closure to a receiver. These messages MUST be in order due to
1579
// the nature of the lightning channel commitment and gossiper state machines.
1580
// TODO(conner): use stream handler interface to abstract out stream
1581
// state/logging.
1582
type msgStream struct {
1583
        streamShutdown int32 // To be used atomically.
1584

1585
        peer *Brontide
1586

1587
        apply func(lnwire.Message)
1588

1589
        startMsg string
1590
        stopMsg  string
1591

1592
        msgCond *sync.Cond
1593
        msgs    []lnwire.Message
1594

1595
        mtx sync.Mutex
1596

1597
        producerSema chan struct{}
1598

1599
        wg   sync.WaitGroup
1600
        quit chan struct{}
1601
}
1602

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

3✔
1611
        stream := &msgStream{
3✔
1612
                peer:         p,
3✔
1613
                apply:        apply,
3✔
1614
                startMsg:     startMsg,
3✔
1615
                stopMsg:      stopMsg,
3✔
1616
                producerSema: make(chan struct{}, bufSize),
3✔
1617
                quit:         make(chan struct{}),
3✔
1618
        }
3✔
1619
        stream.msgCond = sync.NewCond(&stream.mtx)
3✔
1620

3✔
1621
        // Before we return the active stream, we'll populate the producer's
3✔
1622
        // semaphore channel. We'll use this to ensure that the producer won't
3✔
1623
        // attempt to allocate memory in the queue for an item until it has
3✔
1624
        // sufficient extra space.
3✔
1625
        for i := uint32(0); i < bufSize; i++ {
3,003✔
1626
                stream.producerSema <- struct{}{}
3,000✔
1627
        }
3,000✔
1628

1629
        return stream
3✔
1630
}
1631

1632
// Start starts the chanMsgStream.
1633
func (ms *msgStream) Start() {
3✔
1634
        ms.wg.Add(1)
3✔
1635
        go ms.msgConsumer()
3✔
1636
}
3✔
1637

1638
// Stop stops the chanMsgStream.
UNCOV
1639
func (ms *msgStream) Stop() {
×
UNCOV
1640
        // TODO(roasbeef): signal too?
×
UNCOV
1641

×
UNCOV
1642
        close(ms.quit)
×
UNCOV
1643

×
UNCOV
1644
        // Now that we've closed the channel, we'll repeatedly signal the msg
×
UNCOV
1645
        // consumer until we've detected that it has exited.
×
UNCOV
1646
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
×
UNCOV
1647
                ms.msgCond.Signal()
×
UNCOV
1648
                time.Sleep(time.Millisecond * 100)
×
UNCOV
1649
        }
×
1650

UNCOV
1651
        ms.wg.Wait()
×
1652
}
1653

1654
// msgConsumer is the main goroutine that streams messages from the peer's
1655
// readHandler directly to the target channel.
1656
func (ms *msgStream) msgConsumer() {
3✔
1657
        defer ms.wg.Done()
3✔
1658
        defer peerLog.Tracef(ms.stopMsg)
3✔
1659
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
3✔
1660

3✔
1661
        peerLog.Tracef(ms.startMsg)
3✔
1662

3✔
1663
        for {
6✔
1664
                // First, we'll check our condition. If the queue of messages
3✔
1665
                // is empty, then we'll wait until a new item is added.
3✔
1666
                ms.msgCond.L.Lock()
3✔
1667
                for len(ms.msgs) == 0 {
6✔
1668
                        ms.msgCond.Wait()
3✔
1669

3✔
1670
                        // If we woke up in order to exit, then we'll do so.
3✔
1671
                        // Otherwise, we'll check the message queue for any new
3✔
1672
                        // items.
3✔
1673
                        select {
3✔
UNCOV
1674
                        case <-ms.peer.quit:
×
UNCOV
1675
                                ms.msgCond.L.Unlock()
×
UNCOV
1676
                                return
×
UNCOV
1677
                        case <-ms.quit:
×
UNCOV
1678
                                ms.msgCond.L.Unlock()
×
UNCOV
1679
                                return
×
UNCOV
1680
                        default:
×
1681
                        }
1682
                }
1683

1684
                // Grab the message off the front of the queue, shifting the
1685
                // slice's reference down one in order to remove the message
1686
                // from the queue.
UNCOV
1687
                msg := ms.msgs[0]
×
UNCOV
1688
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
×
UNCOV
1689
                ms.msgs = ms.msgs[1:]
×
UNCOV
1690

×
UNCOV
1691
                ms.msgCond.L.Unlock()
×
UNCOV
1692

×
UNCOV
1693
                ms.apply(msg)
×
UNCOV
1694

×
UNCOV
1695
                // We've just successfully processed an item, so we'll signal
×
UNCOV
1696
                // to the producer that a new slot in the buffer. We'll use
×
UNCOV
1697
                // this to bound the size of the buffer to avoid allowing it to
×
UNCOV
1698
                // grow indefinitely.
×
UNCOV
1699
                select {
×
UNCOV
1700
                case ms.producerSema <- struct{}{}:
×
UNCOV
1701
                case <-ms.peer.quit:
×
UNCOV
1702
                        return
×
UNCOV
1703
                case <-ms.quit:
×
UNCOV
1704
                        return
×
1705
                }
1706
        }
1707
}
1708

1709
// AddMsg adds a new message to the msgStream. This function is safe for
1710
// concurrent access.
UNCOV
1711
func (ms *msgStream) AddMsg(msg lnwire.Message) {
×
UNCOV
1712
        // First, we'll attempt to receive from the producerSema struct. This
×
UNCOV
1713
        // acts as a semaphore to prevent us from indefinitely buffering
×
UNCOV
1714
        // incoming items from the wire. Either the msg queue isn't full, and
×
UNCOV
1715
        // we'll not block, or the queue is full, and we'll block until either
×
UNCOV
1716
        // we're signalled to quit, or a slot is freed up.
×
UNCOV
1717
        select {
×
UNCOV
1718
        case <-ms.producerSema:
×
1719
        case <-ms.peer.quit:
×
1720
                return
×
1721
        case <-ms.quit:
×
1722
                return
×
1723
        }
1724

1725
        // Next, we'll lock the condition, and add the message to the end of
1726
        // the message queue.
UNCOV
1727
        ms.msgCond.L.Lock()
×
UNCOV
1728
        ms.msgs = append(ms.msgs, msg)
×
UNCOV
1729
        ms.msgCond.L.Unlock()
×
UNCOV
1730

×
UNCOV
1731
        // With the message added, we signal to the msgConsumer that there are
×
UNCOV
1732
        // additional messages to consume.
×
UNCOV
1733
        ms.msgCond.Signal()
×
1734
}
1735

1736
// waitUntilLinkActive waits until the target link is active and returns a
1737
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1738
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1739
func waitUntilLinkActive(p *Brontide,
UNCOV
1740
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
×
UNCOV
1741

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

×
UNCOV
1744
        // Subscribe to receive channel events.
×
UNCOV
1745
        //
×
UNCOV
1746
        // NOTE: If the link is already active by SubscribeChannelEvents, then
×
UNCOV
1747
        // GetLink will retrieve the link and we can send messages. If the link
×
UNCOV
1748
        // becomes active between SubscribeChannelEvents and GetLink, then GetLink
×
UNCOV
1749
        // will retrieve the link. If the link becomes active after GetLink, then
×
UNCOV
1750
        // we will get an ActiveLinkEvent notification and retrieve the link. If
×
UNCOV
1751
        // the call to GetLink is before SubscribeChannelEvents, however, there
×
UNCOV
1752
        // will be a race condition.
×
UNCOV
1753
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
×
UNCOV
1754
        if err != nil {
×
UNCOV
1755
                // If we have a non-nil error, then the server is shutting down and we
×
UNCOV
1756
                // can exit here and return nil. This means no message will be delivered
×
UNCOV
1757
                // to the link.
×
UNCOV
1758
                return nil
×
UNCOV
1759
        }
×
UNCOV
1760
        defer sub.Cancel()
×
UNCOV
1761

×
UNCOV
1762
        // The link may already be active by this point, and we may have missed the
×
UNCOV
1763
        // ActiveLinkEvent. Check if the link exists.
×
UNCOV
1764
        link := p.fetchLinkFromKeyAndCid(cid)
×
UNCOV
1765
        if link != nil {
×
UNCOV
1766
                return link
×
UNCOV
1767
        }
×
1768

1769
        // If the link is nil, we must wait for it to be active.
UNCOV
1770
        for {
×
UNCOV
1771
                select {
×
1772
                // A new event has been sent by the ChannelNotifier. We first check
1773
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1774
                // that the event is for this channel. Otherwise, we discard the
1775
                // message.
UNCOV
1776
                case e := <-sub.Updates():
×
UNCOV
1777
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
×
UNCOV
1778
                        if !ok {
×
UNCOV
1779
                                // Ignore this notification.
×
UNCOV
1780
                                continue
×
1781
                        }
1782

UNCOV
1783
                        chanPoint := event.ChannelPoint
×
UNCOV
1784

×
UNCOV
1785
                        // Check whether the retrieved chanPoint matches the target
×
UNCOV
1786
                        // channel id.
×
UNCOV
1787
                        if !cid.IsChanPoint(chanPoint) {
×
1788
                                continue
×
1789
                        }
1790

1791
                        // The link shouldn't be nil as we received an
1792
                        // ActiveLinkEvent. If it is nil, we return nil and the
1793
                        // calling function should catch it.
UNCOV
1794
                        return p.fetchLinkFromKeyAndCid(cid)
×
1795

UNCOV
1796
                case <-p.quit:
×
UNCOV
1797
                        return nil
×
1798
                }
1799
        }
1800
}
1801

1802
// newChanMsgStream is used to create a msgStream between the peer and
1803
// particular channel link in the htlcswitch. We utilize additional
1804
// synchronization with the fundingManager to ensure we don't attempt to
1805
// dispatch a message to a channel before it is fully active. A reference to the
1806
// channel this stream forwards to is held in scope to prevent unnecessary
1807
// lookups.
UNCOV
1808
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
×
UNCOV
1809
        var chanLink htlcswitch.ChannelUpdateHandler
×
UNCOV
1810

×
UNCOV
1811
        apply := func(msg lnwire.Message) {
×
UNCOV
1812
                // This check is fine because if the link no longer exists, it will
×
UNCOV
1813
                // be removed from the activeChannels map and subsequent messages
×
UNCOV
1814
                // shouldn't reach the chan msg stream.
×
UNCOV
1815
                if chanLink == nil {
×
UNCOV
1816
                        chanLink = waitUntilLinkActive(p, cid)
×
UNCOV
1817

×
UNCOV
1818
                        // If the link is still not active and the calling function
×
UNCOV
1819
                        // errored out, just return.
×
UNCOV
1820
                        if chanLink == nil {
×
UNCOV
1821
                                p.log.Warnf("Link=%v is not active")
×
UNCOV
1822
                                return
×
UNCOV
1823
                        }
×
1824
                }
1825

1826
                // In order to avoid unnecessarily delivering message
1827
                // as the peer is exiting, we'll check quickly to see
1828
                // if we need to exit.
UNCOV
1829
                select {
×
1830
                case <-p.quit:
×
1831
                        return
×
UNCOV
1832
                default:
×
1833
                }
1834

UNCOV
1835
                chanLink.HandleChannelUpdate(msg)
×
1836
        }
1837

UNCOV
1838
        return newMsgStream(p,
×
UNCOV
1839
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
×
UNCOV
1840
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
×
UNCOV
1841
                1000,
×
UNCOV
1842
                apply,
×
UNCOV
1843
        )
×
1844
}
1845

1846
// newDiscMsgStream is used to setup a msgStream between the peer and the
1847
// authenticated gossiper. This stream should be used to forward all remote
1848
// channel announcements.
1849
func newDiscMsgStream(p *Brontide) *msgStream {
3✔
1850
        apply := func(msg lnwire.Message) {
3✔
UNCOV
1851
                // TODO(yy): `ProcessRemoteAnnouncement` returns an error chan
×
UNCOV
1852
                // and we need to process it.
×
UNCOV
1853
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(msg, p)
×
UNCOV
1854
        }
×
1855

1856
        return newMsgStream(
3✔
1857
                p,
3✔
1858
                "Update stream for gossiper created",
3✔
1859
                "Update stream for gossiper exited",
3✔
1860
                1000,
3✔
1861
                apply,
3✔
1862
        )
3✔
1863
}
1864

1865
// readHandler is responsible for reading messages off the wire in series, then
1866
// properly dispatching the handling of the message to the proper subsystem.
1867
//
1868
// NOTE: This method MUST be run as a goroutine.
1869
func (p *Brontide) readHandler() {
3✔
1870
        defer p.wg.Done()
3✔
1871

3✔
1872
        // We'll stop the timer after a new messages is received, and also
3✔
1873
        // reset it after we process the next message.
3✔
1874
        idleTimer := time.AfterFunc(idleTimeout, func() {
3✔
1875
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
1876
                        p, idleTimeout)
×
1877
                p.Disconnect(err)
×
1878
        })
×
1879

1880
        // Initialize our negotiated gossip sync method before reading messages
1881
        // off the wire. When using gossip queries, this ensures a gossip
1882
        // syncer is active by the time query messages arrive.
1883
        //
1884
        // TODO(conner): have peer store gossip syncer directly and bypass
1885
        // gossiper?
1886
        p.initGossipSync()
3✔
1887

3✔
1888
        discStream := newDiscMsgStream(p)
3✔
1889
        discStream.Start()
3✔
1890
        defer discStream.Stop()
3✔
1891
out:
3✔
1892
        for atomic.LoadInt32(&p.disconnect) == 0 {
7✔
1893
                nextMsg, err := p.readNextMessage()
4✔
1894
                if !idleTimer.Stop() {
4✔
1895
                        select {
×
1896
                        case <-idleTimer.C:
×
1897
                        default:
×
1898
                        }
1899
                }
1900
                if err != nil {
1✔
UNCOV
1901
                        p.log.Infof("unable to read message from peer: %v", err)
×
UNCOV
1902

×
UNCOV
1903
                        // If we could not read our peer's message due to an
×
UNCOV
1904
                        // unknown type or invalid alias, we continue processing
×
UNCOV
1905
                        // as normal. We store unknown message and address
×
UNCOV
1906
                        // types, as they may provide debugging insight.
×
UNCOV
1907
                        switch e := err.(type) {
×
1908
                        // If this is just a message we don't yet recognize,
1909
                        // we'll continue processing as normal as this allows
1910
                        // us to introduce new messages in a forwards
1911
                        // compatible manner.
UNCOV
1912
                        case *lnwire.UnknownMessage:
×
UNCOV
1913
                                p.storeError(e)
×
UNCOV
1914
                                idleTimer.Reset(idleTimeout)
×
UNCOV
1915
                                continue
×
1916

1917
                        // If they sent us an address type that we don't yet
1918
                        // know of, then this isn't a wire error, so we'll
1919
                        // simply continue parsing the remainder of their
1920
                        // messages.
1921
                        case *lnwire.ErrUnknownAddrType:
×
1922
                                p.storeError(e)
×
1923
                                idleTimer.Reset(idleTimeout)
×
1924
                                continue
×
1925

1926
                        // If the NodeAnnouncement has an invalid alias, then
1927
                        // we'll log that error above and continue so we can
1928
                        // continue to read messages from the peer. We do not
1929
                        // store this error because it is of little debugging
1930
                        // value.
1931
                        case *lnwire.ErrInvalidNodeAlias:
×
1932
                                idleTimer.Reset(idleTimeout)
×
1933
                                continue
×
1934

1935
                        // If the error we encountered wasn't just a message we
1936
                        // didn't recognize, then we'll stop all processing as
1937
                        // this is a fatal error.
UNCOV
1938
                        default:
×
UNCOV
1939
                                break out
×
1940
                        }
1941
                }
1942

1943
                // If a message router is active, then we'll try to have it
1944
                // handle this message. If it can, then we're able to skip the
1945
                // rest of the message handling logic.
1946
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
2✔
1947
                        return r.RouteMsg(msgmux.PeerMsg{
1✔
1948
                                PeerPub: *p.IdentityKey(),
1✔
1949
                                Message: nextMsg,
1✔
1950
                        })
1✔
1951
                })
1✔
1952

1953
                // No error occurred, and the message was handled by the
1954
                // router.
1955
                if err == nil {
1✔
1956
                        continue
×
1957
                }
1958

1959
                var (
1✔
1960
                        targetChan   lnwire.ChannelID
1✔
1961
                        isLinkUpdate bool
1✔
1962
                )
1✔
1963

1✔
1964
                switch msg := nextMsg.(type) {
1✔
UNCOV
1965
                case *lnwire.Pong:
×
UNCOV
1966
                        // When we receive a Pong message in response to our
×
UNCOV
1967
                        // last ping message, we send it to the pingManager
×
UNCOV
1968
                        p.pingManager.ReceivedPong(msg)
×
1969

UNCOV
1970
                case *lnwire.Ping:
×
UNCOV
1971
                        // First, we'll store their latest ping payload within
×
UNCOV
1972
                        // the relevant atomic variable.
×
UNCOV
1973
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
UNCOV
1974

×
UNCOV
1975
                        // Next, we'll send over the amount of specified pong
×
UNCOV
1976
                        // bytes.
×
UNCOV
1977
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
×
UNCOV
1978
                        p.queueMsg(pong, nil)
×
1979

1980
                case *lnwire.OpenChannel,
1981
                        *lnwire.AcceptChannel,
1982
                        *lnwire.FundingCreated,
1983
                        *lnwire.FundingSigned,
UNCOV
1984
                        *lnwire.ChannelReady:
×
UNCOV
1985

×
UNCOV
1986
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
×
1987

UNCOV
1988
                case *lnwire.Shutdown:
×
UNCOV
1989
                        select {
×
UNCOV
1990
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
×
1991
                        case <-p.quit:
×
1992
                                break out
×
1993
                        }
UNCOV
1994
                case *lnwire.ClosingSigned:
×
UNCOV
1995
                        select {
×
UNCOV
1996
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
×
1997
                        case <-p.quit:
×
1998
                                break out
×
1999
                        }
2000

2001
                case *lnwire.Warning:
×
2002
                        targetChan = msg.ChanID
×
2003
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2004

UNCOV
2005
                case *lnwire.Error:
×
UNCOV
2006
                        targetChan = msg.ChanID
×
UNCOV
2007
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2008

UNCOV
2009
                case *lnwire.ChannelReestablish:
×
UNCOV
2010
                        targetChan = msg.ChanID
×
UNCOV
2011
                        isLinkUpdate = p.hasChannel(targetChan)
×
UNCOV
2012

×
UNCOV
2013
                        // If we failed to find the link in question, and the
×
UNCOV
2014
                        // message received was a channel sync message, then
×
UNCOV
2015
                        // this might be a peer trying to resync closed channel.
×
UNCOV
2016
                        // In this case we'll try to resend our last channel
×
UNCOV
2017
                        // sync message, such that the peer can recover funds
×
UNCOV
2018
                        // from the closed channel.
×
UNCOV
2019
                        if !isLinkUpdate {
×
UNCOV
2020
                                err := p.resendChanSyncMsg(targetChan)
×
UNCOV
2021
                                if err != nil {
×
UNCOV
2022
                                        // TODO(halseth): send error to peer?
×
UNCOV
2023
                                        p.log.Errorf("resend failed: %v",
×
UNCOV
2024
                                                err)
×
UNCOV
2025
                                }
×
2026
                        }
2027

2028
                // For messages that implement the LinkUpdater interface, we
2029
                // will consider them as link updates and send them to
2030
                // chanStream. These messages will be queued inside chanStream
2031
                // if the channel is not active yet.
UNCOV
2032
                case lnwire.LinkUpdater:
×
UNCOV
2033
                        targetChan = msg.TargetChanID()
×
UNCOV
2034
                        isLinkUpdate = p.hasChannel(targetChan)
×
UNCOV
2035

×
UNCOV
2036
                        // Log an error if we don't have this channel. This
×
UNCOV
2037
                        // means the peer has sent us a message with unknown
×
UNCOV
2038
                        // channel ID.
×
UNCOV
2039
                        if !isLinkUpdate {
×
UNCOV
2040
                                p.log.Errorf("Unknown channel ID: %v found "+
×
UNCOV
2041
                                        "in received msg=%s", targetChan,
×
UNCOV
2042
                                        nextMsg.MsgType())
×
UNCOV
2043
                        }
×
2044

2045
                case *lnwire.ChannelUpdate1,
2046
                        *lnwire.ChannelAnnouncement1,
2047
                        *lnwire.NodeAnnouncement,
2048
                        *lnwire.AnnounceSignatures1,
2049
                        *lnwire.GossipTimestampRange,
2050
                        *lnwire.QueryShortChanIDs,
2051
                        *lnwire.QueryChannelRange,
2052
                        *lnwire.ReplyChannelRange,
UNCOV
2053
                        *lnwire.ReplyShortChanIDsEnd:
×
UNCOV
2054

×
UNCOV
2055
                        discStream.AddMsg(msg)
×
2056

2057
                case *lnwire.Custom:
1✔
2058
                        err := p.handleCustomMessage(msg)
1✔
2059
                        if err != nil {
1✔
2060
                                p.storeError(err)
×
2061
                                p.log.Errorf("%v", err)
×
2062
                        }
×
2063

2064
                default:
×
2065
                        // If the message we received is unknown to us, store
×
2066
                        // the type to track the failure.
×
2067
                        err := fmt.Errorf("unknown message type %v received",
×
2068
                                uint16(msg.MsgType()))
×
2069
                        p.storeError(err)
×
2070

×
2071
                        p.log.Errorf("%v", err)
×
2072
                }
2073

2074
                if isLinkUpdate {
1✔
UNCOV
2075
                        // If this is a channel update, then we need to feed it
×
UNCOV
2076
                        // into the channel's in-order message stream.
×
UNCOV
2077
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
×
UNCOV
2078
                }
×
2079

2080
                idleTimer.Reset(idleTimeout)
1✔
2081
        }
2082

UNCOV
2083
        p.Disconnect(errors.New("read handler closed"))
×
UNCOV
2084

×
UNCOV
2085
        p.log.Trace("readHandler for peer done")
×
2086
}
2087

2088
// handleCustomMessage handles the given custom message if a handler is
2089
// registered.
2090
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
1✔
2091
        if p.cfg.HandleCustomMessage == nil {
1✔
2092
                return fmt.Errorf("no custom message handler for "+
×
2093
                        "message type %v", uint16(msg.MsgType()))
×
2094
        }
×
2095

2096
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
1✔
2097
}
2098

2099
// isLoadedFromDisk returns true if the provided channel ID is loaded from
2100
// disk.
2101
//
2102
// NOTE: only returns true for pending channels.
UNCOV
2103
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
×
UNCOV
2104
        // If this is a newly added channel, no need to reestablish.
×
UNCOV
2105
        _, added := p.addedChannels.Load(chanID)
×
UNCOV
2106
        if added {
×
UNCOV
2107
                return false
×
UNCOV
2108
        }
×
2109

2110
        // Return false if the channel is unknown.
UNCOV
2111
        channel, ok := p.activeChannels.Load(chanID)
×
UNCOV
2112
        if !ok {
×
2113
                return false
×
2114
        }
×
2115

2116
        // During startup, we will use a nil value to mark a pending channel
2117
        // that's loaded from disk.
UNCOV
2118
        return channel == nil
×
2119
}
2120

2121
// isActiveChannel returns true if the provided channel id is active, otherwise
2122
// returns false.
2123
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
8✔
2124
        // The channel would be nil if,
8✔
2125
        // - the channel doesn't exist, or,
8✔
2126
        // - the channel exists, but is pending. In this case, we don't
8✔
2127
        //   consider this channel active.
8✔
2128
        channel, _ := p.activeChannels.Load(chanID)
8✔
2129

8✔
2130
        return channel != nil
8✔
2131
}
8✔
2132

2133
// isPendingChannel returns true if the provided channel ID is pending, and
2134
// returns false if the channel is active or unknown.
2135
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
6✔
2136
        // Return false if the channel is unknown.
6✔
2137
        channel, ok := p.activeChannels.Load(chanID)
6✔
2138
        if !ok {
9✔
2139
                return false
3✔
2140
        }
3✔
2141

2142
        return channel == nil
3✔
2143
}
2144

2145
// hasChannel returns true if the peer has a pending/active channel specified
2146
// by the channel ID.
UNCOV
2147
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
×
UNCOV
2148
        _, ok := p.activeChannels.Load(chanID)
×
UNCOV
2149
        return ok
×
UNCOV
2150
}
×
2151

2152
// storeError stores an error in our peer's buffer of recent errors with the
2153
// current timestamp. Errors are only stored if we have at least one active
2154
// channel with the peer to mitigate a dos vector where a peer costlessly
2155
// connects to us and spams us with errors.
UNCOV
2156
func (p *Brontide) storeError(err error) {
×
UNCOV
2157
        var haveChannels bool
×
UNCOV
2158

×
UNCOV
2159
        p.activeChannels.Range(func(_ lnwire.ChannelID,
×
UNCOV
2160
                channel *lnwallet.LightningChannel) bool {
×
UNCOV
2161

×
UNCOV
2162
                // Pending channels will be nil in the activeChannels map.
×
UNCOV
2163
                if channel == nil {
×
UNCOV
2164
                        // Return true to continue the iteration.
×
UNCOV
2165
                        return true
×
UNCOV
2166
                }
×
2167

UNCOV
2168
                haveChannels = true
×
UNCOV
2169

×
UNCOV
2170
                // Return false to break the iteration.
×
UNCOV
2171
                return false
×
2172
        })
2173

2174
        // If we do not have any active channels with the peer, we do not store
2175
        // errors as a dos mitigation.
UNCOV
2176
        if !haveChannels {
×
UNCOV
2177
                p.log.Trace("no channels with peer, not storing err")
×
UNCOV
2178
                return
×
UNCOV
2179
        }
×
2180

UNCOV
2181
        p.cfg.ErrorBuffer.Add(
×
UNCOV
2182
                &TimestampedError{Timestamp: time.Now(), Error: err},
×
UNCOV
2183
        )
×
2184
}
2185

2186
// handleWarningOrError processes a warning or error msg and returns true if
2187
// msg should be forwarded to the associated channel link. False is returned if
2188
// any necessary forwarding of msg was already handled by this method. If msg is
2189
// an error from a peer with an active channel, we'll store it in memory.
2190
//
2191
// NOTE: This method should only be called from within the readHandler.
2192
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
UNCOV
2193
        msg lnwire.Message) bool {
×
UNCOV
2194

×
UNCOV
2195
        if errMsg, ok := msg.(*lnwire.Error); ok {
×
UNCOV
2196
                p.storeError(errMsg)
×
UNCOV
2197
        }
×
2198

UNCOV
2199
        switch {
×
2200
        // Connection wide messages should be forwarded to all channel links
2201
        // with this peer.
2202
        case chanID == lnwire.ConnectionWideID:
×
2203
                for _, chanStream := range p.activeMsgStreams {
×
2204
                        chanStream.AddMsg(msg)
×
2205
                }
×
2206

2207
                return false
×
2208

2209
        // If the channel ID for the message corresponds to a pending channel,
2210
        // then the funding manager will handle it.
UNCOV
2211
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
×
UNCOV
2212
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
×
UNCOV
2213
                return false
×
2214

2215
        // If not we hand the message to the channel link for this channel.
UNCOV
2216
        case p.isActiveChannel(chanID):
×
UNCOV
2217
                return true
×
2218

UNCOV
2219
        default:
×
UNCOV
2220
                return false
×
2221
        }
2222
}
2223

2224
// messageSummary returns a human-readable string that summarizes a
2225
// incoming/outgoing message. Not all messages will have a summary, only those
2226
// which have additional data that can be informative at a glance.
UNCOV
2227
func messageSummary(msg lnwire.Message) string {
×
UNCOV
2228
        switch msg := msg.(type) {
×
UNCOV
2229
        case *lnwire.Init:
×
UNCOV
2230
                // No summary.
×
UNCOV
2231
                return ""
×
2232

UNCOV
2233
        case *lnwire.OpenChannel:
×
UNCOV
2234
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
×
UNCOV
2235
                        "push_amt=%v, reserve=%v, flags=%v",
×
UNCOV
2236
                        msg.PendingChannelID[:], msg.ChainHash,
×
UNCOV
2237
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
×
UNCOV
2238
                        msg.ChannelReserve, msg.ChannelFlags)
×
2239

UNCOV
2240
        case *lnwire.AcceptChannel:
×
UNCOV
2241
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
×
UNCOV
2242
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
×
UNCOV
2243
                        msg.MinAcceptDepth)
×
2244

UNCOV
2245
        case *lnwire.FundingCreated:
×
UNCOV
2246
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
×
UNCOV
2247
                        msg.PendingChannelID[:], msg.FundingPoint)
×
2248

UNCOV
2249
        case *lnwire.FundingSigned:
×
UNCOV
2250
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
×
2251

UNCOV
2252
        case *lnwire.ChannelReady:
×
UNCOV
2253
                return fmt.Sprintf("chan_id=%v, next_point=%x",
×
UNCOV
2254
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
×
2255

UNCOV
2256
        case *lnwire.Shutdown:
×
UNCOV
2257
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
×
UNCOV
2258
                        msg.Address[:])
×
2259

UNCOV
2260
        case *lnwire.ClosingSigned:
×
UNCOV
2261
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
×
UNCOV
2262
                        msg.FeeSatoshis)
×
2263

UNCOV
2264
        case *lnwire.UpdateAddHTLC:
×
UNCOV
2265
                var blindingPoint []byte
×
UNCOV
2266
                msg.BlindingPoint.WhenSome(
×
UNCOV
2267
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
×
UNCOV
2268
                                *btcec.PublicKey]) {
×
UNCOV
2269

×
UNCOV
2270
                                blindingPoint = b.Val.SerializeCompressed()
×
UNCOV
2271
                        },
×
2272
                )
2273

UNCOV
2274
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
×
UNCOV
2275
                        "hash=%x, blinding_point=%x, custom_records=%v",
×
UNCOV
2276
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
×
UNCOV
2277
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
×
2278

UNCOV
2279
        case *lnwire.UpdateFailHTLC:
×
UNCOV
2280
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
×
UNCOV
2281
                        msg.ID, msg.Reason)
×
2282

UNCOV
2283
        case *lnwire.UpdateFulfillHTLC:
×
UNCOV
2284
                return fmt.Sprintf("chan_id=%v, id=%v, pre_image=%x, "+
×
UNCOV
2285
                        "custom_records=%v", msg.ChanID, msg.ID,
×
UNCOV
2286
                        msg.PaymentPreimage[:], msg.CustomRecords)
×
2287

UNCOV
2288
        case *lnwire.CommitSig:
×
UNCOV
2289
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
×
UNCOV
2290
                        len(msg.HtlcSigs))
×
2291

UNCOV
2292
        case *lnwire.RevokeAndAck:
×
UNCOV
2293
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
×
UNCOV
2294
                        msg.ChanID, msg.Revocation[:],
×
UNCOV
2295
                        msg.NextRevocationKey.SerializeCompressed())
×
2296

UNCOV
2297
        case *lnwire.UpdateFailMalformedHTLC:
×
UNCOV
2298
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
×
UNCOV
2299
                        msg.ChanID, msg.ID, msg.FailureCode)
×
2300

2301
        case *lnwire.Warning:
×
2302
                return fmt.Sprintf("%v", msg.Warning())
×
2303

UNCOV
2304
        case *lnwire.Error:
×
UNCOV
2305
                return fmt.Sprintf("%v", msg.Error())
×
2306

UNCOV
2307
        case *lnwire.AnnounceSignatures1:
×
UNCOV
2308
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
×
UNCOV
2309
                        msg.ShortChannelID.ToUint64())
×
2310

UNCOV
2311
        case *lnwire.ChannelAnnouncement1:
×
UNCOV
2312
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
×
UNCOV
2313
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
×
2314

UNCOV
2315
        case *lnwire.ChannelUpdate1:
×
UNCOV
2316
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
×
UNCOV
2317
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
×
UNCOV
2318
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
×
UNCOV
2319
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
×
2320

UNCOV
2321
        case *lnwire.NodeAnnouncement:
×
UNCOV
2322
                return fmt.Sprintf("node=%x, update_time=%v",
×
UNCOV
2323
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
×
2324

UNCOV
2325
        case *lnwire.Ping:
×
UNCOV
2326
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
2327

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

2331
        case *lnwire.UpdateFee:
×
2332
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2333
                        msg.ChanID, int64(msg.FeePerKw))
×
2334

UNCOV
2335
        case *lnwire.ChannelReestablish:
×
UNCOV
2336
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
×
UNCOV
2337
                        "remote_tail_height=%v", msg.ChanID,
×
UNCOV
2338
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
×
2339

UNCOV
2340
        case *lnwire.ReplyShortChanIDsEnd:
×
UNCOV
2341
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
×
UNCOV
2342
                        msg.Complete)
×
2343

UNCOV
2344
        case *lnwire.ReplyChannelRange:
×
UNCOV
2345
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
×
UNCOV
2346
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
×
UNCOV
2347
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
×
UNCOV
2348
                        msg.EncodingType)
×
2349

UNCOV
2350
        case *lnwire.QueryShortChanIDs:
×
UNCOV
2351
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
×
UNCOV
2352
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
×
2353

UNCOV
2354
        case *lnwire.QueryChannelRange:
×
UNCOV
2355
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
×
UNCOV
2356
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
×
UNCOV
2357
                        msg.LastBlockHeight())
×
2358

UNCOV
2359
        case *lnwire.GossipTimestampRange:
×
UNCOV
2360
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
×
UNCOV
2361
                        "stamp_range=%v", msg.ChainHash,
×
UNCOV
2362
                        time.Unix(int64(msg.FirstTimestamp), 0),
×
UNCOV
2363
                        msg.TimestampRange)
×
2364

2365
        case *lnwire.Stfu:
×
2366
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
×
2367
                        msg.Initiator)
×
2368

UNCOV
2369
        case *lnwire.Custom:
×
UNCOV
2370
                return fmt.Sprintf("type=%d", msg.Type)
×
2371
        }
2372

2373
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2374
}
2375

2376
// logWireMessage logs the receipt or sending of particular wire message. This
2377
// function is used rather than just logging the message in order to produce
2378
// less spammy log messages in trace mode by setting the 'Curve" parameter to
2379
// nil. Doing this avoids printing out each of the field elements in the curve
2380
// parameters for secp256k1.
2381
func (p *Brontide) logWireMessage(msg lnwire.Message, read bool) {
17✔
2382
        summaryPrefix := "Received"
17✔
2383
        if !read {
30✔
2384
                summaryPrefix = "Sending"
13✔
2385
        }
13✔
2386

2387
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
17✔
UNCOV
2388
                // Debug summary of message.
×
UNCOV
2389
                summary := messageSummary(msg)
×
UNCOV
2390
                if len(summary) > 0 {
×
UNCOV
2391
                        summary = "(" + summary + ")"
×
UNCOV
2392
                }
×
2393

UNCOV
2394
                preposition := "to"
×
UNCOV
2395
                if read {
×
UNCOV
2396
                        preposition = "from"
×
UNCOV
2397
                }
×
2398

UNCOV
2399
                var msgType string
×
UNCOV
2400
                if msg.MsgType() < lnwire.CustomTypeStart {
×
UNCOV
2401
                        msgType = msg.MsgType().String()
×
UNCOV
2402
                } else {
×
UNCOV
2403
                        msgType = "custom"
×
UNCOV
2404
                }
×
2405

UNCOV
2406
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
×
UNCOV
2407
                        msgType, summary, preposition, p)
×
2408
        }))
2409

2410
        prefix := "readMessage from peer"
17✔
2411
        if !read {
30✔
2412
                prefix = "writeMessage to peer"
13✔
2413
        }
13✔
2414

2415
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
17✔
2416
}
2417

2418
// writeMessage writes and flushes the target lnwire.Message to the remote peer.
2419
// If the passed message is nil, this method will only try to flush an existing
2420
// message buffered on the connection. It is safe to call this method again
2421
// with a nil message iff a timeout error is returned. This will continue to
2422
// flush the pending message to the wire.
2423
//
2424
// NOTE:
2425
// Besides its usage in Start, this function should not be used elsewhere
2426
// except in writeHandler. If multiple goroutines call writeMessage at the same
2427
// time, panics can occur because WriteMessage and Flush don't use any locking
2428
// internally.
2429
func (p *Brontide) writeMessage(msg lnwire.Message) error {
13✔
2430
        // Only log the message on the first attempt.
13✔
2431
        if msg != nil {
26✔
2432
                p.logWireMessage(msg, false)
13✔
2433
        }
13✔
2434

2435
        noiseConn := p.cfg.Conn
13✔
2436

13✔
2437
        flushMsg := func() error {
26✔
2438
                // Ensure the write deadline is set before we attempt to send
13✔
2439
                // the message.
13✔
2440
                writeDeadline := time.Now().Add(
13✔
2441
                        p.scaleTimeout(writeMessageTimeout),
13✔
2442
                )
13✔
2443
                err := noiseConn.SetWriteDeadline(writeDeadline)
13✔
2444
                if err != nil {
13✔
2445
                        return err
×
2446
                }
×
2447

2448
                // Flush the pending message to the wire. If an error is
2449
                // encountered, e.g. write timeout, the number of bytes written
2450
                // so far will be returned.
2451
                n, err := noiseConn.Flush()
13✔
2452

13✔
2453
                // Record the number of bytes written on the wire, if any.
13✔
2454
                if n > 0 {
13✔
UNCOV
2455
                        atomic.AddUint64(&p.bytesSent, uint64(n))
×
UNCOV
2456
                }
×
2457

2458
                return err
13✔
2459
        }
2460

2461
        // If the current message has already been serialized, encrypted, and
2462
        // buffered on the underlying connection we will skip straight to
2463
        // flushing it to the wire.
2464
        if msg == nil {
13✔
2465
                return flushMsg()
×
2466
        }
×
2467

2468
        // Otherwise, this is a new message. We'll acquire a write buffer to
2469
        // serialize the message and buffer the ciphertext on the connection.
2470
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
26✔
2471
                // Using a buffer allocated by the write pool, encode the
13✔
2472
                // message directly into the buffer.
13✔
2473
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
13✔
2474
                if writeErr != nil {
13✔
2475
                        return writeErr
×
2476
                }
×
2477

2478
                // Finally, write the message itself in a single swoop. This
2479
                // will buffer the ciphertext on the underlying connection. We
2480
                // will defer flushing the message until the write pool has been
2481
                // released.
2482
                return noiseConn.WriteMessage(buf.Bytes())
13✔
2483
        })
2484
        if err != nil {
13✔
2485
                return err
×
2486
        }
×
2487

2488
        return flushMsg()
13✔
2489
}
2490

2491
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2492
// queue, and writing them out to the wire. This goroutine coordinates with the
2493
// queueHandler in order to ensure the incoming message queue is quickly
2494
// drained.
2495
//
2496
// NOTE: This method MUST be run as a goroutine.
2497
func (p *Brontide) writeHandler() {
3✔
2498
        // We'll stop the timer after a new messages is sent, and also reset it
3✔
2499
        // after we process the next message.
3✔
2500
        idleTimer := time.AfterFunc(idleTimeout, func() {
3✔
UNCOV
2501
                err := fmt.Errorf("peer %s no write for %s -- disconnecting",
×
UNCOV
2502
                        p, idleTimeout)
×
UNCOV
2503
                p.Disconnect(err)
×
UNCOV
2504
        })
×
2505

2506
        var exitErr error
3✔
2507

3✔
2508
out:
3✔
2509
        for {
10✔
2510
                select {
7✔
2511
                case outMsg := <-p.sendQueue:
4✔
2512
                        // Record the time at which we first attempt to send the
4✔
2513
                        // message.
4✔
2514
                        startTime := time.Now()
4✔
2515

4✔
2516
                retry:
4✔
2517
                        // Write out the message to the socket. If a timeout
2518
                        // error is encountered, we will catch this and retry
2519
                        // after backing off in case the remote peer is just
2520
                        // slow to process messages from the wire.
2521
                        err := p.writeMessage(outMsg.msg)
4✔
2522
                        if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
4✔
2523
                                p.log.Debugf("Write timeout detected for "+
×
2524
                                        "peer, first write for message "+
×
2525
                                        "attempted %v ago",
×
2526
                                        time.Since(startTime))
×
2527

×
2528
                                // If we received a timeout error, this implies
×
2529
                                // that the message was buffered on the
×
2530
                                // connection successfully and that a flush was
×
2531
                                // attempted. We'll set the message to nil so
×
2532
                                // that on a subsequent pass we only try to
×
2533
                                // flush the buffered message, and forgo
×
2534
                                // reserializing or reencrypting it.
×
2535
                                outMsg.msg = nil
×
2536

×
2537
                                goto retry
×
2538
                        }
2539

2540
                        // The write succeeded, reset the idle timer to prevent
2541
                        // us from disconnecting the peer.
2542
                        if !idleTimer.Stop() {
4✔
2543
                                select {
×
2544
                                case <-idleTimer.C:
×
2545
                                default:
×
2546
                                }
2547
                        }
2548
                        idleTimer.Reset(idleTimeout)
4✔
2549

4✔
2550
                        // If the peer requested a synchronous write, respond
4✔
2551
                        // with the error.
4✔
2552
                        if outMsg.errChan != nil {
5✔
2553
                                outMsg.errChan <- err
1✔
2554
                        }
1✔
2555

2556
                        if err != nil {
4✔
2557
                                exitErr = fmt.Errorf("unable to write "+
×
2558
                                        "message: %v", err)
×
2559
                                break out
×
2560
                        }
2561

UNCOV
2562
                case <-p.quit:
×
UNCOV
2563
                        exitErr = lnpeer.ErrPeerExiting
×
UNCOV
2564
                        break out
×
2565
                }
2566
        }
2567

2568
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2569
        // disconnect.
UNCOV
2570
        p.wg.Done()
×
UNCOV
2571

×
UNCOV
2572
        p.Disconnect(exitErr)
×
UNCOV
2573

×
UNCOV
2574
        p.log.Trace("writeHandler for peer done")
×
2575
}
2576

2577
// queueHandler is responsible for accepting messages from outside subsystems
2578
// to be eventually sent out on the wire by the writeHandler.
2579
//
2580
// NOTE: This method MUST be run as a goroutine.
2581
func (p *Brontide) queueHandler() {
3✔
2582
        defer p.wg.Done()
3✔
2583

3✔
2584
        // priorityMsgs holds an in order list of messages deemed high-priority
3✔
2585
        // to be added to the sendQueue. This predominately includes messages
3✔
2586
        // from the funding manager and htlcswitch.
3✔
2587
        priorityMsgs := list.New()
3✔
2588

3✔
2589
        // lazyMsgs holds an in order list of messages deemed low-priority to be
3✔
2590
        // added to the sendQueue only after all high-priority messages have
3✔
2591
        // been queued. This predominately includes messages from the gossiper.
3✔
2592
        lazyMsgs := list.New()
3✔
2593

3✔
2594
        for {
14✔
2595
                // Examine the front of the priority queue, if it is empty check
11✔
2596
                // the low priority queue.
11✔
2597
                elem := priorityMsgs.Front()
11✔
2598
                if elem == nil {
19✔
2599
                        elem = lazyMsgs.Front()
8✔
2600
                }
8✔
2601

2602
                if elem != nil {
15✔
2603
                        front := elem.Value.(outgoingMsg)
4✔
2604

4✔
2605
                        // There's an element on the queue, try adding
4✔
2606
                        // it to the sendQueue. We also watch for
4✔
2607
                        // messages on the outgoingQueue, in case the
4✔
2608
                        // writeHandler cannot accept messages on the
4✔
2609
                        // sendQueue.
4✔
2610
                        select {
4✔
2611
                        case p.sendQueue <- front:
4✔
2612
                                if front.priority {
7✔
2613
                                        priorityMsgs.Remove(elem)
3✔
2614
                                } else {
4✔
2615
                                        lazyMsgs.Remove(elem)
1✔
2616
                                }
1✔
UNCOV
2617
                        case msg := <-p.outgoingQueue:
×
UNCOV
2618
                                if msg.priority {
×
UNCOV
2619
                                        priorityMsgs.PushBack(msg)
×
UNCOV
2620
                                } else {
×
UNCOV
2621
                                        lazyMsgs.PushBack(msg)
×
UNCOV
2622
                                }
×
2623
                        case <-p.quit:
×
2624
                                return
×
2625
                        }
2626
                } else {
7✔
2627
                        // If there weren't any messages to send to the
7✔
2628
                        // writeHandler, then we'll accept a new message
7✔
2629
                        // into the queue from outside sub-systems.
7✔
2630
                        select {
7✔
2631
                        case msg := <-p.outgoingQueue:
4✔
2632
                                if msg.priority {
7✔
2633
                                        priorityMsgs.PushBack(msg)
3✔
2634
                                } else {
4✔
2635
                                        lazyMsgs.PushBack(msg)
1✔
2636
                                }
1✔
UNCOV
2637
                        case <-p.quit:
×
UNCOV
2638
                                return
×
2639
                        }
2640
                }
2641
        }
2642
}
2643

2644
// PingTime returns the estimated ping time to the peer in microseconds.
UNCOV
2645
func (p *Brontide) PingTime() int64 {
×
UNCOV
2646
        return p.pingManager.GetPingTimeMicroSeconds()
×
UNCOV
2647
}
×
2648

2649
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2650
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2651
// or failed to write, and nil otherwise.
2652
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
25✔
2653
        p.queue(true, msg, errChan)
25✔
2654
}
25✔
2655

2656
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2657
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2658
// queue or failed to write, and nil otherwise.
2659
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
1✔
2660
        p.queue(false, msg, errChan)
1✔
2661
}
1✔
2662

2663
// queue sends a given message to the queueHandler using the passed priority. If
2664
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2665
// failed to write, and nil otherwise.
2666
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2667
        errChan chan error) {
26✔
2668

26✔
2669
        select {
26✔
2670
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
25✔
UNCOV
2671
        case <-p.quit:
×
UNCOV
2672
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
×
UNCOV
2673
                        spew.Sdump(msg))
×
UNCOV
2674
                if errChan != nil {
×
2675
                        errChan <- lnpeer.ErrPeerExiting
×
2676
                }
×
2677
        }
2678
}
2679

2680
// ChannelSnapshots returns a slice of channel snapshots detailing all
2681
// currently active channels maintained with the remote peer.
UNCOV
2682
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
×
UNCOV
2683
        snapshots := make(
×
UNCOV
2684
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
×
UNCOV
2685
        )
×
UNCOV
2686

×
UNCOV
2687
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
×
UNCOV
2688
                activeChan *lnwallet.LightningChannel) error {
×
UNCOV
2689

×
UNCOV
2690
                // If the activeChan is nil, then we skip it as the channel is
×
UNCOV
2691
                // pending.
×
UNCOV
2692
                if activeChan == nil {
×
UNCOV
2693
                        return nil
×
UNCOV
2694
                }
×
2695

2696
                // We'll only return a snapshot for channels that are
2697
                // *immediately* available for routing payments over.
UNCOV
2698
                if activeChan.RemoteNextRevocation() == nil {
×
UNCOV
2699
                        return nil
×
UNCOV
2700
                }
×
2701

UNCOV
2702
                snapshot := activeChan.StateSnapshot()
×
UNCOV
2703
                snapshots = append(snapshots, snapshot)
×
UNCOV
2704

×
UNCOV
2705
                return nil
×
2706
        })
2707

UNCOV
2708
        return snapshots
×
2709
}
2710

2711
// genDeliveryScript returns a new script to be used to send our funds to in
2712
// the case of a cooperative channel close negotiation.
2713
func (p *Brontide) genDeliveryScript() ([]byte, error) {
6✔
2714
        // We'll send a normal p2wkh address unless we've negotiated the
6✔
2715
        // shutdown-any-segwit feature.
6✔
2716
        addrType := lnwallet.WitnessPubKey
6✔
2717
        if p.taprootShutdownAllowed() {
6✔
UNCOV
2718
                addrType = lnwallet.TaprootPubkey
×
UNCOV
2719
        }
×
2720

2721
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
6✔
2722
                addrType, false, lnwallet.DefaultAccountName,
6✔
2723
        )
6✔
2724
        if err != nil {
6✔
2725
                return nil, err
×
2726
        }
×
2727
        p.log.Infof("Delivery addr for channel close: %v",
6✔
2728
                deliveryAddr)
6✔
2729

6✔
2730
        return txscript.PayToAddrScript(deliveryAddr)
6✔
2731
}
2732

2733
// channelManager is goroutine dedicated to handling all requests/signals
2734
// pertaining to the opening, cooperative closing, and force closing of all
2735
// channels maintained with the remote peer.
2736
//
2737
// NOTE: This method MUST be run as a goroutine.
2738
func (p *Brontide) channelManager() {
17✔
2739
        defer p.wg.Done()
17✔
2740

17✔
2741
        // reenableTimeout will fire once after the configured channel status
17✔
2742
        // interval has elapsed. This will trigger us to sign new channel
17✔
2743
        // updates and broadcast them with the "disabled" flag unset.
17✔
2744
        reenableTimeout := time.After(p.cfg.ChanActiveTimeout)
17✔
2745

17✔
2746
out:
17✔
2747
        for {
55✔
2748
                select {
38✔
2749
                // A new pending channel has arrived which means we are about
2750
                // to complete a funding workflow and is waiting for the final
2751
                // `ChannelReady` messages to be exchanged. We will add this
2752
                // channel to the `activeChannels` with a nil value to indicate
2753
                // this is a pending channel.
2754
                case req := <-p.newPendingChannel:
1✔
2755
                        p.handleNewPendingChannel(req)
1✔
2756

2757
                // A new channel has arrived which means we've just completed a
2758
                // funding workflow. We'll initialize the necessary local
2759
                // state, and notify the htlc switch of a new link.
UNCOV
2760
                case req := <-p.newActiveChannel:
×
UNCOV
2761
                        p.handleNewActiveChannel(req)
×
2762

2763
                // The funding flow for a pending channel is failed, we will
2764
                // remove it from Brontide.
2765
                case req := <-p.removePendingChannel:
1✔
2766
                        p.handleRemovePendingChannel(req)
1✔
2767

2768
                // We've just received a local request to close an active
2769
                // channel. It will either kick of a cooperative channel
2770
                // closure negotiation, or be a notification of a breached
2771
                // contract that should be abandoned.
2772
                case req := <-p.localCloseChanReqs:
7✔
2773
                        p.handleLocalCloseReq(req)
7✔
2774

2775
                // We've received a link failure from a link that was added to
2776
                // the switch. This will initiate the teardown of the link, and
2777
                // initiate any on-chain closures if necessary.
UNCOV
2778
                case failure := <-p.linkFailures:
×
UNCOV
2779
                        p.handleLinkFailure(failure)
×
2780

2781
                // We've received a new cooperative channel closure related
2782
                // message from the remote peer, we'll use this message to
2783
                // advance the chan closer state machine.
2784
                case closeMsg := <-p.chanCloseMsgs:
13✔
2785
                        p.handleCloseMsg(closeMsg)
13✔
2786

2787
                // The channel reannounce delay has elapsed, broadcast the
2788
                // reenabled channel updates to the network. This should only
2789
                // fire once, so we set the reenableTimeout channel to nil to
2790
                // mark it for garbage collection. If the peer is torn down
2791
                // before firing, reenabling will not be attempted.
2792
                // TODO(conner): consolidate reenables timers inside chan status
2793
                // manager
UNCOV
2794
                case <-reenableTimeout:
×
UNCOV
2795
                        p.reenableActiveChannels()
×
UNCOV
2796

×
UNCOV
2797
                        // Since this channel will never fire again during the
×
UNCOV
2798
                        // lifecycle of the peer, we nil the channel to mark it
×
UNCOV
2799
                        // eligible for garbage collection, and make this
×
UNCOV
2800
                        // explicitly ineligible to receive in future calls to
×
UNCOV
2801
                        // select. This also shaves a few CPU cycles since the
×
UNCOV
2802
                        // select will ignore this case entirely.
×
UNCOV
2803
                        reenableTimeout = nil
×
UNCOV
2804

×
UNCOV
2805
                        // Once the reenabling is attempted, we also cancel the
×
UNCOV
2806
                        // channel event subscription to free up the overflow
×
UNCOV
2807
                        // queue used in channel notifier.
×
UNCOV
2808
                        //
×
UNCOV
2809
                        // NOTE: channelEventClient will be nil if the
×
UNCOV
2810
                        // reenableTimeout is greater than 1 minute.
×
UNCOV
2811
                        if p.channelEventClient != nil {
×
UNCOV
2812
                                p.channelEventClient.Cancel()
×
UNCOV
2813
                        }
×
2814

UNCOV
2815
                case <-p.quit:
×
UNCOV
2816
                        // As, we've been signalled to exit, we'll reset all
×
UNCOV
2817
                        // our active channel back to their default state.
×
UNCOV
2818
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
×
UNCOV
2819
                                lc *lnwallet.LightningChannel) error {
×
UNCOV
2820

×
UNCOV
2821
                                // Exit if the channel is nil as it's a pending
×
UNCOV
2822
                                // channel.
×
UNCOV
2823
                                if lc == nil {
×
UNCOV
2824
                                        return nil
×
UNCOV
2825
                                }
×
2826

UNCOV
2827
                                lc.ResetState()
×
UNCOV
2828

×
UNCOV
2829
                                return nil
×
2830
                        })
2831

UNCOV
2832
                        break out
×
2833
                }
2834
        }
2835
}
2836

2837
// reenableActiveChannels searches the index of channels maintained with this
2838
// peer, and reenables each public, non-pending channel. This is done at the
2839
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
2840
// No message will be sent if the channel is already enabled.
UNCOV
2841
func (p *Brontide) reenableActiveChannels() {
×
UNCOV
2842
        // First, filter all known channels with this peer for ones that are
×
UNCOV
2843
        // both public and not pending.
×
UNCOV
2844
        activePublicChans := p.filterChannelsToEnable()
×
UNCOV
2845

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

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

×
UNCOV
2855
                switch {
×
2856
                // No error occurred, continue to request the next channel.
UNCOV
2857
                case err == nil:
×
UNCOV
2858
                        continue
×
2859

2860
                // Cannot auto enable a manually disabled channel so we do
2861
                // nothing but proceed to the next channel.
UNCOV
2862
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
×
UNCOV
2863
                        p.log.Debugf("Channel(%v) was manually disabled, "+
×
UNCOV
2864
                                "ignoring automatic enable request", chanPoint)
×
UNCOV
2865

×
UNCOV
2866
                        continue
×
2867

2868
                // If the channel is reported as inactive, we will give it
2869
                // another chance. When handling the request, ChanStatusManager
2870
                // will check whether the link is active or not. One of the
2871
                // conditions is whether the link has been marked as
2872
                // reestablished, which happens inside a goroutine(htlcManager)
2873
                // after the link is started. And we may get a false negative
2874
                // saying the link is not active because that goroutine hasn't
2875
                // reached the line to mark the reestablishment. Thus we give
2876
                // it a second chance to send the request.
2877
                case errors.Is(err, netann.ErrEnableInactiveChan):
×
2878
                        // If we don't have a client created, it means we
×
2879
                        // shouldn't retry enabling the channel.
×
2880
                        if p.channelEventClient == nil {
×
2881
                                p.log.Errorf("Channel(%v) request enabling "+
×
2882
                                        "failed due to inactive link",
×
2883
                                        chanPoint)
×
2884

×
2885
                                continue
×
2886
                        }
2887

2888
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
2889
                                "ChanStatusManager reported inactive, retrying")
×
2890

×
2891
                        // Add the channel to the retry map.
×
2892
                        retryChans[chanPoint] = struct{}{}
×
2893
                }
2894
        }
2895

2896
        // Retry the channels if we have any.
UNCOV
2897
        if len(retryChans) != 0 {
×
2898
                p.retryRequestEnable(retryChans)
×
2899
        }
×
2900
}
2901

2902
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
2903
// for the target channel ID. If the channel isn't active an error is returned.
2904
// Otherwise, either an existing state machine will be returned, or a new one
2905
// will be created.
2906
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
2907
        *chancloser.ChanCloser, error) {
13✔
2908

13✔
2909
        chanCloser, found := p.activeChanCloses[chanID]
13✔
2910
        if found {
23✔
2911
                // An entry will only be found if the closer has already been
10✔
2912
                // created for a non-pending channel or for a channel that had
10✔
2913
                // previously started the shutdown process but the connection
10✔
2914
                // was restarted.
10✔
2915
                return chanCloser, nil
10✔
2916
        }
10✔
2917

2918
        // First, we'll ensure that we actually know of the target channel. If
2919
        // not, we'll ignore this message.
2920
        channel, ok := p.activeChannels.Load(chanID)
3✔
2921

3✔
2922
        // If the channel isn't in the map or the channel is nil, return
3✔
2923
        // ErrChannelNotFound as the channel is pending.
3✔
2924
        if !ok || channel == nil {
3✔
UNCOV
2925
                return nil, ErrChannelNotFound
×
UNCOV
2926
        }
×
2927

2928
        // We'll create a valid closing state machine in order to respond to
2929
        // the initiated cooperative channel closure. First, we set the
2930
        // delivery script that our funds will be paid out to. If an upfront
2931
        // shutdown script was set, we will use it. Otherwise, we get a fresh
2932
        // delivery script.
2933
        //
2934
        // TODO: Expose option to allow upfront shutdown script from watch-only
2935
        // accounts.
2936
        deliveryScript := channel.LocalUpfrontShutdownScript()
3✔
2937
        if len(deliveryScript) == 0 {
6✔
2938
                var err error
3✔
2939
                deliveryScript, err = p.genDeliveryScript()
3✔
2940
                if err != nil {
3✔
2941
                        p.log.Errorf("unable to gen delivery script: %v",
×
2942
                                err)
×
2943
                        return nil, fmt.Errorf("close addr unavailable")
×
2944
                }
×
2945
        }
2946

2947
        // In order to begin fee negotiations, we'll first compute our target
2948
        // ideal fee-per-kw.
2949
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
2950
                p.cfg.CoopCloseTargetConfs,
3✔
2951
        )
3✔
2952
        if err != nil {
3✔
2953
                p.log.Errorf("unable to query fee estimator: %v", err)
×
2954
                return nil, fmt.Errorf("unable to estimate fee")
×
2955
        }
×
2956

2957
        addr, err := p.addrWithInternalKey(deliveryScript)
3✔
2958
        if err != nil {
3✔
2959
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
2960
        }
×
2961
        chanCloser, err = p.createChanCloser(
3✔
2962
                channel, addr, feePerKw, nil, lntypes.Remote,
3✔
2963
        )
3✔
2964
        if err != nil {
3✔
2965
                p.log.Errorf("unable to create chan closer: %v", err)
×
2966
                return nil, fmt.Errorf("unable to create chan closer")
×
2967
        }
×
2968

2969
        p.activeChanCloses[chanID] = chanCloser
3✔
2970

3✔
2971
        return chanCloser, nil
3✔
2972
}
2973

2974
// filterChannelsToEnable filters a list of channels to be enabled upon start.
2975
// The filtered channels are active channels that's neither private nor
2976
// pending.
UNCOV
2977
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
×
UNCOV
2978
        var activePublicChans []wire.OutPoint
×
UNCOV
2979

×
UNCOV
2980
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
×
UNCOV
2981
                lnChan *lnwallet.LightningChannel) bool {
×
UNCOV
2982

×
UNCOV
2983
                // If the lnChan is nil, continue as this is a pending channel.
×
UNCOV
2984
                if lnChan == nil {
×
2985
                        return true
×
2986
                }
×
2987

UNCOV
2988
                dbChan := lnChan.State()
×
UNCOV
2989
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
×
UNCOV
2990
                if !isPublic || dbChan.IsPending {
×
2991
                        return true
×
2992
                }
×
2993

2994
                // We'll also skip any channels added during this peer's
2995
                // lifecycle since they haven't waited out the timeout. Their
2996
                // first announcement will be enabled, and the chan status
2997
                // manager will begin monitoring them passively since they exist
2998
                // in the database.
UNCOV
2999
                if _, ok := p.addedChannels.Load(chanID); ok {
×
UNCOV
3000
                        return true
×
UNCOV
3001
                }
×
3002

UNCOV
3003
                activePublicChans = append(
×
UNCOV
3004
                        activePublicChans, dbChan.FundingOutpoint,
×
UNCOV
3005
                )
×
UNCOV
3006

×
UNCOV
3007
                return true
×
3008
        })
3009

UNCOV
3010
        return activePublicChans
×
3011
}
3012

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

×
3020
        // retryEnable is a helper closure that sends an enable request and
×
3021
        // removes the channel from the map if it's matched.
×
3022
        retryEnable := func(chanPoint wire.OutPoint) error {
×
3023
                // If this is an active channel event, check whether it's in
×
3024
                // our targeted channels map.
×
3025
                _, found := activeChans[chanPoint]
×
3026

×
3027
                // If this channel is irrelevant, return nil so the loop can
×
3028
                // jump to next iteration.
×
3029
                if !found {
×
3030
                        return nil
×
3031
                }
×
3032

3033
                // Otherwise we've just received an active signal for a channel
3034
                // that's previously failed to be enabled, we send the request
3035
                // again.
3036
                //
3037
                // We only give the channel one more shot, so we delete it from
3038
                // our map first to keep it from being attempted again.
3039
                delete(activeChans, chanPoint)
×
3040

×
3041
                // Send the request.
×
3042
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3043
                if err != nil {
×
3044
                        return fmt.Errorf("request enabling channel %v "+
×
3045
                                "failed: %w", chanPoint, err)
×
3046
                }
×
3047

3048
                return nil
×
3049
        }
3050

3051
        for {
×
3052
                // If activeChans is empty, we've done processing all the
×
3053
                // channels.
×
3054
                if len(activeChans) == 0 {
×
3055
                        p.log.Debug("Finished retry enabling channels")
×
3056
                        return
×
3057
                }
×
3058

3059
                select {
×
3060
                // A new event has been sent by the ChannelNotifier. We now
3061
                // check whether it's an active or inactive channel event.
3062
                case e := <-p.channelEventClient.Updates():
×
3063
                        // If this is an active channel event, try enable the
×
3064
                        // channel then jump to the next iteration.
×
3065
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
3066
                        if ok {
×
3067
                                chanPoint := *active.ChannelPoint
×
3068

×
3069
                                // If we received an error for this particular
×
3070
                                // channel, we log an error and won't quit as
×
3071
                                // we still want to retry other channels.
×
3072
                                if err := retryEnable(chanPoint); err != nil {
×
3073
                                        p.log.Errorf("Retry failed: %v", err)
×
3074
                                }
×
3075

3076
                                continue
×
3077
                        }
3078

3079
                        // Otherwise check for inactive link event, and jump to
3080
                        // next iteration if it's not.
3081
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3082
                        if !ok {
×
3083
                                continue
×
3084
                        }
3085

3086
                        // Found an inactive link event, if this is our
3087
                        // targeted channel, remove it from our map.
3088
                        chanPoint := *inactive.ChannelPoint
×
3089
                        _, found := activeChans[chanPoint]
×
3090
                        if !found {
×
3091
                                continue
×
3092
                        }
3093

3094
                        delete(activeChans, chanPoint)
×
3095
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3096
                                "inactive link event", chanPoint)
×
3097

3098
                case <-p.quit:
×
3099
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3100
                        return
×
3101
                }
3102
        }
3103
}
3104

3105
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3106
// a suitable script to close out to. This may be nil if neither script is
3107
// set. If both scripts are set, this function will error if they do not match.
3108
func chooseDeliveryScript(upfront,
3109
        requested lnwire.DeliveryAddress) (lnwire.DeliveryAddress, error) {
12✔
3110

12✔
3111
        // If no upfront shutdown script was provided, return the user
12✔
3112
        // requested address (which may be nil).
12✔
3113
        if len(upfront) == 0 {
18✔
3114
                return requested, nil
6✔
3115
        }
6✔
3116

3117
        // If an upfront shutdown script was provided, and the user did not
3118
        // request a custom shutdown script, return the upfront address.
3119
        if len(requested) == 0 {
8✔
3120
                return upfront, nil
2✔
3121
        }
2✔
3122

3123
        // If both an upfront shutdown script and a custom close script were
3124
        // provided, error if the user provided shutdown script does not match
3125
        // the upfront shutdown script (because closing out to a different
3126
        // script would violate upfront shutdown).
3127
        if !bytes.Equal(upfront, requested) {
6✔
3128
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
3129
        }
2✔
3130

3131
        // The user requested script matches the upfront shutdown script, so we
3132
        // can return it without error.
3133
        return upfront, nil
2✔
3134
}
3135

3136
// restartCoopClose checks whether we need to restart the cooperative close
3137
// process for a given channel.
3138
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3139
        *lnwire.Shutdown, error) {
×
3140

×
3141
        // If this channel has status ChanStatusCoopBroadcasted and does not
×
3142
        // have a closing transaction, then the cooperative close process was
×
3143
        // started but never finished. We'll re-create the chanCloser state
×
3144
        // machine and resend Shutdown. BOLT#2 requires that we retransmit
×
3145
        // Shutdown exactly, but doing so would mean persisting the RPC
×
3146
        // provided close script. Instead use the LocalUpfrontShutdownScript
×
3147
        // or generate a script.
×
3148
        c := lnChan.State()
×
3149
        _, err := c.BroadcastedCooperative()
×
3150
        if err != nil && err != channeldb.ErrNoCloseTx {
×
3151
                // An error other than ErrNoCloseTx was encountered.
×
3152
                return nil, err
×
3153
        } else if err == nil {
×
3154
                // This channel has already completed the coop close
×
3155
                // negotiation.
×
3156
                return nil, nil
×
3157
        }
×
3158

3159
        var deliveryScript []byte
×
3160

×
3161
        shutdownInfo, err := c.ShutdownInfo()
×
3162
        switch {
×
3163
        // We have previously stored the delivery script that we need to use
3164
        // in the shutdown message. Re-use this script.
3165
        case err == nil:
×
3166
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
×
3167
                        deliveryScript = info.DeliveryScript.Val
×
3168
                })
×
3169

3170
        // An error other than ErrNoShutdownInfo was returned
3171
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3172
                return nil, err
×
3173

3174
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3175
                deliveryScript = c.LocalShutdownScript
×
3176
                if len(deliveryScript) == 0 {
×
3177
                        var err error
×
3178
                        deliveryScript, err = p.genDeliveryScript()
×
3179
                        if err != nil {
×
3180
                                p.log.Errorf("unable to gen delivery script: "+
×
3181
                                        "%v", err)
×
3182

×
3183
                                return nil, fmt.Errorf("close addr unavailable")
×
3184
                        }
×
3185
                }
3186
        }
3187

3188
        // Compute an ideal fee.
3189
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
3190
                p.cfg.CoopCloseTargetConfs,
×
3191
        )
×
3192
        if err != nil {
×
3193
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3194
                return nil, fmt.Errorf("unable to estimate fee")
×
3195
        }
×
3196

3197
        // Determine whether we or the peer are the initiator of the coop
3198
        // close attempt by looking at the channel's status.
3199
        closingParty := lntypes.Remote
×
3200
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3201
                closingParty = lntypes.Local
×
3202
        }
×
3203

3204
        addr, err := p.addrWithInternalKey(deliveryScript)
×
3205
        if err != nil {
×
3206
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3207
        }
×
3208
        chanCloser, err := p.createChanCloser(
×
3209
                lnChan, addr, feePerKw, nil, closingParty,
×
3210
        )
×
3211
        if err != nil {
×
3212
                p.log.Errorf("unable to create chan closer: %v", err)
×
3213
                return nil, fmt.Errorf("unable to create chan closer")
×
3214
        }
×
3215

3216
        // This does not need a mutex even though it is in a different
3217
        // goroutine since this is done before the channelManager goroutine is
3218
        // created.
3219
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
×
3220
        p.activeChanCloses[chanID] = chanCloser
×
3221

×
3222
        // Create the Shutdown message.
×
3223
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3224
        if err != nil {
×
3225
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3226
                delete(p.activeChanCloses, chanID)
×
3227
                return nil, err
×
3228
        }
×
3229

3230
        return shutdownMsg, nil
×
3231
}
3232

3233
// createChanCloser constructs a ChanCloser from the passed parameters and is
3234
// used to de-duplicate code.
3235
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3236
        deliveryScript *chancloser.DeliveryAddrWithKey,
3237
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3238
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
9✔
3239

9✔
3240
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
9✔
3241
        if err != nil {
9✔
3242
                p.log.Errorf("unable to obtain best block: %v", err)
×
3243
                return nil, fmt.Errorf("cannot obtain best block")
×
3244
        }
×
3245

3246
        // The req will only be set if we initiated the co-op closing flow.
3247
        var maxFee chainfee.SatPerKWeight
9✔
3248
        if req != nil {
15✔
3249
                maxFee = req.MaxFee
6✔
3250
        }
6✔
3251

3252
        chanCloser := chancloser.NewChanCloser(
9✔
3253
                chancloser.ChanCloseCfg{
9✔
3254
                        Channel:      channel,
9✔
3255
                        MusigSession: NewMusigChanCloser(channel),
9✔
3256
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
9✔
3257
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
9✔
3258
                        AuxCloser:    p.cfg.AuxChanCloser,
9✔
3259
                        DisableChannel: func(op wire.OutPoint) error {
18✔
3260
                                return p.cfg.ChanStatusMgr.RequestDisable(
9✔
3261
                                        op, false,
9✔
3262
                                )
9✔
3263
                        },
9✔
3264
                        MaxFee: maxFee,
3265
                        Disconnect: func() error {
×
3266
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
3267
                        },
×
3268
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3269
                        Quit:        p.quit,
3270
                },
3271
                *deliveryScript,
3272
                fee,
3273
                uint32(startingHeight),
3274
                req,
3275
                closer,
3276
        )
3277

3278
        return chanCloser, nil
9✔
3279
}
3280

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

7✔
3286
        channel, ok := p.activeChannels.Load(chanID)
7✔
3287

7✔
3288
        // Though this function can't be called for pending channels, we still
7✔
3289
        // check whether channel is nil for safety.
7✔
3290
        if !ok || channel == nil {
7✔
3291
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
×
3292
                        "unknown", chanID)
×
3293
                p.log.Errorf(err.Error())
×
3294
                req.Err <- err
×
3295
                return
×
3296
        }
×
3297

3298
        switch req.CloseType {
7✔
3299
        // A type of CloseRegular indicates that the user has opted to close
3300
        // out this channel on-chain, so we execute the cooperative channel
3301
        // closure workflow.
3302
        case contractcourt.CloseRegular:
7✔
3303
                // First, we'll choose a delivery address that we'll use to send the
7✔
3304
                // funds to in the case of a successful negotiation.
7✔
3305

7✔
3306
                // An upfront shutdown and user provided script are both optional,
7✔
3307
                // but must be equal if both set  (because we cannot serve a request
7✔
3308
                // to close out to a script which violates upfront shutdown). Get the
7✔
3309
                // appropriate address to close out to (which may be nil if neither
7✔
3310
                // are set) and error if they are both set and do not match.
7✔
3311
                deliveryScript, err := chooseDeliveryScript(
7✔
3312
                        channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
7✔
3313
                )
7✔
3314
                if err != nil {
8✔
3315
                        p.log.Errorf("cannot close channel %v: %v", req.ChanPoint, err)
1✔
3316
                        req.Err <- err
1✔
3317
                        return
1✔
3318
                }
1✔
3319

3320
                // If neither an upfront address or a user set address was
3321
                // provided, generate a fresh script.
3322
                if len(deliveryScript) == 0 {
9✔
3323
                        deliveryScript, err = p.genDeliveryScript()
3✔
3324
                        if err != nil {
3✔
3325
                                p.log.Errorf(err.Error())
×
3326
                                req.Err <- err
×
3327
                                return
×
3328
                        }
×
3329
                }
3330
                addr, err := p.addrWithInternalKey(deliveryScript)
6✔
3331
                if err != nil {
6✔
3332
                        err = fmt.Errorf("unable to parse addr for channel "+
×
3333
                                "%v: %w", req.ChanPoint, err)
×
3334
                        p.log.Errorf(err.Error())
×
3335
                        req.Err <- err
×
3336

×
3337
                        return
×
3338
                }
×
3339
                chanCloser, err := p.createChanCloser(
6✔
3340
                        channel, addr, req.TargetFeePerKw, req, lntypes.Local,
6✔
3341
                )
6✔
3342
                if err != nil {
6✔
3343
                        p.log.Errorf(err.Error())
×
3344
                        req.Err <- err
×
3345
                        return
×
3346
                }
×
3347

3348
                p.activeChanCloses[chanID] = chanCloser
6✔
3349

6✔
3350
                // Finally, we'll initiate the channel shutdown within the
6✔
3351
                // chanCloser, and send the shutdown message to the remote
6✔
3352
                // party to kick things off.
6✔
3353
                shutdownMsg, err := chanCloser.ShutdownChan()
6✔
3354
                if err != nil {
6✔
3355
                        p.log.Errorf(err.Error())
×
3356
                        req.Err <- err
×
3357
                        delete(p.activeChanCloses, chanID)
×
3358

×
3359
                        // As we were unable to shutdown the channel, we'll
×
3360
                        // return it back to its normal state.
×
3361
                        channel.ResetState()
×
3362
                        return
×
3363
                }
×
3364

3365
                link := p.fetchLinkFromKeyAndCid(chanID)
6✔
3366
                if link == nil {
6✔
3367
                        // If the link is nil then it means it was already
×
3368
                        // removed from the switch or it never existed in the
×
3369
                        // first place. The latter case is handled at the
×
3370
                        // beginning of this function, so in the case where it
×
3371
                        // has already been removed, we can skip adding the
×
3372
                        // commit hook to queue a Shutdown message.
×
3373
                        p.log.Warnf("link not found during attempted closure: "+
×
3374
                                "%v", chanID)
×
3375
                        return
×
3376
                }
×
3377

3378
                if !link.DisableAdds(htlcswitch.Outgoing) {
6✔
3379
                        p.log.Warnf("Outgoing link adds already "+
×
3380
                                "disabled: %v", link.ChanID())
×
3381
                }
×
3382

3383
                link.OnCommitOnce(htlcswitch.Outgoing, func() {
12✔
3384
                        p.queueMsg(shutdownMsg, nil)
6✔
3385
                })
6✔
3386

3387
        // A type of CloseBreach indicates that the counterparty has breached
3388
        // the channel therefore we need to clean up our local state.
UNCOV
3389
        case contractcourt.CloseBreach:
×
UNCOV
3390
                // TODO(roasbeef): no longer need with newer beach logic?
×
UNCOV
3391
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
×
UNCOV
3392
                        "channel", req.ChanPoint)
×
UNCOV
3393
                p.WipeChannel(req.ChanPoint)
×
3394
        }
3395
}
3396

3397
// linkFailureReport is sent to the channelManager whenever a link reports a
3398
// link failure, and is forced to exit. The report houses the necessary
3399
// information to clean up the channel state, send back the error message, and
3400
// force close if necessary.
3401
type linkFailureReport struct {
3402
        chanPoint   wire.OutPoint
3403
        chanID      lnwire.ChannelID
3404
        shortChanID lnwire.ShortChannelID
3405
        linkErr     htlcswitch.LinkFailureError
3406
}
3407

3408
// handleLinkFailure processes a link failure report when a link in the switch
3409
// fails. It facilitates the removal of all channel state within the peer,
3410
// force closing the channel depending on severity, and sending the error
3411
// message back to the remote party.
UNCOV
3412
func (p *Brontide) handleLinkFailure(failure linkFailureReport) {
×
UNCOV
3413
        // Retrieve the channel from the map of active channels. We do this to
×
UNCOV
3414
        // have access to it even after WipeChannel remove it from the map.
×
UNCOV
3415
        chanID := lnwire.NewChanIDFromOutPoint(failure.chanPoint)
×
UNCOV
3416
        lnChan, _ := p.activeChannels.Load(chanID)
×
UNCOV
3417

×
UNCOV
3418
        // We begin by wiping the link, which will remove it from the switch,
×
UNCOV
3419
        // such that it won't be attempted used for any more updates.
×
UNCOV
3420
        //
×
UNCOV
3421
        // TODO(halseth): should introduce a way to atomically stop/pause the
×
UNCOV
3422
        // link and cancel back any adds in its mailboxes such that we can
×
UNCOV
3423
        // safely force close without the link being added again and updates
×
UNCOV
3424
        // being applied.
×
UNCOV
3425
        p.WipeChannel(&failure.chanPoint)
×
UNCOV
3426

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

×
UNCOV
3432
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
×
UNCOV
3433
                        failure.chanPoint,
×
UNCOV
3434
                )
×
UNCOV
3435
                if err != nil {
×
UNCOV
3436
                        p.log.Errorf("unable to force close "+
×
UNCOV
3437
                                "link(%v): %v", failure.shortChanID, err)
×
UNCOV
3438
                } else {
×
UNCOV
3439
                        p.log.Infof("channel(%v) force "+
×
UNCOV
3440
                                "closed with txid %v",
×
UNCOV
3441
                                failure.shortChanID, closeTx.TxHash())
×
UNCOV
3442
                }
×
3443
        }
3444

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

×
3450
                if err := lnChan.State().MarkBorked(); err != nil {
×
3451
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
3452
                                failure.shortChanID, err)
×
3453
                }
×
3454
        }
3455

3456
        // Send an error to the peer, why we failed the channel.
UNCOV
3457
        if failure.linkErr.ShouldSendToPeer() {
×
UNCOV
3458
                // If SendData is set, send it to the peer. If not, we'll use
×
UNCOV
3459
                // the standard error messages in the payload. We only include
×
UNCOV
3460
                // sendData in the cases where the error data does not contain
×
UNCOV
3461
                // sensitive information.
×
UNCOV
3462
                data := []byte(failure.linkErr.Error())
×
UNCOV
3463
                if failure.linkErr.SendData != nil {
×
3464
                        data = failure.linkErr.SendData
×
3465
                }
×
3466

UNCOV
3467
                var networkMsg lnwire.Message
×
UNCOV
3468
                if failure.linkErr.Warning {
×
3469
                        networkMsg = &lnwire.Warning{
×
3470
                                ChanID: failure.chanID,
×
3471
                                Data:   data,
×
3472
                        }
×
UNCOV
3473
                } else {
×
UNCOV
3474
                        networkMsg = &lnwire.Error{
×
UNCOV
3475
                                ChanID: failure.chanID,
×
UNCOV
3476
                                Data:   data,
×
UNCOV
3477
                        }
×
UNCOV
3478
                }
×
3479

UNCOV
3480
                err := p.SendMessage(true, networkMsg)
×
UNCOV
3481
                if err != nil {
×
3482
                        p.log.Errorf("unable to send msg to "+
×
3483
                                "remote peer: %v", err)
×
3484
                }
×
3485
        }
3486

3487
        // If the failure action is disconnect, then we'll execute that now. If
3488
        // we had to send an error above, it was a sync call, so we expect the
3489
        // message to be flushed on the wire by now.
UNCOV
3490
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
×
3491
                p.Disconnect(fmt.Errorf("link requested disconnect"))
×
3492
        }
×
3493
}
3494

3495
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
3496
// public key and the channel id.
3497
func (p *Brontide) fetchLinkFromKeyAndCid(
3498
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
19✔
3499

19✔
3500
        var chanLink htlcswitch.ChannelUpdateHandler
19✔
3501

19✔
3502
        // We don't need to check the error here, and can instead just loop
19✔
3503
        // over the slice and return nil.
19✔
3504
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
19✔
3505
        for _, link := range links {
37✔
3506
                if link.ChanID() == cid {
36✔
3507
                        chanLink = link
18✔
3508
                        break
18✔
3509
                }
3510
        }
3511

3512
        return chanLink
19✔
3513
}
3514

3515
// finalizeChanClosure performs the final clean up steps once the cooperative
3516
// closure transaction has been fully broadcast. The finalized closing state
3517
// machine should be passed in. Once the transaction has been sufficiently
3518
// confirmed, the channel will be marked as fully closed within the database,
3519
// and any clients will be notified of updates to the closing state.
3520
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
4✔
3521
        closeReq := chanCloser.CloseRequest()
4✔
3522

4✔
3523
        // First, we'll clear all indexes related to the channel in question.
4✔
3524
        chanPoint := chanCloser.Channel().ChannelPoint()
4✔
3525
        p.WipeChannel(&chanPoint)
4✔
3526

4✔
3527
        // Also clear the activeChanCloses map of this channel.
4✔
3528
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
3529
        delete(p.activeChanCloses, cid)
4✔
3530

4✔
3531
        // Next, we'll launch a goroutine which will request to be notified by
4✔
3532
        // the ChainNotifier once the closure transaction obtains a single
4✔
3533
        // confirmation.
4✔
3534
        notifier := p.cfg.ChainNotifier
4✔
3535

4✔
3536
        // If any error happens during waitForChanToClose, forward it to
4✔
3537
        // closeReq. If this channel closure is not locally initiated, closeReq
4✔
3538
        // will be nil, so just ignore the error.
4✔
3539
        errChan := make(chan error, 1)
4✔
3540
        if closeReq != nil {
6✔
3541
                errChan = closeReq.Err
2✔
3542
        }
2✔
3543

3544
        closingTx, err := chanCloser.ClosingTx()
4✔
3545
        if err != nil {
4✔
3546
                if closeReq != nil {
×
3547
                        p.log.Error(err)
×
3548
                        closeReq.Err <- err
×
3549
                }
×
3550
        }
3551

3552
        closingTxid := closingTx.TxHash()
4✔
3553

4✔
3554
        // If this is a locally requested shutdown, update the caller with a
4✔
3555
        // new event detailing the current pending state of this request.
4✔
3556
        if closeReq != nil {
6✔
3557
                closeReq.Updates <- &PendingUpdate{
2✔
3558
                        Txid: closingTxid[:],
2✔
3559
                }
2✔
3560
        }
2✔
3561

3562
        localOut := chanCloser.LocalCloseOutput()
4✔
3563
        remoteOut := chanCloser.RemoteCloseOutput()
4✔
3564
        auxOut := chanCloser.AuxOutputs()
4✔
3565
        go WaitForChanToClose(
4✔
3566
                chanCloser.NegotiationHeight(), notifier, errChan,
4✔
3567
                &chanPoint, &closingTxid, closingTx.TxOut[0].PkScript, func() {
8✔
3568
                        // Respond to the local subsystem which requested the
4✔
3569
                        // channel closure.
4✔
3570
                        if closeReq != nil {
6✔
3571
                                closeReq.Updates <- &ChannelCloseUpdate{
2✔
3572
                                        ClosingTxid:       closingTxid[:],
2✔
3573
                                        Success:           true,
2✔
3574
                                        LocalCloseOutput:  localOut,
2✔
3575
                                        RemoteCloseOutput: remoteOut,
2✔
3576
                                        AuxOutputs:        auxOut,
2✔
3577
                                }
2✔
3578
                        }
2✔
3579
                },
3580
        )
3581
}
3582

3583
// WaitForChanToClose uses the passed notifier to wait until the channel has
3584
// been detected as closed on chain and then concludes by executing the
3585
// following actions: the channel point will be sent over the settleChan, and
3586
// finally the callback will be executed. If any error is encountered within
3587
// the function, then it will be sent over the errChan.
3588
func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
3589
        errChan chan error, chanPoint *wire.OutPoint,
3590
        closingTxID *chainhash.Hash, closeScript []byte, cb func()) {
4✔
3591

4✔
3592
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
4✔
3593
                "with txid: %v", chanPoint, closingTxID)
4✔
3594

4✔
3595
        // TODO(roasbeef): add param for num needed confs
4✔
3596
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
4✔
3597
                closingTxID, closeScript, 1, bestHeight,
4✔
3598
        )
4✔
3599
        if err != nil {
4✔
3600
                if errChan != nil {
×
3601
                        errChan <- err
×
3602
                }
×
3603
                return
×
3604
        }
3605

3606
        // In the case that the ChainNotifier is shutting down, all subscriber
3607
        // notification channels will be closed, generating a nil receive.
3608
        height, ok := <-confNtfn.Confirmed
4✔
3609
        if !ok {
4✔
UNCOV
3610
                return
×
UNCOV
3611
        }
×
3612

3613
        // The channel has been closed, remove it from any active indexes, and
3614
        // the database state.
3615
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
4✔
3616
                "height %v", chanPoint, height.BlockHeight)
4✔
3617

4✔
3618
        // Finally, execute the closure call back to mark the confirmation of
4✔
3619
        // the transaction closing the contract.
4✔
3620
        cb()
4✔
3621
}
3622

3623
// WipeChannel removes the passed channel point from all indexes associated with
3624
// the peer and the switch.
3625
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
4✔
3626
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
4✔
3627

4✔
3628
        p.activeChannels.Delete(chanID)
4✔
3629

4✔
3630
        // Instruct the HtlcSwitch to close this link as the channel is no
4✔
3631
        // longer active.
4✔
3632
        p.cfg.Switch.RemoveLink(chanID)
4✔
3633
}
4✔
3634

3635
// handleInitMsg handles the incoming init message which contains global and
3636
// local feature vectors. If feature vectors are incompatible then disconnect.
3637
func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
3✔
3638
        // First, merge any features from the legacy global features field into
3✔
3639
        // those presented in the local features fields.
3✔
3640
        err := msg.Features.Merge(msg.GlobalFeatures)
3✔
3641
        if err != nil {
3✔
3642
                return fmt.Errorf("unable to merge legacy global features: %w",
×
3643
                        err)
×
3644
        }
×
3645

3646
        // Then, finalize the remote feature vector providing the flattened
3647
        // feature bit namespace.
3648
        p.remoteFeatures = lnwire.NewFeatureVector(
3✔
3649
                msg.Features, lnwire.Features,
3✔
3650
        )
3✔
3651

3✔
3652
        // Now that we have their features loaded, we'll ensure that they
3✔
3653
        // didn't set any required bits that we don't know of.
3✔
3654
        err = feature.ValidateRequired(p.remoteFeatures)
3✔
3655
        if err != nil {
3✔
3656
                return fmt.Errorf("invalid remote features: %w", err)
×
3657
        }
×
3658

3659
        // Ensure the remote party's feature vector contains all transitive
3660
        // dependencies. We know ours are correct since they are validated
3661
        // during the feature manager's instantiation.
3662
        err = feature.ValidateDeps(p.remoteFeatures)
3✔
3663
        if err != nil {
3✔
3664
                return fmt.Errorf("invalid remote features: %w", err)
×
3665
        }
×
3666

3667
        // Now that we know we understand their requirements, we'll check to
3668
        // see if they don't support anything that we deem to be mandatory.
3669
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
3✔
3670
                return fmt.Errorf("data loss protection required")
×
3671
        }
×
3672

3673
        return nil
3✔
3674
}
3675

3676
// LocalFeatures returns the set of global features that has been advertised by
3677
// the local node. This allows sub-systems that use this interface to gate their
3678
// behavior off the set of negotiated feature bits.
3679
//
3680
// NOTE: Part of the lnpeer.Peer interface.
UNCOV
3681
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
×
UNCOV
3682
        return p.cfg.Features
×
UNCOV
3683
}
×
3684

3685
// RemoteFeatures returns the set of global features that has been advertised by
3686
// the remote node. This allows sub-systems that use this interface to gate
3687
// their behavior off the set of negotiated feature bits.
3688
//
3689
// NOTE: Part of the lnpeer.Peer interface.
3690
func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector {
6✔
3691
        return p.remoteFeatures
6✔
3692
}
6✔
3693

3694
// hasNegotiatedScidAlias returns true if we've negotiated the
3695
// option-scid-alias feature bit with the peer.
3696
func (p *Brontide) hasNegotiatedScidAlias() bool {
3✔
3697
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
3✔
3698
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
3✔
3699
        return peerHas && localHas
3✔
3700
}
3✔
3701

3702
// sendInitMsg sends the Init message to the remote peer. This message contains
3703
// our currently supported local and global features.
3704
func (p *Brontide) sendInitMsg(legacyChan bool) error {
7✔
3705
        features := p.cfg.Features.Clone()
7✔
3706
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
7✔
3707

7✔
3708
        // If we have a legacy channel open with a peer, we downgrade static
7✔
3709
        // remote required to optional in case the peer does not understand the
7✔
3710
        // required feature bit. If we do not do this, the peer will reject our
7✔
3711
        // connection because it does not understand a required feature bit, and
7✔
3712
        // our channel will be unusable.
7✔
3713
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
8✔
3714
                p.log.Infof("Legacy channel open with peer, " +
1✔
3715
                        "downgrading static remote required feature bit to " +
1✔
3716
                        "optional")
1✔
3717

1✔
3718
                // Unset and set in both the local and global features to
1✔
3719
                // ensure both sets are consistent and merge able by old and
1✔
3720
                // new nodes.
1✔
3721
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3722
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3723

1✔
3724
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
3725
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
3726
        }
1✔
3727

3728
        msg := lnwire.NewInitMessage(
7✔
3729
                legacyFeatures.RawFeatureVector,
7✔
3730
                features.RawFeatureVector,
7✔
3731
        )
7✔
3732

7✔
3733
        return p.writeMessage(msg)
7✔
3734
}
3735

3736
// resendChanSyncMsg will attempt to find a channel sync message for the closed
3737
// channel and resend it to our peer.
UNCOV
3738
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
×
UNCOV
3739
        // If we already re-sent the mssage for this channel, we won't do it
×
UNCOV
3740
        // again.
×
UNCOV
3741
        if _, ok := p.resentChanSyncMsg[cid]; ok {
×
UNCOV
3742
                return nil
×
UNCOV
3743
        }
×
3744

3745
        // Check if we have any channel sync messages stored for this channel.
UNCOV
3746
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
×
UNCOV
3747
        if err != nil {
×
UNCOV
3748
                return fmt.Errorf("unable to fetch channel sync messages for "+
×
UNCOV
3749
                        "peer %v: %v", p, err)
×
UNCOV
3750
        }
×
3751

UNCOV
3752
        if c.LastChanSyncMsg == nil {
×
3753
                return fmt.Errorf("no chan sync message stored for channel %v",
×
3754
                        cid)
×
3755
        }
×
3756

UNCOV
3757
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
×
3758
                return fmt.Errorf("ignoring channel reestablish from "+
×
3759
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
3760
        }
×
3761

UNCOV
3762
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
×
UNCOV
3763
                "peer", cid)
×
UNCOV
3764

×
UNCOV
3765
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
×
3766
                return fmt.Errorf("failed resending channel sync "+
×
3767
                        "message to peer %v: %v", p, err)
×
3768
        }
×
3769

UNCOV
3770
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
×
UNCOV
3771
                cid)
×
UNCOV
3772

×
UNCOV
3773
        // Note down that we sent the message, so we won't resend it again for
×
UNCOV
3774
        // this connection.
×
UNCOV
3775
        p.resentChanSyncMsg[cid] = struct{}{}
×
UNCOV
3776

×
UNCOV
3777
        return nil
×
3778
}
3779

3780
// SendMessage sends a variadic number of high-priority messages to the remote
3781
// peer. The first argument denotes if the method should block until the
3782
// messages have been sent to the remote peer or an error is returned,
3783
// otherwise it returns immediately after queuing.
3784
//
3785
// NOTE: Part of the lnpeer.Peer interface.
3786
func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error {
3✔
3787
        return p.sendMessage(sync, true, msgs...)
3✔
3788
}
3✔
3789

3790
// SendMessageLazy sends a variadic number of low-priority messages to the
3791
// remote peer. The first argument denotes if the method should block until
3792
// the messages have been sent to the remote peer or an error is returned,
3793
// otherwise it returns immediately after queueing.
3794
//
3795
// NOTE: Part of the lnpeer.Peer interface.
3796
func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
1✔
3797
        return p.sendMessage(sync, false, msgs...)
1✔
3798
}
1✔
3799

3800
// sendMessage queues a variadic number of messages using the passed priority
3801
// to the remote peer. If sync is true, this method will block until the
3802
// messages have been sent to the remote peer or an error is returned, otherwise
3803
// it returns immediately after queueing.
3804
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
4✔
3805
        // Add all incoming messages to the outgoing queue. A list of error
4✔
3806
        // chans is populated for each message if the caller requested a sync
4✔
3807
        // send.
4✔
3808
        var errChans []chan error
4✔
3809
        if sync {
5✔
3810
                errChans = make([]chan error, 0, len(msgs))
1✔
3811
        }
1✔
3812
        for _, msg := range msgs {
8✔
3813
                // If a sync send was requested, create an error chan to listen
4✔
3814
                // for an ack from the writeHandler.
4✔
3815
                var errChan chan error
4✔
3816
                if sync {
5✔
3817
                        errChan = make(chan error, 1)
1✔
3818
                        errChans = append(errChans, errChan)
1✔
3819
                }
1✔
3820

3821
                if priority {
7✔
3822
                        p.queueMsg(msg, errChan)
3✔
3823
                } else {
4✔
3824
                        p.queueMsgLazy(msg, errChan)
1✔
3825
                }
1✔
3826
        }
3827

3828
        // Wait for all replies from the writeHandler. For async sends, this
3829
        // will be a NOP as the list of error chans is nil.
3830
        for _, errChan := range errChans {
5✔
3831
                select {
1✔
3832
                case err := <-errChan:
1✔
3833
                        return err
1✔
3834
                case <-p.quit:
×
3835
                        return lnpeer.ErrPeerExiting
×
UNCOV
3836
                case <-p.cfg.Quit:
×
UNCOV
3837
                        return lnpeer.ErrPeerExiting
×
3838
                }
3839
        }
3840

3841
        return nil
3✔
3842
}
3843

3844
// PubKey returns the pubkey of the peer in compressed serialized format.
3845
//
3846
// NOTE: Part of the lnpeer.Peer interface.
3847
func (p *Brontide) PubKey() [33]byte {
2✔
3848
        return p.cfg.PubKeyBytes
2✔
3849
}
2✔
3850

3851
// IdentityKey returns the public key of the remote peer.
3852
//
3853
// NOTE: Part of the lnpeer.Peer interface.
3854
func (p *Brontide) IdentityKey() *btcec.PublicKey {
15✔
3855
        return p.cfg.Addr.IdentityKey
15✔
3856
}
15✔
3857

3858
// Address returns the network address of the remote peer.
3859
//
3860
// NOTE: Part of the lnpeer.Peer interface.
UNCOV
3861
func (p *Brontide) Address() net.Addr {
×
UNCOV
3862
        return p.cfg.Addr.Address
×
UNCOV
3863
}
×
3864

3865
// AddNewChannel adds a new channel to the peer. The channel should fail to be
3866
// added if the cancel channel is closed.
3867
//
3868
// NOTE: Part of the lnpeer.Peer interface.
3869
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
UNCOV
3870
        cancel <-chan struct{}) error {
×
UNCOV
3871

×
UNCOV
3872
        errChan := make(chan error, 1)
×
UNCOV
3873
        newChanMsg := &newChannelMsg{
×
UNCOV
3874
                channel: newChan,
×
UNCOV
3875
                err:     errChan,
×
UNCOV
3876
        }
×
UNCOV
3877

×
UNCOV
3878
        select {
×
UNCOV
3879
        case p.newActiveChannel <- newChanMsg:
×
3880
        case <-cancel:
×
3881
                return errors.New("canceled adding new channel")
×
3882
        case <-p.quit:
×
3883
                return lnpeer.ErrPeerExiting
×
3884
        }
3885

3886
        // We pause here to wait for the peer to recognize the new channel
3887
        // before we close the channel barrier corresponding to the channel.
UNCOV
3888
        select {
×
UNCOV
3889
        case err := <-errChan:
×
UNCOV
3890
                return err
×
3891
        case <-p.quit:
×
3892
                return lnpeer.ErrPeerExiting
×
3893
        }
3894
}
3895

3896
// AddPendingChannel adds a pending open channel to the peer. The channel
3897
// should fail to be added if the cancel channel is closed.
3898
//
3899
// NOTE: Part of the lnpeer.Peer interface.
3900
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
UNCOV
3901
        cancel <-chan struct{}) error {
×
UNCOV
3902

×
UNCOV
3903
        errChan := make(chan error, 1)
×
UNCOV
3904
        newChanMsg := &newChannelMsg{
×
UNCOV
3905
                channelID: cid,
×
UNCOV
3906
                err:       errChan,
×
UNCOV
3907
        }
×
UNCOV
3908

×
UNCOV
3909
        select {
×
UNCOV
3910
        case p.newPendingChannel <- newChanMsg:
×
3911

3912
        case <-cancel:
×
3913
                return errors.New("canceled adding pending channel")
×
3914

3915
        case <-p.quit:
×
3916
                return lnpeer.ErrPeerExiting
×
3917
        }
3918

3919
        // We pause here to wait for the peer to recognize the new pending
3920
        // channel before we close the channel barrier corresponding to the
3921
        // channel.
UNCOV
3922
        select {
×
UNCOV
3923
        case err := <-errChan:
×
UNCOV
3924
                return err
×
3925

3926
        case <-cancel:
×
3927
                return errors.New("canceled adding pending channel")
×
3928

3929
        case <-p.quit:
×
3930
                return lnpeer.ErrPeerExiting
×
3931
        }
3932
}
3933

3934
// RemovePendingChannel removes a pending open channel from the peer.
3935
//
3936
// NOTE: Part of the lnpeer.Peer interface.
UNCOV
3937
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
×
UNCOV
3938
        errChan := make(chan error, 1)
×
UNCOV
3939
        newChanMsg := &newChannelMsg{
×
UNCOV
3940
                channelID: cid,
×
UNCOV
3941
                err:       errChan,
×
UNCOV
3942
        }
×
UNCOV
3943

×
UNCOV
3944
        select {
×
UNCOV
3945
        case p.removePendingChannel <- newChanMsg:
×
3946
        case <-p.quit:
×
3947
                return lnpeer.ErrPeerExiting
×
3948
        }
3949

3950
        // We pause here to wait for the peer to respond to the cancellation of
3951
        // the pending channel before we close the channel barrier
3952
        // corresponding to the channel.
UNCOV
3953
        select {
×
UNCOV
3954
        case err := <-errChan:
×
UNCOV
3955
                return err
×
3956

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

3962
// StartTime returns the time at which the connection was established if the
3963
// peer started successfully, and zero otherwise.
UNCOV
3964
func (p *Brontide) StartTime() time.Time {
×
UNCOV
3965
        return p.startTime
×
UNCOV
3966
}
×
3967

3968
// handleCloseMsg is called when a new cooperative channel closure related
3969
// message is received from the remote peer. We'll use this message to advance
3970
// the chan closer state machine.
3971
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
13✔
3972
        link := p.fetchLinkFromKeyAndCid(msg.cid)
13✔
3973

13✔
3974
        // We'll now fetch the matching closing state machine in order to continue,
13✔
3975
        // or finalize the channel closure process.
13✔
3976
        chanCloser, err := p.fetchActiveChanCloser(msg.cid)
13✔
3977
        if err != nil {
13✔
UNCOV
3978
                // If the channel is not known to us, we'll simply ignore this message.
×
UNCOV
3979
                if err == ErrChannelNotFound {
×
UNCOV
3980
                        return
×
UNCOV
3981
                }
×
3982

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

×
3985
                errMsg := &lnwire.Error{
×
3986
                        ChanID: msg.cid,
×
3987
                        Data:   lnwire.ErrorData(err.Error()),
×
3988
                }
×
3989
                p.queueMsg(errMsg, nil)
×
3990
                return
×
3991
        }
3992

3993
        handleErr := func(err error) {
13✔
UNCOV
3994
                err = fmt.Errorf("unable to process close msg: %w", err)
×
UNCOV
3995
                p.log.Error(err)
×
UNCOV
3996

×
UNCOV
3997
                // As the negotiations failed, we'll reset the channel state machine to
×
UNCOV
3998
                // ensure we act to on-chain events as normal.
×
UNCOV
3999
                chanCloser.Channel().ResetState()
×
UNCOV
4000

×
UNCOV
4001
                if chanCloser.CloseRequest() != nil {
×
4002
                        chanCloser.CloseRequest().Err <- err
×
4003
                }
×
UNCOV
4004
                delete(p.activeChanCloses, msg.cid)
×
UNCOV
4005

×
UNCOV
4006
                p.Disconnect(err)
×
4007
        }
4008

4009
        // Next, we'll process the next message using the target state machine.
4010
        // We'll either continue negotiation, or halt.
4011
        switch typed := msg.msg.(type) {
13✔
4012
        case *lnwire.Shutdown:
5✔
4013
                // Disable incoming adds immediately.
5✔
4014
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
5✔
4015
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
4016
                                link.ChanID())
×
4017
                }
×
4018

4019
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
5✔
4020
                if err != nil {
5✔
4021
                        handleErr(err)
×
4022
                        return
×
4023
                }
×
4024

4025
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
8✔
4026
                        // If the link is nil it means we can immediately queue
3✔
4027
                        // the Shutdown message since we don't have to wait for
3✔
4028
                        // commitment transaction synchronization.
3✔
4029
                        if link == nil {
4✔
4030
                                p.queueMsg(&msg, nil)
1✔
4031
                                return
1✔
4032
                        }
1✔
4033

4034
                        // Immediately disallow any new HTLC's from being added
4035
                        // in the outgoing direction.
4036
                        if !link.DisableAdds(htlcswitch.Outgoing) {
2✔
4037
                                p.log.Warnf("Outgoing link adds already "+
×
4038
                                        "disabled: %v", link.ChanID())
×
4039
                        }
×
4040

4041
                        // When we have a Shutdown to send, we defer it till the
4042
                        // next time we send a CommitSig to remain spec
4043
                        // compliant.
4044
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
4✔
4045
                                p.queueMsg(&msg, nil)
2✔
4046
                        })
2✔
4047
                })
4048

4049
                beginNegotiation := func() {
10✔
4050
                        oClosingSigned, err := chanCloser.BeginNegotiation()
5✔
4051
                        if err != nil {
5✔
UNCOV
4052
                                handleErr(err)
×
UNCOV
4053
                                return
×
UNCOV
4054
                        }
×
4055

4056
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
10✔
4057
                                p.queueMsg(&msg, nil)
5✔
4058
                        })
5✔
4059
                }
4060

4061
                if link == nil {
6✔
4062
                        beginNegotiation()
1✔
4063
                } else {
5✔
4064
                        // Now we register a flush hook to advance the
4✔
4065
                        // ChanCloser and possibly send out a ClosingSigned
4✔
4066
                        // when the link finishes draining.
4✔
4067
                        link.OnFlushedOnce(func() {
8✔
4068
                                // Remove link in goroutine to prevent deadlock.
4✔
4069
                                go p.cfg.Switch.RemoveLink(msg.cid)
4✔
4070
                                beginNegotiation()
4✔
4071
                        })
4✔
4072
                }
4073

4074
        case *lnwire.ClosingSigned:
8✔
4075
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
8✔
4076
                if err != nil {
8✔
4077
                        handleErr(err)
×
4078
                        return
×
4079
                }
×
4080

4081
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
16✔
4082
                        p.queueMsg(&msg, nil)
8✔
4083
                })
8✔
4084

4085
        default:
×
4086
                panic("impossible closeMsg type")
×
4087
        }
4088

4089
        // If we haven't finished close negotiations, then we'll continue as we
4090
        // can't yet finalize the closure.
4091
        if _, err := chanCloser.ClosingTx(); err != nil {
20✔
4092
                return
8✔
4093
        }
8✔
4094

4095
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
4096
        // the channel closure by notifying relevant sub-systems and launching a
4097
        // goroutine to wait for close tx conf.
4098
        p.finalizeChanClosure(chanCloser)
4✔
4099
}
4100

4101
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
4102
// the channelManager goroutine, which will shut down the link and possibly
4103
// close the channel.
UNCOV
4104
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
×
UNCOV
4105
        select {
×
UNCOV
4106
        case p.localCloseChanReqs <- req:
×
UNCOV
4107
                p.log.Info("Local close channel request is going to be " +
×
UNCOV
4108
                        "delivered to the peer")
×
4109
        case <-p.quit:
×
4110
                p.log.Info("Unable to deliver local close channel request " +
×
4111
                        "to peer")
×
4112
        }
4113
}
4114

4115
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
UNCOV
4116
func (p *Brontide) NetAddress() *lnwire.NetAddress {
×
UNCOV
4117
        return p.cfg.Addr
×
UNCOV
4118
}
×
4119

4120
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
UNCOV
4121
func (p *Brontide) Inbound() bool {
×
UNCOV
4122
        return p.cfg.Inbound
×
UNCOV
4123
}
×
4124

4125
// ConnReq is a getter for the Brontide's connReq in cfg.
UNCOV
4126
func (p *Brontide) ConnReq() *connmgr.ConnReq {
×
UNCOV
4127
        return p.cfg.ConnReq
×
UNCOV
4128
}
×
4129

4130
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
UNCOV
4131
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
×
UNCOV
4132
        return p.cfg.ErrorBuffer
×
UNCOV
4133
}
×
4134

4135
// SetAddress sets the remote peer's address given an address.
4136
func (p *Brontide) SetAddress(address net.Addr) {
×
4137
        p.cfg.Addr.Address = address
×
4138
}
×
4139

4140
// ActiveSignal returns the peer's active signal.
UNCOV
4141
func (p *Brontide) ActiveSignal() chan struct{} {
×
UNCOV
4142
        return p.activeSignal
×
UNCOV
4143
}
×
4144

4145
// Conn returns a pointer to the peer's connection struct.
UNCOV
4146
func (p *Brontide) Conn() net.Conn {
×
UNCOV
4147
        return p.cfg.Conn
×
UNCOV
4148
}
×
4149

4150
// BytesReceived returns the number of bytes received from the peer.
UNCOV
4151
func (p *Brontide) BytesReceived() uint64 {
×
UNCOV
4152
        return atomic.LoadUint64(&p.bytesReceived)
×
UNCOV
4153
}
×
4154

4155
// BytesSent returns the number of bytes sent to the peer.
UNCOV
4156
func (p *Brontide) BytesSent() uint64 {
×
UNCOV
4157
        return atomic.LoadUint64(&p.bytesSent)
×
UNCOV
4158
}
×
4159

4160
// LastRemotePingPayload returns the last payload the remote party sent as part
4161
// of their ping.
UNCOV
4162
func (p *Brontide) LastRemotePingPayload() []byte {
×
UNCOV
4163
        pingPayload := p.lastPingPayload.Load()
×
UNCOV
4164
        if pingPayload == nil {
×
UNCOV
4165
                return []byte{}
×
UNCOV
4166
        }
×
4167

UNCOV
4168
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
UNCOV
4169
        if !ok {
×
4170
                return nil
×
4171
        }
×
4172

UNCOV
4173
        return pingBytes
×
4174
}
4175

4176
// attachChannelEventSubscription creates a channel event subscription and
4177
// attaches to client to Brontide if the reenableTimeout is no greater than 1
4178
// minute.
4179
func (p *Brontide) attachChannelEventSubscription() error {
3✔
4180
        // If the timeout is greater than 1 minute, it's unlikely that the link
3✔
4181
        // hasn't yet finished its reestablishment. Return a nil without
3✔
4182
        // creating the client to specify that we don't want to retry.
3✔
4183
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
3✔
UNCOV
4184
                return nil
×
UNCOV
4185
        }
×
4186

4187
        // When the reenable timeout is less than 1 minute, it's likely the
4188
        // channel link hasn't finished its reestablishment yet. In that case,
4189
        // we'll give it a second chance by subscribing to the channel update
4190
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
4191
        // enabling the channel again.
4192
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
3✔
4193
        if err != nil {
3✔
4194
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
4195
        }
×
4196

4197
        p.channelEventClient = sub
3✔
4198

3✔
4199
        return nil
3✔
4200
}
4201

4202
// updateNextRevocation updates the existing channel's next revocation if it's
4203
// nil.
4204
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
3✔
4205
        chanPoint := c.FundingOutpoint
3✔
4206
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4207

3✔
4208
        // Read the current channel.
3✔
4209
        currentChan, loaded := p.activeChannels.Load(chanID)
3✔
4210

3✔
4211
        // currentChan should exist, but we perform a check anyway to avoid nil
3✔
4212
        // pointer dereference.
3✔
4213
        if !loaded {
4✔
4214
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
4215
                        chanID)
1✔
4216
        }
1✔
4217

4218
        // currentChan should not be nil, but we perform a check anyway to
4219
        // avoid nil pointer dereference.
4220
        if currentChan == nil {
3✔
4221
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
4222
                        chanID)
1✔
4223
        }
1✔
4224

4225
        // If we're being sent a new channel, and our existing channel doesn't
4226
        // have the next revocation, then we need to update the current
4227
        // existing channel.
4228
        if currentChan.RemoteNextRevocation() != nil {
1✔
4229
                return nil
×
4230
        }
×
4231

4232
        p.log.Infof("Processing retransmitted ChannelReady for "+
1✔
4233
                "ChannelPoint(%v)", chanPoint)
1✔
4234

1✔
4235
        nextRevoke := c.RemoteNextRevocation
1✔
4236

1✔
4237
        err := currentChan.InitNextRevocation(nextRevoke)
1✔
4238
        if err != nil {
1✔
4239
                return fmt.Errorf("unable to init next revocation: %w", err)
×
4240
        }
×
4241

4242
        return nil
1✔
4243
}
4244

4245
// addActiveChannel adds a new active channel to the `activeChannels` map. It
4246
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
4247
// it and assembles it with a channel link.
UNCOV
4248
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
×
UNCOV
4249
        chanPoint := c.FundingOutpoint
×
UNCOV
4250
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
4251

×
UNCOV
4252
        // If we've reached this point, there are two possible scenarios.  If
×
UNCOV
4253
        // the channel was in the active channels map as nil, then it was
×
UNCOV
4254
        // loaded from disk and we need to send reestablish. Else, it was not
×
UNCOV
4255
        // loaded from disk and we don't need to send reestablish as this is a
×
UNCOV
4256
        // fresh channel.
×
UNCOV
4257
        shouldReestablish := p.isLoadedFromDisk(chanID)
×
UNCOV
4258

×
UNCOV
4259
        chanOpts := c.ChanOpts
×
UNCOV
4260
        if shouldReestablish {
×
UNCOV
4261
                // If we have to do the reestablish dance for this channel,
×
UNCOV
4262
                // ensure that we don't try to call InitRemoteMusigNonces twice
×
UNCOV
4263
                // by calling SkipNonceInit.
×
UNCOV
4264
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
×
UNCOV
4265
        }
×
4266

UNCOV
4267
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
×
4268
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
4269
        })
×
UNCOV
4270
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
×
4271
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
4272
        })
×
UNCOV
4273
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
×
4274
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
4275
        })
×
4276

4277
        // If not already active, we'll add this channel to the set of active
4278
        // channels, so we can look it up later easily according to its channel
4279
        // ID.
UNCOV
4280
        lnChan, err := lnwallet.NewLightningChannel(
×
UNCOV
4281
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
×
UNCOV
4282
        )
×
UNCOV
4283
        if err != nil {
×
4284
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
4285
        }
×
4286

4287
        // Store the channel in the activeChannels map.
UNCOV
4288
        p.activeChannels.Store(chanID, lnChan)
×
UNCOV
4289

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

×
UNCOV
4292
        // Next, we'll assemble a ChannelLink along with the necessary items it
×
UNCOV
4293
        // needs to function.
×
UNCOV
4294
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
×
UNCOV
4295
        if err != nil {
×
4296
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
4297
                        err)
×
4298
        }
×
4299

4300
        // We'll query the channel DB for the new channel's initial forwarding
4301
        // policies to determine the policy we start out with.
UNCOV
4302
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
×
UNCOV
4303
        if err != nil {
×
4304
                return fmt.Errorf("unable to query for initial forwarding "+
×
4305
                        "policy: %v", err)
×
4306
        }
×
4307

4308
        // Create the link and add it to the switch.
UNCOV
4309
        err = p.addLink(
×
UNCOV
4310
                &chanPoint, lnChan, initialPolicy, chainEvents,
×
UNCOV
4311
                shouldReestablish, fn.None[lnwire.Shutdown](),
×
UNCOV
4312
        )
×
UNCOV
4313
        if err != nil {
×
4314
                return fmt.Errorf("can't register new channel link(%v) with "+
×
4315
                        "peer", chanPoint)
×
4316
        }
×
4317

UNCOV
4318
        return nil
×
4319
}
4320

4321
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
4322
// know this channel ID or not, we'll either add it to the `activeChannels` map
4323
// or init the next revocation for it.
UNCOV
4324
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
×
UNCOV
4325
        newChan := req.channel
×
UNCOV
4326
        chanPoint := newChan.FundingOutpoint
×
UNCOV
4327
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
4328

×
UNCOV
4329
        // Only update RemoteNextRevocation if the channel is in the
×
UNCOV
4330
        // activeChannels map and if we added the link to the switch. Only
×
UNCOV
4331
        // active channels will be added to the switch.
×
UNCOV
4332
        if p.isActiveChannel(chanID) {
×
UNCOV
4333
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
×
UNCOV
4334
                        chanPoint)
×
UNCOV
4335

×
UNCOV
4336
                // Handle it and close the err chan on the request.
×
UNCOV
4337
                close(req.err)
×
UNCOV
4338

×
UNCOV
4339
                // Update the next revocation point.
×
UNCOV
4340
                err := p.updateNextRevocation(newChan.OpenChannel)
×
UNCOV
4341
                if err != nil {
×
4342
                        p.log.Errorf(err.Error())
×
4343
                }
×
4344

UNCOV
4345
                return
×
4346
        }
4347

4348
        // This is a new channel, we now add it to the map.
UNCOV
4349
        if err := p.addActiveChannel(req.channel); err != nil {
×
4350
                // Log and send back the error to the request.
×
4351
                p.log.Errorf(err.Error())
×
4352
                req.err <- err
×
4353

×
4354
                return
×
4355
        }
×
4356

4357
        // Close the err chan if everything went fine.
UNCOV
4358
        close(req.err)
×
4359
}
4360

4361
// handleNewPendingChannel takes a `newChannelMsg` request and add it to
4362
// `activeChannels` map with nil value. This pending channel will be saved as
4363
// it may become active in the future. Once active, the funding manager will
4364
// send it again via `AddNewChannel`, and we'd handle the link creation there.
4365
func (p *Brontide) handleNewPendingChannel(req *newChannelMsg) {
4✔
4366
        defer close(req.err)
4✔
4367

4✔
4368
        chanID := req.channelID
4✔
4369

4✔
4370
        // If we already have this channel, something is wrong with the funding
4✔
4371
        // flow as it will only be marked as active after `ChannelReady` is
4✔
4372
        // handled. In this case, we will do nothing but log an error, just in
4✔
4373
        // case this is a legit channel.
4✔
4374
        if p.isActiveChannel(chanID) {
5✔
4375
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
4376
                        "pending channel request", chanID)
1✔
4377

1✔
4378
                return
1✔
4379
        }
1✔
4380

4381
        // The channel has already been added, we will do nothing and return.
4382
        if p.isPendingChannel(chanID) {
4✔
4383
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
4384
                        "pending channel request", chanID)
1✔
4385

1✔
4386
                return
1✔
4387
        }
1✔
4388

4389
        // This is a new channel, we now add it to the map `activeChannels`
4390
        // with nil value and mark it as a newly added channel in
4391
        // `addedChannels`.
4392
        p.activeChannels.Store(chanID, nil)
2✔
4393
        p.addedChannels.Store(chanID, struct{}{})
2✔
4394
}
4395

4396
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
4397
// from `activeChannels` map. The request will be ignored if the channel is
4398
// considered active by Brontide. Noop if the channel ID cannot be found.
4399
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
4✔
4400
        defer close(req.err)
4✔
4401

4✔
4402
        chanID := req.channelID
4✔
4403

4✔
4404
        // If we already have this channel, something is wrong with the funding
4✔
4405
        // flow as it will only be marked as active after `ChannelReady` is
4✔
4406
        // handled. In this case, we will log an error and exit.
4✔
4407
        if p.isActiveChannel(chanID) {
5✔
4408
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
4409
                        chanID)
1✔
4410
                return
1✔
4411
        }
1✔
4412

4413
        // The channel has not been added yet, we will log a warning as there
4414
        // is an unexpected call from funding manager.
4415
        if !p.isPendingChannel(chanID) {
4✔
4416
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
1✔
4417
        }
1✔
4418

4419
        // Remove the record of this pending channel.
4420
        p.activeChannels.Delete(chanID)
3✔
4421
        p.addedChannels.Delete(chanID)
3✔
4422
}
4423

4424
// sendLinkUpdateMsg sends a message that updates the channel to the
4425
// channel's message stream.
UNCOV
4426
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
×
UNCOV
4427
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
×
UNCOV
4428

×
UNCOV
4429
        chanStream, ok := p.activeMsgStreams[cid]
×
UNCOV
4430
        if !ok {
×
UNCOV
4431
                // If a stream hasn't yet been created, then we'll do so, add
×
UNCOV
4432
                // it to the map, and finally start it.
×
UNCOV
4433
                chanStream = newChanMsgStream(p, cid)
×
UNCOV
4434
                p.activeMsgStreams[cid] = chanStream
×
UNCOV
4435
                chanStream.Start()
×
UNCOV
4436

×
UNCOV
4437
                // Stop the stream when quit.
×
UNCOV
4438
                go func() {
×
UNCOV
4439
                        <-p.quit
×
UNCOV
4440
                        chanStream.Stop()
×
UNCOV
4441
                }()
×
4442
        }
4443

4444
        // With the stream obtained, add the message to the stream so we can
4445
        // continue processing message.
UNCOV
4446
        chanStream.AddMsg(msg)
×
4447
}
4448

4449
// scaleTimeout multiplies the argument duration by a constant factor depending
4450
// on variious heuristics. Currently this is only used to check whether our peer
4451
// appears to be connected over Tor and relaxes the timout deadline. However,
4452
// this is subject to change and should be treated as opaque.
4453
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
67✔
4454
        if p.isTorConnection {
67✔
UNCOV
4455
                return timeout * time.Duration(torTimeoutMultiplier)
×
UNCOV
4456
        }
×
4457

4458
        return timeout
67✔
4459
}
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