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

lightningnetwork / lnd / 11393106485

17 Oct 2024 09:10PM UTC coverage: 57.848% (-1.0%) from 58.81%
11393106485

Pull #9148

github

ProofOfKeags
lnwire: convert DynPropose and DynCommit to use typed tlv records
Pull Request #9148: DynComms [2/n]: lnwire: add authenticated wire messages for Dyn*

142 of 177 new or added lines in 4 files covered. (80.23%)

18983 existing lines in 242 files now uncovered.

99003 of 171143 relevant lines covered (57.85%)

36968.25 hits per line

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

37.64
/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
        // MaxFeeExposure limits the number of outstanding fees in a channel.
415
        // This value will be passed to created links.
416
        MaxFeeExposure lnwire.MilliSatoshi
417

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

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

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

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

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

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

463
        pingManager *PingManager
464

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

472
        cfg Config
473

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
657
                return lastSerializedBlockHeader[:]
×
658
        }
659

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

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

689
        return p
25✔
690
}
691

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

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

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

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

718
        if len(activeChans) == 0 {
4✔
719
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
1✔
720
        }
1✔
721

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

UNCOV
730
                haveLegacyChan = true
×
UNCOV
731
                break
×
732
        }
733

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

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

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

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

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

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

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

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

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

812
        p.startTime = time.Now()
3✔
813

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

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

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

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

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

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

3✔
860
        return nil
3✔
861
}
862

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

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

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

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

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

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

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

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

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

3✔
942
        // Return a slice of messages to send to the peers in case the channel
3✔
943
        // cannot be loaded normally.
3✔
944
        var msgs []lnwire.Message
3✔
945

3✔
946
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
3✔
947

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

UNCOV
968
                                err = p.cfg.AddLocalAlias(
×
UNCOV
969
                                        aliasScid, dbChan.ShortChanID(), false,
×
UNCOV
970
                                        false,
×
UNCOV
971
                                )
×
UNCOV
972
                                if err != nil {
×
973
                                        return nil, err
×
974
                                }
×
975

UNCOV
976
                                chanID := lnwire.NewChanIDFromOutPoint(
×
UNCOV
977
                                        dbChan.FundingOutpoint,
×
UNCOV
978
                                )
×
UNCOV
979

×
UNCOV
980
                                // Fetch the second commitment point to send in
×
UNCOV
981
                                // the channel_ready message.
×
UNCOV
982
                                second, err := dbChan.SecondCommitmentPoint()
×
UNCOV
983
                                if err != nil {
×
984
                                        return nil, err
×
985
                                }
×
986

UNCOV
987
                                channelReadyMsg := lnwire.NewChannelReady(
×
UNCOV
988
                                        chanID, second,
×
UNCOV
989
                                )
×
UNCOV
990
                                channelReadyMsg.AliasScid = &aliasScid
×
UNCOV
991

×
UNCOV
992
                                msgs = append(msgs, channelReadyMsg)
×
993
                        }
994

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

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

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

1029
                chanPoint := dbChan.FundingOutpoint
2✔
1030

2✔
1031
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
1032

2✔
1033
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
2✔
1034
                        chanPoint, lnChan.IsPending())
2✔
1035

2✔
1036
                // Skip adding any permanently irreconcilable channels to the
2✔
1037
                // htlcswitch.
2✔
1038
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
2✔
1039
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
4✔
1040

2✔
1041
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
2✔
1042
                                "start.", chanPoint, dbChan.ChanStatus())
2✔
1043

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

1058
                        msgs = append(msgs, chanSync)
2✔
1059

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

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

1075
                                if shutdownMsg == nil {
×
1076
                                        continue
×
1077
                                }
1078

1079
                                // Append the message to the set of messages to
1080
                                // send.
1081
                                msgs = append(msgs, shutdownMsg)
×
1082
                        }
1083

1084
                        continue
2✔
1085
                }
1086

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

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

×
UNCOV
1109
                        selfPolicy = p1
×
UNCOV
1110
                } else {
×
UNCOV
1111
                        selfPolicy = p2
×
UNCOV
1112
                }
×
1113

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

UNCOV
1127
                        inboundFee := models.NewInboundFeeFromWire(
×
UNCOV
1128
                                inboundWireFee,
×
UNCOV
1129
                        )
×
UNCOV
1130

×
UNCOV
1131
                        forwardingPolicy = &models.ForwardingPolicy{
×
UNCOV
1132
                                MinHTLCOut:    selfPolicy.MinHTLC,
×
UNCOV
1133
                                MaxHTLC:       selfPolicy.MaxHTLC,
×
UNCOV
1134
                                BaseFee:       selfPolicy.FeeBaseMSat,
×
UNCOV
1135
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
×
UNCOV
1136
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
×
UNCOV
1137

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

UNCOV
1147
                p.log.Tracef("Using link policy of: %v",
×
UNCOV
1148
                        spew.Sdump(forwardingPolicy))
×
UNCOV
1149

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

×
UNCOV
1159
                        continue
×
1160
                }
1161

UNCOV
1162
                shutdownInfo, err := lnChan.State().ShutdownInfo()
×
UNCOV
1163
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
×
1164
                        return nil, err
×
1165
                }
×
1166

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

×
1180
                                return
×
1181
                        }
×
1182

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

×
1198
                                return
×
1199
                        }
×
1200

UNCOV
1201
                        chanID := lnwire.NewChanIDFromOutPoint(
×
UNCOV
1202
                                lnChan.State().FundingOutpoint,
×
UNCOV
1203
                        )
×
UNCOV
1204

×
UNCOV
1205
                        p.activeChanCloses[chanID] = chanCloser
×
UNCOV
1206

×
UNCOV
1207
                        // Create the Shutdown message.
×
UNCOV
1208
                        shutdown, err := chanCloser.ShutdownChan()
×
UNCOV
1209
                        if err != nil {
×
1210
                                delete(p.activeChanCloses, chanID)
×
1211
                                shutdownInfoErr = err
×
1212

×
1213
                                return
×
1214
                        }
×
1215

UNCOV
1216
                        shutdownMsg = fn.Some(*shutdown)
×
1217
                })
UNCOV
1218
                if shutdownInfoErr != nil {
×
1219
                        return nil, shutdownInfoErr
×
1220
                }
×
1221

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

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

UNCOV
1239
                p.activeChannels.Store(chanID, lnChan)
×
1240
        }
1241

1242
        return msgs, nil
3✔
1243
}
1244

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

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

×
UNCOV
1258
                failure := linkFailureReport{
×
UNCOV
1259
                        chanPoint:   *chanPoint,
×
UNCOV
1260
                        chanID:      chanID,
×
UNCOV
1261
                        shortChanID: shortChanID,
×
UNCOV
1262
                        linkErr:     linkErr,
×
UNCOV
1263
                }
×
UNCOV
1264

×
UNCOV
1265
                select {
×
UNCOV
1266
                case p.linkFailures <- failure:
×
1267
                case <-p.quit:
×
1268
                case <-p.cfg.Quit:
×
1269
                }
1270
        }
1271

UNCOV
1272
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
×
UNCOV
1273
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
×
UNCOV
1274
        }
×
1275

UNCOV
1276
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
×
UNCOV
1277
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
×
UNCOV
1278
        }
×
1279

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

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

×
UNCOV
1331
        // With the channel link created, we'll now notify the htlc switch so
×
UNCOV
1332
        // this channel can be used to dispatch local payments and also
×
UNCOV
1333
        // passively forward payments.
×
UNCOV
1334
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
×
1335
}
1336

1337
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1338
// one confirmed public channel exists with them.
1339
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
3✔
1340
        defer p.wg.Done()
3✔
1341

3✔
1342
        hasConfirmedPublicChan := false
3✔
1343
        for _, channel := range channels {
5✔
1344
                if channel.IsPending {
2✔
UNCOV
1345
                        continue
×
1346
                }
1347
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
4✔
1348
                        continue
2✔
1349
                }
1350

UNCOV
1351
                hasConfirmedPublicChan = true
×
UNCOV
1352
                break
×
1353
        }
1354
        if !hasConfirmedPublicChan {
6✔
1355
                return
3✔
1356
        }
3✔
1357

UNCOV
1358
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
×
UNCOV
1359
        if err != nil {
×
1360
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1361
                return
×
1362
        }
×
1363

UNCOV
1364
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
×
1365
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1366
        }
×
1367
}
1368

1369
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1370
// have any active channels with them.
1371
func (p *Brontide) maybeSendChannelUpdates() {
3✔
1372
        defer p.wg.Done()
3✔
1373

3✔
1374
        // If we don't have any active channels, then we can exit early.
3✔
1375
        if p.activeChannels.Len() == 0 {
4✔
1376
                return
1✔
1377
        }
1✔
1378

1379
        maybeSendUpd := func(cid lnwire.ChannelID,
2✔
1380
                lnChan *lnwallet.LightningChannel) error {
4✔
1381

2✔
1382
                // Nil channels are pending, so we'll skip them.
2✔
1383
                if lnChan == nil {
2✔
UNCOV
1384
                        return nil
×
UNCOV
1385
                }
×
1386

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

1395
                        // Otherwise, we can use the normal scid.
1396
                        default:
2✔
1397
                                return dbChan.ShortChanID()
2✔
1398
                        }
1399
                }()
1400

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

×
UNCOV
1411
                        return nil
×
UNCOV
1412
                }
×
1413

1414
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
2✔
1415
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
2✔
1416

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

×
1426
                        return err
×
1427
                }
×
1428

1429
                return nil
2✔
1430
        }
1431

1432
        p.activeChannels.ForEach(maybeSendUpd)
2✔
1433
}
1434

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

UNCOV
1452
        select {
×
UNCOV
1453
        case <-ready:
×
UNCOV
1454
        case <-p.quit:
×
1455
        }
1456

UNCOV
1457
        p.wg.Wait()
×
1458
}
1459

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

1468
        // Make sure initialization has completed before we try to tear things
1469
        // down.
UNCOV
1470
        select {
×
UNCOV
1471
        case <-p.startReady:
×
1472
        case <-p.quit:
×
1473
                return
×
1474
        }
1475

UNCOV
1476
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
×
UNCOV
1477
        p.storeError(err)
×
UNCOV
1478

×
UNCOV
1479
        p.log.Infof(err.Error())
×
UNCOV
1480

×
UNCOV
1481
        // Stop PingManager before closing TCP connection.
×
UNCOV
1482
        p.pingManager.Stop()
