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

lightningnetwork / lnd / 12058234999

27 Nov 2024 09:06PM UTC coverage: 57.847% (-1.1%) from 58.921%
12058234999

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%)

19365 existing lines in 251 files now uncovered.

100876 of 174383 relevant lines covered (57.85%)

25338.28 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

120
        err chan error
121
}
122

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

430
        // ShouldFwdExpEndorsement is a closure that indicates whether
431
        // experimental endorsement signals should be set.
432
        ShouldFwdExpEndorsement func() bool
433

434
        // Quit is the server's quit channel. If this is closed, we halt operation.
435
        Quit chan struct{}
436
}
437

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

449
        // MUST be used atomically.
450
        bytesReceived uint64
451
        bytesSent     uint64
452

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

470
        pingManager *PingManager
471

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

479
        cfg Config
480

481
        // activeSignal when closed signals that the peer is now active and
482
        // ready to process messages.
483
        activeSignal chan struct{}
484

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

489
        // sendQueue is the channel which is used to queue outgoing messages to be
490
        // written onto the wire. Note that this channel is unbuffered.
491
        sendQueue chan outgoingMsg
492

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

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

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

516
        // newActiveChannel is used by the fundingManager to send fully opened
517
        // channels to the source peer which handled the funding workflow.
518
        newActiveChannel chan *newChannelMsg
519

520
        // newPendingChannel is used by the fundingManager to send pending open
521
        // channels to the source peer which handled the funding workflow.
522
        newPendingChannel chan *newChannelMsg
523

524
        // removePendingChannel is used by the fundingManager to cancel pending
525
        // open channels to the source peer when the funding flow is failed.
526
        removePendingChannel chan *newChannelMsg
527

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

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

538
        // localCloseChanReqs is a channel in which any local requests to close
539
        // a particular channel are sent over.
540
        localCloseChanReqs chan *htlcswitch.ChanClose
541

542
        // linkFailures receives all reported channel failures from the switch,
543
        // and instructs the channelManager to clean remaining channel state.
544
        linkFailures chan linkFailureReport
545

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

551
        // remoteFeatures is the feature vector received from the peer during
552
        // the connection handshake.
553
        remoteFeatures *lnwire.FeatureVector
554

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

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

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

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

579
        startReady chan struct{}
580
        quit       chan struct{}
581
        wg         sync.WaitGroup
582

583
        // log is a peer-specific logging instance.
584
        log btclog.Logger
585
}
586

587
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer interface.
588
var _ lnpeer.Peer = (*Brontide)(nil)
589

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

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

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

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

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

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

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

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

UNCOV
664
                return lastSerializedBlockHeader[:]
×
665
        }
666

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

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

696
        return p
25✔
697
}
698

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

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

3✔
711
        p.log.Tracef("starting with conn[%v->%v]",
3✔
712
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
3✔
713

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

725
        if len(activeChans) == 0 {
4✔
726
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
1✔
727
        }
1✔
728

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

UNCOV
737
                haveLegacyChan = true
×
UNCOV
738
                break
×
739
        }
740

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

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

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

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

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

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

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

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

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

819
        p.startTime = time.Now()
3✔
820

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

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

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

843
        p.wg.Add(4)
3✔
844
        go p.queueHandler()
3✔
845
        go p.writeHandler()
3✔
846
        go p.channelManager()
3✔
847
        go p.readHandler()
3✔
848

3✔
849
        // Signal to any external processes that the peer is now active.
3✔
850
        close(p.activeSignal)
3✔
851

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

3✔
867
        return nil
3✔
868
}
869

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

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

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

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

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

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

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

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

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

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

3✔
953
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
3✔
954

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

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

UNCOV
983
                                chanID := lnwire.NewChanIDFromOutPoint(
×
UNCOV
984
                                        dbChan.FundingOutpoint,
×
UNCOV
985
                                )
×
UNCOV
986

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

UNCOV
994
                                channelReadyMsg := lnwire.NewChannelReady(
×
UNCOV
995
                                        chanID, second,
×
UNCOV
996
                                )
×
UNCOV
997
                                channelReadyMsg.AliasScid = &aliasScid
×
UNCOV
998

×
UNCOV
999
                                msgs = append(msgs, channelReadyMsg)
×
1000
                        }
1001

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

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

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

1036
                chanPoint := dbChan.FundingOutpoint
2✔
1037

2✔
1038
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
1039

2✔
1040
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
2✔
1041
                        chanPoint, lnChan.IsPending())
2✔
1042

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

2✔
1048
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
2✔
1049
                                "start.", chanPoint, dbChan.ChanStatus())
2✔
1050

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

1065
                        msgs = append(msgs, chanSync)
2✔
1066

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

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

1082
                                if shutdownMsg == nil {
×
1083
                                        continue
×
1084
                                }
1085

1086
                                // Append the message to the set of messages to
1087
                                // send.
1088
                                msgs = append(msgs, shutdownMsg)
×
1089
                        }
1090

1091
                        continue
2✔
1092
                }
1093

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

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

×
UNCOV
1116
                        selfPolicy = p1
×
UNCOV
1117
                } else {
×
UNCOV
1118
                        selfPolicy = p2
×
UNCOV
1119
                }
×
1120

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

UNCOV
1134
                        inboundFee := models.NewInboundFeeFromWire(
×
UNCOV
1135
                                inboundWireFee,
×
UNCOV
1136
                        )
×
UNCOV
1137

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

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

UNCOV
1154
                p.log.Tracef("Using link policy of: %v",
×
UNCOV
1155
                        spew.Sdump(forwardingPolicy))
×
UNCOV
1156

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

×
UNCOV
1166
                        continue
×
1167
                }
1168

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

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

×
1187
                                return
×
1188
                        }
×
1189

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

×
1205
                                return
×
1206
                        }
×
1207

UNCOV
1208
                        chanID := lnwire.NewChanIDFromOutPoint(
×
UNCOV
1209
                                lnChan.State().FundingOutpoint,
×
UNCOV
1210
                        )
×
UNCOV
1211

×
UNCOV
1212
                        p.activeChanCloses[chanID] = chanCloser
×
UNCOV
1213

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

×
1220
                                return
×
1221
                        }
×
1222

UNCOV
1223
                        shutdownMsg = fn.Some(*shutdown)
×
1224
                })
UNCOV
1225
                if shutdownInfoErr != nil {
×
1226
                        return nil, shutdownInfoErr
×
1227
                }
×
1228

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

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

UNCOV
1246
                p.activeChannels.Store(chanID, lnChan)
×
1247
        }
1248

1249
        return msgs, nil
3✔
1250
}
1251

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

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

×
UNCOV
1265
                failure := linkFailureReport{
×
UNCOV
1266
                        chanPoint:   *chanPoint,
×
UNCOV
1267
                        chanID:      chanID,
×
UNCOV
1268
                        shortChanID: shortChanID,
×
UNCOV
1269
                        linkErr:     linkErr,
×
UNCOV
1270
                }
×
UNCOV
1271

×
UNCOV
1272
                select {
×
UNCOV
1273
                case p.linkFailures <- failure:
×
1274
                case <-p.quit:
×
1275
                case <-p.cfg.Quit:
×
1276
                }
1277
        }
1278

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

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

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

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

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

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

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

UNCOV
1361
                hasConfirmedPublicChan = true
×
UNCOV
1362
                break
×
1363
        }
1364
        if !hasConfirmedPublicChan {
6✔
1365
                return
3✔
1366
        }
3✔
1367

UNCOV
1368
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
×
UNCOV
1369
        if err != nil {
×
1370
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1371
                return
×
1372
        }
×
1373

UNCOV
1374
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
×
1375
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1376
        }
×
1377
}
1378

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

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

1389
        maybeSendUpd := func(cid lnwire.ChannelID,
2✔
1390
                lnChan *lnwallet.LightningChannel) error {
4✔
1391

2✔
1392
                // Nil channels are pending, so we'll skip them.
2✔
1393
                if lnChan == nil {
2✔
UNCOV
1394
                        return nil
×
UNCOV
1395
                }
×
1396

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

1405
                        // Otherwise, we can use the normal scid.
1406
                        default:
2✔
1407
                                return dbChan.ShortChanID()
2✔
1408
                        }
1409
                }()
1410

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

×
UNCOV
1421
                        return nil
×
UNCOV
1422
                }
×
1423

1424
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
2✔
1425
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
2✔
1426

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

×
1436
                        return err
×
1437
                }
×
1438

1439
                return nil
2✔
1440
        }
1441

1442
        p.activeChannels.ForEach(maybeSendUpd)
2✔
1443
}
1444

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

UNCOV
1462
        select {
×
UNCOV
1463
        case <-ready:
×
1464
        case <-p.quit:
×
1465
        }
1466

UNCOV
1467
        p.wg.Wait()
×
1468
}
1469

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

1478
        // Make sure initialization has completed before we try to tear things
1479
        // down.
1480
        //
1481
        // NOTE: We only read the `startReady` chan if the peer has been
1482
        // started, otherwise we will skip reading it as this chan won't be
1483
        // closed, hence blocks forever.
1484
        if atomic.LoadInt32(&p.started) == 1 {
1✔
UNCOV
1485
                p.log.Debugf("Started, waiting on startReady signal")
×
UNCOV
1486

×
UNCOV
1487
                select {
×
UNCOV
1488
                case <-p.startReady:
×
1489
                case <-p.quit:
×
1490
                        return
×
1491
                }
1492
        }
1493

1494
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
1✔
1495
        p.storeError(err)
1✔
1496

1✔
1497
        p.log.Infof(err.Error())
1✔
1498

1✔
1499
        // Stop PingManager before closing TCP connection.
1✔
1500
        p.pingManager.Stop()
1✔
1501

1✔
1502
        // Ensure that the TCP connection is properly closed before continuing.
1✔
1503
        p.cfg.Conn.Close()
1✔
1504

1✔
1505
        close(p.quit)
1✔
1506

1✔
1507
        // If our msg router isn't global (local to this instance), then we'll
1✔
1508
        // stop it. Otherwise, we'll leave it running.
1✔
1509
        if !p.globalMsgRouter {
2✔
1510
                p.msgRouter.WhenSome(func(router msgmux.Router) {
2✔
1511
                        router.Stop()
1✔
1512
                })
1✔
1513
        }
1514
}
1515

1516
// String returns the string representation of this peer.
1517
func (p *Brontide) String() string {
1✔
1518
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
1✔
1519
}
1✔
1520

1521
// readNextMessage reads, and returns the next message on the wire along with
1522
// any additional raw payload.
1523
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
7✔
1524
        noiseConn := p.cfg.Conn
7✔
1525
        err := noiseConn.SetReadDeadline(time.Time{})
7✔
1526
        if err != nil {
7✔
1527
                return nil, err
×
1528
        }
×
1529

1530
        pktLen, err := noiseConn.ReadNextHeader()
7✔
1531
        if err != nil {
7✔
UNCOV
1532
                return nil, fmt.Errorf("read next header: %w", err)
×
UNCOV
1533
        }
×
1534

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

1557
                // The ReadNextBody method will actually end up re-using the
1558
                // buffer, so within this closure, we can continue to use
1559
                // rawMsg as it's just a slice into the buf from the buffer
1560
                // pool.
1561
                rawMsg, readErr := noiseConn.ReadNextBody(buf[:pktLen])
4✔
1562
                if readErr != nil {
4✔
1563
                        return fmt.Errorf("read next body: %w", readErr)
×
1564
                }
×
1565
                msgLen = uint64(len(rawMsg))
4✔
1566

4✔
1567
                // Next, create a new io.Reader implementation from the raw
4✔
1568
                // message, and use this to decode the message directly from.
4✔
1569
                msgReader := bytes.NewReader(rawMsg)
4✔
1570
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
4✔
1571
                if err != nil {
4✔
UNCOV
1572
                        return err
×
UNCOV
1573
                }
×
1574

1575
                // At this point, rawMsg and buf will be returned back to the
1576
                // buffer pool for re-use.
1577
                return nil
4✔
1578
        })
1579
        atomic.AddUint64(&p.bytesReceived, msgLen)
4✔
1580
        if err != nil {
4✔
UNCOV
1581
                return nil, err
×
UNCOV
1582
        }
×
1583

1584
        p.logWireMessage(nextMsg, true)
4✔
1585

4✔
1586
        return nextMsg, nil
4✔
1587
}
1588

1589
// msgStream implements a goroutine-safe, in-order stream of messages to be
1590
// delivered via closure to a receiver. These messages MUST be in order due to
1591
// the nature of the lightning channel commitment and gossiper state machines.
1592
// TODO(conner): use stream handler interface to abstract out stream
1593
// state/logging.
1594
type msgStream struct {
1595
        streamShutdown int32 // To be used atomically.
1596

1597
        peer *Brontide
1598

1599
        apply func(lnwire.Message)
1600

1601
        startMsg string
1602
        stopMsg  string
1603

1604
        msgCond *sync.Cond
1605
        msgs    []lnwire.Message
1606

1607
        mtx sync.Mutex
1608

1609
        producerSema chan struct{}
1610

1611
        wg   sync.WaitGroup
1612
        quit chan struct{}
1613
}
1614

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

3✔
1623
        stream := &msgStream{
3✔
1624
                peer:         p,
3✔
1625
                apply:        apply,
3✔
1626
                startMsg:     startMsg,
3✔
1627
                stopMsg:      stopMsg,
3✔
1628
                producerSema: make(chan struct{}, bufSize),
3✔
1629
                quit:         make(chan struct{}),
3✔
1630
        }
3✔
1631
        stream.msgCond = sync.NewCond(&stream.mtx)
3✔
1632

3✔
1633
        // Before we return the active stream, we'll populate the producer's
3✔
1634
        // semaphore channel. We'll use this to ensure that the producer won't
3✔
1635
        // attempt to allocate memory in the queue for an item until it has
3✔
1636
        // sufficient extra space.
3✔
1637
        for i := uint32(0); i < bufSize; i++ {
3,003✔
1638
                stream.producerSema <- struct{}{}
3,000✔
1639
        }
3,000✔
1640

1641
        return stream
3✔
1642
}
1643

1644
// Start starts the chanMsgStream.
1645
func (ms *msgStream) Start() {
3✔
1646
        ms.wg.Add(1)
3✔
1647
        go ms.msgConsumer()
3✔
1648
}
3✔
1649

1650
// Stop stops the chanMsgStream.
UNCOV
1651
func (ms *msgStream) Stop() {
×
UNCOV
1652
        // TODO(roasbeef): signal too?
×
UNCOV
1653

×
UNCOV
1654
        close(ms.quit)
×
UNCOV
1655

×
UNCOV
1656
        // Now that we've closed the channel, we'll repeatedly signal the msg
×
UNCOV
1657
        // consumer until we've detected that it has exited.
×
UNCOV
1658
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
×
UNCOV
1659
                ms.msgCond.Signal()
×
UNCOV
1660
                time.Sleep(time.Millisecond * 100)
×
UNCOV
1661
        }
×
1662

UNCOV
1663
        ms.wg.Wait()
×
1664
}
1665