×
UNCOV
1483

×
UNCOV
1484
        // Ensure that the TCP connection is properly closed before continuing.
×
UNCOV
1485
        p.cfg.Conn.Close()
×
UNCOV
1486

×
UNCOV
1487
        close(p.quit)
×
UNCOV
1488

×
UNCOV
1489
        // If our msg router isn't global (local to this instance), then we'll
×
UNCOV
1490
        // stop it. Otherwise, we'll leave it running.
×
UNCOV
1491
        if !p.globalMsgRouter {
×
UNCOV
1492
                p.msgRouter.WhenSome(func(router msgmux.Router) {
×
UNCOV
1493
                        router.Stop()
×
UNCOV
1494
                })
×
1495
        }
1496
}
1497

1498
// String returns the string representation of this peer.
UNCOV
1499
func (p *Brontide) String() string {
×
UNCOV
1500
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
×
UNCOV
1501
}
×
1502

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

1512
        pktLen, err := noiseConn.ReadNextHeader()
7✔
1513
        if err != nil {
7✔
UNCOV
1514
                return nil, fmt.Errorf("read next header: %w", err)
×
UNCOV
1515
        }
×
1516

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

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

4✔
1549
                // Next, create a new io.Reader implementation from the raw
4✔
1550
                // message, and use this to decode the message directly from.
4✔
1551
                msgReader := bytes.NewReader(rawMsg)
4✔
1552
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
4✔
1553
                if err != nil {
4✔
UNCOV
1554
                        return err
×
UNCOV
1555
                }
×
1556

1557
                // At this point, rawMsg and buf will be returned back to the
1558
                // buffer pool for re-use.
1559
                return nil
4✔
1560
        })
1561
        atomic.AddUint64(&p.bytesReceived, msgLen)
4✔
1562
        if err != nil {
4✔
UNCOV
1563
                return nil, err
×
UNCOV
1564
        }
×
1565

1566
        p.logWireMessage(nextMsg, true)
4✔
1567

4✔
1568
        return nextMsg, nil
4✔
1569
}
1570

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

1579
        peer *Brontide
1580

1581
        apply func(lnwire.Message)
1582

1583
        startMsg string
1584
        stopMsg  string
1585

1586
        msgCond *sync.Cond
1587
        msgs    []lnwire.Message
1588

1589
        mtx sync.Mutex
1590

1591
        producerSema chan struct{}
1592

1593
        wg   sync.WaitGroup
1594
        quit chan struct{}
1595
}
1596

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

3✔
1605
        stream := &msgStream{
3✔
1606
                peer:         p,
3✔
1607
                apply:        apply,
3✔
1608
                startMsg:     startMsg,
3✔
1609
                stopMsg:      stopMsg,
3✔
1610
                producerSema: make(chan struct{}, bufSize),
3✔
1611
                quit:         make(chan struct{}),
3✔
1612
        }
3✔
1613
        stream.msgCond = sync.NewCond(&stream.mtx)
3✔
1614

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

1623
        return stream
3✔
1624
}
1625

1626
// Start starts the chanMsgStream.
1627
func (ms *msgStream) Start() {
3✔
1628
        ms.wg.Add(1)
3✔
1629
        go ms.msgConsumer()
3✔
1630
}
3✔
1631

1632
// Stop stops the chanMsgStream.
UNCOV
1633
func (ms *msgStream) Stop() {
×
UNCOV
1634
        // TODO(roasbeef): signal too?
×
UNCOV
1635

×
UNCOV
1636
        close(ms.quit)
×
UNCOV
1637

×
UNCOV
1638
        // Now that we've closed the channel, we'll repeatedly signal the msg
×
UNCOV
1639
        // consumer until we've detected that it has exited.
×
UNCOV
1640
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
×
UNCOV
1641
                ms.msgCond.Signal()
×
UNCOV
1642
                time.Sleep(time.Millisecond * 100)
×
UNCOV
1643
        }
×
1644

UNCOV
1645
        ms.wg.Wait()
×
1646
}
1647

1648
// msgConsumer is the main goroutine that streams messages from the peer's
1649
// readHandler directly to the target channel.
1650
func (ms *msgStream) msgConsumer() {
3✔
1651
        defer ms.wg.Done()
3✔
1652
        defer peerLog.Tracef(ms.stopMsg)
3✔
1653
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
3✔
1654

3✔
1655
        peerLog.Tracef(ms.startMsg)
3✔
1656

3✔
1657
        for {
6✔
1658
                // First, we'll check our condition. If the queue of messages
3✔
1659
                // is empty, then we'll wait until a new item is added.
3✔
1660
                ms.msgCond.L.Lock()
3✔
1661
                for len(ms.msgs) == 0 {
6✔
1662
                        ms.msgCond.Wait()
3✔
1663

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

1678
                // Grab the message off the front of the queue, shifting the
1679
                // slice's reference down one in order to remove the message
1680
                // from the queue.
UNCOV
1681
                msg := ms.msgs[0]
×
UNCOV
1682
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
×
UNCOV
1683
                ms.msgs = ms.msgs[1:]
×
UNCOV
1684

×
UNCOV
1685
                ms.msgCond.L.Unlock()
×
UNCOV
1686

×
UNCOV
1687
                ms.apply(msg)
×
UNCOV
1688

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

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

1719
        // Next, we'll lock the condition, and add the message to the end of
1720
        // the message queue.
UNCOV
1721
        ms.msgCond.L.Lock()
×
UNCOV
1722
        ms.msgs = append(ms.msgs, msg)
×
UNCOV
1723
        ms.msgCond.L.Unlock()
×
UNCOV
1724

×
UNCOV
1725
        // With the message added, we signal to the msgConsumer that there are
×
UNCOV
1726
        // additional messages to consume.
×
UNCOV
1727
        ms.msgCond.Signal()
×
1728
}
1729

1730
// waitUntilLinkActive waits until the target link is active and returns a
1731
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1732
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1733
func waitUntilLinkActive(p *Brontide,
UNCOV
1734
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
×
UNCOV
1735

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

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

×
UNCOV
1756
        // The link may already be active by this point, and we may have missed the
×
UNCOV
1757
        // ActiveLinkEvent. Check if the link exists.
×
UNCOV
1758
        link := p.fetchLinkFromKeyAndCid(cid)
×
UNCOV
1759
        if link != nil {
×
UNCOV
1760
                return link
×
UNCOV
1761
        }
×
1762

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

UNCOV
1777
                        chanPoint := event.ChannelPoint
×
UNCOV
1778

×
UNCOV
1779
                        // Check whether the retrieved chanPoint matches the target
×
UNCOV
1780
                        // channel id.
×
UNCOV
1781
                        if !cid.IsChanPoint(chanPoint) {
×
1782
                                continue
×
1783
                        }
1784

1785
                        // The link shouldn't be nil as we received an
1786
                        // ActiveLinkEvent. If it is nil, we return nil and the
1787
                        // calling function should catch it.
UNCOV
1788
                        return p.fetchLinkFromKeyAndCid(cid)
×
1789

UNCOV
1790
                case <-p.quit:
×
UNCOV
1791
                        return nil
×
1792
                }
1793
        }
1794
}
1795

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

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

×
UNCOV
1812
                        // If the link is still not active and the calling function
×
UNCOV
1813
                        // errored out, just return.
×
UNCOV
1814
                        if chanLink == nil {
×
UNCOV
1815
                                p.log.Warnf("Link=%v is not active")
×
UNCOV
1816
                                return
×
UNCOV
1817
                        }
×
1818
                }
1819

1820
                // In order to avoid unnecessarily delivering message
1821
                // as the peer is exiting, we'll check quickly to see
1822
                // if we need to exit.
UNCOV
1823
                select {
×
1824
                case <-p.quit:
×
1825
                        return
×
UNCOV
1826
                default:
×
1827
                }
1828

UNCOV
1829
                chanLink.HandleChannelUpdate(msg)
×
1830
        }
1831

UNCOV
1832
        return newMsgStream(p,
×
UNCOV
1833
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
×
UNCOV
1834
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
×
UNCOV
1835
                1000,
×
UNCOV
1836
                apply,
×
UNCOV
1837
        )
×
1838
}
1839

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

1850
        return newMsgStream(
3✔
1851
                p,
3✔
1852
                "Update stream for gossiper created",
3✔
1853
                "Update stream for gossiper exited",
3✔
1854
                1000,
3✔
1855
                apply,
3✔
1856
        )
3✔
1857
}
1858

1859
// readHandler is responsible for reading messages off the wire in series, then
1860
// properly dispatching the handling of the message to the proper subsystem.
1861
//
1862
// NOTE: This method MUST be run as a goroutine.
1863
func (p *Brontide) readHandler() {
3✔
1864
        defer p.wg.Done()
3✔
1865

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

1874
        // Initialize our negotiated gossip sync method before reading messages
1875
        // off the wire. When using gossip queries, this ensures a gossip
1876
        // syncer is active by the time query messages arrive.
1877
        //
1878
        // TODO(conner): have peer store gossip syncer directly and bypass
1879
        // gossiper?
1880
        p.initGossipSync()
3✔
1881

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

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

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

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

1929
                        // If the error we encountered wasn't just a message we
1930
                        // didn't recognize, then we'll stop all processing as
1931
                        // this is a fatal error.
UNCOV
1932
                        default:
×
UNCOV
1933
                                break out
×
1934
                        }
1935
                }
1936

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

1947
                // No error occurred, and the message was handled by the
1948
                // router.
1949
                if err == nil {
1✔
1950
                        continue
×
1951
                }
1952

1953
                var (
1✔
1954
                        targetChan   lnwire.ChannelID
1✔
1955
                        isLinkUpdate bool
1✔
1956
                )
1✔
1957

1✔
1958
                switch msg := nextMsg.(type) {
1✔
UNCOV
1959
                case *lnwire.Pong:
×
UNCOV
1960
                        // When we receive a Pong message in response to our
×
UNCOV
1961
                        // last ping message, we send it to the pingManager
×
UNCOV
1962
                        p.pingManager.ReceivedPong(msg)
×
1963

UNCOV
1964
                case *lnwire.Ping:
×
UNCOV
1965
                        // First, we'll store their latest ping payload within
×
UNCOV
1966
                        // the relevant atomic variable.
×
UNCOV
1967
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
UNCOV
1968

×
UNCOV
1969
                        // Next, we'll send over the amount of specified pong
×
UNCOV
1970
                        // bytes.
×
UNCOV
1971
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
×
UNCOV
1972
                        p.queueMsg(pong, nil)
×
1973

1974
                case *lnwire.OpenChannel,
1975
                        *lnwire.AcceptChannel,
1976
                        *lnwire.FundingCreated,
1977
                        *lnwire.FundingSigned,
UNCOV
1978
                        *lnwire.ChannelReady:
×
UNCOV
1979

×
UNCOV
1980
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
×
1981

UNCOV
1982
                case *lnwire.Shutdown:
×
UNCOV
1983
                        select {
×
UNCOV
1984
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
×
1985
                        case <-p.quit:
×
1986
                                break out
×
1987
                        }
UNCOV
1988
                case *lnwire.ClosingSigned:
×
UNCOV
1989
                        select {
×
UNCOV
1990
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
×
1991
                        case <-p.quit:
×
1992
                                break out
×
1993
                        }
1994

1995
                case *lnwire.Warning:
×
1996
                        targetChan = msg.ChanID
×
1997
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
1998

UNCOV
1999
                case *lnwire.Error:
×
UNCOV
2000
                        targetChan = msg.ChanID
×
UNCOV
2001
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2002

UNCOV
2003
                case *lnwire.ChannelReestablish:
×
UNCOV
2004
                        targetChan = msg.ChanID
×
UNCOV
2005
                        isLinkUpdate = p.hasChannel(targetChan)
×
UNCOV
2006

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

2022
                // For messages that implement the LinkUpdater interface, we
2023
                // will consider them as link updates and send them to
2024
                // chanStream. These messages will be queued inside chanStream
2025
                // if the channel is not active yet.
UNCOV
2026
                case lnwire.LinkUpdater:
×
UNCOV
2027
                        targetChan = msg.TargetChanID()
×
UNCOV
2028
                        isLinkUpdate = p.hasChannel(targetChan)
×
UNCOV
2029

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

2039
                case *lnwire.ChannelUpdate1,
2040
                        *lnwire.ChannelAnnouncement1,
2041
                        *lnwire.NodeAnnouncement,
2042
                        *lnwire.AnnounceSignatures1,
2043
                        *lnwire.GossipTimestampRange,
2044
                        *lnwire.QueryShortChanIDs,
2045
                        *lnwire.QueryChannelRange,
2046
                        *lnwire.ReplyChannelRange,
UNCOV
2047
                        *lnwire.ReplyShortChanIDsEnd:
×
UNCOV
2048

×
UNCOV
2049
                        discStream.AddMsg(msg)
×
2050

2051
                case *lnwire.Custom:
1✔
2052
                        err := p.handleCustomMessage(msg)
1✔
2053
                        if err != nil {
1✔
2054
                                p.storeError(err)
×
2055
                                p.log.Errorf("%v", err)
×
2056
                        }
×
2057

2058
                default:
×
2059
                        // If the message we received is unknown to us, store
×
2060
                        // the type to track the failure.
×
2061
                        err := fmt.Errorf("unknown message type %v received",
×
2062
                                uint16(msg.MsgType()))
×
2063
                        p.storeError(err)
×
2064

×
2065
                        p.log.Errorf("%v", err)
×
2066
                }
2067

2068
                if isLinkUpdate {
1✔
UNCOV
2069
                        // If this is a channel update, then we need to feed it
×
UNCOV
2070
                        // into the channel's in-order message stream.
×
UNCOV
2071
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
×
UNCOV
2072
                }
×
2073

2074
                idleTimer.Reset(idleTimeout)
1✔
2075
        }
2076

UNCOV
2077
        p.Disconnect(errors.New("read handler closed"))
×
UNCOV
2078

×
UNCOV
2079
        p.log.Trace("readHandler for peer done")
×
2080
}
2081

2082
// handleCustomMessage handles the given custom message if a handler is
2083
// registered.
2084
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
1✔
2085
        if p.cfg.HandleCustomMessage == nil {
1✔
2086
                return fmt.Errorf("no custom message handler for "+
×
2087
                        "message type %v", uint16(msg.MsgType()))
×
2088
        }
×
2089

2090
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
1✔
2091
}
2092

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

2104
        // Return false if the channel is unknown.
UNCOV
2105
        channel, ok := p.activeChannels.Load(chanID)
×
UNCOV
2106
        if !ok {
×
2107
                return false
×
2108
        }
×
2109

2110
        // During startup, we will use a nil value to mark a pending channel
2111
        // that's loaded from disk.
UNCOV
2112
        return channel == nil
×
2113
}
2114

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

8✔
2124
        return channel != nil
8✔
2125
}
8✔
2126

2127
// isPendingChannel returns true if the provided channel ID is pending, and
2128
// returns false if the channel is active or unknown.
2129
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
6✔
2130
        // Return false if the channel is unknown.
6✔
2131
        channel, ok := p.activeChannels.Load(chanID)
6✔
2132
        if !ok {
9✔
2133
                return false
3✔
2134
        }
3✔
2135

2136
        return channel == nil
3✔
2137
}
2138

2139
// hasChannel returns true if the peer has a pending/active channel specified
2140
// by the channel ID.
UNCOV
2141
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
×
UNCOV
2142
        _, ok := p.activeChannels.Load(chanID)
×
UNCOV
2143
        return ok
×
UNCOV
2144
}
×
2145

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

×
UNCOV
2153
        p.activeChannels.Range(func(_ lnwire.ChannelID,
×
UNCOV
2154
                channel *lnwallet.LightningChannel) bool {
×
UNCOV
2155

×
UNCOV
2156
                // Pending channels will be nil in the activeChannels map.
×
UNCOV
2157
                if channel == nil {
×
UNCOV
2158
                        // Return true to continue the iteration.
×
UNCOV
2159
                        return true
×
UNCOV
2160
                }
×
2161

UNCOV
2162
                haveChannels = true
×
UNCOV
2163

×
UNCOV
2164
                // Return false to break the iteration.
×
UNCOV
2165
                return false
×
2166
        })
2167

2168
        // If we do not have any active channels with the peer, we do not store
2169
        // errors as a dos mitigation.
UNCOV
2170
        if !haveChannels {
×
UNCOV
2171
                p.log.Trace("no channels with peer, not storing err")
×
UNCOV
2172
                return
×
UNCOV
2173
        }
×
2174

UNCOV
2175
        p.cfg.ErrorBuffer.Add(
×
UNCOV
2176
                &TimestampedError{Timestamp: time.Now(), Error: err},
×
UNCOV
2177
        )
×
2178
}
2179

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

×
UNCOV
2189
        if errMsg, ok := msg.(*lnwire.Error); ok {
×
UNCOV
2190
                p.storeError(errMsg)
×
UNCOV
2191
        }
×
2192

UNCOV
2193
        switch {
×
2194
        // Connection wide messages should be forwarded to all channel links
2195
        // with this peer.
2196
        case chanID == lnwire.ConnectionWideID:
×
2197
                for _, chanStream := range p.activeMsgStreams {
×
2198
                        chanStream.AddMsg(msg)
×
2199
                }
×
2200

2201
                return false
×
2202

2203
        // If the channel ID for the message corresponds to a pending channel,
2204
        // then the funding manager will handle it.
UNCOV
2205
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
×
UNCOV
2206
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
×
UNCOV
2207
                return false
×
2208

2209
        // If not we hand the message to the channel link for this channel.
UNCOV
2210
        case p.isActiveChannel(chanID):
×
UNCOV
2211
                return true
×
2212

UNCOV
2213
        default:
×
UNCOV
2214
                return false
×
2215
        }
2216
}
2217

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

UNCOV
2227
        case *lnwire.OpenChannel:
×
UNCOV
2228
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
×
UNCOV
2229
                        "push_amt=%v, reserve=%v, flags=%v",
×
UNCOV
2230
                        msg.PendingChannelID[:], msg.ChainHash,
×
UNCOV
2231
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
×
UNCOV
2232
                        msg.ChannelReserve, msg.ChannelFlags)
×
2233

UNCOV
2234
        case *lnwire.AcceptChannel:
×
UNCOV
2235
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
×
UNCOV
2236
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
×
UNCOV
2237
                        msg.MinAcceptDepth)
×
2238

UNCOV
2239
        case *lnwire.FundingCreated:
×
UNCOV
2240
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
×
UNCOV
2241
                        msg.PendingChannelID[:], msg.FundingPoint)
×
2242

UNCOV
2243
        case *lnwire.FundingSigned:
×
UNCOV
2244
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
×
2245

UNCOV
2246
        case *lnwire.ChannelReady:
×
UNCOV
2247
                return fmt.Sprintf("chan_id=%v, next_point=%x",
×
UNCOV
2248
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
×
2249

UNCOV
2250
        case *lnwire.Shutdown:
×
UNCOV
2251
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
×
UNCOV
2252
                        msg.Address[:])
×
2253

UNCOV
2254
        case *lnwire.ClosingSigned:
×
UNCOV
2255
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
×
UNCOV
2256
                        msg.FeeSatoshis)
×
2257

UNCOV
2258
        case *lnwire.UpdateAddHTLC:
×
UNCOV
2259
                var blindingPoint []byte
×
UNCOV
2260
                msg.BlindingPoint.WhenSome(
×
UNCOV
2261
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
×
UNCOV
2262
                                *btcec.PublicKey]) {
×
UNCOV
2263

×
UNCOV
2264
                                blindingPoint = b.Val.SerializeCompressed()
×
UNCOV
2265
                        },
×
2266
                )
2267

UNCOV
2268
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
×
UNCOV
2269
                        "hash=%x, blinding_point=%x, custom_records=%v",
×
UNCOV
2270
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
×
UNCOV
2271
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
×
2272

UNCOV
2273
        case *lnwire.UpdateFailHTLC:
×
UNCOV
2274
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
×
UNCOV
2275
                        msg.ID, msg.Reason)
×
2276

UNCOV
2277
        case *lnwire.UpdateFulfillHTLC:
×
UNCOV
2278
                return fmt.Sprintf("chan_id=%v, id=%v, pre_image=%x, "+
×
UNCOV
2279
                        "custom_records=%v", msg.ChanID, msg.ID,
×
UNCOV
2280
                        msg.PaymentPreimage[:], msg.CustomRecords)
×
2281

UNCOV
2282
        case *lnwire.CommitSig:
×
UNCOV
2283
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
×
UNCOV
2284
                        len(msg.HtlcSigs))
×
2285

UNCOV
2286
        case *lnwire.RevokeAndAck:
×
UNCOV
2287
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
×
UNCOV
2288
                        msg.ChanID, msg.Revocation[:],
×
UNCOV
2289
                        msg.NextRevocationKey.SerializeCompressed())
×
2290

UNCOV
2291
        case *lnwire.UpdateFailMalformedHTLC:
×
UNCOV
2292
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
×
UNCOV
2293
                        msg.ChanID, msg.ID, msg.FailureCode)
×
2294

2295
        case *lnwire.Warning:
×
2296
                return fmt.Sprintf("%v", msg.Warning())
×
2297

UNCOV
2298
        case *lnwire.Error:
×
UNCOV
2299
                return fmt.Sprintf("%v", msg.Error())
×
2300

UNCOV
2301
        case *lnwire.AnnounceSignatures1:
×
UNCOV
2302
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
×
UNCOV
2303
                        msg.ShortChannelID.ToUint64())
×
2304

UNCOV
2305
        case *lnwire.ChannelAnnouncement1:
×
UNCOV
2306
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
×
UNCOV
2307
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
×
2308

UNCOV
2309
        case *lnwire.ChannelUpdate1:
×
UNCOV
2310
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
×
UNCOV
2311
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
×
UNCOV
2312
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
×
UNCOV
2313
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
×
2314

UNCOV
2315
        case *lnwire.NodeAnnouncement:
×
UNCOV
2316
                return fmt.Sprintf("node=%x, update_time=%v",
×
UNCOV
2317
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
×
2318

UNCOV
2319
        case *lnwire.Ping:
×
UNCOV
2320
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
2321

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

2325
        case *lnwire.UpdateFee:
×
2326
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2327
                        msg.ChanID, int64(msg.FeePerKw))
×
2328

UNCOV
2329
        case *lnwire.ChannelReestablish:
×
UNCOV
2330
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
×
UNCOV
2331
                        "remote_tail_height=%v", msg.ChanID,
×
UNCOV
2332
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
×
2333

UNCOV
2334
        case *lnwire.ReplyShortChanIDsEnd:
×
UNCOV
2335
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
×
UNCOV
2336
                        msg.Complete)
×
2337

UNCOV
2338
        case *lnwire.ReplyChannelRange:
×
UNCOV
2339
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
×
UNCOV
2340
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
×
UNCOV
2341
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
×
UNCOV
2342
                        msg.EncodingType)
×
2343

UNCOV
2344
        case *lnwire.QueryShortChanIDs:
×
UNCOV
2345
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
×
UNCOV
2346
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
×
2347

UNCOV
2348
        case *lnwire.QueryChannelRange:
×
UNCOV
2349
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
×
UNCOV
2350
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
×
UNCOV
2351
                        msg.LastBlockHeight())
×
2352

UNCOV
2353
        case *lnwire.GossipTimestampRange:
×
UNCOV
2354
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
×
UNCOV
2355
                        "stamp_range=%v", msg.ChainHash,
×
UNCOV
2356
                        time.Unix(int64(msg.FirstTimestamp), 0),
×
UNCOV
2357
                        msg.TimestampRange)
×
2358

2359
        case *lnwire.Stfu:
×
2360
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
×
2361
                        msg.Initiator)
×
2362

UNCOV
2363
        case *lnwire.Custom:
×
UNCOV
2364
                return fmt.Sprintf("type=%d", msg.Type)
×
2365
        }
2366

2367
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2368
}
2369

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

2381
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
17✔
UNCOV
2382
                // Debug summary of message.
×
UNCOV
2383
                summary := messageSummary(msg)
×
UNCOV
2384
                if len(summary) > 0 {
×
UNCOV
2385
                        summary = "(" + summary + ")"
×
UNCOV
2386
                }
×
2387

UNCOV
2388
                preposition := "to"
×
UNCOV
2389
                if read {
×
UNCOV
2390
                        preposition = "from"
×
UNCOV
2391
                }
×
2392

UNCOV
2393
                var msgType string
×
UNCOV
2394
                if msg.MsgType() < lnwire.CustomTypeStart {
×
UNCOV
2395
                        msgType = msg.MsgType().String()
×
UNCOV
2396
                } else {
×
UNCOV
2397
                        msgType = "custom"
×
UNCOV
2398
                }
×
2399

UNCOV
2400
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
×
UNCOV
2401
                        msgType, summary, preposition, p)
×
2402
        }))
2403

2404
        prefix := "readMessage from peer"
17✔
2405
        if !read {
30✔
2406
                prefix = "writeMessage to peer"
13✔
2407
        }
13✔
2408

2409
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
17✔
2410
}
2411

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

2429
        noiseConn := p.cfg.Conn
13✔
2430

13✔
2431
        flushMsg := func() error {
26✔
2432
                // Ensure the write deadline is set before we attempt to send
13✔
2433
                // the message.
13✔
2434
                writeDeadline := time.Now().Add(
13✔
2435
                        p.scaleTimeout(writeMessageTimeout),
13✔
2436
                )
13✔
2437
                err := noiseConn.SetWriteDeadline(writeDeadline)
13✔
2438
                if err != nil {
13✔
2439
                        return err
×
2440
                }
×
2441

2442
                // Flush the pending message to the wire. If an error is
2443
                // encountered, e.g. write timeout, the number of bytes written
2444
                // so far will be returned.
2445
                n, err := noiseConn.Flush()
13✔
2446

13✔
2447
                // Record the number of bytes written on the wire, if any.
13✔
2448
                if n > 0 {
13✔
UNCOV
2449
                        atomic.AddUint64(&p.bytesSent, uint64(n))
×
UNCOV
2450
                }
×
2451

2452
                return err
13✔
2453
        }
2454

2455
        // If the current message has already been serialized, encrypted, and
2456
        // buffered on the underlying connection we will skip straight to
2457
        // flushing it to the wire.
2458
        if msg == nil {
13✔
2459
                return flushMsg()
×
2460
        }
×
2461

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

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

2482
        return flushMsg()
13✔
2483
}
2484

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

2500
        var exitErr error
3✔
2501

3✔
2502
out:
3✔
2503
        for {
10✔
2504
                select {
7✔
2505
                case outMsg := <-p.sendQueue:
4✔
2506
                        // Record the time at which we first attempt to send the
4✔
2507
                        // message.
4✔
2508
                        startTime := time.Now()
4✔
2509

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

×
2522
                                // If we received a timeout error, this implies
×
2523
                                // that the message was buffered on the
×
2524
                                // connection successfully and that a flush was
×
2525
                                // attempted. We'll set the message to nil so
×
2526
                                // that on a subsequent pass we only try to
×
2527
                                // flush the buffered message, and forgo
×
2528
                                // reserializing or reencrypting it.
×
2529
                                outMsg.msg = nil
×
2530

×
2531
                                goto retry
×
2532
                        }
2533

2534
                        // The write succeeded, reset the idle timer to prevent
2535
                        // us from disconnecting the peer.
2536
                        if !idleTimer.Stop() {
4✔
2537
                                select {
×
2538
                                case <-idleTimer.C:
×
2539
                                default:
×
2540
                                }
2541
                        }
2542
                        idleTimer.Reset(idleTimeout)
4✔
2543

4✔
2544
                        // If the peer requested a synchronous write, respond
4✔
2545
                        // with the error.
4✔
2546
                        if outMsg.errChan != nil {
5✔
2547
                                outMsg.errChan <- err
1✔
2548
                        }
1✔
2549

2550
                        if err != nil {
4✔
2551
                                exitErr = fmt.Errorf("unable to write "+
×
2552
                                        "message: %v", err)
×
2553
                                break out
×
2554
                        }
2555

UNCOV
2556
                case <-p.quit:
×
UNCOV
2557
                        exitErr = lnpeer.ErrPeerExiting
×
UNCOV
2558
                        break out
×
2559
                }
2560
        }
2561

2562
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2563
        // disconnect.
UNCOV
2564
        p.wg.Done()
×
UNCOV
2565

×
UNCOV
2566
        p.Disconnect(exitErr)
×
UNCOV
2567

×
UNCOV
2568
        p.log.Trace("writeHandler for peer done")
×
2569
}
2570

2571
// queueHandler is responsible for accepting messages from outside subsystems
2572
// to be eventually sent out on the wire by the writeHandler.
2573
//
2574
// NOTE: This method MUST be run as a goroutine.
2575
func (p *Brontide) queueHandler() {
3✔
2576
        defer p.wg.Done()
3✔
2577

3✔
2578
        // priorityMsgs holds an in order list of messages deemed high-priority
3✔
2579
        // to be added to the sendQueue. This predominately includes messages
3✔
2580
        // from the funding manager and htlcswitch.
3✔
2581
        priorityMsgs := list.New()
3✔
2582

3✔
2583
        // lazyMsgs holds an in order list of messages deemed low-priority to be
3✔
2584
        // added to the sendQueue only after all high-priority messages have
3✔
2585
        // been queued. This predominately includes messages from the gossiper.
3✔
2586
        lazyMsgs := list.New()
3✔
2587

3✔
2588
        for {
14✔
2589
                // Examine the front of the priority queue, if it is empty check
11✔
2590
                // the low priority queue.
11✔
2591
                elem := priorityMsgs.Front()
11✔
2592
                if elem == nil {
19✔
2593
                        elem = lazyMsgs.Front()
8✔
2594
                }
8✔
2595

2596
                if elem != nil {
15✔
2597
                        front := elem.Value.(outgoingMsg)
4✔
2598

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

2638
// PingTime returns the estimated ping time to the peer in microseconds.
UNCOV
2639
func (p *Brontide) PingTime() int64 {
×
UNCOV
2640
        return p.pingManager.GetPingTimeMicroSeconds()
×
UNCOV
2641
}
×
2642

2643
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2644
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2645
// or failed to write, and nil otherwise.
2646
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
25✔
2647
        p.queue(true, msg, errChan)
25✔
2648
}
25✔
2649

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

2657
// queue sends a given message to the queueHandler using the passed priority. If
2658
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2659
// failed to write, and nil otherwise.
2660
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2661
        errChan chan error) {
26✔
2662

26✔
2663
        select {
26✔
2664
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
25✔
UNCOV
2665
        case <-p.quit:
×
UNCOV
2666
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
×
UNCOV
2667
                        spew.Sdump(msg))
×
UNCOV
2668
                if errChan != nil {
×
2669
                        errChan <- lnpeer.ErrPeerExiting
×
2670
                }
×
2671
        }
2672
}
2673