1666
// msgConsumer is the main goroutine that streams messages from the peer's
1667
// readHandler directly to the target channel.
1668
func (ms *msgStream) msgConsumer() {
3✔
1669
        defer ms.wg.Done()
3✔
1670
        defer peerLog.Tracef(ms.stopMsg)
3✔
1671
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
3✔
1672

3✔
1673
        peerLog.Tracef(ms.startMsg)
3✔
1674

3✔
1675
        for {
6✔
1676
                // First, we'll check our condition. If the queue of messages
3✔
1677
                // is empty, then we'll wait until a new item is added.
3✔
1678
                ms.msgCond.L.Lock()
3✔
1679
                for len(ms.msgs) == 0 {
6✔
1680
                        ms.msgCond.Wait()
3✔
1681

3✔
1682
                        // If we woke up in order to exit, then we'll do so.
3✔
1683
                        // Otherwise, we'll check the message queue for any new
3✔
1684
                        // items.
3✔
1685
                        select {
3✔
UNCOV
1686
                        case <-ms.peer.quit:
×
UNCOV
1687
                                ms.msgCond.L.Unlock()
×
UNCOV
1688
                                return
×
UNCOV
1689
                        case <-ms.quit:
×
UNCOV
1690
                                ms.msgCond.L.Unlock()
×
UNCOV
1691
                                return
×
UNCOV
1692
                        default:
×
1693
                        }
1694
                }
1695

1696
                // Grab the message off the front of the queue, shifting the
1697
                // slice's reference down one in order to remove the message
1698
                // from the queue.
UNCOV
1699
                msg := ms.msgs[0]
×
UNCOV
1700
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
×
UNCOV
1701
                ms.msgs = ms.msgs[1:]
×
UNCOV
1702

×
UNCOV
1703
                ms.msgCond.L.Unlock()
×
UNCOV
1704

×
UNCOV
1705
                ms.apply(msg)
×
UNCOV
1706

×
UNCOV
1707
                // We've just successfully processed an item, so we'll signal
×
UNCOV
1708
                // to the producer that a new slot in the buffer. We'll use
×
UNCOV
1709
                // this to bound the size of the buffer to avoid allowing it to
×
UNCOV
1710
                // grow indefinitely.
×
UNCOV
1711
                select {
×
UNCOV
1712
                case ms.producerSema <- struct{}{}:
×
UNCOV
1713
                case <-ms.peer.quit:
×
UNCOV
1714
                        return
×
UNCOV
1715
                case <-ms.quit:
×
UNCOV
1716
                        return
×
1717
                }
1718
        }
1719
}
1720

1721
// AddMsg adds a new message to the msgStream. This function is safe for
1722
// concurrent access.
UNCOV
1723
func (ms *msgStream) AddMsg(msg lnwire.Message) {
×
UNCOV
1724
        // First, we'll attempt to receive from the producerSema struct. This
×
UNCOV
1725
        // acts as a semaphore to prevent us from indefinitely buffering
×
UNCOV
1726
        // incoming items from the wire. Either the msg queue isn't full, and
×
UNCOV
1727
        // we'll not block, or the queue is full, and we'll block until either
×
UNCOV
1728
        // we're signalled to quit, or a slot is freed up.
×
UNCOV
1729
        select {
×
UNCOV
1730
        case <-ms.producerSema:
×
1731
        case <-ms.peer.quit:
×
1732
                return
×
1733
        case <-ms.quit:
×
1734
                return
×
1735
        }
1736

1737
        // Next, we'll lock the condition, and add the message to the end of
1738
        // the message queue.
UNCOV
1739
        ms.msgCond.L.Lock()
×
UNCOV
1740
        ms.msgs = append(ms.msgs, msg)
×
UNCOV
1741
        ms.msgCond.L.Unlock()
×
UNCOV
1742

×
UNCOV
1743
        // With the message added, we signal to the msgConsumer that there are
×
UNCOV
1744
        // additional messages to consume.
×
UNCOV
1745
        ms.msgCond.Signal()
×
1746
}
1747

1748
// waitUntilLinkActive waits until the target link is active and returns a
1749
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1750
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1751
func waitUntilLinkActive(p *Brontide,
UNCOV
1752
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
×
UNCOV
1753

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

×
UNCOV
1756
        // Subscribe to receive channel events.
×
UNCOV
1757
        //
×
UNCOV
1758
        // NOTE: If the link is already active by SubscribeChannelEvents, then
×
UNCOV
1759
        // GetLink will retrieve the link and we can send messages. If the link
×
UNCOV
1760
        // becomes active between SubscribeChannelEvents and GetLink, then GetLink
×
UNCOV
1761
        // will retrieve the link. If the link becomes active after GetLink, then
×
UNCOV
1762
        // we will get an ActiveLinkEvent notification and retrieve the link. If
×
UNCOV
1763
        // the call to GetLink is before SubscribeChannelEvents, however, there
×
UNCOV
1764
        // will be a race condition.
×
UNCOV
1765
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
×
UNCOV
1766
        if err != nil {
×
UNCOV
1767
                // If we have a non-nil error, then the server is shutting down and we
×
UNCOV
1768
                // can exit here and return nil. This means no message will be delivered
×
UNCOV
1769
                // to the link.
×
UNCOV
1770
                return nil
×
UNCOV
1771
        }
×
UNCOV
1772
        defer sub.Cancel()
×
UNCOV
1773

×
UNCOV
1774
        // The link may already be active by this point, and we may have missed the
×
UNCOV
1775
        // ActiveLinkEvent. Check if the link exists.
×
UNCOV
1776
        link := p.fetchLinkFromKeyAndCid(cid)
×
UNCOV
1777
        if link != nil {
×
UNCOV
1778
                return link
×
UNCOV
1779
        }
×
1780

1781
        // If the link is nil, we must wait for it to be active.
UNCOV
1782
        for {
×
UNCOV
1783
                select {
×
1784
                // A new event has been sent by the ChannelNotifier. We first check
1785
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1786
                // that the event is for this channel. Otherwise, we discard the
1787
                // message.
UNCOV
1788
                case e := <-sub.Updates():
×
UNCOV
1789
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
×
UNCOV
1790
                        if !ok {
×
UNCOV
1791
                                // Ignore this notification.
×
UNCOV
1792
                                continue
×
1793
                        }
1794

UNCOV
1795
                        chanPoint := event.ChannelPoint
×
UNCOV
1796

×
UNCOV
1797
                        // Check whether the retrieved chanPoint matches the target
×
UNCOV
1798
                        // channel id.
×
UNCOV
1799
                        if !cid.IsChanPoint(chanPoint) {
×
1800
                                continue
×
1801
                        }
1802

1803
                        // The link shouldn't be nil as we received an
1804
                        // ActiveLinkEvent. If it is nil, we return nil and the
1805
                        // calling function should catch it.
UNCOV
1806
                        return p.fetchLinkFromKeyAndCid(cid)
×
1807

UNCOV
1808
                case <-p.quit:
×
UNCOV
1809
                        return nil
×
1810
                }
1811
        }
1812
}
1813

1814
// newChanMsgStream is used to create a msgStream between the peer and
1815
// particular channel link in the htlcswitch. We utilize additional
1816
// synchronization with the fundingManager to ensure we don't attempt to
1817
// dispatch a message to a channel before it is fully active. A reference to the
1818
// channel this stream forwards to is held in scope to prevent unnecessary
1819
// lookups.
UNCOV
1820
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
×
UNCOV
1821
        var chanLink htlcswitch.ChannelUpdateHandler
×
UNCOV
1822

×
UNCOV
1823
        apply := func(msg lnwire.Message) {
×
UNCOV
1824
                // This check is fine because if the link no longer exists, it will
×
UNCOV
1825
                // be removed from the activeChannels map and subsequent messages
×
UNCOV
1826
                // shouldn't reach the chan msg stream.
×
UNCOV
1827
                if chanLink == nil {
×
UNCOV
1828
                        chanLink = waitUntilLinkActive(p, cid)
×
UNCOV
1829

×
UNCOV
1830
                        // If the link is still not active and the calling function
×
UNCOV
1831
                        // errored out, just return.
×
UNCOV
1832
                        if chanLink == nil {
×
UNCOV
1833
                                p.log.Warnf("Link=%v is not active", cid)
×
UNCOV
1834
                                return
×
UNCOV
1835
                        }
×
1836
                }
1837

1838
                // In order to avoid unnecessarily delivering message
1839
                // as the peer is exiting, we'll check quickly to see
1840
                // if we need to exit.
UNCOV
1841
                select {
×
1842
                case <-p.quit:
×
1843
                        return
×
UNCOV
1844
                default:
×
1845
                }
1846

UNCOV
1847
                chanLink.HandleChannelUpdate(msg)
×
1848
        }
1849

UNCOV
1850
        return newMsgStream(p,
×
UNCOV
1851
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
×
UNCOV
1852
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
×
UNCOV
1853
                1000,
×
UNCOV
1854
                apply,
×
UNCOV
1855
        )
×
1856
}
1857

1858
// newDiscMsgStream is used to setup a msgStream between the peer and the
1859
// authenticated gossiper. This stream should be used to forward all remote
1860
// channel announcements.
1861
func newDiscMsgStream(p *Brontide) *msgStream {
3✔
1862
        apply := func(msg lnwire.Message) {
3✔
UNCOV
1863
                // TODO(yy): `ProcessRemoteAnnouncement` returns an error chan
×
UNCOV
1864
                // and we need to process it.
×
UNCOV
1865
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(msg, p)
×
UNCOV
1866
        }
×
1867

1868
        return newMsgStream(
3✔
1869
                p,
3✔
1870
                "Update stream for gossiper created",
3✔
1871
                "Update stream for gossiper exited",
3✔
1872
                1000,
3✔
1873
                apply,
3✔
1874
        )
3✔
1875
}
1876

1877
// readHandler is responsible for reading messages off the wire in series, then
1878
// properly dispatching the handling of the message to the proper subsystem.
1879
//
1880
// NOTE: This method MUST be run as a goroutine.
1881
func (p *Brontide) readHandler() {
3✔
1882
        defer p.wg.Done()
3✔
1883

3✔
1884
        // We'll stop the timer after a new messages is received, and also
3✔
1885
        // reset it after we process the next message.
3✔
1886
        idleTimer := time.AfterFunc(idleTimeout, func() {
3✔
1887
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
1888
                        p, idleTimeout)
×
1889
                p.Disconnect(err)
×
1890
        })
×
1891

1892
        // Initialize our negotiated gossip sync method before reading messages
1893
        // off the wire. When using gossip queries, this ensures a gossip
1894
        // syncer is active by the time query messages arrive.
1895
        //
1896
        // TODO(conner): have peer store gossip syncer directly and bypass
1897
        // gossiper?
1898
        p.initGossipSync()
3✔
1899

3✔
1900
        discStream := newDiscMsgStream(p)
3✔
1901
        discStream.Start()
3✔
1902
        defer discStream.Stop()
3✔
1903
out:
3✔
1904
        for atomic.LoadInt32(&p.disconnect) == 0 {
7✔
1905
                nextMsg, err := p.readNextMessage()
4✔
1906
                if !idleTimer.Stop() {
4✔
1907
                        select {
×
1908
                        case <-idleTimer.C:
×
1909
                        default:
×
1910
                        }
1911
                }
1912
                if err != nil {
1✔
UNCOV
1913
                        p.log.Infof("unable to read message from peer: %v", err)
×
UNCOV
1914

×
UNCOV
1915
                        // If we could not read our peer's message due to an
×
UNCOV
1916
                        // unknown type or invalid alias, we continue processing
×
UNCOV
1917
                        // as normal. We store unknown message and address
×
UNCOV
1918
                        // types, as they may provide debugging insight.
×
UNCOV
1919
                        switch e := err.(type) {
×
1920
                        // If this is just a message we don't yet recognize,
1921
                        // we'll continue processing as normal as this allows
1922
                        // us to introduce new messages in a forwards
1923
                        // compatible manner.
UNCOV
1924
                        case *lnwire.UnknownMessage:
×
UNCOV
1925
                                p.storeError(e)
×
UNCOV
1926
                                idleTimer.Reset(idleTimeout)
×
UNCOV
1927
                                continue
×
1928

1929
                        // If they sent us an address type that we don't yet
1930
                        // know of, then this isn't a wire error, so we'll
1931
                        // simply continue parsing the remainder of their
1932
                        // messages.
1933
                        case *lnwire.ErrUnknownAddrType:
×
1934
                                p.storeError(e)
×
1935
                                idleTimer.Reset(idleTimeout)
×
1936
                                continue
×
1937

1938
                        // If the NodeAnnouncement has an invalid alias, then
1939
                        // we'll log that error above and continue so we can
1940
                        // continue to read messages from the peer. We do not
1941
                        // store this error because it is of little debugging
1942
                        // value.
1943
                        case *lnwire.ErrInvalidNodeAlias:
×
1944
                                idleTimer.Reset(idleTimeout)
×
1945
                                continue
×
1946

1947
                        // If the error we encountered wasn't just a message we
1948
                        // didn't recognize, then we'll stop all processing as
1949
                        // this is a fatal error.
UNCOV
1950
                        default:
×
UNCOV
1951
                                break out
×
1952
                        }
1953
                }
1954

1955
                // If a message router is active, then we'll try to have it
1956
                // handle this message. If it can, then we're able to skip the
1957
                // rest of the message handling logic.
1958
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
2✔
1959
                        return r.RouteMsg(msgmux.PeerMsg{
1✔
1960
                                PeerPub: *p.IdentityKey(),
1✔
1961
                                Message: nextMsg,
1✔
1962
                        })
1✔
1963
                })
1✔
1964

1965
                // No error occurred, and the message was handled by the
1966
                // router.
1967
                if err == nil {
1✔
1968
                        continue
×
1969
                }
1970

1971
                var (
1✔
1972
                        targetChan   lnwire.ChannelID
1✔
1973
                        isLinkUpdate bool
1✔
1974
                )
1✔
1975