2674
// ChannelSnapshots returns a slice of channel snapshots detailing all
2675
// currently active channels maintained with the remote peer.
UNCOV
2676
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
×
UNCOV
2677
        snapshots := make(
×
UNCOV
2678
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
×
UNCOV
2679
        )
×
UNCOV
2680

×
UNCOV
2681
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
×
UNCOV
2682
                activeChan *lnwallet.LightningChannel) error {
×
UNCOV
2683

×
UNCOV
2684
                // If the activeChan is nil, then we skip it as the channel is
×
UNCOV
2685
                // pending.
×
UNCOV
2686
                if activeChan == nil {
×
UNCOV
2687
                        return nil
×
UNCOV
2688
                }
×
2689

2690
                // We'll only return a snapshot for channels that are
2691
                // *immediately* available for routing payments over.
UNCOV
2692
                if activeChan.RemoteNextRevocation() == nil {
×
UNCOV
2693
                        return nil
×
UNCOV
2694
                }
×
2695

UNCOV
2696
                snapshot := activeChan.StateSnapshot()
×
UNCOV
2697
                snapshots = append(snapshots, snapshot)
×
UNCOV
2698

×
UNCOV
2699
                return nil
×
2700
        })
2701

UNCOV
2702
        return snapshots
×
2703
}
2704

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

2715
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
6✔
2716
                addrType, false, lnwallet.DefaultAccountName,
6✔
2717
        )
6✔
2718
        if err != nil {
6✔
2719
                return nil, err
×
2720
        }
×
2721
        p.log.Infof("Delivery addr for channel close: %v",
6✔
2722
                deliveryAddr)
6✔
2723

6✔
2724
        return txscript.PayToAddrScript(deliveryAddr)
6✔
2725
}
2726

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

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

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

2751
                // A new channel has arrived which means we've just completed a
2752
                // funding workflow. We'll initialize the necessary local
2753
                // state, and notify the htlc switch of a new link.
UNCOV
2754
                case req := <-p.newActiveChannel:
×
UNCOV
2755
                        p.handleNewActiveChannel(req)
×
2756

2757
                // The funding flow for a pending channel is failed, we will
2758
                // remove it from Brontide.
2759
                case req := <-p.removePendingChannel:
1✔
2760
                        p.handleRemovePendingChannel(req)
1✔
2761

2762
                // We've just received a local request to close an active
2763
                // channel. It will either kick of a cooperative channel
2764
                // closure negotiation, or be a notification of a breached
2765
                // contract that should be abandoned.
2766
                case req := <-p.localCloseChanReqs:
7✔
2767
                        p.handleLocalCloseReq(req)
7✔
2768

2769
                // We've received a link failure from a link that was added to
2770
                // the switch. This will initiate the teardown of the link, and
2771
                // initiate any on-chain closures if necessary.
UNCOV
2772
                case failure := <-p.linkFailures:
×
UNCOV
2773
                        p.handleLinkFailure(failure)
×
2774

2775
                // We've received a new cooperative channel closure related
2776
                // message from the remote peer, we'll use this message to
2777
                // advance the chan closer state machine.
2778
                case closeMsg := <-p.chanCloseMsgs:
13✔
2779
                        p.handleCloseMsg(closeMsg)
13✔
2780

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

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

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

UNCOV
2809
                case <-p.quit:
×
UNCOV
2810
                        // As, we've been signalled to exit, we'll reset all
×
UNCOV
2811
                        // our active channel back to their default state.
×
UNCOV
2812
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
×
UNCOV
2813
                                lc *lnwallet.LightningChannel) error {
×
UNCOV
2814

×
UNCOV
2815
                                // Exit if the channel is nil as it's a pending
×
UNCOV
2816
                                // channel.
×
UNCOV
2817
                                if lc == nil {
×
UNCOV
2818
                                        return nil
×
UNCOV
2819
                                }
×
2820

UNCOV
2821
                                lc.ResetState()
×
UNCOV
2822

×
UNCOV
2823
                                return nil
×
2824
                        })
2825

UNCOV
2826
                        break out
×
2827
                }
2828
        }
2829
}
2830

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

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

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

×
UNCOV
2849
                switch {
×
2850
                // No error occurred, continue to request the next channel.
UNCOV
2851
                case err == nil:
×
UNCOV
2852
                        continue
×
2853

2854
                // Cannot auto enable a manually disabled channel so we do
2855
                // nothing but proceed to the next channel.
UNCOV
2856
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
×
UNCOV
2857
                        p.log.Debugf("Channel(%v) was manually disabled, "+
×
UNCOV
2858
                                "ignoring automatic enable request", chanPoint)
×
UNCOV
2859

×
UNCOV
2860
                        continue
×
2861

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

×
2879
                                continue
×
2880
                        }
2881

2882
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
2883
                                "ChanStatusManager reported inactive, retrying")
×
2884

×
2885
                        // Add the channel to the retry map.
×
2886
                        retryChans[chanPoint] = struct{}{}
×
2887
                }
2888
        }
2889

2890
        // Retry the channels if we have any.
UNCOV
2891
        if len(retryChans) != 0 {
×
2892
                p.retryRequestEnable(retryChans)
×
2893
        }
×
2894
}
2895

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

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

2912
        // First, we'll ensure that we actually know of the target channel. If
2913
        // not, we'll ignore this message.
2914
        channel, ok := p.activeChannels.Load(chanID)
3✔
2915

3✔
2916
        // If the channel isn't in the map or the channel is nil, return
3✔
2917
        // ErrChannelNotFound as the channel is pending.
3✔
2918
        if !ok || channel == nil {
3✔
UNCOV
2919
                return nil, ErrChannelNotFound
×
UNCOV
2920
        }
×
2921

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

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

2951
        addr, err := p.addrWithInternalKey(deliveryScript)
3✔
2952
        if err != nil {
3✔
2953
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
2954
        }
×
2955
        chanCloser, err = p.createChanCloser(
3✔
2956
                channel, addr, feePerKw, nil, lntypes.Remote,
3✔
2957
        )
3✔
2958
        if err != nil {
3✔
2959
                p.log.Errorf("unable to create chan closer: %v", err)
×
2960
                return nil, fmt.Errorf("unable to create chan closer")
×
2961
        }
×
2962

2963
        p.activeChanCloses[chanID] = chanCloser
3✔
2964

3✔
2965
        return chanCloser, nil
3✔
2966
}
2967

2968
// filterChannelsToEnable filters a list of channels to be enabled upon start.
2969
// The filtered channels are active channels that's neither private nor
2970
// pending.
UNCOV
2971
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
×
UNCOV
2972
        var activePublicChans []wire.OutPoint
×
UNCOV
2973

×
UNCOV
2974
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
×
UNCOV
2975
                lnChan *lnwallet.LightningChannel) bool {
×
UNCOV
2976

×
UNCOV
2977
                // If the lnChan is nil, continue as this is a pending channel.
×
UNCOV
2978
                if lnChan == nil {
×
2979
                        return true
×
2980
                }
×
2981

UNCOV
2982
                dbChan := lnChan.State()
×
UNCOV
2983
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
×
UNCOV
2984
                if !isPublic || dbChan.IsPending {
×
2985
                        return true
×
2986
                }
×
2987

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

UNCOV
2997
                activePublicChans = append(
×
UNCOV
2998
                        activePublicChans, dbChan.FundingOutpoint,
×
UNCOV
2999
                )
×
UNCOV
3000

×
UNCOV
3001
                return true
×
3002
        })
3003

UNCOV
3004
        return activePublicChans
×
3005
}
3006

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

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

×
3021
                // If this channel is irrelevant, return nil so the loop can
×
3022
                // jump to next iteration.
×
3023
                if !found {
×
3024
                        return nil
×
3025
                }
×
3026

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

×
3035
                // Send the request.
×
3036
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3037
                if err != nil {
×
3038
                        return fmt.Errorf("request enabling channel %v "+
×
3039
                                "failed: %w", chanPoint, err)
×
3040
                }
×
3041

3042
                return nil
×
3043
        }
3044

3045
        for {
×
3046
                // If activeChans is empty, we've done processing all the
×
3047
                // channels.
×
3048
                if len(activeChans) == 0 {
×
3049
                        p.log.Debug("Finished retry enabling channels")
×
3050
                        return
×
3051
                }
×
3052

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

×
3063
                                // If we received an error for this particular
×
3064
                                // channel, we log an error and won't quit as
×
3065
                                // we still want to retry other channels.
×
3066
                                if err := retryEnable(chanPoint); err != nil {
×
3067
                                        p.log.Errorf("Retry failed: %v", err)
×
3068
                                }
×
3069

3070
                                continue
×
3071
                        }
3072

3073
                        // Otherwise check for inactive link event, and jump to
3074
                        // next iteration if it's not.
3075
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3076
                        if !ok {
×
3077
                                continue
×
3078
                        }
3079

3080
                        // Found an inactive link event, if this is our
3081
                        // targeted channel, remove it from our map.
3082
                        chanPoint := *inactive.ChannelPoint
×
3083
                        _, found := activeChans[chanPoint]
×
3084
                        if !found {
×
3085
                                continue
×
3086
                        }
3087

3088
                        delete(activeChans, chanPoint)
×
3089
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3090
                                "inactive link event", chanPoint)
×
3091

3092
                case <-p.quit:
×
3093
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3094
                        return
×
3095
                }
3096
        }
3097
}
3098

3099
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3100
// a suitable script to close out to. This may be nil if neither script is
3101
// set. If both scripts are set, this function will error if they do not match.
3102
func chooseDeliveryScript(upfront,
3103
        requested lnwire.DeliveryAddress) (lnwire.DeliveryAddress, error) {
12✔
3104

12✔
3105
        // If no upfront shutdown script was provided, return the user
12✔
3106
        // requested address (which may be nil).
12✔
3107
        if len(upfront) == 0 {
18✔
3108
                return requested, nil
6✔
3109
        }
6✔
3110

3111
        // If an upfront shutdown script was provided, and the user did not
3112
        // request a custom shutdown script, return the upfront address.
3113
        if len(requested) == 0 {
8✔
3114
                return upfront, nil
2✔
3115
        }
2✔
3116

3117
        // If both an upfront shutdown script and a custom close script were
3118
        // provided, error if the user provided shutdown script does not match
3119
        // the upfront shutdown script (because closing out to a different
3120
        // script would violate upfront shutdown).
3121
        if !bytes.Equal(upfront, requested) {
6✔
3122
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
3123
        }
2✔
3124

3125
        // The user requested script matches the upfront shutdown script, so we
3126
        // can return it without error.
3127
        return upfront, nil
2✔
3128
}
3129