1✔
1976
                switch msg := nextMsg.(type) {
1✔
UNCOV
1977
                case *lnwire.Pong:
×
UNCOV
1978
                        // When we receive a Pong message in response to our
×
UNCOV
1979
                        // last ping message, we send it to the pingManager
×
UNCOV
1980
                        p.pingManager.ReceivedPong(msg)
×
1981

UNCOV
1982
                case *lnwire.Ping:
×
UNCOV
1983
                        // First, we'll store their latest ping payload within
×
UNCOV
1984
                        // the relevant atomic variable.
×
UNCOV
1985
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
UNCOV
1986

×
UNCOV
1987
                        // Next, we'll send over the amount of specified pong
×
UNCOV
1988
                        // bytes.
×
UNCOV
1989
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
×
UNCOV
1990
                        p.queueMsg(pong, nil)
×
1991

1992
                case *lnwire.OpenChannel,
1993
                        *lnwire.AcceptChannel,
1994
                        *lnwire.FundingCreated,
1995
                        *lnwire.FundingSigned,
UNCOV
1996
                        *lnwire.ChannelReady:
×
UNCOV
1997

×
UNCOV
1998
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
×
1999

UNCOV
2000
                case *lnwire.Shutdown:
×
UNCOV
2001
                        select {
×
UNCOV
2002
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
×
2003
                        case <-p.quit:
×
2004
                                break out
×
2005
                        }
UNCOV
2006
                case *lnwire.ClosingSigned:
×
UNCOV
2007
                        select {
×
UNCOV
2008
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
×
2009
                        case <-p.quit:
×
2010
                                break out
×
2011
                        }
2012

2013
                case *lnwire.Warning:
×
2014
                        targetChan = msg.ChanID
×
2015
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2016

UNCOV
2017
                case *lnwire.Error:
×
UNCOV
2018
                        targetChan = msg.ChanID
×
UNCOV
2019
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2020

UNCOV
2021
                case *lnwire.ChannelReestablish:
×
UNCOV
2022
                        targetChan = msg.ChanID
×
UNCOV
2023
                        isLinkUpdate = p.hasChannel(targetChan)
×
UNCOV
2024

×
UNCOV
2025
                        // If we failed to find the link in question, and the
×
UNCOV
2026
                        // message received was a channel sync message, then
×
UNCOV
2027
                        // this might be a peer trying to resync closed channel.
×
UNCOV
2028
                        // In this case we'll try to resend our last channel
×
UNCOV
2029
                        // sync message, such that the peer can recover funds
×
UNCOV
2030
                        // from the closed channel.
×
UNCOV
2031
                        if !isLinkUpdate {
×
UNCOV
2032
                                err := p.resendChanSyncMsg(targetChan)
×
UNCOV
2033
                                if err != nil {
×
UNCOV
2034
                                        // TODO(halseth): send error to peer?
×
UNCOV
2035
                                        p.log.Errorf("resend failed: %v",
×
UNCOV
2036
                                                err)
×
UNCOV
2037
                                }
×
2038
                        }
2039

2040
                // For messages that implement the LinkUpdater interface, we
2041
                // will consider them as link updates and send them to
2042
                // chanStream. These messages will be queued inside chanStream
2043
                // if the channel is not active yet.
UNCOV
2044
                case lnwire.LinkUpdater:
×
UNCOV
2045
                        targetChan = msg.TargetChanID()
×
UNCOV
2046
                        isLinkUpdate = p.hasChannel(targetChan)
×
UNCOV
2047

×
UNCOV
2048
                        // Log an error if we don't have this channel. This
×
UNCOV
2049
                        // means the peer has sent us a message with unknown
×
UNCOV
2050
                        // channel ID.
×
UNCOV
2051
                        if !isLinkUpdate {
×
UNCOV
2052
                                p.log.Errorf("Unknown channel ID: %v found "+
×
UNCOV
2053
                                        "in received msg=%s", targetChan,
×
UNCOV
2054
                                        nextMsg.MsgType())
×
UNCOV
2055
                        }
×
2056

2057
                case *lnwire.ChannelUpdate1,
2058
                        *lnwire.ChannelAnnouncement1,
2059
                        *lnwire.NodeAnnouncement,
2060
                        *lnwire.AnnounceSignatures1,
2061
                        *lnwire.GossipTimestampRange,
2062
                        *lnwire.QueryShortChanIDs,
2063
                        *lnwire.QueryChannelRange,
2064
                        *lnwire.ReplyChannelRange,
UNCOV
2065
                        *lnwire.ReplyShortChanIDsEnd:
×
UNCOV
2066

×
UNCOV
2067
                        discStream.AddMsg(msg)
×
2068

2069
                case *lnwire.Custom:
1✔
2070
                        err := p.handleCustomMessage(msg)
1✔
2071
                        if err != nil {
1✔
2072
                                p.storeError(err)
×
2073
                                p.log.Errorf("%v", err)
×
2074
                        }
×
2075

2076
                default:
×
2077
                        // If the message we received is unknown to us, store
×
2078
                        // the type to track the failure.
×
2079
                        err := fmt.Errorf("unknown message type %v received",
×
2080
                                uint16(msg.MsgType()))
×
2081
                        p.storeError(err)
×
2082

×
2083
                        p.log.Errorf("%v", err)
×
2084
                }
2085

2086
                if isLinkUpdate {
1✔
UNCOV
2087
                        // If this is a channel update, then we need to feed it
×
UNCOV
2088
                        // into the channel's in-order message stream.
×
UNCOV
2089
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
×
UNCOV
2090
                }
×
2091

2092
                idleTimer.Reset(idleTimeout)
1✔
2093
        }
2094

UNCOV
2095
        p.Disconnect(errors.New("read handler closed"))
×
UNCOV
2096

×
UNCOV
2097
        p.log.Trace("readHandler for peer done")
×
2098
}
2099

2100
// handleCustomMessage handles the given custom message if a handler is
2101
// registered.
2102
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
1✔
2103
        if p.cfg.HandleCustomMessage == nil {
1✔
2104
                return fmt.Errorf("no custom message handler for "+
×
2105
                        "message type %v", uint16(msg.MsgType()))
×
2106
        }
×
2107

2108
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
1✔
2109
}
2110

2111
// isLoadedFromDisk returns true if the provided channel ID is loaded from
2112
// disk.
2113
//
2114
// NOTE: only returns true for pending channels.
UNCOV
2115
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
×
UNCOV
2116
        // If this is a newly added channel, no need to reestablish.
×
UNCOV
2117
        _, added := p.addedChannels.Load(chanID)
×
UNCOV
2118
        if added {
×
UNCOV
2119
                return false
×
UNCOV
2120
        }
×
2121

2122
        // Return false if the channel is unknown.
UNCOV
2123
        channel, ok := p.activeChannels.Load(chanID)
×
UNCOV
2124
        if !ok {
×
2125
                return false
×
2126
        }
×
2127

2128
        // During startup, we will use a nil value to mark a pending channel
2129
        // that's loaded from disk.
UNCOV
2130
        return channel == nil
×
2131
}
2132

2133
// isActiveChannel returns true if the provided channel id is active, otherwise
2134
// returns false.
2135
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
8✔
2136
        // The channel would be nil if,
8✔
2137
        // - the channel doesn't exist, or,
8✔
2138
        // - the channel exists, but is pending. In this case, we don't
8✔
2139
        //   consider this channel active.
8✔
2140
        channel, _ := p.activeChannels.Load(chanID)
8✔
2141

8✔
2142
        return channel != nil
8✔
2143
}
8✔
2144

2145
// isPendingChannel returns true if the provided channel ID is pending, and
2146
// returns false if the channel is active or unknown.
2147
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
6✔
2148
        // Return false if the channel is unknown.
6✔
2149
        channel, ok := p.activeChannels.Load(chanID)
6✔
2150
        if !ok {
9✔
2151
                return false
3✔
2152
        }
3✔
2153

2154
        return channel == nil
3✔
2155
}
2156

2157
// hasChannel returns true if the peer has a pending/active channel specified
2158
// by the channel ID.
UNCOV
2159
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
×
UNCOV
2160
        _, ok := p.activeChannels.Load(chanID)
×
UNCOV
2161
        return ok
×
UNCOV
2162
}
×
2163

2164
// storeError stores an error in our peer's buffer of recent errors with the
2165
// current timestamp. Errors are only stored if we have at least one active
2166
// channel with the peer to mitigate a dos vector where a peer costlessly
2167
// connects to us and spams us with errors.
2168
func (p *Brontide) storeError(err error) {
1✔
2169
        var haveChannels bool
1✔
2170

1✔
2171
        p.activeChannels.Range(func(_ lnwire.ChannelID,
1✔
2172
                channel *lnwallet.LightningChannel) bool {
2✔
2173

1✔
2174
                // Pending channels will be nil in the activeChannels map.
1✔
2175
                if channel == nil {
1✔
UNCOV
2176
                        // Return true to continue the iteration.
×
UNCOV
2177
                        return true
×
UNCOV
2178
                }
×
2179

2180
                haveChannels = true
1✔
2181

1✔
2182
                // Return false to break the iteration.
1✔
2183
                return false
1✔
2184
        })
2185

2186
        // If we do not have any active channels with the peer, we do not store
2187
        // errors as a dos mitigation.
2188
        if !haveChannels {
1✔
UNCOV
2189
                p.log.Trace("no channels with peer, not storing err")
×
UNCOV
2190
                return
×
UNCOV
2191
        }
×
2192

2193
        p.cfg.ErrorBuffer.Add(
1✔
2194
                &TimestampedError{Timestamp: time.Now(), Error: err},
1✔
2195
        )
1✔
2196
}
2197

2198
// handleWarningOrError processes a warning or error msg and returns true if
2199
// msg should be forwarded to the associated channel link. False is returned if
2200
// any necessary forwarding of msg was already handled by this method. If msg is
2201
// an error from a peer with an active channel, we'll store it in memory.
2202
//
2203
// NOTE: This method should only be called from within the readHandler.
2204
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
UNCOV
2205
        msg lnwire.Message) bool {
×
UNCOV
2206

×
UNCOV
2207
        if errMsg, ok := msg.(*lnwire.Error); ok {
×
UNCOV
2208
                p.storeError(errMsg)
×
UNCOV
2209
        }
×
2210

UNCOV
2211
        switch {
×
2212
        // Connection wide messages should be forwarded to all channel links
2213
        // with this peer.
2214
        case chanID == lnwire.ConnectionWideID:
×
2215
                for _, chanStream := range p.activeMsgStreams {
×
2216
                        chanStream.AddMsg(msg)
×
2217
                }
×
2218

2219
                return false
×
2220

2221
        // If the channel ID for the message corresponds to a pending channel,
2222
        // then the funding manager will handle it.
UNCOV
2223
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
×
UNCOV
2224
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
×
UNCOV
2225
                return false
×
2226

2227
        // If not we hand the message to the channel link for this channel.
UNCOV
2228
        case p.isActiveChannel(chanID):
×
UNCOV
2229
                return true
×
2230

UNCOV
2231
        default:
×
UNCOV
2232
                return false
×
2233
        }
2234
}
2235

2236
// messageSummary returns a human-readable string that summarizes a
2237
// incoming/outgoing message. Not all messages will have a summary, only those
2238
// which have additional data that can be informative at a glance.
UNCOV
2239
func messageSummary(msg lnwire.Message) string {
×
UNCOV
2240
        switch msg := msg.(type) {
×
UNCOV
2241
        case *lnwire.Init:
×
UNCOV
2242
                // No summary.
×
UNCOV
2243
                return ""
×
2244

UNCOV
2245
        case *lnwire.OpenChannel:
×
UNCOV
2246
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
×
UNCOV
2247
                        "push_amt=%v, reserve=%v, flags=%v",
×
UNCOV
2248
                        msg.PendingChannelID[:], msg.ChainHash,
×
UNCOV
2249
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
×
UNCOV
2250
                        msg.ChannelReserve, msg.ChannelFlags)
×
2251

UNCOV
2252
        case *lnwire.AcceptChannel:
×
UNCOV
2253
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
×
UNCOV
2254
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
×
UNCOV
2255
                        msg.MinAcceptDepth)
×
2256

UNCOV
2257
        case *lnwire.FundingCreated:
×
UNCOV
2258
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
×
UNCOV
2259
                        msg.PendingChannelID[:], msg.FundingPoint)
×
2260

UNCOV
2261
        case *lnwire.FundingSigned:
×
UNCOV
2262
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
×
2263

UNCOV
2264
        case *lnwire.ChannelReady:
×
UNCOV
2265
                return fmt.Sprintf("chan_id=%v, next_point=%x",
×
UNCOV
2266
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
×
2267

UNCOV
2268
        case *lnwire.Shutdown:
×
UNCOV
2269
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
×
UNCOV
2270
                        msg.Address[:])
×
2271

UNCOV
2272
        case *lnwire.ClosingSigned:
×
UNCOV
2273
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
×
UNCOV
2274
                        msg.FeeSatoshis)
×
2275

UNCOV
2276
        case *lnwire.UpdateAddHTLC:
×
UNCOV
2277
                var blindingPoint []byte
×
UNCOV
2278
                msg.BlindingPoint.WhenSome(
×
UNCOV
2279
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
×
UNCOV
2280
                                *btcec.PublicKey]) {
×
UNCOV
2281

×
UNCOV
2282
                                blindingPoint = b.Val.SerializeCompressed()
×
UNCOV
2283
                        },
×
2284
                )
2285

UNCOV
2286
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
×
UNCOV
2287
                        "hash=%x, blinding_point=%x, custom_records=%v",
×
UNCOV
2288
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
×
UNCOV
2289
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
×
2290

UNCOV
2291
        case *lnwire.UpdateFailHTLC:
×
UNCOV
2292
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
×
UNCOV
2293
                        msg.ID, msg.Reason)
×
2294

UNCOV
2295
        case *lnwire.UpdateFulfillHTLC:
×
UNCOV
2296
                return fmt.Sprintf("chan_id=%v, id=%v, pre_image=%x, "+
×
UNCOV
2297
                        "custom_records=%v", msg.ChanID, msg.ID,
×
UNCOV
2298
                        msg.PaymentPreimage[:], msg.CustomRecords)
×
2299

UNCOV
2300
        case *lnwire.CommitSig:
×
UNCOV
2301
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
×
UNCOV
2302
                        len(msg.HtlcSigs))
×
2303

UNCOV
2304
        case *lnwire.RevokeAndAck:
×
UNCOV
2305
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
×
UNCOV
2306
                        msg.ChanID, msg.Revocation[:],
×
UNCOV
2307
                        msg.NextRevocationKey.SerializeCompressed())
×
2308

UNCOV
2309
        case *lnwire.UpdateFailMalformedHTLC:
×
UNCOV
2310
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
×
UNCOV
2311
                        msg.ChanID, msg.ID, msg.FailureCode)
×
2312

2313
        case *lnwire.Warning:
×
2314
                return fmt.Sprintf("%v", msg.Warning())
×
2315

UNCOV
2316
        case *lnwire.Error:
×
UNCOV
2317
                return fmt.Sprintf("%v", msg.Error())
×
2318

UNCOV
2319
        case *lnwire.AnnounceSignatures1:
×
UNCOV
2320
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
×
UNCOV
2321
                        msg.ShortChannelID.ToUint64())
×
2322

UNCOV
2323
        case *lnwire.ChannelAnnouncement1:
×
UNCOV
2324
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
×
UNCOV
2325
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
×
2326

UNCOV
2327
        case *lnwire.ChannelUpdate1:
×
UNCOV
2328
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
×
UNCOV
2329
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
×
UNCOV
2330
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
×
UNCOV
2331
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
×
2332

UNCOV
2333
        case *lnwire.NodeAnnouncement:
×
UNCOV
2334
                return fmt.Sprintf("node=%x, update_time=%v",
×
UNCOV
2335
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
×
2336

UNCOV
2337
        case *lnwire.Ping:
×
UNCOV
2338
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
2339

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

2343
        case *lnwire.UpdateFee:
×
2344
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2345
                        msg.ChanID, int64(msg.FeePerKw))
×
2346

UNCOV
2347
        case *lnwire.ChannelReestablish:
×
UNCOV
2348
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
×
UNCOV
2349
                        "remote_tail_height=%v", msg.ChanID,
×
UNCOV
2350
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
×
2351

UNCOV
2352
        case *lnwire.ReplyShortChanIDsEnd:
×
UNCOV
2353
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
×
UNCOV
2354
                        msg.Complete)
×
2355

UNCOV
2356
        case *lnwire.ReplyChannelRange:
×
UNCOV
2357
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
×
UNCOV
2358
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
×
UNCOV
2359
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
×
UNCOV
2360
                        msg.EncodingType)
×
2361

UNCOV
2362
        case *lnwire.QueryShortChanIDs:
×
UNCOV
2363
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
×
UNCOV
2364
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
×
2365

UNCOV
2366
        case *lnwire.QueryChannelRange:
×
UNCOV
2367
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
×
UNCOV
2368
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
×
UNCOV
2369
                        msg.LastBlockHeight())
×
2370

UNCOV
2371
        case *lnwire.GossipTimestampRange:
×
UNCOV
2372
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
×
UNCOV
2373
                        "stamp_range=%v", msg.ChainHash,
×
UNCOV
2374
                        time.Unix(int64(msg.FirstTimestamp), 0),
×
UNCOV
2375
                        msg.TimestampRange)
×
2376

UNCOV
2377
        case *lnwire.Stfu:
×
UNCOV
2378
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
×
UNCOV
2379
                        msg.Initiator)
×
2380

UNCOV
2381
        case *lnwire.Custom:
×
UNCOV
2382
                return fmt.Sprintf("type=%d", msg.Type)
×
2383
        }
2384

2385
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2386
}
2387