3130
// restartCoopClose checks whether we need to restart the cooperative close
3131
// process for a given channel.
3132
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3133
        *lnwire.Shutdown, error) {
×
3134

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

3153
        var deliveryScript []byte
×
3154

×
3155
        shutdownInfo, err := c.ShutdownInfo()
×
3156
        switch {
×
3157
        // We have previously stored the delivery script that we need to use
3158
        // in the shutdown message. Re-use this script.
3159
        case err == nil:
×
3160
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
×
3161
                        deliveryScript = info.DeliveryScript.Val
×
3162
                })
×
3163

3164
        // An error other than ErrNoShutdownInfo was returned
3165
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3166
                return nil, err
×
3167

3168
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3169
                deliveryScript = c.LocalShutdownScript
×
3170
                if len(deliveryScript) == 0 {
×
3171
                        var err error
×
3172
                        deliveryScript, err = p.genDeliveryScript()
×
3173
                        if err != nil {
×
3174
                                p.log.Errorf("unable to gen delivery script: "+
×
3175
                                        "%v", err)
×
3176

×
3177
                                return nil, fmt.Errorf("close addr unavailable")
×
3178
                        }
×
3179
                }
3180
        }
3181

3182
        // Compute an ideal fee.
3183
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
3184
                p.cfg.CoopCloseTargetConfs,
×
3185
        )
×
3186
        if err != nil {
×
3187
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3188
                return nil, fmt.Errorf("unable to estimate fee")
×
3189
        }
×
3190

3191
        // Determine whether we or the peer are the initiator of the coop
3192
        // close attempt by looking at the channel's status.
3193
        closingParty := lntypes.Remote
×
3194
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3195
                closingParty = lntypes.Local
×
3196
        }
×
3197

3198
        addr, err := p.addrWithInternalKey(deliveryScript)
×
3199
        if err != nil {
×
3200
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3201
        }
×
3202
        chanCloser, err := p.createChanCloser(
×
3203
                lnChan, addr, feePerKw, nil, closingParty,
×
3204
        )
×
3205
        if err != nil {
×
3206
                p.log.Errorf("unable to create chan closer: %v", err)
×
3207
                return nil, fmt.Errorf("unable to create chan closer")
×
3208
        }
×
3209

3210
        // This does not need a mutex even though it is in a different
3211
        // goroutine since this is done before the channelManager goroutine is
3212
        // created.
3213
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
×
3214
        p.activeChanCloses[chanID] = chanCloser
×
3215

×
3216
        // Create the Shutdown message.
×
3217
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3218
        if err != nil {
×
3219
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3220
                delete(p.activeChanCloses, chanID)
×
3221
                return nil, err
×
3222
        }
×
3223

3224
        return shutdownMsg, nil
×
3225
}
3226

3227
// createChanCloser constructs a ChanCloser from the passed parameters and is
3228
// used to de-duplicate code.
3229
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3230
        deliveryScript *chancloser.DeliveryAddrWithKey,
3231
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3232
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
9✔
3233

9✔
3234
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
9✔
3235
        if err != nil {
9✔
3236
                p.log.Errorf("unable to obtain best block: %v", err)
×
3237
                return nil, fmt.Errorf("cannot obtain best block")
×
3238
        }
×
3239

3240
        // The req will only be set if we initiated the co-op closing flow.
3241
        var maxFee chainfee.SatPerKWeight
9✔
3242
        if req != nil {
15✔
3243
                maxFee = req.MaxFee
6✔
3244
        }
6✔
3245

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

3272
        return chanCloser, nil
9✔
3273
}
3274

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

7✔
3280
        channel, ok := p.activeChannels.Load(chanID)
7✔
3281

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

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

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

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

×
3331
                        return
×
3332
                }
×
3333
                chanCloser, err := p.createChanCloser(
6✔
3334
                        channel, addr, req.TargetFeePerKw, req, lntypes.Local,
6✔
3335
                )
6✔
3336
                if err != nil {
6✔
3337
                        p.log.Errorf(err.Error())
×
3338
                        req.Err <- err
×
3339
                        return
×
3340
                }
×
3341

3342
                p.activeChanCloses[chanID] = chanCloser
6✔
3343

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

×
3353
                        // As we were unable to shutdown the channel, we'll
×
3354
                        // return it back to its normal state.
×
3355
                        channel.ResetState()
×
3356
                        return
×
3357
                }
×
3358

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

3372
                if !link.DisableAdds(htlcswitch.Outgoing) {
6✔
3373
                        p.log.Warnf("Outgoing link adds already "+
×
3374
                                "disabled: %v", link.ChanID())
×
3375
                }
×
3376

3377
                link.OnCommitOnce(htlcswitch.Outgoing, func() {
12✔
3378
                        p.queueMsg(shutdownMsg, nil)
6✔
3379
                })
6✔
3380

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

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

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

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

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

×
UNCOV
3426
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
×
UNCOV
3427
                        failure.chanPoint,
×
UNCOV
3428
                )
×
UNCOV
3429
                if err != nil {
×
UNCOV
3430
                        p.log.Errorf("unable to force close "+
×
UNCOV
3431
                                "link(%v): %v", failure.shortChanID, err)
×
UNCOV
3432
                } else {
×
UNCOV
3433
                        p.log.Infof("channel(%v) force "+
×
UNCOV
3434
                                "closed with txid %v",
×
UNCOV
3435
                                failure.shortChanID, closeTx.TxHash())
×
UNCOV
3436
                }
×
3437
        }
3438

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

×
3444
                if err := lnChan.State().MarkBorked(); err != nil {
×
3445
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
3446
                                failure.shortChanID, err)
×
3447
                }
×
3448
        }
3449

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

UNCOV
3461
                var networkMsg lnwire.Message
×
UNCOV
3462
                if failure.linkErr.Warning {
×
3463
                        networkMsg = &lnwire.Warning{
×
3464
                                ChanID: failure.chanID,
×
3465
                                Data:   data,
×
3466
                        }
×
UNCOV
3467
                } else {
×
UNCOV
3468
                        networkMsg = &lnwire.Error{
×
UNCOV
3469
                                ChanID: failure.chanID,
×
UNCOV
3470
                                Data:   data,
×
UNCOV
3471
                        }
×
UNCOV
3472
                }
×
3473

UNCOV
3474
                err := p.SendMessage(true, networkMsg)
×
UNCOV
3475
                if err != nil {
×
3476
                        p.log.Errorf("unable to send msg to "+
×
3477
                                "remote peer: %v", err)
×
3478
                }
×
3479
        }
3480

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

3489
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
3490
// public key and the channel id.
3491
func (p *Brontide) fetchLinkFromKeyAndCid(
3492
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
19✔
3493

19✔
3494
        var chanLink htlcswitch.ChannelUpdateHandler
19✔
3495

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

3506
        return chanLink
19✔
3507
}
3508

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

4✔
3517
        // First, we'll clear all indexes related to the channel in question.
4✔
3518
        chanPoint := chanCloser.Channel().ChannelPoint()
4✔
3519
        p.WipeChannel(&chanPoint)
4✔
3520

4✔
3521
        // Also clear the activeChanCloses map of this channel.
4✔
3522
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
3523
        delete(p.activeChanCloses, cid)
4✔
3524

4✔
3525
        // Next, we'll launch a goroutine which will request to be notified by
4✔
3526
        // the ChainNotifier once the closure transaction obtains a single
4✔
3527
        // confirmation.
4✔
3528
        notifier := p.cfg.ChainNotifier
4✔
3529

4✔
3530
        // If any error happens during waitForChanToClose, forward it to
4✔
3531
        // closeReq. If this channel closure is not locally initiated, closeReq
4✔
3532
        // will be nil, so just ignore the error.
4✔
3533
        errChan := make(chan error, 1)
4✔
3534
        if closeReq != nil {
6✔
3535
                errChan = closeReq.Err
2✔
3536
        }
2✔
3537

3538
        closingTx, err := chanCloser.ClosingTx()
4✔
3539
        if err != nil {
4✔
3540
                if closeReq != nil {
×
3541
                        p.log.Error(err)
×
3542
                        closeReq.Err <- err
×
3543
                }
×
3544
        }
3545

3546
        closingTxid := closingTx.TxHash()
4✔
3547

4✔
3548
        // If this is a locally requested shutdown, update the caller with a
4✔
3549
        // new event detailing the current pending state of this request.
4✔
3550
        if closeReq != nil {
6✔
3551
                closeReq.Updates <- &PendingUpdate{
2✔
3552
                        Txid: closingTxid[:],
2✔
3553
                }
2✔
3554
        }
2✔
3555

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

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

4✔
3586
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
4✔
3587
                "with txid: %v", chanPoint, closingTxID)
4✔
3588

4✔
3589
        // TODO(roasbeef): add param for num needed confs
4✔
3590
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
4✔
3591
                closingTxID, closeScript, 1, bestHeight,
4✔
3592
        )
4✔
3593
        if err != nil {
4✔
3594
                if errChan != nil {
×
3595
                        errChan <- err
×
3596
                }
×
3597
                return
×
3598
        }
3599

3600
        // In the case that the ChainNotifier is shutting down, all subscriber
3601
        // notification channels will be closed, generating a nil receive.
3602
        height, ok := <-confNtfn.Confirmed
4✔
3603
        if !ok {
4✔
UNCOV
3604
                return
×
UNCOV
3605
        }
×
3606

3607
        // The channel has been closed, remove it from any active indexes, and
3608
        // the database state.
3609
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
4✔
3610
                "height %v", chanPoint, height.BlockHeight)
4✔
3611

4✔
3612
        // Finally, execute the closure call back to mark the confirmation of
4✔
3613
        // the transaction closing the contract.
4✔
3614
        cb()
4✔
3615
}
3616

3617
// WipeChannel removes the passed channel point from all indexes associated with
3618
// the peer and the switch.
3619
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
4✔
3620
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
4✔
3621

4✔
3622
        p.activeChannels.Delete(chanID)
4✔
3623

4✔
3624
        // Instruct the HtlcSwitch to close this link as the channel is no
4✔
3625
        // longer active.
4✔
3626
        p.cfg.Switch.RemoveLink(chanID)
4✔
3627
}
4✔
3628

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

3640
        // Then, finalize the remote feature vector providing the flattened