2388
// logWireMessage logs the receipt or sending of particular wire message. This
2389
// function is used rather than just logging the message in order to produce
2390
// less spammy log messages in trace mode by setting the 'Curve" parameter to
2391
// nil. Doing this avoids printing out each of the field elements in the curve
2392
// parameters for secp256k1.
2393
func (p *Brontide) logWireMessage(msg lnwire.Message, read bool) {
17✔
2394
        summaryPrefix := "Received"
17✔
2395
        if !read {
30✔
2396
                summaryPrefix = "Sending"
13✔
2397
        }
13✔
2398

2399
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
17✔
UNCOV
2400
                // Debug summary of message.
×
UNCOV
2401
                summary := messageSummary(msg)
×
UNCOV
2402
                if len(summary) > 0 {
×
UNCOV
2403
                        summary = "(" + summary + ")"
×
UNCOV
2404
                }
×
2405

UNCOV
2406
                preposition := "to"
×
UNCOV
2407
                if read {
×
UNCOV
2408
                        preposition = "from"
×
UNCOV
2409
                }
×
2410

UNCOV
2411
                var msgType string
×
UNCOV
2412
                if msg.MsgType() < lnwire.CustomTypeStart {
×
UNCOV
2413
                        msgType = msg.MsgType().String()
×
UNCOV
2414
                } else {
×
UNCOV
2415
                        msgType = "custom"
×
UNCOV
2416
                }
×
2417

UNCOV
2418
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
×
UNCOV
2419
                        msgType, summary, preposition, p)
×
2420
        }))
2421

2422
        prefix := "readMessage from peer"
17✔
2423
        if !read {
30✔
2424
                prefix = "writeMessage to peer"
13✔
2425
        }
13✔
2426

2427
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
17✔
2428
}
2429

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

2447
        noiseConn := p.cfg.Conn
13✔
2448

13✔
2449
        flushMsg := func() error {
26✔
2450
                // Ensure the write deadline is set before we attempt to send
13✔
2451
                // the message.
13✔
2452
                writeDeadline := time.Now().Add(
13✔
2453
                        p.scaleTimeout(writeMessageTimeout),
13✔
2454
                )
13✔
2455
                err := noiseConn.SetWriteDeadline(writeDeadline)
13✔
2456
                if err != nil {
13✔
2457
                        return err
×
2458
                }
×
2459

2460
                // Flush the pending message to the wire. If an error is
2461
                // encountered, e.g. write timeout, the number of bytes written
2462
                // so far will be returned.
2463
                n, err := noiseConn.Flush()
13✔
2464

13✔
2465
                // Record the number of bytes written on the wire, if any.
13✔
2466
                if n > 0 {
13✔
UNCOV
2467
                        atomic.AddUint64(&p.bytesSent, uint64(n))
×
UNCOV
2468
                }
×
2469

2470
                return err
13✔
2471
        }
2472

2473
        // If the current message has already been serialized, encrypted, and
2474
        // buffered on the underlying connection we will skip straight to
2475
        // flushing it to the wire.
2476
        if msg == nil {
13✔
2477
                return flushMsg()
×
2478
        }
×
2479

2480
        // Otherwise, this is a new message. We'll acquire a write buffer to
2481
        // serialize the message and buffer the ciphertext on the connection.
2482
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
26✔
2483
                // Using a buffer allocated by the write pool, encode the
13✔
2484
                // message directly into the buffer.
13✔
2485
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
13✔
2486
                if writeErr != nil {
13✔
2487
                        return writeErr
×
2488
                }
×
2489

2490
                // Finally, write the message itself in a single swoop. This
2491
                // will buffer the ciphertext on the underlying connection. We
2492
                // will defer flushing the message until the write pool has been
2493
                // released.
2494
                return noiseConn.WriteMessage(buf.Bytes())
13✔
2495
        })
2496
        if err != nil {
13✔
2497
                return err
×
2498
        }
×
2499

2500
        return flushMsg()
13✔
2501
}
2502

2503
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2504
// queue, and writing them out to the wire. This goroutine coordinates with the
2505
// queueHandler in order to ensure the incoming message queue is quickly
2506
// drained.
2507
//
2508
// NOTE: This method MUST be run as a goroutine.
2509
func (p *Brontide) writeHandler() {
3✔
2510
        // We'll stop the timer after a new messages is sent, and also reset it
3✔
2511
        // after we process the next message.
3✔
2512
        idleTimer := time.AfterFunc(idleTimeout, func() {
3✔
2513
                err := fmt.Errorf("peer %s no write for %s -- disconnecting",
×
2514
                        p, idleTimeout)
×
2515
                p.Disconnect(err)
×
2516
        })
×
2517

2518
        var exitErr error
3✔
2519

3✔
2520
out:
3✔
2521
        for {
10✔
2522
                select {
7✔
2523
                case outMsg := <-p.sendQueue:
4✔
2524
                        // Record the time at which we first attempt to send the
4✔
2525
                        // message.
4✔
2526
                        startTime := time.Now()
4✔
2527

4✔
2528
                retry:
4✔
2529
                        // Write out the message to the socket. If a timeout
2530
                        // error is encountered, we will catch this and retry
2531
                        // after backing off in case the remote peer is just
2532
                        // slow to process messages from the wire.
2533
                        err := p.writeMessage(outMsg.msg)
4✔
2534
                        if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
4✔
2535
                                p.log.Debugf("Write timeout detected for "+
×
2536
                                        "peer, first write for message "+
×
2537
                                        "attempted %v ago",
×
2538
                                        time.Since(startTime))
×
2539

×
2540
                                // If we received a timeout error, this implies
×
2541
                                // that the message was buffered on the
×
2542
                                // connection successfully and that a flush was
×
2543
                                // attempted. We'll set the message to nil so
×
2544
                                // that on a subsequent pass we only try to
×
2545
                                // flush the buffered message, and forgo
×
2546
                                // reserializing or reencrypting it.
×
2547
                                outMsg.msg = nil
×
2548

×
2549
                                goto retry
×
2550
                        }
2551

2552
                        // The write succeeded, reset the idle timer to prevent
2553
                        // us from disconnecting the peer.
2554
                        if !idleTimer.Stop() {
4✔
2555
                                select {
×
2556
                                case <-idleTimer.C:
×
2557
                                default:
×
2558
                                }
2559
                        }
2560
                        idleTimer.Reset(idleTimeout)
4✔
2561

4✔
2562
                        // If the peer requested a synchronous write, respond
4✔
2563
                        // with the error.
4✔
2564
                        if outMsg.errChan != nil {
5✔
2565
                                outMsg.errChan <- err
1✔
2566
                        }
1✔
2567

2568
                        if err != nil {
4✔
2569
                                exitErr = fmt.Errorf("unable to write "+
×
2570
                                        "message: %v", err)
×
2571
                                break out
×
2572
                        }
2573

UNCOV
2574
                case <-p.quit:
×
UNCOV
2575
                        exitErr = lnpeer.ErrPeerExiting
×
UNCOV
2576
                        break out
×
2577
                }
2578
        }
2579

2580
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2581
        // disconnect.
UNCOV
2582
        p.wg.Done()
×
UNCOV
2583

×
UNCOV
2584
        p.Disconnect(exitErr)
×
UNCOV
2585

×
UNCOV
2586
        p.log.Trace("writeHandler for peer done")
×
2587
}
2588

2589
// queueHandler is responsible for accepting messages from outside subsystems
2590
// to be eventually sent out on the wire by the writeHandler.
2591
//
2592
// NOTE: This method MUST be run as a goroutine.
2593
func (p *Brontide) queueHandler() {
3✔
2594
        defer p.wg.Done()
3✔
2595

3✔
2596
        // priorityMsgs holds an in order list of messages deemed high-priority
3✔
2597
        // to be added to the sendQueue. This predominately includes messages
3✔
2598
        // from the funding manager and htlcswitch.
3✔
2599
        priorityMsgs := list.New()
3✔
2600

3✔
2601
        // lazyMsgs holds an in order list of messages deemed low-priority to be
3✔
2602
        // added to the sendQueue only after all high-priority messages have
3✔
2603
        // been queued. This predominately includes messages from the gossiper.
3✔
2604
        lazyMsgs := list.New()
3✔
2605

3✔
2606
        for {
14✔
2607
                // Examine the front of the priority queue, if it is empty check
11✔
2608
                // the low priority queue.
11✔
2609
                elem := priorityMsgs.Front()
11✔
2610
                if elem == nil {
19✔
2611
                        elem = lazyMsgs.Front()
8✔
2612
                }
8✔
2613

2614
                if elem != nil {
15✔
2615
                        front := elem.Value.(outgoingMsg)
4✔
2616

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

2656
// PingTime returns the estimated ping time to the peer in microseconds.
UNCOV
2657
func (p *Brontide) PingTime() int64 {
×
UNCOV
2658
        return p.pingManager.GetPingTimeMicroSeconds()
×
UNCOV
2659
}
×
2660

2661
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2662
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2663
// or failed to write, and nil otherwise.
2664
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
24✔
2665
        p.queue(true, msg, errChan)
24✔
2666
}
24✔
2667

2668
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2669
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2670
// queue or failed to write, and nil otherwise.
2671
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
1✔
2672
        p.queue(false, msg, errChan)
1✔
2673
}
1✔
2674

2675
// queue sends a given message to the queueHandler using the passed priority. If
2676
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2677
// failed to write, and nil otherwise.
2678
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2679
        errChan chan error) {
25✔
2680

25✔
2681
        select {
25✔
2682
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
25✔
UNCOV
2683
        case <-p.quit:
×
UNCOV
2684
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
×
UNCOV
2685
                        spew.Sdump(msg))
×
UNCOV
2686
                if errChan != nil {
×
2687
                        errChan <- lnpeer.ErrPeerExiting
×
2688
                }
×
2689
        }
2690
}
2691

2692
// ChannelSnapshots returns a slice of channel snapshots detailing all
2693
// currently active channels maintained with the remote peer.
UNCOV
2694
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
×
UNCOV
2695
        snapshots := make(
×
UNCOV
2696
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
×
UNCOV
2697
        )
×
UNCOV
2698

×
UNCOV
2699
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
×
UNCOV
2700
                activeChan *lnwallet.LightningChannel) error {
×
UNCOV
2701

×
UNCOV
2702
                // If the activeChan is nil, then we skip it as the channel is
×
UNCOV
2703
                // pending.
×
UNCOV
2704
                if activeChan == nil {
×
UNCOV
2705
                        return nil
×
UNCOV
2706
                }
×
2707

2708
                // We'll only return a snapshot for channels that are
2709
                // *immediately* available for routing payments over.
UNCOV
2710
                if activeChan.RemoteNextRevocation() == nil {
×
UNCOV
2711
                        return nil
×
UNCOV
2712
                }
×
2713

UNCOV
2714
                snapshot := activeChan.StateSnapshot()
×
UNCOV
2715
                snapshots = append(snapshots, snapshot)
×
UNCOV
2716

×
UNCOV
2717
                return nil
×
2718
        })
2719

UNCOV
2720
        return snapshots
×
2721
}
2722

2723
// genDeliveryScript returns a new script to be used to send our funds to in
2724
// the case of a cooperative channel close negotiation.
2725
func (p *Brontide) genDeliveryScript() ([]byte, error) {
6✔
2726
        // We'll send a normal p2wkh address unless we've negotiated the
6✔
2727
        // shutdown-any-segwit feature.
6✔
2728
        addrType := lnwallet.WitnessPubKey
6✔
2729
        if p.taprootShutdownAllowed() {
6✔
UNCOV
2730
                addrType = lnwallet.TaprootPubkey
×
UNCOV
2731
        }
×
2732

2733
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
6✔
2734
                addrType, false, lnwallet.DefaultAccountName,
6✔
2735
        )
6✔
2736
        if err != nil {
6✔
2737
                return nil, err
×
2738
        }
×
2739
        p.log.Infof("Delivery addr for channel close: %v",
6✔
2740
                deliveryAddr)
6✔
2741

6✔
2742
        return txscript.PayToAddrScript(deliveryAddr)
6✔
2743
}
2744

2745
// channelManager is goroutine dedicated to handling all requests/signals
2746
// pertaining to the opening, cooperative closing, and force closing of all
2747
// channels maintained with the remote peer.
2748
//
2749
// NOTE: This method MUST be run as a goroutine.
2750
func (p *Brontide) channelManager() {
17✔
2751
        defer p.wg.Done()
17✔
2752

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

17✔
2758
out:
17✔
2759
        for {
56✔
2760
                select {
39✔
2761
                // A new pending channel has arrived which means we are about
2762
                // to complete a funding workflow and is waiting for the final
2763
                // `ChannelReady` messages to be exchanged. We will add this
2764
                // channel to the `activeChannels` with a nil value to indicate
2765
                // this is a pending channel.
2766
                case req := <-p.newPendingChannel:
1✔
2767
                        p.handleNewPendingChannel(req)
1✔
2768

2769
                // A new channel has arrived which means we've just completed a
2770
                // funding workflow. We'll initialize the necessary local
2771
                // state, and notify the htlc switch of a new link.
UNCOV
2772
                case req := <-p.newActiveChannel:
×
UNCOV
2773
                        p.handleNewActiveChannel(req)
×
2774

2775
                // The funding flow for a pending channel is failed, we will
2776
                // remove it from Brontide.
2777
                case req := <-p.removePendingChannel:
1✔
2778
                        p.handleRemovePendingChannel(req)
1✔
2779

2780
                // We've just received a local request to close an active
2781
                // channel. It will either kick of a cooperative channel
2782
                // closure negotiation, or be a notification of a breached
2783
                // contract that should be abandoned.
2784
                case req := <-p.localCloseChanReqs:
7✔
2785
                        p.handleLocalCloseReq(req)
7✔
2786

2787
                // We've received a link failure from a link that was added to
2788
                // the switch. This will initiate the teardown of the link, and
2789
                // initiate any on-chain closures if necessary.
UNCOV
2790
                case failure := <-p.linkFailures:
×
UNCOV
2791
                        p.handleLinkFailure(failure)
×
2792

2793
                // We've received a new cooperative channel closure related
2794
                // message from the remote peer, we'll use this message to
2795
                // advance the chan closer state machine.
2796
                case closeMsg := <-p.chanCloseMsgs:
13✔
2797
                        p.handleCloseMsg(closeMsg)
13✔
2798

2799
                // The channel reannounce delay has elapsed, broadcast the
2800
                // reenabled channel updates to the network. This should only
2801
                // fire once, so we set the reenableTimeout channel to nil to
2802
                // mark it for garbage collection. If the peer is torn down
2803
                // before firing, reenabling will not be attempted.
2804
                // TODO(conner): consolidate reenables timers inside chan status
2805
                // manager
UNCOV
2806
                case <-reenableTimeout:
×
UNCOV
2807
                        p.reenableActiveChannels()
×
UNCOV
2808

×
UNCOV
2809
                        // Since this channel will never fire again during the
×
UNCOV
2810
                        // lifecycle of the peer, we nil the channel to mark it
×
UNCOV
2811
                        // eligible for garbage collection, and make this
×
UNCOV
2812
                        // explicitly ineligible to receive in future calls to
×
UNCOV
2813
                        // select. This also shaves a few CPU cycles since the
×
UNCOV
2814
                        // select will ignore this case entirely.
×
UNCOV
2815
                        reenableTimeout = nil
×
UNCOV
2816

×
UNCOV
2817
                        // Once the reenabling is attempted, we also cancel the
×
UNCOV
2818
                        // channel event subscription to free up the overflow
×
UNCOV
2819
                        // queue used in channel notifier.
×
UNCOV
2820
                        //
×
UNCOV
2821
                        // NOTE: channelEventClient will be nil if the
×
UNCOV
2822
                        // reenableTimeout is greater than 1 minute.
×
UNCOV
2823
                        if p.channelEventClient != nil {
×
UNCOV
2824
                                p.channelEventClient.Cancel()
×
UNCOV
2825
                        }
×
2826

2827
                case <-p.quit:
1✔
2828
                        // As, we've been signalled to exit, we'll reset all
1✔
2829
                        // our active channel back to their default state.
1✔
2830
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
1✔
2831
                                lc *lnwallet.LightningChannel) error {
2✔
2832

1✔
2833
                                // Exit if the channel is nil as it's a pending
1✔
2834
                                // channel.
1✔
2835
                                if lc == nil {
1✔
UNCOV
2836
                                        return nil
×
UNCOV
2837
                                }
×
2838

2839
                                lc.ResetState()
1✔
2840

1✔
2841
                                return nil
1✔
2842
                        })
2843

2844
                        break out
1✔
2845
                }
2846
        }
2847
}
2848

2849
// reenableActiveChannels searches the index of channels maintained with this
2850
// peer, and reenables each public, non-pending channel. This is done at the
2851
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
2852
// No message will be sent if the channel is already enabled.
UNCOV
2853
func (p *Brontide) reenableActiveChannels() {
×
UNCOV
2854
        // First, filter all known channels with this peer for ones that are
×
UNCOV
2855
        // both public and not pending.
×
UNCOV
2856
        activePublicChans := p.filterChannelsToEnable()
×
UNCOV
2857

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

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

×
UNCOV
2867
                switch {
×
2868
                // No error occurred, continue to request the next channel.
UNCOV
2869
                case err == nil:
×
UNCOV
2870
                        continue
×
2871

2872
                // Cannot auto enable a manually disabled channel so we do
2873
                // nothing but proceed to the next channel.
UNCOV
2874
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
×
UNCOV
2875
                        p.log.Debugf("Channel(%v) was manually disabled, "+
×
UNCOV
2876
                                "ignoring automatic enable request", chanPoint)
×
UNCOV
2877

×
UNCOV
2878
                        continue
×
2879

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

×
2897
                                continue
×
2898
                        }
2899

2900
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
2901
                                "ChanStatusManager reported inactive, retrying")
×
2902

×
2903
                        // Add the channel to the retry map.
×
2904
                        retryChans[chanPoint] = struct{}{}
×
2905
                }
2906
        }
2907

2908
        // Retry the channels if we have any.
UNCOV
2909
        if len(retryChans) != 0 {
×
2910
                p.retryRequestEnable(retryChans)
×
2911
        }
×
2912
}
2913

2914
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
2915
// for the target channel ID. If the channel isn't active an error is returned.
2916
// Otherwise, either an existing state machine will be returned, or a new one
2917
// will be created.
2918
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
2919
        *chancloser.ChanCloser, error) {
13✔
2920

13✔
2921
        chanCloser, found := p.activeChanCloses[chanID]
13✔
2922
        if found {
23✔
2923
                // An entry will only be found if the closer has already been
10✔
2924
                // created for a non-pending channel or for a channel that had
10✔
2925
                // previously started the shutdown process but the connection
10✔
2926
                // was restarted.
10✔
2927
                return chanCloser, nil
10✔
2928
        }
10✔
2929

2930
        // First, we'll ensure that we actually know of the target channel. If
2931
        // not, we'll ignore this message.
2932
        channel, ok := p.activeChannels.Load(chanID)
3✔
2933

3✔
2934
        // If the channel isn't in the map or the channel is nil, return
3✔
2935
        // ErrChannelNotFound as the channel is pending.
3✔
2936
        if !ok || channel == nil {
3✔
UNCOV
2937
                return nil, ErrChannelNotFound
×
UNCOV
2938
        }
×
2939

2940
        // We'll create a valid closing state machine in order to respond to
2941
        // the initiated cooperative channel closure. First, we set the
2942
        // delivery script that our funds will be paid out to. If an upfront
2943
        // shutdown script was set, we will use it. Otherwise, we get a fresh
2944
        // delivery script.
2945
        //
2946
        // TODO: Expose option to allow upfront shutdown script from watch-only
2947
        // accounts.
2948
        deliveryScript := channel.LocalUpfrontShutdownScript()
3✔
2949
        if len(deliveryScript) == 0 {
6✔
2950
                var err error
3✔
2951
                deliveryScript, err = p.genDeliveryScript()
3✔
2952
                if err != nil {
3✔
2953
                        p.log.Errorf("unable to gen delivery script: %v",
×
2954
                                err)
×
2955
                        return nil, fmt.Errorf("close addr unavailable")
×
2956
                }
×
2957
        }
2958

2959
        // In order to begin fee negotiations, we'll first compute our target
2960
        // ideal fee-per-kw.
2961
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
2962
                p.cfg.CoopCloseTargetConfs,
3✔
2963
        )
3✔
2964
        if err != nil {
3✔
2965
                p.log.Errorf("unable to query fee estimator: %v", err)
×
2966
                return nil, fmt.Errorf("unable to estimate fee")
×
2967
        }
×
2968

2969
        addr, err := p.addrWithInternalKey(deliveryScript)
3✔
2970
        if err != nil {
3✔
2971
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
2972
        }
×
2973
        chanCloser, err = p.createChanCloser(
3✔
2974
                channel, addr, feePerKw, nil, lntypes.Remote,
3✔
2975
        )
3✔
2976
        if err != nil {
3✔
2977
                p.log.Errorf("unable to create chan closer: %v", err)
×
2978
                return nil, fmt.Errorf("unable to create chan closer")
×
2979
        }
×
2980

2981
        p.activeChanCloses[chanID] = chanCloser
3✔
2982

3✔
2983
        return chanCloser, nil
3✔
2984
}
2985

2986
// filterChannelsToEnable filters a list of channels to be enabled upon start.
2987
// The filtered channels are active channels that's neither private nor
2988
// pending.
UNCOV
2989
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
×
UNCOV
2990
        var activePublicChans []wire.OutPoint
×
UNCOV
2991

×
UNCOV
2992
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
×
UNCOV
2993
                lnChan *lnwallet.LightningChannel) bool {
×
UNCOV
2994

×
UNCOV
2995
                // If the lnChan is nil, continue as this is a pending channel.
×
UNCOV
2996
                if lnChan == nil {
×
UNCOV
2997
                        return true
×
UNCOV
2998
                }
×
2999

UNCOV
3000
                dbChan := lnChan.State()
×
UNCOV
3001
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
×
UNCOV
3002
                if !isPublic || dbChan.IsPending {
×
3003
                        return true
×
3004
                }
×
3005

3006
                // We'll also skip any channels added during this peer's
3007
                // lifecycle since they haven't waited out the timeout. Their
3008
                // first announcement will be enabled, and the chan status
3009
                // manager will begin monitoring them passively since they exist
3010
                // in the database.
UNCOV
3011
                if _, ok := p.addedChannels.Load(chanID); ok {
×
3012
                        return true
×
3013
                }
×
3014

UNCOV
3015
                activePublicChans = append(
×
UNCOV
3016
                        activePublicChans, dbChan.FundingOutpoint,
×
UNCOV
3017
                )
×
UNCOV
3018

×
UNCOV
3019
                return true
×
3020
        })
3021

UNCOV
3022
        return activePublicChans
×
3023
}
3024

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

×
3032
        // retryEnable is a helper closure that sends an enable request and
×
3033
        // removes the channel from the map if it's matched.
×
3034
        retryEnable := func(chanPoint wire.OutPoint) error {
×
3035
                // If this is an active channel event, check whether it's in
×
3036
                // our targeted channels map.
×
3037
                _, found := activeChans[chanPoint]
×
3038

×
3039
                // If this channel is irrelevant, return nil so the loop can
×
3040
                // jump to next iteration.
×
3041
                if !found {
×
3042
                        return nil
×
3043
                }
×
3044

3045
                // Otherwise we've just received an active signal for a channel
3046
                // that's previously failed to be enabled, we send the request
3047
                // again.
3048
                //
3049
                // We only give the channel one more shot, so we delete it from
3050
                // our map first to keep it from being attempted again.
3051
                delete(activeChans, chanPoint)
×
3052

×
3053
                // Send the request.
×
3054
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3055
                if err != nil {
×
3056
                        return fmt.Errorf("request enabling channel %v "+
×
3057
                                "failed: %w", chanPoint, err)
×
3058
                }
×
3059

3060
                return nil
×
3061
        }
3062

3063
        for {
×
3064
                // If activeChans is empty, we've done processing all the
×
3065
                // channels.
×
3066
                if len(activeChans) == 0 {
×
3067
                        p.log.Debug("Finished retry enabling channels")
×
3068
                        return
×
3069
                }
×
3070

3071
                select {
×
3072
                // A new event has been sent by the ChannelNotifier. We now
3073
                // check whether it's an active or inactive channel event.
3074
                case e := <-p.channelEventClient.Updates():
×
3075
                        // If this is an active channel event, try enable the
×
3076
                        // channel then jump to the next iteration.
×
3077
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
3078
                        if ok {
×
3079
                                chanPoint := *active.ChannelPoint
×
3080

×
3081
                                // If we received an error for this particular
×
3082
                                // channel, we log an error and won't quit as
×
3083
                                // we still want to retry other channels.
×
3084
                                if err := retryEnable(chanPoint); err != nil {
×
3085
                                        p.log.Errorf("Retry failed: %v", err)
×
3086
                                }
×
3087

3088
                                continue
×
3089
                        }
3090

3091
                        // Otherwise check for inactive link event, and jump to
3092
                        // next iteration if it's not.
3093
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3094
                        if !ok {
×
3095
                                continue
×
3096
                        }
3097

3098
                        // Found an inactive link event, if this is our
3099
                        // targeted channel, remove it from our map.
3100
                        chanPoint := *inactive.ChannelPoint
×
3101
                        _, found := activeChans[chanPoint]
×
3102
                        if !found {
×
3103
                                continue
×
3104
                        }
3105

3106
                        delete(activeChans, chanPoint)
×
3107
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3108
                                "inactive link event", chanPoint)
×
3109

3110
                case <-p.quit:
×
3111
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3112
                        return
×
3113
                }
3114
        }
3115
}
3116

3117
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3118
// a suitable script to close out to. This may be nil if neither script is
3119
// set. If both scripts are set, this function will error if they do not match.
3120
func chooseDeliveryScript(upfront,
3121
        requested lnwire.DeliveryAddress) (lnwire.DeliveryAddress, error) {
12✔
3122

12✔
3123
        // If no upfront shutdown script was provided, return the user
12✔
3124
        // requested address (which may be nil).
12✔
3125
        if len(upfront) == 0 {
18✔
3126
                return requested, nil
6✔
3127
        }
6✔
3128

3129
        // If an upfront shutdown script was provided, and the user did not
3130
        // request a custom shutdown script, return the upfront address.
3131
        if len(requested) == 0 {
8✔
3132
                return upfront, nil
2✔
3133
        }
2✔
3134

3135
        // If both an upfront shutdown script and a custom close script were
3136
        // provided, error if the user provided shutdown script does not match
3137
        // the upfront shutdown script (because closing out to a different
3138
        // script would violate upfront shutdown).
3139
        if !bytes.Equal(upfront, requested) {
6✔
3140
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
3141
        }
2✔
3142

3143
        // The user requested script matches the upfront shutdown script, so we
3144
        // can return it without error.
3145
        return upfront, nil
2✔
3146
}
3147

3148
// restartCoopClose checks whether we need to restart the cooperative close
3149
// process for a given channel.
3150
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3151
        *lnwire.Shutdown, error) {
×
3152

×
3153
        // If this channel has status ChanStatusCoopBroadcasted and does not
×
3154
        // have a closing transaction, then the cooperative close process was
×
3155
        // started but never finished. We'll re-create the chanCloser state
×
3156
        // machine and resend Shutdown. BOLT#2 requires that we retransmit
×
3157
        // Shutdown exactly, but doing so would mean persisting the RPC
×
3158
        // provided close script. Instead use the LocalUpfrontShutdownScript
×
3159
        // or generate a script.
×
3160
        c := lnChan.State()
×
3161
        _, err := c.BroadcastedCooperative()
×
3162
        if err != nil && err != channeldb.ErrNoCloseTx {
×
3163
                // An error other than ErrNoCloseTx was encountered.
×
3164
                return nil, err
×
3165
        } else if err == nil {
×
3166
                // This channel has already completed the coop close
×
3167
                // negotiation.
×
3168
                return nil, nil
×
3169
        }
×
3170

3171
        var deliveryScript []byte
×
3172

×
3173
        shutdownInfo, err := c.ShutdownInfo()
×
3174
        switch {
×
3175
        // We have previously stored the delivery script that we need to use
3176
        // in the shutdown message. Re-use this script.
3177
        case err == nil:
×
3178
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
×
3179
                        deliveryScript = info.DeliveryScript.Val
×
3180
                })
×
3181

3182
        // An error other than ErrNoShutdownInfo was returned
3183
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3184
                return nil, err
×
3185

3186
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3187
                deliveryScript = c.LocalShutdownScript
×
3188
                if len(deliveryScript) == 0 {
×
3189
                        var err error
×
3190
                        deliveryScript, err = p.genDeliveryScript()
×
3191
                        if err != nil {
×
3192
                                p.log.Errorf("unable to gen delivery script: "+
×
3193
                                        "%v", err)
×
3194

×
3195
                                return nil, fmt.Errorf("close addr unavailable")
×
3196
                        }
×
3197
                }
3198
        }
3199

3200
        // Compute an ideal fee.
3201
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
3202
                p.cfg.CoopCloseTargetConfs,
×
3203
        )
×
3204
        if err != nil {
×
3205
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3206
                return nil, fmt.Errorf("unable to estimate fee")
×
3207
        }
×
3208

3209
        // Determine whether we or the peer are the initiator of the coop
3210
        // close attempt by looking at the channel's status.
3211
        closingParty := lntypes.Remote
×
3212
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3213
                closingParty = lntypes.Local
×
3214
        }
×
3215

3216
        addr, err := p.addrWithInternalKey(deliveryScript)
×
3217
        if err != nil {
×
3218
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3219
        }
×
3220
        chanCloser, err := p.createChanCloser(
×
3221
                lnChan, addr, feePerKw, nil, closingParty,
×
3222
        )
×
3223
        if err != nil {
×
3224
                p.log.Errorf("unable to create chan closer: %v", err)
×
3225
                return nil, fmt.Errorf("unable to create chan closer")
×
3226
        }
×
3227

3228
        // This does not need a mutex even though it is in a different
3229
        // goroutine since this is done before the channelManager goroutine is
3230
        // created.
3231
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
×
3232
        p.activeChanCloses[chanID] = chanCloser
×
3233

×
3234
        // Create the Shutdown message.
×
3235
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3236
        if err != nil {
×
3237
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3238
                delete(p.activeChanCloses, chanID)
×
3239
                return nil, err
×
3240
        }
×
3241

3242
        return shutdownMsg, nil
×
3243
}
3244

3245
// createChanCloser constructs a ChanCloser from the passed parameters and is
3246
// used to de-duplicate code.
3247
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3248
        deliveryScript *chancloser.DeliveryAddrWithKey,
3249
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3250
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
9✔
3251

9✔
3252
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
9✔
3253
        if err != nil {
9✔
3254
                p.log.Errorf("unable to obtain best block: %v", err)
×
3255
                return nil, fmt.Errorf("cannot obtain best block")
×
3256
        }
×
3257

3258
        // The req will only be set if we initiated the co-op closing flow.
3259
        var maxFee chainfee.SatPerKWeight
9✔
3260
        if req != nil {
15✔
3261
                maxFee = req.MaxFee
6✔
3262
        }
6✔
3263

3264
        chanCloser := chancloser.NewChanCloser(
9✔
3265
                chancloser.ChanCloseCfg{
9✔
3266
                        Channel:      channel,
9✔
3267
                        MusigSession: NewMusigChanCloser(channel),
9✔
3268
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
9✔
3269
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
9✔
3270
                        AuxCloser:    p.cfg.AuxChanCloser,
9✔
3271
                        DisableChannel: func(op wire.OutPoint) error {
18✔
3272
                                return p.cfg.ChanStatusMgr.RequestDisable(
9✔
3273
                                        op, false,
9✔
3274
                                )
9✔
3275
                        },
9✔
3276
                        MaxFee: maxFee,
3277
                        Disconnect: func() error {
×
3278
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
3279
                        },
×
3280
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3281
                        Quit:        p.quit,
3282
                },
3283
                *deliveryScript,
3284
                fee,
3285
                uint32(startingHeight),
3286
                req,
3287
                closer,
3288
        )