3641
        // feature bit namespace.
3642
        p.remoteFeatures = lnwire.NewFeatureVector(
3✔
3643
                msg.Features, lnwire.Features,
3✔
3644
        )
3✔
3645

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

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

3661
        // Now that we know we understand their requirements, we'll check to
3662
        // see if they don't support anything that we deem to be mandatory.
3663
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
3✔
3664
                return fmt.Errorf("data loss protection required")
×
3665
        }
×
3666

3667
        return nil
3✔
3668
}
3669

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

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

3688
// hasNegotiatedScidAlias returns true if we've negotiated the
3689
// option-scid-alias feature bit with the peer.
3690
func (p *Brontide) hasNegotiatedScidAlias() bool {
3✔
3691
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
3✔
3692
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
3✔
3693
        return peerHas && localHas
3✔
3694
}
3✔
3695

3696
// sendInitMsg sends the Init message to the remote peer. This message contains
3697
// our currently supported local and global features.
3698
func (p *Brontide) sendInitMsg(legacyChan bool) error {
7✔
3699
        features := p.cfg.Features.Clone()
7✔
3700
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
7✔
3701

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

1✔
3712
                // Unset and set in both the local and global features to
1✔
3713
                // ensure both sets are consistent and merge able by old and
1✔
3714
                // new nodes.
1✔
3715
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3716
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3717

1✔
3718
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
3719
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
3720
        }
1✔
3721

3722
        msg := lnwire.NewInitMessage(
7✔
3723
                legacyFeatures.RawFeatureVector,
7✔
3724
                features.RawFeatureVector,
7✔
3725
        )
7✔
3726

7✔
3727
        return p.writeMessage(msg)
7✔
3728
}
3729

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

3739
        // Check if we have any channel sync messages stored for this channel.
UNCOV
3740
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
×
UNCOV
3741
        if err != nil {
×
UNCOV
3742
                return fmt.Errorf("unable to fetch channel sync messages for "+
×
UNCOV
3743
                        "peer %v: %v", p, err)
×
UNCOV
3744
        }
×
3745

UNCOV
3746
        if c.LastChanSyncMsg == nil {
×
3747
                return fmt.Errorf("no chan sync message stored for channel %v",
×
3748
                        cid)
×
3749
        }
×
3750

UNCOV
3751
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
×
3752
                return fmt.Errorf("ignoring channel reestablish from "+
×
3753
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
3754
        }
×
3755

UNCOV
3756
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
×
UNCOV
3757
                "peer", cid)
×
UNCOV
3758

×
UNCOV
3759
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
×
3760
                return fmt.Errorf("failed resending channel sync "+
×
3761
                        "message to peer %v: %v", p, err)
×
3762
        }
×
3763

UNCOV
3764
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
×
UNCOV
3765
                cid)
×
UNCOV
3766

×
UNCOV
3767
        // Note down that we sent the message, so we won't resend it again for
×
UNCOV
3768
        // this connection.
×
UNCOV
3769
        p.resentChanSyncMsg[cid] = struct{}{}
×
UNCOV
3770

×
UNCOV
3771
        return nil
×
3772
}
3773

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

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

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

3815
                if priority {
7✔
3816
                        p.queueMsg(msg, errChan)
3✔
3817
                } else {
4✔
3818
                        p.queueMsgLazy(msg, errChan)
1✔
3819
                }
1✔
3820
        }
3821

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

3835
        return nil
3✔
3836
}
3837

3838
// PubKey returns the pubkey of the peer in compressed serialized format.
3839
//
3840
// NOTE: Part of the lnpeer.Peer interface.
3841
func (p *Brontide) PubKey() [33]byte {
2✔
3842
        return p.cfg.PubKeyBytes
2✔
3843
}
2✔
3844

3845
// IdentityKey returns the public key of the remote peer.
3846
//
3847
// NOTE: Part of the lnpeer.Peer interface.
3848
func (p *Brontide) IdentityKey() *btcec.PublicKey {
15✔
3849
        return p.cfg.Addr.IdentityKey
15✔
3850
}
15✔
3851

3852
// Address returns the network address of the remote peer.
3853
//
3854
// NOTE: Part of the lnpeer.Peer interface.
UNCOV
3855
func (p *Brontide) Address() net.Addr {
×
UNCOV
3856
        return p.cfg.Addr.Address
×
UNCOV
3857
}
×
3858

3859
// AddNewChannel adds a new channel to the peer. The channel should fail to be
3860
// added if the cancel channel is closed.
3861
//
3862
// NOTE: Part of the lnpeer.Peer interface.
3863
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
UNCOV
3864
        cancel <-chan struct{}) error {
×
UNCOV
3865

×
UNCOV
3866
        errChan := make(chan error, 1)
×
UNCOV
3867
        newChanMsg := &newChannelMsg{
×
UNCOV
3868
                channel: newChan,
×
UNCOV
3869
                err:     errChan,
×
UNCOV
3870
        }
×
UNCOV
3871

×
UNCOV
3872
        select {
×
UNCOV
3873
        case p.newActiveChannel <- newChanMsg:
×
3874
        case <-cancel:
×
3875
                return errors.New("canceled adding new channel")
×
3876
        case <-p.quit:
×
3877
                return lnpeer.ErrPeerExiting
×
3878
        }
3879

3880
        // We pause here to wait for the peer to recognize the new channel
3881
        // before we close the channel barrier corresponding to the channel.
UNCOV
3882
        select {
×
UNCOV
3883
        case err := <-errChan:
×
UNCOV
3884
                return err
×
3885
        case <-p.quit:
×
3886
                return lnpeer.ErrPeerExiting
×
3887
        }
3888
}
3889

3890
// AddPendingChannel adds a pending open channel to the peer. The channel
3891
// should fail to be added if the cancel channel is closed.
3892
//
3893
// NOTE: Part of the lnpeer.Peer interface.
3894
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
UNCOV
3895
        cancel <-chan struct{}) error {
×
UNCOV
3896

×
UNCOV
3897
        errChan := make(chan error, 1)
×
UNCOV
3898
        newChanMsg := &newChannelMsg{
×
UNCOV
3899
                channelID: cid,
×
UNCOV
3900
                err:       errChan,
×
UNCOV
3901
        }
×
UNCOV
3902

×
UNCOV
3903
        select {
×
UNCOV
3904
        case p.newPendingChannel <- newChanMsg:
×
3905

3906
        case <-cancel:
×
3907
                return errors.New("canceled adding pending channel")
×
3908

3909
        case <-p.quit:
×
3910
                return lnpeer.ErrPeerExiting
×
3911
        }
3912

3913
        // We pause here to wait for the peer to recognize the new pending
3914
        // channel before we close the channel barrier corresponding to the
3915
        // channel.
UNCOV
3916
        select {
×
UNCOV
3917
        case err := <-errChan:
×
UNCOV
3918
                return err
×
3919

3920
        case <-cancel:
×
3921
                return errors.New("canceled adding pending channel")
×
3922

3923
        case <-p.quit:
×
3924
                return lnpeer.ErrPeerExiting
×
3925
        }
3926
}
3927

3928
// RemovePendingChannel removes a pending open channel from the peer.
3929
//
3930
// NOTE: Part of the lnpeer.Peer interface.
UNCOV
3931
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
×
UNCOV
3932
        errChan := make(chan error, 1)
×
UNCOV
3933
        newChanMsg := &newChannelMsg{
×
UNCOV
3934
                channelID: cid,
×
UNCOV
3935
                err:       errChan,
×
UNCOV
3936
        }
×
UNCOV
3937

×
UNCOV
3938
        select {
×
UNCOV
3939
        case p.removePendingChannel <- newChanMsg:
×
3940
        case <-p.quit:
×
3941
                return lnpeer.ErrPeerExiting
×
3942
        }
3943

3944
        // We pause here to wait for the peer to respond to the cancellation of
3945
        // the pending channel before we close the channel barrier
3946
        // corresponding to the channel.
UNCOV
3947
        select {
×
UNCOV
3948
        case err := <-errChan:
×
UNCOV
3949
                return err
×
3950

3951
        case <-p.quit:
×
3952
                return lnpeer.ErrPeerExiting
×
3953
        }
3954
}
3955

3956
// StartTime returns the time at which the connection was established if the
3957
// peer started successfully, and zero otherwise.
UNCOV
3958
func (p *Brontide) StartTime() time.Time {
×
UNCOV
3959
        return p.startTime
×
UNCOV
3960
}
×
3961

3962
// handleCloseMsg is called when a new cooperative channel closure related
3963
// message is received from the remote peer. We'll use this message to advance
3964
// the chan closer state machine.
3965
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
13✔
3966
        link := p.fetchLinkFromKeyAndCid(msg.cid)
13✔
3967

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

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

×
3979
                errMsg := &lnwire.Error{
×
3980
                        ChanID: msg.cid,
×
3981
                        Data:   lnwire.ErrorData(err.Error()),
×
3982
                }
×
3983
                p.queueMsg(errMsg, nil)
×
3984
                return
×
3985
        }
3986

3987
        handleErr := func(err error) {
13✔
UNCOV
3988
                err = fmt.Errorf("unable to process close msg: %w", err)
×
UNCOV
3989
                p.log.Error(err)
×
UNCOV
3990

×
UNCOV
3991
                // As the negotiations failed, we'll reset the channel state machine to
×
UNCOV
3992
                // ensure we act to on-chain events as normal.
×
UNCOV
3993
                chanCloser.Channel().ResetState()
×
UNCOV
3994

×
UNCOV
3995
                if chanCloser.CloseRequest() != nil {
×
3996
                        chanCloser.CloseRequest().Err <- err
×
3997
                }
×
UNCOV
3998
                delete(p.activeChanCloses, msg.cid)
×
UNCOV
3999

×
UNCOV
4000
                p.Disconnect(err)
×
4001
        }
4002

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

4013
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
5✔
4014
                if err != nil {
5✔
4015
                        handleErr(err)
×
4016
                        return
×
4017
                }
×
4018

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

4028
                        // Immediately disallow any new HTLC's from being added
4029
                        // in the outgoing direction.
4030
                        if !link.DisableAdds(htlcswitch.Outgoing) {
2✔
4031
                                p.log.Warnf("Outgoing link adds already "+
×
4032
                                        "disabled: %v", link.ChanID())
×
4033
                        }
×
4034

4035
                        // When we have a Shutdown to send, we defer it till the
4036
                        // next time we send a CommitSig to remain spec