3289

3290
        return chanCloser, nil
9✔
3291
}
3292

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

7✔
3298
        channel, ok := p.activeChannels.Load(chanID)
7✔
3299

7✔
3300
        // Though this function can't be called for pending channels, we still
7✔
3301
        // check whether channel is nil for safety.
7✔
3302
        if !ok || channel == nil {
7✔
3303
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
×
3304
                        "unknown", chanID)
×
3305
                p.log.Errorf(err.Error())
×
3306
                req.Err <- err
×
3307
                return
×
3308
        }
×
3309

3310
        switch req.CloseType {
7✔
3311
        // A type of CloseRegular indicates that the user has opted to close
3312
        // out this channel on-chain, so we execute the cooperative channel
3313
        // closure workflow.
3314
        case contractcourt.CloseRegular:
7✔
3315
                // First, we'll choose a delivery address that we'll use to send the
7✔
3316
                // funds to in the case of a successful negotiation.
7✔
3317

7✔
3318
                // An upfront shutdown and user provided script are both optional,
7✔
3319
                // but must be equal if both set  (because we cannot serve a request
7✔
3320
                // to close out to a script which violates upfront shutdown). Get the
7✔
3321
                // appropriate address to close out to (which may be nil if neither
7✔
3322
                // are set) and error if they are both set and do not match.
7✔
3323
                deliveryScript, err := chooseDeliveryScript(
7✔
3324
                        channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
7✔
3325
                )
7✔
3326
                if err != nil {
8✔
3327
                        p.log.Errorf("cannot close channel %v: %v", req.ChanPoint, err)
1✔
3328
                        req.Err <- err
1✔
3329
                        return
1✔
3330
                }
1✔
3331

3332
                // If neither an upfront address or a user set address was
3333
                // provided, generate a fresh script.
3334
                if len(deliveryScript) == 0 {
9✔
3335
                        deliveryScript, err = p.genDeliveryScript()
3✔
3336
                        if err != nil {
3✔
3337
                                p.log.Errorf(err.Error())
×
3338
                                req.Err <- err
×
3339
                                return
×
3340
                        }
×
3341
                }
3342
                addr, err := p.addrWithInternalKey(deliveryScript)
6✔
3343
                if err != nil {
6✔
3344
                        err = fmt.Errorf("unable to parse addr for channel "+
×
3345
                                "%v: %w", req.ChanPoint, err)
×
3346
                        p.log.Errorf(err.Error())
×
3347
                        req.Err <- err
×
3348

×
3349
                        return
×
3350
                }
×
3351
                chanCloser, err := p.createChanCloser(
6✔
3352
                        channel, addr, req.TargetFeePerKw, req, lntypes.Local,
6✔
3353
                )
6✔
3354
                if err != nil {
6✔
3355
                        p.log.Errorf(err.Error())
×
3356
                        req.Err <- err
×
3357
                        return
×
3358
                }
×
3359

3360
                p.activeChanCloses[chanID] = chanCloser
6✔
3361

6✔
3362
                // Finally, we'll initiate the channel shutdown within the
6✔
3363
                // chanCloser, and send the shutdown message to the remote
6✔
3364
                // party to kick things off.
6✔
3365
                shutdownMsg, err := chanCloser.ShutdownChan()
6✔
3366
                if err != nil {
6✔
3367
                        p.log.Errorf(err.Error())
×
3368
                        req.Err <- err
×
3369
                        delete(p.activeChanCloses, chanID)
×
3370

×
3371
                        // As we were unable to shutdown the channel, we'll
×
3372
                        // return it back to its normal state.
×
3373
                        channel.ResetState()
×
3374
                        return
×
3375
                }
×
3376

3377
                link := p.fetchLinkFromKeyAndCid(chanID)
6✔
3378
                if link == nil {
6✔
3379
                        // If the link is nil then it means it was already
×
3380
                        // removed from the switch or it never existed in the
×
3381
                        // first place. The latter case is handled at the
×
3382
                        // beginning of this function, so in the case where it
×
3383
                        // has already been removed, we can skip adding the
×
3384
                        // commit hook to queue a Shutdown message.
×
3385
                        p.log.Warnf("link not found during attempted closure: "+
×
3386
                                "%v", chanID)
×
3387
                        return
×
3388
                }
×
3389

3390
                if !link.DisableAdds(htlcswitch.Outgoing) {
6✔
3391
                        p.log.Warnf("Outgoing link adds already "+
×
3392
                                "disabled: %v", link.ChanID())
×
3393
                }
×
3394

3395
                link.OnCommitOnce(htlcswitch.Outgoing, func() {
12✔
3396
                        p.queueMsg(shutdownMsg, nil)
6✔
3397
                })
6✔
3398

3399
        // A type of CloseBreach indicates that the counterparty has breached
3400
        // the channel therefore we need to clean up our local state.
3401
        case contractcourt.CloseBreach:
×
3402
                // TODO(roasbeef): no longer need with newer beach logic?
×
3403
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
×
3404
                        "channel", req.ChanPoint)
×
3405
                p.WipeChannel(req.ChanPoint)
×
3406
        }
3407
}
3408

3409
// linkFailureReport is sent to the channelManager whenever a link reports a
3410
// link failure, and is forced to exit. The report houses the necessary
3411
// information to clean up the channel state, send back the error message, and
3412
// force close if necessary.
3413
type linkFailureReport struct {
3414
        chanPoint   wire.OutPoint
3415
        chanID      lnwire.ChannelID
3416
        shortChanID lnwire.ShortChannelID
3417
        linkErr     htlcswitch.LinkFailureError
3418
}
3419

3420
// handleLinkFailure processes a link failure report when a link in the switch
3421
// fails. It facilitates the removal of all channel state within the peer,
3422
// force closing the channel depending on severity, and sending the error
3423
// message back to the remote party.
UNCOV
3424
func (p *Brontide) handleLinkFailure(failure linkFailureReport) {
×
UNCOV
3425
        // Retrieve the channel from the map of active channels. We do this to
×
UNCOV
3426
        // have access to it even after WipeChannel remove it from the map.
×
UNCOV
3427
        chanID := lnwire.NewChanIDFromOutPoint(failure.chanPoint)
×
UNCOV
3428
        lnChan, _ := p.activeChannels.Load(chanID)
×
UNCOV
3429

×
UNCOV
3430
        // We begin by wiping the link, which will remove it from the switch,
×
UNCOV
3431
        // such that it won't be attempted used for any more updates.
×
UNCOV
3432
        //
×
UNCOV
3433
        // TODO(halseth): should introduce a way to atomically stop/pause the
×
UNCOV
3434
        // link and cancel back any adds in its mailboxes such that we can
×
UNCOV
3435
        // safely force close without the link being added again and updates
×
UNCOV
3436
        // being applied.
×
UNCOV
3437
        p.WipeChannel(&failure.chanPoint)
×
UNCOV
3438

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

×
UNCOV
3444
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
×
UNCOV
3445
                        failure.chanPoint,
×
UNCOV
3446
                )
×
UNCOV
3447
                if err != nil {
×
UNCOV
3448
                        p.log.Errorf("unable to force close "+
×
UNCOV
3449
                                "link(%v): %v", failure.shortChanID, err)
×
UNCOV
3450
                } else {
×
UNCOV
3451
                        p.log.Infof("channel(%v) force "+
×
UNCOV
3452
                                "closed with txid %v",
×
UNCOV
3453
                                failure.shortChanID, closeTx.TxHash())
×
UNCOV
3454
                }
×
3455
        }
3456

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

×
3462
                if err := lnChan.State().MarkBorked(); err != nil {
×
3463
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
3464
                                failure.shortChanID, err)
×
3465
                }
×
3466
        }
3467

3468
        // Send an error to the peer, why we failed the channel.
UNCOV
3469
        if failure.linkErr.ShouldSendToPeer() {
×
UNCOV
3470
                // If SendData is set, send it to the peer. If not, we'll use
×
UNCOV
3471
                // the standard error messages in the payload. We only include
×
UNCOV
3472
                // sendData in the cases where the error data does not contain
×
UNCOV
3473
                // sensitive information.
×
UNCOV
3474
                data := []byte(failure.linkErr.Error())
×
UNCOV
3475
                if failure.linkErr.SendData != nil {
×
3476
                        data = failure.linkErr.SendData
×
3477
                }
×
3478

UNCOV
3479
                var networkMsg lnwire.Message
×
UNCOV
3480
                if failure.linkErr.Warning {
×
3481
                        networkMsg = &lnwire.Warning{
×
3482
                                ChanID: failure.chanID,
×
3483
                                Data:   data,
×
3484
                        }
×
UNCOV
3485
                } else {
×
UNCOV
3486
                        networkMsg = &lnwire.Error{
×
UNCOV
3487
                                ChanID: failure.chanID,
×
UNCOV
3488
                                Data:   data,
×
UNCOV
3489
                        }
×
UNCOV
3490
                }
×
3491

UNCOV
3492
                err := p.SendMessage(true, networkMsg)
×
UNCOV
3493
                if err != nil {
×
3494
                        p.log.Errorf("unable to send msg to "+
×
3495
                                "remote peer: %v", err)
×
3496
                }
×
3497
        }
3498

3499
        // If the failure action is disconnect, then we'll execute that now. If
3500
        // we had to send an error above, it was a sync call, so we expect the
3501
        // message to be flushed on the wire by now.
UNCOV
3502
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
×
3503
                p.Disconnect(fmt.Errorf("link requested disconnect"))
×
3504
        }
×
3505
}
3506

3507
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
3508
// public key and the channel id.
3509
func (p *Brontide) fetchLinkFromKeyAndCid(
3510
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
19✔
3511

19✔
3512
        var chanLink htlcswitch.ChannelUpdateHandler
19✔
3513

19✔
3514
        // We don't need to check the error here, and can instead just loop
19✔
3515
        // over the slice and return nil.
19✔
3516
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
19✔
3517
        for _, link := range links {
37✔
3518
                if link.ChanID() == cid {
36✔
3519
                        chanLink = link
18✔
3520
                        break
18✔
3521
                }
3522
        }
3523

3524
        return chanLink
19✔
3525
}
3526

3527
// finalizeChanClosure performs the final clean up steps once the cooperative
3528
// closure transaction has been fully broadcast. The finalized closing state
3529
// machine should be passed in. Once the transaction has been sufficiently
3530
// confirmed, the channel will be marked as fully closed within the database,
3531
// and any clients will be notified of updates to the closing state.
3532
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
4✔
3533
        closeReq := chanCloser.CloseRequest()
4✔
3534

4✔
3535
        // First, we'll clear all indexes related to the channel in question.
4✔
3536
        chanPoint := chanCloser.Channel().ChannelPoint()
4✔
3537
        p.WipeChannel(&chanPoint)
4✔
3538

4✔
3539
        // Also clear the activeChanCloses map of this channel.
4✔
3540
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
3541
        delete(p.activeChanCloses, cid)
4✔
3542

4✔
3543
        // Next, we'll launch a goroutine which will request to be notified by
4✔
3544
        // the ChainNotifier once the closure transaction obtains a single
4✔
3545
        // confirmation.
4✔
3546
        notifier := p.cfg.ChainNotifier
4✔
3547

4✔
3548
        // If any error happens during waitForChanToClose, forward it to
4✔
3549
        // closeReq. If this channel closure is not locally initiated, closeReq
4✔
3550
        // will be nil, so just ignore the error.
4✔
3551
        errChan := make(chan error, 1)
4✔
3552
        if closeReq != nil {
6✔
3553
                errChan = closeReq.Err
2✔
3554
        }
2✔
3555

3556
        closingTx, err := chanCloser.ClosingTx()
4✔
3557
        if err != nil {
4✔
3558
                if closeReq != nil {
×
3559
                        p.log.Error(err)
×
3560
                        closeReq.Err <- err
×
3561
                }
×
3562
        }
3563

3564
        closingTxid := closingTx.TxHash()
4✔
3565

4✔
3566
        // If this is a locally requested shutdown, update the caller with a
4✔
3567
        // new event detailing the current pending state of this request.
4✔
3568
        if closeReq != nil {
6✔
3569
                closeReq.Updates <- &PendingUpdate{
2✔
3570
                        Txid: closingTxid[:],
2✔
3571
                }
2✔
3572
        }
2✔
3573

3574
        localOut := chanCloser.LocalCloseOutput()
4✔
3575
        remoteOut := chanCloser.RemoteCloseOutput()
4✔
3576
        auxOut := chanCloser.AuxOutputs()
4✔
3577
        go WaitForChanToClose(
4✔
3578
                chanCloser.NegotiationHeight(), notifier, errChan,
4✔
3579
                &chanPoint, &closingTxid, closingTx.TxOut[0].PkScript, func() {
8✔
3580
                        // Respond to the local subsystem which requested the
4✔
3581
                        // channel closure.
4✔
3582
                        if closeReq != nil {
6✔
3583
                                closeReq.Updates <- &ChannelCloseUpdate{
2✔
3584
                                        ClosingTxid:       closingTxid[:],
2✔
3585
                                        Success:           true,
2✔
3586
                                        LocalCloseOutput:  localOut,
2✔
3587
                                        RemoteCloseOutput: remoteOut,
2✔
3588
                                        AuxOutputs:        auxOut,
2✔
3589
                                }
2✔
3590
                        }
2✔
3591
                },
3592
        )
3593
}
3594

3595
// WaitForChanToClose uses the passed notifier to wait until the channel has
3596
// been detected as closed on chain and then concludes by executing the
3597
// following actions: the channel point will be sent over the settleChan, and
3598
// finally the callback will be executed. If any error is encountered within
3599
// the function, then it will be sent over the errChan.
3600
func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
3601
        errChan chan error, chanPoint *wire.OutPoint,
3602
        closingTxID *chainhash.Hash, closeScript []byte, cb func()) {
4✔
3603

4✔
3604
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
4✔
3605
                "with txid: %v", chanPoint, closingTxID)
4✔
3606

4✔
3607
        // TODO(roasbeef): add param for num needed confs
4✔
3608
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
4✔
3609
                closingTxID, closeScript, 1, bestHeight,
4✔
3610
        )
4✔
3611
        if err != nil {
4✔
3612
                if errChan != nil {
×
3613
                        errChan <- err
×
3614
                }
×
3615
                return
×
3616
        }
3617

3618
        // In the case that the ChainNotifier is shutting down, all subscriber
3619
        // notification channels will be closed, generating a nil receive.
3620
        height, ok := <-confNtfn.Confirmed
4✔
3621
        if !ok {
4✔
UNCOV
3622
                return
×
UNCOV
3623
        }
×
3624

3625
        // The channel has been closed, remove it from any active indexes, and
3626
        // the database state.
3627
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
4✔
3628
                "height %v", chanPoint, height.BlockHeight)
4✔
3629

4✔
3630
        // Finally, execute the closure call back to mark the confirmation of
4✔
3631
        // the transaction closing the contract.
4✔
3632
        cb()
4✔
3633
}
3634

3635
// WipeChannel removes the passed channel point from all indexes associated with
3636
// the peer and the switch.
3637
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
4✔
3638
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
4✔
3639

4✔
3640
        p.activeChannels.Delete(chanID)
4✔
3641

4✔
3642
        // Instruct the HtlcSwitch to close this link as the channel is no
4✔
3643
        // longer active.
4✔
3644
        p.cfg.Switch.RemoveLink(chanID)
4✔
3645
}
4✔
3646