4037
                        // compliant.
4038
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
4✔
4039
                                p.queueMsg(&msg, nil)
2✔
4040
                        })
2✔
4041
                })
4042

4043
                beginNegotiation := func() {
10✔
4044
                        oClosingSigned, err := chanCloser.BeginNegotiation()
5✔
4045
                        if err != nil {
5✔
UNCOV
4046
                                handleErr(err)
×
UNCOV
4047
                                return
×
UNCOV
4048
                        }
×
4049

4050
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
10✔
4051
                                p.queueMsg(&msg, nil)
5✔
4052
                        })
5✔
4053
                }
4054

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

4068
        case *lnwire.ClosingSigned:
8✔
4069
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
8✔
4070
                if err != nil {
8✔
4071
                        handleErr(err)
×
4072
                        return
×
4073
                }
×
4074

4075
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
16✔
4076
                        p.queueMsg(&msg, nil)
8✔
4077
                })
8✔
4078

4079
        default:
×
4080
                panic("impossible closeMsg type")
×
4081
        }
4082

4083
        // If we haven't finished close negotiations, then we'll continue as we
4084
        // can't yet finalize the closure.
4085
        if _, err := chanCloser.ClosingTx(); err != nil {
20✔
4086
                return
8✔
4087
        }
8✔
4088

4089
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
4090
        // the channel closure by notifying relevant sub-systems and launching a
4091
        // goroutine to wait for close tx conf.
4092
        p.finalizeChanClosure(chanCloser)
4✔
4093
}
4094

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

4109
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
UNCOV
4110
func (p *Brontide) NetAddress() *lnwire.NetAddress {
×
UNCOV
4111
        return p.cfg.Addr
×
UNCOV
4112
}
×
4113

4114
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
UNCOV
4115
func (p *Brontide) Inbound() bool {
×
UNCOV
4116
        return p.cfg.Inbound
×
UNCOV
4117
}
×
4118

4119
// ConnReq is a getter for the Brontide's connReq in cfg.
UNCOV
4120
func (p *Brontide) ConnReq() *connmgr.ConnReq {
×
UNCOV
4121
        return p.cfg.ConnReq
×
UNCOV
4122
}
×
4123

4124
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
UNCOV
4125
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
×
UNCOV
4126
        return p.cfg.ErrorBuffer
×
UNCOV
4127
}
×
4128

4129
// SetAddress sets the remote peer's address given an address.
4130
func (p *Brontide) SetAddress(address net.Addr) {
×
4131
        p.cfg.Addr.Address = address
×
4132
}
×
4133

4134
// ActiveSignal returns the peer's active signal.
UNCOV
4135
func (p *Brontide) ActiveSignal() chan struct{} {
×
UNCOV
4136
        return p.activeSignal
×
UNCOV
4137
}
×
4138

4139
// Conn returns a pointer to the peer's connection struct.
UNCOV
4140
func (p *Brontide) Conn() net.Conn {
×
UNCOV
4141
        return p.cfg.Conn
×
UNCOV
4142
}
×
4143

4144
// BytesReceived returns the number of bytes received from the peer.
UNCOV
4145
func (p *Brontide) BytesReceived() uint64 {
×
UNCOV
4146
        return atomic.LoadUint64(&p.bytesReceived)
×
UNCOV
4147
}
×
4148

4149
// BytesSent returns the number of bytes sent to the peer.
UNCOV
4150
func (p *Brontide) BytesSent() uint64 {
×
UNCOV
4151
        return atomic.LoadUint64(&p.bytesSent)
×
UNCOV
4152
}
×
4153

4154
// LastRemotePingPayload returns the last payload the remote party sent as part
4155
// of their ping.
UNCOV
4156
func (p *Brontide) LastRemotePingPayload() []byte {
×
UNCOV
4157
        pingPayload := p.lastPingPayload.Load()
×
UNCOV
4158
        if pingPayload == nil {
×
UNCOV
4159
                return []byte{}
×
UNCOV
4160
        }
×
4161

UNCOV
4162
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
UNCOV
4163
        if !ok {
×
4164
                return nil
×
4165
        }
×
4166

UNCOV
4167
        return pingBytes
×
4168
}
4169

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

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

4191
        p.channelEventClient = sub
3✔
4192

3✔
4193
        return nil
3✔
4194
}
4195

4196
// updateNextRevocation updates the existing channel's next revocation if it's
4197
// nil.
4198
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
3✔
4199
        chanPoint := c.FundingOutpoint
3✔
4200
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4201

3✔
4202
        // Read the current channel.
3✔
4203
        currentChan, loaded := p.activeChannels.Load(chanID)
3✔
4204

3✔
4205
        // currentChan should exist, but we perform a check anyway to avoid nil
3✔
4206
        // pointer dereference.
3✔
4207
        if !loaded {
4✔
4208
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
4209
                        chanID)
1✔
4210
        }
1✔
4211

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

4219
        // If we're being sent a new channel, and our existing channel doesn't
4220
        // have the next revocation, then we need to update the current
4221
        // existing channel.
4222
        if currentChan.RemoteNextRevocation() != nil {
1✔
4223
                return nil
×
4224
        }
×
4225

4226
        p.log.Infof("Processing retransmitted ChannelReady for "+
1✔
4227
                "ChannelPoint(%v)", chanPoint)
1✔
4228

1✔
4229
        nextRevoke := c.RemoteNextRevocation
1✔
4230

1✔
4231
        err := currentChan.InitNextRevocation(nextRevoke)
1✔
4232
        if err != nil {
1✔
4233
                return fmt.Errorf("unable to init next revocation: %w", err)
×
4234
        }
×
4235

4236
        return nil
1✔
4237
}
4238

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

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

×
UNCOV
4253
        chanOpts := c.ChanOpts
×
UNCOV
4254
        if shouldReestablish {
×
UNCOV
4255
                // If we have to do the reestablish dance for this channel,
×
UNCOV
4256
                // ensure that we don't try to call InitRemoteMusigNonces twice
×
UNCOV
4257
                // by calling SkipNonceInit.
×
UNCOV
4258
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
×
UNCOV
4259
        }
×
4260

UNCOV
4261
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
×
4262
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
4263
        })
×
UNCOV
4264
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
×
4265
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
4266
        })
×
UNCOV
4267
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
×
4268
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
4269
        })
×
4270

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

4281
        // Store the channel in the activeChannels map.
UNCOV
4282
        p.activeChannels.Store(chanID, lnChan)
×
UNCOV
4283

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

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

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

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

UNCOV
4312
        return nil
×
4313
}
4314

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

×
UNCOV
4323
        // Only update RemoteNextRevocation if the channel is in the
×
UNCOV
4324
        // activeChannels map and if we added the link to the switch. Only
×
UNCOV
4325
        // active channels will be added to the switch.
×
UNCOV
4326
        if p.isActiveChannel(chanID) {
×
UNCOV
4327
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
×
UNCOV
4328
                        chanPoint)
×
UNCOV
4329

×
UNCOV
4330
                // Handle it and close the err chan on the request.
×
UNCOV
4331
                close(req.err)
×
UNCOV
4332

×
UNCOV
4333
                // Update the next revocation point.
×
UNCOV
4334
                err := p.updateNextRevocation(newChan.OpenChannel)
×
UNCOV
4335
                if err != nil {
×
4336
                        p.log.Errorf(err.Error())
×
4337
                }
×
4338

UNCOV
4339
                return
×
4340
        }
4341

4342
        // This is a new channel, we now add it to the map.
UNCOV
4343
        if err := p.addActiveChannel(req.channel); err != nil {
×
4344
                // Log and send back the error to the request.
×
4345
                p.log.Errorf(err.Error())
×
4346
                req.err <- err
×
4347

×
4348
                return
×
4349
        }
×
4350

4351
        // Close the err chan if everything went fine.
UNCOV
4352
        close(req.err)
×
4353
}
4354

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

4✔
4362
        chanID := req.channelID
4✔
4363

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

1✔
4372
                return
1✔
4373
        }
1✔
4374

4375
        // The channel has already been added, we will do nothing and return.
4376
        if p.isPendingChannel(chanID) {
4✔
4377
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
4378
                        "pending channel request", chanID)
1✔
4379

1✔
4380
                return
1✔
4381
        }
1✔
4382

4383
        // This is a new channel, we now add it to the map `activeChannels`
4384
        // with nil value and mark it as a newly added channel in
4385
        // `addedChannels`.
4386
        p.activeChannels.Store(chanID, nil)
2✔
4387
        p.addedChannels.Store(chanID, struct{}{})
2✔
4388
}
4389

4390
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
4391
// from `activeChannels` map. The request will be ignored if the channel is
4392
// considered active by Brontide. Noop if the channel ID cannot be found.
4393
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
4✔
4394
        defer close(req.err)
4✔
4395

4✔
4396
        chanID := req.channelID
4✔
4397

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

4407
        // The channel has not been added yet, we will log a warning as there
4408
        // is an unexpected call from funding manager.
4409
        if !p.isPendingChannel(chanID) {
4✔
4410
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
1✔
4411
        }
1✔
4412

4413
        // Remove the record of this pending channel.
4414
        p.activeChannels.Delete(chanID)
3✔
4415
        p.addedChannels.Delete(chanID)
3✔
4416
}
4417

4418
// sendLinkUpdateMsg sends a message that updates the channel to the
4419
// channel's message stream.
UNCOV
4420
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
×
UNCOV
4421
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
×
UNCOV
4422

×
UNCOV
4423
        chanStream, ok := p.activeMsgStreams[cid]
×
UNCOV
4424
        if !ok {
×
UNCOV
4425
                // If a stream hasn't yet been created, then we'll do so, add
×
UNCOV
4426
                // it to the map, and finally start it.
×
UNCOV
4427
                chanStream = newChanMsgStream(p, cid)
×
UNCOV
4428
                p.activeMsgStreams[cid] = chanStream
×
UNCOV
4429
                chanStream.Start()
×
UNCOV
4430

×
UNCOV
4431
                // Stop the stream when quit.
×
UNCOV
4432
                go func() {
×
UNCOV
4433
                        <-p.quit
×
UNCOV
4434
                        chanStream.Stop()
×
UNCOV
4435
                }()
×
4436
        }
4437

4438
        // With the stream obtained, add the message to the stream so we can
4439
        // continue processing message.
UNCOV
4440
        chanStream.AddMsg(msg)
×
4441
}
4442

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

4452
        return timeout
67✔
4453
}
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