3647
// handleInitMsg handles the incoming init message which contains global and
3648
// local feature vectors. If feature vectors are incompatible then disconnect.
3649
func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
3✔
3650
        // First, merge any features from the legacy global features field into
3✔
3651
        // those presented in the local features fields.
3✔
3652
        err := msg.Features.Merge(msg.GlobalFeatures)
3✔
3653
        if err != nil {
3✔
3654
                return fmt.Errorf("unable to merge legacy global features: %w",
×
3655
                        err)
×
3656
        }
×
3657

3658
        // Then, finalize the remote feature vector providing the flattened
3659
        // feature bit namespace.
3660
        p.remoteFeatures = lnwire.NewFeatureVector(
3✔
3661
                msg.Features, lnwire.Features,
3✔
3662
        )
3✔
3663

3✔
3664
        // Now that we have their features loaded, we'll ensure that they
3✔
3665
        // didn't set any required bits that we don't know of.
3✔
3666
        err = feature.ValidateRequired(p.remoteFeatures)
3✔
3667
        if err != nil {
3✔
3668
                return fmt.Errorf("invalid remote features: %w", err)
×
3669
        }
×
3670

3671
        // Ensure the remote party's feature vector contains all transitive
3672
        // dependencies. We know ours are correct since they are validated
3673
        // during the feature manager's instantiation.
3674
        err = feature.ValidateDeps(p.remoteFeatures)
3✔
3675
        if err != nil {
3✔
3676
                return fmt.Errorf("invalid remote features: %w", err)
×
3677
        }
×
3678

3679
        // Now that we know we understand their requirements, we'll check to
3680
        // see if they don't support anything that we deem to be mandatory.
3681
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
3✔
3682
                return fmt.Errorf("data loss protection required")
×
3683
        }
×
3684

3685
        return nil
3✔
3686
}
3687

3688
// LocalFeatures returns the set of global features that has been advertised by
3689
// the local node. This allows sub-systems that use this interface to gate their
3690
// behavior off the set of negotiated feature bits.
3691
//
3692
// NOTE: Part of the lnpeer.Peer interface.
UNCOV
3693
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
×
UNCOV
3694
        return p.cfg.Features
×
UNCOV
3695
}
×
3696

3697
// RemoteFeatures returns the set of global features that has been advertised by
3698
// the remote node. This allows sub-systems that use this interface to gate
3699
// their behavior off the set of negotiated feature bits.
3700
//
3701
// NOTE: Part of the lnpeer.Peer interface.
3702
func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector {
6✔
3703
        return p.remoteFeatures
6✔
3704
}
6✔
3705

3706
// hasNegotiatedScidAlias returns true if we've negotiated the
3707
// option-scid-alias feature bit with the peer.
3708
func (p *Brontide) hasNegotiatedScidAlias() bool {
3✔
3709
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
3✔
3710
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
3✔
3711
        return peerHas && localHas
3✔
3712
}
3✔
3713

3714
// sendInitMsg sends the Init message to the remote peer. This message contains
3715
// our currently supported local and global features.
3716
func (p *Brontide) sendInitMsg(legacyChan bool) error {
7✔
3717
        features := p.cfg.Features.Clone()
7✔
3718
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
7✔
3719

7✔
3720
        // If we have a legacy channel open with a peer, we downgrade static
7✔
3721
        // remote required to optional in case the peer does not understand the
7✔
3722
        // required feature bit. If we do not do this, the peer will reject our
7✔
3723
        // connection because it does not understand a required feature bit, and
7✔
3724
        // our channel will be unusable.
7✔
3725
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
8✔
3726
                p.log.Infof("Legacy channel open with peer, " +
1✔
3727
                        "downgrading static remote required feature bit to " +
1✔
3728
                        "optional")
1✔
3729

1✔
3730
                // Unset and set in both the local and global features to
1✔
3731
                // ensure both sets are consistent and merge able by old and
1✔
3732
                // new nodes.
1✔
3733
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3734
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3735

1✔
3736
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
3737
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
3738
        }
1✔
3739

3740
        msg := lnwire.NewInitMessage(
7✔
3741
                legacyFeatures.RawFeatureVector,
7✔
3742
                features.RawFeatureVector,
7✔
3743
        )
7✔
3744

7✔
3745
        return p.writeMessage(msg)
7✔
3746
}
3747

3748
// resendChanSyncMsg will attempt to find a channel sync message for the closed
3749
// channel and resend it to our peer.
UNCOV
3750
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
×
UNCOV
3751
        // If we already re-sent the mssage for this channel, we won't do it
×
UNCOV
3752
        // again.
×
UNCOV
3753
        if _, ok := p.resentChanSyncMsg[cid]; ok {
×
UNCOV
3754
                return nil
×
UNCOV
3755
        }
×
3756

3757
        // Check if we have any channel sync messages stored for this channel.
UNCOV
3758
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
×
UNCOV
3759
        if err != nil {
×
UNCOV
3760
                return fmt.Errorf("unable to fetch channel sync messages for "+
×
UNCOV
3761
                        "peer %v: %v", p, err)
×
UNCOV
3762
        }
×
3763

UNCOV
3764
        if c.LastChanSyncMsg == nil {
×
3765
                return fmt.Errorf("no chan sync message stored for channel %v",
×
3766
                        cid)
×
3767
        }
×
3768

UNCOV
3769
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
×
3770
                return fmt.Errorf("ignoring channel reestablish from "+
×
3771
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
3772
        }
×
3773

UNCOV
3774
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
×
UNCOV
3775
                "peer", cid)
×
UNCOV
3776

×
UNCOV
3777
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
×
3778
                return fmt.Errorf("failed resending channel sync "+
×
3779
                        "message to peer %v: %v", p, err)
×
3780
        }
×
3781

UNCOV
3782
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
×
UNCOV
3783
                cid)
×
UNCOV
3784

×
UNCOV
3785
        // Note down that we sent the message, so we won't resend it again for
×
UNCOV
3786
        // this connection.
×
UNCOV
3787
        p.resentChanSyncMsg[cid] = struct{}{}
×
UNCOV
3788

×
UNCOV
3789
        return nil
×
3790
}
3791

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

3802
// SendMessageLazy sends a variadic number of low-priority messages to the
3803
// remote peer. The first argument denotes if the method should block until
3804
// the messages have been sent to the remote peer or an error is returned,
3805
// otherwise it returns immediately after queueing.
3806
//
3807
// NOTE: Part of the lnpeer.Peer interface.
3808
func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
1✔
3809
        return p.sendMessage(sync, false, msgs...)
1✔
3810
}
1✔
3811

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

3833
                if priority {
7✔
3834
                        p.queueMsg(msg, errChan)
3✔
3835
                } else {
4✔
3836
                        p.queueMsgLazy(msg, errChan)
1✔
3837
                }
1✔
3838
        }
3839

3840
        // Wait for all replies from the writeHandler. For async sends, this
3841
        // will be a NOP as the list of error chans is nil.
3842
        for _, errChan := range errChans {
5✔
3843
                select {
1✔
3844
                case err := <-errChan:
1✔
3845
                        return err
1✔
3846
                case <-p.quit:
×
3847
                        return lnpeer.ErrPeerExiting
×
3848
                case <-p.cfg.Quit:
×
3849
                        return lnpeer.ErrPeerExiting
×
3850
                }
3851
        }
3852

3853
        return nil
3✔
3854
}
3855

3856
// PubKey returns the pubkey of the peer in compressed serialized format.
3857
//
3858
// NOTE: Part of the lnpeer.Peer interface.
3859
func (p *Brontide) PubKey() [33]byte {
2✔
3860
        return p.cfg.PubKeyBytes
2✔
3861
}
2✔
3862

3863
// IdentityKey returns the public key of the remote peer.
3864
//
3865
// NOTE: Part of the lnpeer.Peer interface.
3866
func (p *Brontide) IdentityKey() *btcec.PublicKey {
15✔
3867
        return p.cfg.Addr.IdentityKey
15✔
3868
}
15✔
3869

3870
// Address returns the network address of the remote peer.
3871
//
3872
// NOTE: Part of the lnpeer.Peer interface.
UNCOV
3873
func (p *Brontide) Address() net.Addr {
×
UNCOV
3874
        return p.cfg.Addr.Address
×
UNCOV
3875
}
×
3876

3877
// AddNewChannel adds a new channel to the peer. The channel should fail to be
3878
// added if the cancel channel is closed.
3879
//
3880
// NOTE: Part of the lnpeer.Peer interface.
3881
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
UNCOV
3882
        cancel <-chan struct{}) error {
×
UNCOV
3883

×
UNCOV
3884
        errChan := make(chan error, 1)
×
UNCOV
3885
        newChanMsg := &newChannelMsg{
×
UNCOV
3886
                channel: newChan,
×
UNCOV
3887
                err:     errChan,
×
UNCOV
3888
        }
×
UNCOV
3889

×
UNCOV
3890
        select {
×
UNCOV
3891
        case p.newActiveChannel <- newChanMsg:
×
3892
        case <-cancel:
×
3893
                return errors.New("canceled adding new channel")
×
3894
        case <-p.quit:
×
3895
                return lnpeer.ErrPeerExiting
×
3896
        }
3897

3898
        // We pause here to wait for the peer to recognize the new channel
3899
        // before we close the channel barrier corresponding to the channel.
UNCOV
3900
        select {
×
UNCOV
3901
        case err := <-errChan:
×
UNCOV
3902
                return err
×
3903
        case <-p.quit:
×
3904
                return lnpeer.ErrPeerExiting
×
3905
        }
3906
}
3907

3908
// AddPendingChannel adds a pending open channel to the peer. The channel
3909
// should fail to be added if the cancel channel is closed.
3910
//
3911
// NOTE: Part of the lnpeer.Peer interface.
3912
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
UNCOV
3913
        cancel <-chan struct{}) error {
×
UNCOV
3914

×
UNCOV
3915
        errChan := make(chan error, 1)
×
UNCOV
3916
        newChanMsg := &newChannelMsg{
×
UNCOV
3917
                channelID: cid,
×
UNCOV
3918
                err:       errChan,
×
UNCOV
3919
        }
×
UNCOV
3920

×
UNCOV
3921
        select {
×
UNCOV
3922
        case p.newPendingChannel <- newChanMsg:
×
3923

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

3927
        case <-p.quit:
×
3928
                return lnpeer.ErrPeerExiting
×
3929
        }
3930

3931
        // We pause here to wait for the peer to recognize the new pending
3932
        // channel before we close the channel barrier corresponding to the
3933
        // channel.
UNCOV
3934
        select {
×
UNCOV
3935
        case err := <-errChan:
×
UNCOV
3936
                return err
×
3937

3938
        case <-cancel:
×
3939
                return errors.New("canceled adding pending channel")
×
3940

3941
        case <-p.quit:
×
3942
                return lnpeer.ErrPeerExiting
×
3943
        }
3944
}
3945

3946
// RemovePendingChannel removes a pending open channel from the peer.
3947
//
3948
// NOTE: Part of the lnpeer.Peer interface.
UNCOV
3949
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
×
UNCOV
3950
        errChan := make(chan error, 1)
×
UNCOV
3951
        newChanMsg := &newChannelMsg{
×
UNCOV
3952
                channelID: cid,
×
UNCOV
3953
                err:       errChan,
×
UNCOV
3954
        }
×
UNCOV
3955

×
UNCOV
3956
        select {
×
UNCOV
3957
        case p.removePendingChannel <- newChanMsg:
×
3958
        case <-p.quit:
×
3959
                return lnpeer.ErrPeerExiting
×
3960
        }
3961

3962
        // We pause here to wait for the peer to respond to the cancellation of
3963
        // the pending channel before we close the channel barrier
3964
        // corresponding to the channel.
UNCOV
3965
        select {
×
UNCOV
3966
        case err := <-errChan:
×
UNCOV
3967
                return err
×
3968

3969
        case <-p.quit:
×
3970
                return lnpeer.ErrPeerExiting
×
3971
        }
3972
}
3973

3974
// StartTime returns the time at which the connection was established if the
3975
// peer started successfully, and zero otherwise.
UNCOV
3976
func (p *Brontide) StartTime() time.Time {
×
UNCOV
3977
        return p.startTime
×
UNCOV
3978
}
×
3979

3980
// handleCloseMsg is called when a new cooperative channel closure related
3981
// message is received from the remote peer. We'll use this message to advance
3982
// the chan closer state machine.
3983
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
13✔
3984
        link := p.fetchLinkFromKeyAndCid(msg.cid)
13✔
3985

13✔
3986
        // We'll now fetch the matching closing state machine in order to continue,
13✔
3987
        // or finalize the channel closure process.
13✔
3988
        chanCloser, err := p.fetchActiveChanCloser(msg.cid)
13✔
3989
        if err != nil {
13✔
UNCOV
3990
                // If the channel is not known to us, we'll simply ignore this message.
×
UNCOV
3991
                if err == ErrChannelNotFound {
×
UNCOV
3992
                        return
×
UNCOV
3993
                }
×
3994

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

×
3997
                errMsg := &lnwire.Error{
×
3998
                        ChanID: msg.cid,
×
3999
                        Data:   lnwire.ErrorData(err.Error()),
×
4000
                }
×
4001
                p.queueMsg(errMsg, nil)
×
4002
                return
×
4003
        }
4004

4005
        handleErr := func(err error) {
14✔
4006
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
4007
                p.log.Error(err)
1✔
4008

1✔
4009
                // As the negotiations failed, we'll reset the channel state machine to
1✔
4010
                // ensure we act to on-chain events as normal.
1✔
4011
                chanCloser.Channel().ResetState()
1✔
4012

1✔
4013
                if chanCloser.CloseRequest() != nil {
1✔
4014
                        chanCloser.CloseRequest().Err <- err
×
4015
                }
×
4016
                delete(p.activeChanCloses, msg.cid)
1✔
4017

1✔
4018
                p.Disconnect(err)
1✔
4019
        }
4020

4021
        // Next, we'll process the next message using the target state machine.
4022
        // We'll either continue negotiation, or halt.
4023
        switch typed := msg.msg.(type) {
13✔
4024
        case *lnwire.Shutdown:
5✔
4025
                // Disable incoming adds immediately.
5✔
4026
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
5✔
4027
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
4028
                                link.ChanID())
×
4029
                }
×
4030

4031
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
5✔
4032
                if err != nil {
5✔
4033
                        handleErr(err)
×
4034
                        return
×
4035
                }
×
4036

4037
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
8✔
4038
                        // If the link is nil it means we can immediately queue
3✔
4039
                        // the Shutdown message since we don't have to wait for
3✔
4040
                        // commitment transaction synchronization.
3✔
4041
                        if link == nil {
4✔
4042
                                p.queueMsg(&msg, nil)
1✔
4043
                                return
1✔
4044
                        }
1✔
4045

4046
                        // Immediately disallow any new HTLC's from being added
4047
                        // in the outgoing direction.
4048
                        if !link.DisableAdds(htlcswitch.Outgoing) {
2✔
4049
                                p.log.Warnf("Outgoing link adds already "+
×
4050
                                        "disabled: %v", link.ChanID())
×
4051
                        }
×
4052

4053
                        // When we have a Shutdown to send, we defer it till the
4054
                        // next time we send a CommitSig to remain spec
4055
                        // compliant.
4056
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
4✔
4057
                                p.queueMsg(&msg, nil)
2✔
4058
                        })
2✔
4059
                })
4060

4061
                beginNegotiation := func() {
10✔
4062
                        oClosingSigned, err := chanCloser.BeginNegotiation()
5✔
4063
                        if err != nil {
6✔
4064
                                handleErr(err)
1✔
4065
                                return
1✔
4066
                        }
1✔
4067

4068
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
8✔
4069
                                p.queueMsg(&msg, nil)
4✔
4070
                        })
4✔
4071
                }
4072

4073
                if link == nil {
6✔
4074
                        beginNegotiation()
1✔
4075
                } else {
5✔
4076
                        // Now we register a flush hook to advance the
4✔
4077
                        // ChanCloser and possibly send out a ClosingSigned
4✔
4078
                        // when the link finishes draining.
4✔
4079
                        link.OnFlushedOnce(func() {
8✔
4080
                                // Remove link in goroutine to prevent deadlock.
4✔
4081
                                go p.cfg.Switch.RemoveLink(msg.cid)
4✔
4082
                                beginNegotiation()
4✔
4083
                        })
4✔
4084
                }
4085

4086
        case *lnwire.ClosingSigned:
8✔
4087
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
8✔
4088
                if err != nil {
8✔
4089
                        handleErr(err)
×
4090
                        return
×
4091
                }
×
4092

4093
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
16✔
4094
                        p.queueMsg(&msg, nil)
8✔
4095
                })
8✔
4096

4097
        default:
×
4098
                panic("impossible closeMsg type")
×
4099
        }
4100

4101
        // If we haven't finished close negotiations, then we'll continue as we
4102
        // can't yet finalize the closure.
4103
        if _, err := chanCloser.ClosingTx(); err != nil {
22✔
4104
                return
9✔
4105
        }
9✔
4106

4107
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
4108
        // the channel closure by notifying relevant sub-systems and launching a
4109
        // goroutine to wait for close tx conf.
4110
        p.finalizeChanClosure(chanCloser)
4✔
4111
}
4112

4113
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
4114
// the channelManager goroutine, which will shut down the link and possibly
4115
// close the channel.
UNCOV
4116
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
×
UNCOV
4117
        select {
×
UNCOV
4118
        case p.localCloseChanReqs <- req:
×
UNCOV
4119
                p.log.Info("Local close channel request is going to be " +
×
UNCOV
4120
                        "delivered to the peer")
×
4121
        case <-p.quit:
×
4122
                p.log.Info("Unable to deliver local close channel request " +
×
4123
                        "to peer")
×
4124
        }
4125
}
4126

4127
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
UNCOV
4128
func (p *Brontide) NetAddress() *lnwire.NetAddress {
×
UNCOV
4129
        return p.cfg.Addr
×
UNCOV
4130
}
×
4131

4132
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
UNCOV
4133
func (p *Brontide) Inbound() bool {
×
UNCOV
4134
        return p.cfg.Inbound
×
UNCOV
4135
}
×
4136

4137
// ConnReq is a getter for the Brontide's connReq in cfg.
UNCOV
4138
func (p *Brontide) ConnReq() *connmgr.ConnReq {
×
UNCOV
4139
        return p.cfg.ConnReq
×
UNCOV
4140
}
×
4141

4142
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
UNCOV
4143
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
×
UNCOV
4144
        return p.cfg.ErrorBuffer
×
UNCOV
4145
}
×
4146

4147
// SetAddress sets the remote peer's address given an address.
4148
func (p *Brontide) SetAddress(address net.Addr) {
×
4149
        p.cfg.Addr.Address = address
×
4150
}
×
4151

4152
// ActiveSignal returns the peer's active signal.
UNCOV
4153
func (p *Brontide) ActiveSignal() chan struct{} {
×
UNCOV
4154
        return p.activeSignal
×
UNCOV
4155
}
×
4156

4157
// Conn returns a pointer to the peer's connection struct.
UNCOV
4158
func (p *Brontide) Conn() net.Conn {
×
UNCOV
4159
        return p.cfg.Conn
×
UNCOV
4160
}
×
4161

4162
// BytesReceived returns the number of bytes received from the peer.
UNCOV
4163
func (p *Brontide) BytesReceived() uint64 {
×
UNCOV
4164
        return atomic.LoadUint64(&p.bytesReceived)
×
UNCOV
4165
}
×
4166

4167
// BytesSent returns the number of bytes sent to the peer.
UNCOV
4168
func (p *Brontide) BytesSent() uint64 {
×
UNCOV
4169
        return atomic.LoadUint64(&p.bytesSent)
×
UNCOV
4170
}
×
4171

4172
// LastRemotePingPayload returns the last payload the remote party sent as part
4173
// of their ping.
UNCOV
4174
func (p *Brontide) LastRemotePingPayload() []byte {
×
UNCOV
4175
        pingPayload := p.lastPingPayload.Load()
×
UNCOV
4176
        if pingPayload == nil {
×
UNCOV
4177
                return []byte{}
×
UNCOV
4178
        }
×
4179

UNCOV
4180
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
UNCOV
4181
        if !ok {
×
4182
                return nil
×
4183
        }
×
4184

UNCOV
4185
        return pingBytes
×
4186
}
4187

4188
// attachChannelEventSubscription creates a channel event subscription and
4189
// attaches to client to Brontide if the reenableTimeout is no greater than 1
4190
// minute.
4191
func (p *Brontide) attachChannelEventSubscription() error {
3✔
4192
        // If the timeout is greater than 1 minute, it's unlikely that the link
3✔
4193
        // hasn't yet finished its reestablishment. Return a nil without
3✔
4194
        // creating the client to specify that we don't want to retry.
3✔
4195
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
3✔
UNCOV
4196
                return nil
×
UNCOV
4197
        }
×
4198

4199
        // When the reenable timeout is less than 1 minute, it's likely the
4200
        // channel link hasn't finished its reestablishment yet. In that case,
4201
        // we'll give it a second chance by subscribing to the channel update
4202
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
4203
        // enabling the channel again.
4204
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
3✔
4205
        if err != nil {
3✔
4206
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
4207
        }
×
4208

4209
        p.channelEventClient = sub
3✔
4210

3✔
4211
        return nil
3✔
4212
}
4213

4214
// updateNextRevocation updates the existing channel's next revocation if it's
4215
// nil.
4216
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
3✔
4217
        chanPoint := c.FundingOutpoint
3✔
4218
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4219

3✔
4220
        // Read the current channel.
3✔
4221
        currentChan, loaded := p.activeChannels.Load(chanID)
3✔
4222

3✔
4223
        // currentChan should exist, but we perform a check anyway to avoid nil
3✔
4224
        // pointer dereference.
3✔
4225
        if !loaded {
4✔
4226
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
4227
                        chanID)
1✔
4228
        }
1✔
4229

4230
        // currentChan should not be nil, but we perform a check anyway to
4231
        // avoid nil pointer dereference.
4232
        if currentChan == nil {
3✔
4233
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
4234
                        chanID)
1✔
4235
        }
1✔
4236

4237
        // If we're being sent a new channel, and our existing channel doesn't
4238
        // have the next revocation, then we need to update the current
4239
        // existing channel.
4240
        if currentChan.RemoteNextRevocation() != nil {
1✔
4241
                return nil
×
4242
        }
×
4243

4244
        p.log.Infof("Processing retransmitted ChannelReady for "+
1✔
4245
                "ChannelPoint(%v)", chanPoint)
1✔
4246

1✔
4247
        nextRevoke := c.RemoteNextRevocation
1✔
4248

1✔
4249
        err := currentChan.InitNextRevocation(nextRevoke)
1✔
4250
        if err != nil {
1✔
4251
                return fmt.Errorf("unable to init next revocation: %w", err)
×
4252
        }
×
4253

4254
        return nil
1✔
4255
}
4256

4257
// addActiveChannel adds a new active channel to the `activeChannels` map. It
4258
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
4259
// it and assembles it with a channel link.
UNCOV
4260
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
×
UNCOV
4261
        chanPoint := c.FundingOutpoint
×
UNCOV
4262
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
4263

×
UNCOV
4264
        // If we've reached this point, there are two possible scenarios.  If
×
UNCOV
4265
        // the channel was in the active channels map as nil, then it was
×
UNCOV
4266
        // loaded from disk and we need to send reestablish. Else, it was not
×
UNCOV
4267
        // loaded from disk and we don't need to send reestablish as this is a
×
UNCOV
4268
        // fresh channel.
×
UNCOV
4269
        shouldReestablish := p.isLoadedFromDisk(chanID)
×
UNCOV
4270

×
UNCOV
4271
        chanOpts := c.ChanOpts
×
UNCOV
4272
        if shouldReestablish {
×
UNCOV
4273
                // If we have to do the reestablish dance for this channel,
×
UNCOV
4274
                // ensure that we don't try to call InitRemoteMusigNonces twice
×
UNCOV
4275
                // by calling SkipNonceInit.
×
UNCOV
4276
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
×
UNCOV
4277
        }
×
4278

UNCOV
4279
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
×
4280
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
4281
        })
×
UNCOV
4282
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
×
4283
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
4284
        })
×
UNCOV
4285
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
×
4286
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
4287
        })
×
4288

4289
        // If not already active, we'll add this channel to the set of active
4290
        // channels, so we can look it up later easily according to its channel
4291
        // ID.
UNCOV
4292
        lnChan, err := lnwallet.NewLightningChannel(
×
UNCOV
4293
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
×
UNCOV
4294
        )
×
UNCOV
4295
        if err != nil {
×
4296
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
4297
        }
×
4298

4299
        // Store the channel in the activeChannels map.
UNCOV
4300
        p.activeChannels.Store(chanID, lnChan)
×
UNCOV
4301

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

×
UNCOV
4304
        // Next, we'll assemble a ChannelLink along with the necessary items it
×
UNCOV
4305
        // needs to function.
×
UNCOV
4306
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
×
UNCOV
4307
        if err != nil {
×
4308
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
4309
                        err)
×
4310
        }
×
4311

4312
        // We'll query the channel DB for the new channel's initial forwarding
4313
        // policies to determine the policy we start out with.
UNCOV
4314
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
×
UNCOV
4315
        if err != nil {
×
4316
                return fmt.Errorf("unable to query for initial forwarding "+
×
4317
                        "policy: %v", err)
×
4318
        }
×
4319

4320
        // Create the link and add it to the switch.
UNCOV
4321
        err = p.addLink(
×
UNCOV
4322
                &chanPoint, lnChan, initialPolicy, chainEvents,
×
UNCOV
4323
                shouldReestablish, fn.None[lnwire.Shutdown](),
×
UNCOV
4324
        )
×
UNCOV
4325
        if err != nil {
×
4326
                return fmt.Errorf("can't register new channel link(%v) with "+
×
4327
                        "peer", chanPoint)
×
4328
        }
×
4329

UNCOV
4330
        return nil
×
4331
}
4332

4333
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
4334
// know this channel ID or not, we'll either add it to the `activeChannels` map
4335
// or init the next revocation for it.
UNCOV
4336
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
×
UNCOV
4337
        newChan := req.channel
×
UNCOV
4338
        chanPoint := newChan.FundingOutpoint
×
UNCOV
4339
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
4340

×
UNCOV
4341
        // Only update RemoteNextRevocation if the channel is in the
×
UNCOV
4342
        // activeChannels map and if we added the link to the switch. Only
×
UNCOV
4343
        // active channels will be added to the switch.
×
UNCOV
4344
        if p.isActiveChannel(chanID) {
×
UNCOV
4345
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
×
UNCOV
4346
                        chanPoint)
×
UNCOV
4347

×
UNCOV
4348
                // Handle it and close the err chan on the request.
×
UNCOV
4349
                close(req.err)
×
UNCOV
4350

×
UNCOV
4351
                // Update the next revocation point.
×
UNCOV
4352
                err := p.updateNextRevocation(newChan.OpenChannel)
×
UNCOV
4353
                if err != nil {
×
4354
                        p.log.Errorf(err.Error())
×
4355
                }
×
4356

UNCOV
4357
                return
×
4358
        }
4359

4360
        // This is a new channel, we now add it to the map.
UNCOV
4361
        if err := p.addActiveChannel(req.channel); err != nil {
×
4362
                // Log and send back the error to the request.
×
4363
                p.log.Errorf(err.Error())
×
4364
                req.err <- err
×
4365

×
4366
                return
×
4367
        }
×
4368

4369
        // Close the err chan if everything went fine.
UNCOV
4370
        close(req.err)
×
4371
}
4372

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

4✔
4380
        chanID := req.channelID
4✔
4381

4✔
4382
        // If we already have this channel, something is wrong with the funding
4✔
4383
        // flow as it will only be marked as active after `ChannelReady` is
4✔
4384
        // handled. In this case, we will do nothing but log an error, just in
4✔
4385
        // case this is a legit channel.
4✔
4386
        if p.isActiveChannel(chanID) {
5✔
4387
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
4388
                        "pending channel request", chanID)
1✔
4389

1✔
4390
                return
1✔
4391
        }
1✔
4392

4393
        // The channel has already been added, we will do nothing and return.
4394
        if p.isPendingChannel(chanID) {
4✔
4395
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
4396
                        "pending channel request", chanID)
1✔
4397

1✔
4398
                return
1✔
4399
        }
1✔
4400

4401
        // This is a new channel, we now add it to the map `activeChannels`
4402
        // with nil value and mark it as a newly added channel in
4403
        // `addedChannels`.
4404
        p.activeChannels.Store(chanID, nil)
2✔
4405
        p.addedChannels.Store(chanID, struct{}{})
2✔
4406
}
4407

4408
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
4409
// from `activeChannels` map. The request will be ignored if the channel is
4410
// considered active by Brontide. Noop if the channel ID cannot be found.
4411
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
4✔
4412
        defer close(req.err)
4✔
4413

4✔
4414
        chanID := req.channelID
4✔
4415

4✔
4416
        // If we already have this channel, something is wrong with the funding
4✔
4417
        // flow as it will only be marked as active after `ChannelReady` is
4✔
4418
        // handled. In this case, we will log an error and exit.
4✔
4419
        if p.isActiveChannel(chanID) {
5✔
4420
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
4421
                        chanID)
1✔
4422
                return
1✔
4423
        }
1✔
4424

4425
        // The channel has not been added yet, we will log a warning as there
4426
        // is an unexpected call from funding manager.
4427
        if !p.isPendingChannel(chanID) {
4✔
4428
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
1✔
4429
        }
1✔
4430

4431
        // Remove the record of this pending channel.
4432
        p.activeChannels.Delete(chanID)
3✔
4433
        p.addedChannels.Delete(chanID)
3✔
4434
}
4435

4436
// sendLinkUpdateMsg sends a message that updates the channel to the
4437
// channel's message stream.
UNCOV
4438
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
×
UNCOV
4439
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
×
UNCOV
4440

×
UNCOV
4441
        chanStream, ok := p.activeMsgStreams[cid]
×
UNCOV
4442
        if !ok {
×
UNCOV
4443
                // If a stream hasn't yet been created, then we'll do so, add
×
UNCOV
4444
                // it to the map, and finally start it.
×
UNCOV
4445
                chanStream = newChanMsgStream(p, cid)
×
UNCOV
4446
                p.activeMsgStreams[cid] = chanStream
×
UNCOV
4447
                chanStream.Start()
×
UNCOV
4448

×
UNCOV
4449
                // Stop the stream when quit.
×
UNCOV
4450
                go func() {
×
UNCOV
4451
                        <-p.quit
×
UNCOV
4452
                        chanStream.Stop()
×
UNCOV
4453
                }()
×
4454
        }
4455

4456
        // With the stream obtained, add the message to the stream so we can
4457
        // continue processing message.
UNCOV
4458
        chanStream.AddMsg(msg)
×
4459
}
4460

4461
// scaleTimeout multiplies the argument duration by a constant factor depending
4462
// on variious heuristics. Currently this is only used to check whether our peer
4463
// appears to be connected over Tor and relaxes the timout deadline. However,
4464
// this is subject to change and should be treated as opaque.
4465
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
67✔
4466
        if p.isTorConnection {
67✔
UNCOV
4467
                return timeout * time.Duration(torTimeoutMultiplier)
×
UNCOV
4468
        }
×
4469

4470
        return timeout
67✔
4471
}
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