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

lightningnetwork / lnd / 13593508312

28 Feb 2025 05:41PM UTC coverage: 58.287% (-10.4%) from 68.65%
13593508312

Pull #9458

github

web-flow
Merge d40067c0c into f1182e433
Pull Request #9458: multi+server.go: add initial permissions for some peers

346 of 548 new or added lines in 10 files covered. (63.14%)

27412 existing lines in 442 files now uncovered.

94709 of 162488 relevant lines covered (58.29%)

1.81 hits per line

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

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

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

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

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

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

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

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

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

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

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

94
        // msgStreamSize is the size of the message streams.
95
        msgStreamSize = 5
96
)
97

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

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

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

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

124
        err chan error
125
}
126

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

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

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

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

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

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

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

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

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

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

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

187
        // Addr is the network address of the peer.
188
        Addr *lnwire.NetAddress
189

190
        // Inbound indicates whether or not the peer is an inbound peer.
191
        Inbound bool
192

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

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

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

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

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

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

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

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

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

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

240
        // ChannelGraph is a pointer to the channel graph which is used to
241
        // query information about the set of known active channels.
242
        ChannelGraph *graphdb.ChannelGraph
243

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

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

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

256
        // ChainIO is used to retrieve the best block.
257
        ChainIO lnwallet.BlockChainIO
258

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

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

266
        // SigPool is used when creating *lnwallet.LightningChannel instances.
267
        SigPool *lnwallet.SigPool
268

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

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

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

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

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

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

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

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

302
        // HtlcNotifier is used when creating a ChannelLink.
303
        HtlcNotifier *htlcswitch.HtlcNotifier
304

305
        // TowerClient is used to backup revoked states.
306
        TowerClient wtclient.ClientManager
307

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

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

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

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

326
        // FundingManager is an implementation of the funding.Controller interface.
327
        FundingManager funding.Controller
328

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

406
        // AuxTrafficShaper is an optional auxiliary traffic shaper that can be
407
        // used to manage the bandwidth of peer links.
408
        AuxTrafficShaper fn.Option[htlcswitch.AuxTrafficShaper]
409

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

416
        // Adds the option to disable forwarding payments in blinded routes
417
        // by failing back any blinding-related payloads as if they were
418
        // invalid.
419
        DisallowRouteBlinding bool
420

421
        // DisallowQuiescence is a flag that indicates whether the Brontide
422
        // should have the quiescence feature disabled.
423
        DisallowQuiescence bool
424

425
        // MaxFeeExposure limits the number of outstanding fees in a channel.
426
        // This value will be passed to created links.
427
        MaxFeeExposure lnwire.MilliSatoshi
428

429
        // MsgRouter is an optional instance of the main message router that
430
        // the peer will use. If None, then a new default version will be used
431
        // in place.
432
        MsgRouter fn.Option[msgmux.Router]
433

434
        // AuxChanCloser is an optional instance of an abstraction that can be
435
        // used to modify the way the co-op close transaction is constructed.
436
        AuxChanCloser fn.Option[chancloser.AuxChanCloser]
437

438
        // ShouldFwdExpEndorsement is a closure that indicates whether
439
        // experimental endorsement signals should be set.
440
        ShouldFwdExpEndorsement func() bool
441

442
        // Quit is the server's quit channel. If this is closed, we halt operation.
443
        Quit chan struct{}
444
}
445

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

457
        // MUST be used atomically.
458
        bytesReceived uint64
459
        bytesSent     uint64
460

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

478
        pingManager *PingManager
479

480
        // lastPingPayload stores an unsafe pointer wrapped as an atomic
481
        // variable which points to the last payload the remote party sent us
482
        // as their ping.
483
        //
484
        // MUST be used atomically.
485
        lastPingPayload atomic.Value
486

487
        cfg Config
488

489
        // activeSignal when closed signals that the peer is now active and
490
        // ready to process messages.
491
        activeSignal chan struct{}
492

493
        // startTime is the time this peer connection was successfully established.
494
        // It will be zero for peers that did not successfully call Start().
495
        startTime time.Time
496

497
        // sendQueue is the channel which is used to queue outgoing messages to be
498
        // written onto the wire. Note that this channel is unbuffered.
499
        sendQueue chan outgoingMsg
500

501
        // outgoingQueue is a buffered channel which allows second/third party
502
        // objects to queue messages to be sent out on the wire.
503
        outgoingQueue chan outgoingMsg
504

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

518
        // addedChannels tracks any new channels opened during this peer's
519
        // lifecycle. We use this to filter out these new channels when the time
520
        // comes to request a reenable for active channels, since they will have
521
        // waited a shorter duration.
522
        addedChannels *lnutils.SyncMap[lnwire.ChannelID, struct{}]
523

524
        // newActiveChannel is used by the fundingManager to send fully opened
525
        // channels to the source peer which handled the funding workflow.
526
        newActiveChannel chan *newChannelMsg
527

528
        // newPendingChannel is used by the fundingManager to send pending open
529
        // channels to the source peer which handled the funding workflow.
530
        newPendingChannel chan *newChannelMsg
531

532
        // removePendingChannel is used by the fundingManager to cancel pending
533
        // open channels to the source peer when the funding flow is failed.
534
        removePendingChannel chan *newChannelMsg
535

536
        // activeMsgStreams is a map from channel id to the channel streams that
537
        // proxy messages to individual, active links.
538
        activeMsgStreams map[lnwire.ChannelID]*msgStream
539

540
        // activeChanCloses is a map that keeps track of all the active
541
        // cooperative channel closures. Any channel closing messages are directed
542
        // to one of these active state machines. Once the channel has been closed,
543
        // the state machine will be deleted from the map.
544
        activeChanCloses map[lnwire.ChannelID]*chancloser.ChanCloser
545

546
        // localCloseChanReqs is a channel in which any local requests to close
547
        // a particular channel are sent over.
548
        localCloseChanReqs chan *htlcswitch.ChanClose
549

550
        // linkFailures receives all reported channel failures from the switch,
551
        // and instructs the channelManager to clean remaining channel state.
552
        linkFailures chan linkFailureReport
553

554
        // chanCloseMsgs is a channel that any message related to channel
555
        // closures are sent over. This includes lnwire.Shutdown message as
556
        // well as lnwire.ClosingSigned messages.
557
        chanCloseMsgs chan *closeMsg
558

559
        // remoteFeatures is the feature vector received from the peer during
560
        // the connection handshake.
561
        remoteFeatures *lnwire.FeatureVector
562

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

569
        // channelEventClient is the channel event subscription client that's
570
        // used to assist retry enabling the channels. This client is only
571
        // created when the reenableTimeout is no greater than 1 minute. Once
572
        // created, it is canceled once the reenabling has been finished.
573
        //
574
        // NOTE: we choose to create the client conditionally to avoid
575
        // potentially holding lots of un-consumed events.
576
        channelEventClient *subscribe.Client
577

578
        // msgRouter is an instance of the msgmux.Router which is used to send
579
        // off new wire messages for handing.
580
        msgRouter fn.Option[msgmux.Router]
581

582
        // globalMsgRouter is a flag that indicates whether we have a global
583
        // msg router. If so, then we don't worry about stopping the msg router
584
        // when a peer disconnects.
585
        globalMsgRouter bool
586

587
        startReady chan struct{}
588
        quit       chan struct{}
589
        wg         sync.WaitGroup
590

591
        // log is a peer-specific logging instance.
592
        log btclog.Logger
593
}
594

595
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer interface.
596
var _ lnpeer.Peer = (*Brontide)(nil)
597

598
// NewBrontide creates a new Brontide from a peer.Config struct.
599
func NewBrontide(cfg Config) *Brontide {
3✔
600
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
3✔
601

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

3✔
607
        // We'll either use the msg router instance passed in, or create a new
3✔
608
        // blank instance.
3✔
609
        msgRouter := cfg.MsgRouter.Alt(fn.Some[msgmux.Router](
3✔
610
                msgmux.NewMultiMsgRouter(),
3✔
611
        ))
3✔
612

3✔
613
        p := &Brontide{
3✔
614
                cfg:           cfg,
3✔
615
                activeSignal:  make(chan struct{}),
3✔
616
                sendQueue:     make(chan outgoingMsg),
3✔
617
                outgoingQueue: make(chan outgoingMsg),
3✔
618
                addedChannels: &lnutils.SyncMap[lnwire.ChannelID, struct{}]{},
3✔
619
                activeChannels: &lnutils.SyncMap[
3✔
620
                        lnwire.ChannelID, *lnwallet.LightningChannel,
3✔
621
                ]{},
3✔
622
                newActiveChannel:     make(chan *newChannelMsg, 1),
3✔
623
                newPendingChannel:    make(chan *newChannelMsg, 1),
3✔
624
                removePendingChannel: make(chan *newChannelMsg),
3✔
625

3✔
626
                activeMsgStreams:   make(map[lnwire.ChannelID]*msgStream),
3✔
627
                activeChanCloses:   make(map[lnwire.ChannelID]*chancloser.ChanCloser),
3✔
628
                localCloseChanReqs: make(chan *htlcswitch.ChanClose),
3✔
629
                linkFailures:       make(chan linkFailureReport),
3✔
630
                chanCloseMsgs:      make(chan *closeMsg),
3✔
631
                resentChanSyncMsg:  make(map[lnwire.ChannelID]struct{}),
3✔
632
                startReady:         make(chan struct{}),
3✔
633
                quit:               make(chan struct{}),
3✔
634
                log:                peerLog.WithPrefix(logPrefix),
3✔
635
                msgRouter:          msgRouter,
3✔
636
                globalMsgRouter:    globalMsgRouter,
3✔
637
        }
3✔
638

3✔
639
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
6✔
640
                remoteAddr := cfg.Conn.RemoteAddr().String()
3✔
641
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
3✔
642
                        strings.Contains(remoteAddr, "127.0.0.1")
3✔
643
        }
3✔
644

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

661
                buf := bytes.NewBuffer(lastSerializedBlockHeader[0:0])
×
662
                err = header.Serialize(buf)
×
663
                if err == nil {
×
664
                        lastBlockHeader = header
×
665
                } else {
×
666
                        p.log.Warn("unable to serialize current block" +
×
667
                                "header for ping payload generation." +
×
668
                                "This should be impossible and means" +
×
669
                                "there is an implementation bug.")
×
670
                }
×
671

672
                return lastSerializedBlockHeader[:]
×
673
        }
674

675
        // TODO(roasbeef): make dynamic in order to create fake cover traffic.
676
        //
677
        // NOTE(proofofkeags): this was changed to be dynamic to allow better
678
        // pong identification, however, more thought is needed to make this
679
        // actually usable as a traffic decoy.
680
        randPongSize := func() uint16 {
3✔
681
                return uint16(
×
682
                        // We don't need cryptographic randomness here.
×
683
                        /* #nosec */
×
684
                        rand.Intn(pongSizeCeiling) + 1,
×
685
                )
×
686
        }
×
687

688
        p.pingManager = NewPingManager(&PingManagerConfig{
3✔
689
                NewPingPayload:   newPingPayload,
3✔
690
                NewPongSize:      randPongSize,
3✔
691
                IntervalDuration: p.scaleTimeout(pingInterval),
3✔
692
                TimeoutDuration:  p.scaleTimeout(pingTimeout),
3✔
693
                SendPing: func(ping *lnwire.Ping) {
3✔
694
                        p.queueMsg(ping, nil)
×
695
                },
×
696
                OnPongFailure: func(err error) {
×
697
                        eStr := "pong response failure for %s: %v " +
×
698
                                "-- disconnecting"
×
699
                        p.log.Warnf(eStr, p, err)
×
700
                        go p.Disconnect(fmt.Errorf(eStr, p, err))
×
701
                },
×
702
        })
703

704
        return p
3✔
705
}
706

707
// Start starts all helper goroutines the peer needs for normal operations.  In
708
// the case this peer has already been started, then this function is a noop.
709
func (p *Brontide) Start() error {
3✔
710
        if atomic.AddInt32(&p.started, 1) != 1 {
3✔
711
                return nil
×
712
        }
×
713

714
        // Once we've finished starting up the peer, we'll signal to other
715
        // goroutines that the they can move forward to tear down the peer, or
716
        // carry out other relevant changes.
717
        defer close(p.startReady)
3✔
718

3✔
719
        p.log.Tracef("starting with conn[%v->%v]",
3✔
720
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
3✔
721

3✔
722
        // Fetch and then load all the active channels we have with this remote
3✔
723
        // peer from the database.
3✔
724
        activeChans, err := p.cfg.ChannelDB.FetchOpenChannels(
3✔
725
                p.cfg.Addr.IdentityKey,
3✔
726
        )
3✔
727
        if err != nil {
3✔
728
                p.log.Errorf("Unable to fetch active chans "+
×
729
                        "for peer: %v", err)
×
730
                return err
×
731
        }
×
732

733
        if len(activeChans) == 0 {
6✔
734
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
3✔
735
        }
3✔
736

737
        // Quickly check if we have any existing legacy channels with this
738
        // peer.
739
        haveLegacyChan := false
3✔
740
        for _, c := range activeChans {
6✔
741
                if c.ChanType.IsTweakless() {
6✔
742
                        continue
3✔
743
                }
744

745
                haveLegacyChan = true
3✔
746
                break
3✔
747
        }
748

749
        // Exchange local and global features, the init message should be very
750
        // first between two nodes.
751
        if err := p.sendInitMsg(haveLegacyChan); err != nil {
6✔
752
                return fmt.Errorf("unable to send init msg: %w", err)
3✔
753
        }
3✔
754

755
        // Before we launch any of the helper goroutines off the peer struct,
756
        // we'll first ensure proper adherence to the p2p protocol. The init
757
        // message MUST be sent before any other message.
758
        readErr := make(chan error, 1)
3✔
759
        msgChan := make(chan lnwire.Message, 1)
3✔
760
        p.wg.Add(1)
3✔
761
        go func() {
6✔
762
                defer p.wg.Done()
3✔
763

3✔
764
                msg, err := p.readNextMessage()
3✔
765
                if err != nil {
4✔
766
                        readErr <- err
1✔
767
                        msgChan <- nil
1✔
768
                        return
1✔
769
                }
1✔
770
                readErr <- nil
3✔
771
                msgChan <- msg
3✔
772
        }()
773

774
        select {
3✔
775
        // In order to avoid blocking indefinitely, we'll give the other peer
776
        // an upper timeout to respond before we bail out early.
777
        case <-time.After(handshakeTimeout):
×
778
                return fmt.Errorf("peer did not complete handshake within %v",
×
779
                        handshakeTimeout)
×
780
        case err := <-readErr:
3✔
781
                if err != nil {
4✔
782
                        return fmt.Errorf("unable to read init msg: %w", err)
1✔
783
                }
1✔
784
        }
785

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

799
        // Next, load all the active channels we have with this peer,
800
        // registering them with the switch and launching the necessary
801
        // goroutines required to operate them.
802
        p.log.Debugf("Loaded %v active channels from database",
3✔
803
                len(activeChans))
3✔
804

3✔
805
        // Conditionally subscribe to channel events before loading channels so
3✔
806
        // we won't miss events. This subscription is used to listen to active
3✔
807
        // channel event when reenabling channels. Once the reenabling process
3✔
808
        // is finished, this subscription will be canceled.
3✔
809
        //
3✔
810
        // NOTE: ChannelNotifier must be started before subscribing events
3✔
811
        // otherwise we'd panic here.
3✔
812
        if err := p.attachChannelEventSubscription(); err != nil {
3✔
813
                return err
×
814
        }
×
815

816
        // Register the message router now as we may need to register some
817
        // endpoints while loading the channels below.
818
        p.msgRouter.WhenSome(func(router msgmux.Router) {
6✔
819
                router.Start()
3✔
820
        })
3✔
821

822
        msgs, err := p.loadActiveChannels(activeChans)
3✔
823
        if err != nil {
3✔
824
                return fmt.Errorf("unable to load channels: %w", err)
×
825
        }
×
826

827
        p.startTime = time.Now()
3✔
828

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

3✔
836
                // Send the messages directly via writeMessage and bypass the
3✔
837
                // writeHandler goroutine.
3✔
838
                for _, msg := range msgs {
6✔
839
                        if err := p.writeMessage(msg); err != nil {
3✔
840
                                return fmt.Errorf("unable to send "+
×
841
                                        "reestablish msg: %v", err)
×
842
                        }
×
843
                }
844
        }
845

846
        err = p.pingManager.Start()
3✔
847
        if err != nil {
3✔
848
                return fmt.Errorf("could not start ping manager %w", err)
×
849
        }
×
850

851
        p.wg.Add(4)
3✔
852
        go p.queueHandler()
3✔
853
        go p.writeHandler()
3✔
854
        go p.channelManager()
3✔
855
        go p.readHandler()
3✔
856

3✔
857
        // Signal to any external processes that the peer is now active.
3✔
858
        close(p.activeSignal)
3✔
859

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

3✔
875
        return nil
3✔
876
}
877

878
// initGossipSync initializes either a gossip syncer or an initial routing
879
// dump, depending on the negotiated synchronization method.
880
func (p *Brontide) initGossipSync() {
3✔
881
        // If the remote peer knows of the new gossip queries feature, then
3✔
882
        // we'll create a new gossipSyncer in the AuthenticatedGossiper for it.
3✔
883
        if p.remoteFeatures.HasFeature(lnwire.GossipQueriesOptional) {
6✔
884
                p.log.Info("Negotiated chan series queries")
3✔
885

3✔
886
                if p.cfg.AuthGossiper == nil {
3✔
UNCOV
887
                        // This should only ever be hit in the unit tests.
×
UNCOV
888
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
×
UNCOV
889
                                "gossip sync.")
×
UNCOV
890
                        return
×
UNCOV
891
                }
×
892

893
                // Register the peer's gossip syncer with the gossiper.
894
                // This blocks synchronously to ensure the gossip syncer is
895
                // registered with the gossiper before attempting to read
896
                // messages from the remote peer.
897
                //
898
                // TODO(wilmer): Only sync updates from non-channel peers. This
899
                // requires an improved version of the current network
900
                // bootstrapper to ensure we can find and connect to non-channel
901
                // peers.
902
                p.cfg.AuthGossiper.InitSyncState(p)
3✔
903
        }
904
}
905

906
// taprootShutdownAllowed returns true if both parties have negotiated the
907
// shutdown-any-segwit feature.
908
func (p *Brontide) taprootShutdownAllowed() bool {
3✔
909
        return p.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
3✔
910
                p.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
3✔
911
}
3✔
912

913
// QuitSignal is a method that should return a channel which will be sent upon
914
// or closed once the backing peer exits. This allows callers using the
915
// interface to cancel any processing in the event the backing implementation
916
// exits.
917
//
918
// NOTE: Part of the lnpeer.Peer interface.
919
func (p *Brontide) QuitSignal() <-chan struct{} {
3✔
920
        return p.quit
3✔
921
}
3✔
922

923
// addrWithInternalKey takes a delivery script, then attempts to supplement it
924
// with information related to the internal key for the addr, but only if it's
925
// a taproot addr.
926
func (p *Brontide) addrWithInternalKey(
927
        deliveryScript []byte) (*chancloser.DeliveryAddrWithKey, error) {
3✔
928

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

940
        return &chancloser.DeliveryAddrWithKey{
3✔
941
                DeliveryAddress: deliveryScript,
3✔
942
                InternalKey: fn.MapOption(
3✔
943
                        func(desc keychain.KeyDescriptor) btcec.PublicKey {
6✔
944
                                return *desc.PubKey
3✔
945
                        },
3✔
946
                )(internalKeyDesc),
947
        }, nil
948
}
949

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

3✔
957
        // Return a slice of messages to send to the peers in case the channel
3✔
958
        // cannot be loaded normally.
3✔
959
        var msgs []lnwire.Message
3✔
960

3✔
961
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
3✔
962

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

983
                                err = p.cfg.AddLocalAlias(
3✔
984
                                        aliasScid, dbChan.ShortChanID(), false,
3✔
985
                                        false,
3✔
986
                                )
3✔
987
                                if err != nil {
3✔
988
                                        return nil, err
×
989
                                }
×
990

991
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
992
                                        dbChan.FundingOutpoint,
3✔
993
                                )
3✔
994

3✔
995
                                // Fetch the second commitment point to send in
3✔
996
                                // the channel_ready message.
3✔
997
                                second, err := dbChan.SecondCommitmentPoint()
3✔
998
                                if err != nil {
3✔
999
                                        return nil, err
×
1000
                                }
×
1001

1002
                                channelReadyMsg := lnwire.NewChannelReady(
3✔
1003
                                        chanID, second,
3✔
1004
                                )
3✔
1005
                                channelReadyMsg.AliasScid = &aliasScid
3✔
1006

3✔
1007
                                msgs = append(msgs, channelReadyMsg)
3✔
1008
                        }
1009

1010
                        // If we've negotiated the option-scid-alias feature
1011
                        // and this channel does not have ScidAliasFeature set
1012
                        // to true due to an upgrade where the feature bit was
1013
                        // turned on, we'll update the channel's database
1014
                        // state.
1015
                        err := dbChan.MarkScidAliasNegotiated()
3✔
1016
                        if err != nil {
3✔
1017
                                return nil, err
×
1018
                        }
×
1019
                }
1020

1021
                var chanOpts []lnwallet.ChannelOpt
3✔
1022
                p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
3✔
1023
                        chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
1024
                })
×
1025
                p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
3✔
1026
                        chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
1027
                })
×
1028
                p.cfg.AuxResolver.WhenSome(
3✔
1029
                        func(s lnwallet.AuxContractResolver) {
3✔
1030
                                chanOpts = append(
×
1031
                                        chanOpts, lnwallet.WithAuxResolver(s),
×
1032
                                )
×
1033
                        },
×
1034
                )
1035

1036
                lnChan, err := lnwallet.NewLightningChannel(
3✔
1037
                        p.cfg.Signer, dbChan, p.cfg.SigPool, chanOpts...,
3✔
1038
                )
3✔
1039
                if err != nil {
3✔
1040
                        return nil, fmt.Errorf("unable to create channel "+
×
1041
                                "state machine: %w", err)
×
1042
                }
×
1043

1044
                chanPoint := dbChan.FundingOutpoint
3✔
1045

3✔
1046
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1047

3✔
1048
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
3✔
1049
                        chanPoint, lnChan.IsPending())
3✔
1050

3✔
1051
                // Skip adding any permanently irreconcilable channels to the
3✔
1052
                // htlcswitch.
3✔
1053
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
3✔
1054
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
6✔
1055

3✔
1056
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
3✔
1057
                                "start.", chanPoint, dbChan.ChanStatus())
3✔
1058

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

1073
                        msgs = append(msgs, chanSync)
3✔
1074

3✔
1075
                        // Check if this channel needs to have the cooperative
3✔
1076
                        // close process restarted. If so, we'll need to send
3✔
1077
                        // the Shutdown message that is returned.
3✔
1078
                        if dbChan.HasChanStatus(
3✔
1079
                                channeldb.ChanStatusCoopBroadcasted,
3✔
1080
                        ) {
3✔
1081

×
1082
                                shutdownMsg, err := p.restartCoopClose(lnChan)
×
1083
                                if err != nil {
×
1084
                                        p.log.Errorf("Unable to restart "+
×
1085
                                                "coop close for channel: %v",
×
1086
                                                err)
×
1087
                                        continue
×
1088
                                }
1089

1090
                                if shutdownMsg == nil {
×
1091
                                        continue
×
1092
                                }
1093

1094
                                // Append the message to the set of messages to
1095
                                // send.
1096
                                msgs = append(msgs, shutdownMsg)
×
1097
                        }
1098

1099
                        continue
3✔
1100
                }
1101

1102
                // Before we register this new link with the HTLC Switch, we'll
1103
                // need to fetch its current link-layer forwarding policy from
1104
                // the database.
1105
                graph := p.cfg.ChannelGraph
3✔
1106
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
3✔
1107
                        &chanPoint,
3✔
1108
                )
3✔
1109
                if err != nil && !errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1110
                        return nil, err
×
1111
                }
×
1112

1113
                // We'll filter out our policy from the directional channel
1114
                // edges based whom the edge connects to. If it doesn't connect
1115
                // to us, then we know that we were the one that advertised the
1116
                // policy.
1117
                //
1118
                // TODO(roasbeef): can add helper method to get policy for
1119
                // particular channel.
1120
                var selfPolicy *models.ChannelEdgePolicy
3✔
1121
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
3✔
1122
                        p.cfg.ServerPubKey[:]) {
6✔
1123

3✔
1124
                        selfPolicy = p1
3✔
1125
                } else {
6✔
1126
                        selfPolicy = p2
3✔
1127
                }
3✔
1128

1129
                // If we don't yet have an advertised routing policy, then
1130
                // we'll use the current default, otherwise we'll translate the
1131
                // routing policy into a forwarding policy.
1132
                var forwardingPolicy *models.ForwardingPolicy
3✔
1133
                if selfPolicy != nil {
6✔
1134
                        var inboundWireFee lnwire.Fee
3✔
1135
                        _, err := selfPolicy.ExtraOpaqueData.ExtractRecords(
3✔
1136
                                &inboundWireFee,
3✔
1137
                        )
3✔
1138
                        if err != nil {
3✔
1139
                                return nil, err
×
1140
                        }
×
1141

1142
                        inboundFee := models.NewInboundFeeFromWire(
3✔
1143
                                inboundWireFee,
3✔
1144
                        )
3✔
1145

3✔
1146
                        forwardingPolicy = &models.ForwardingPolicy{
3✔
1147
                                MinHTLCOut:    selfPolicy.MinHTLC,
3✔
1148
                                MaxHTLC:       selfPolicy.MaxHTLC,
3✔
1149
                                BaseFee:       selfPolicy.FeeBaseMSat,
3✔
1150
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
3✔
1151
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
3✔
1152

3✔
1153
                                InboundFee: inboundFee,
3✔
1154
                        }
3✔
1155
                } else {
3✔
1156
                        p.log.Warnf("Unable to find our forwarding policy "+
3✔
1157
                                "for channel %v, using default values",
3✔
1158
                                chanPoint)
3✔
1159
                        forwardingPolicy = &p.cfg.RoutingPolicy
3✔
1160
                }
3✔
1161

1162
                p.log.Tracef("Using link policy of: %v",
3✔
1163
                        spew.Sdump(forwardingPolicy))
3✔
1164

3✔
1165
                // If the channel is pending, set the value to nil in the
3✔
1166
                // activeChannels map. This is done to signify that the channel
3✔
1167
                // is pending. We don't add the link to the switch here - it's
3✔
1168
                // the funding manager's responsibility to spin up pending
3✔
1169
                // channels. Adding them here would just be extra work as we'll
3✔
1170
                // tear them down when creating + adding the final link.
3✔
1171
                if lnChan.IsPending() {
6✔
1172
                        p.activeChannels.Store(chanID, nil)
3✔
1173

3✔
1174
                        continue
3✔
1175
                }
1176

1177
                shutdownInfo, err := lnChan.State().ShutdownInfo()
3✔
1178
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
3✔
1179
                        return nil, err
×
1180
                }
×
1181

1182
                var (
3✔
1183
                        shutdownMsg     fn.Option[lnwire.Shutdown]
3✔
1184
                        shutdownInfoErr error
3✔
1185
                )
3✔
1186
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
6✔
1187
                        // Compute an ideal fee.
3✔
1188
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
1189
                                p.cfg.CoopCloseTargetConfs,
3✔
1190
                        )
3✔
1191
                        if err != nil {
3✔
1192
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1193
                                        "estimate fee: %w", err)
×
1194

×
1195
                                return
×
1196
                        }
×
1197

1198
                        addr, err := p.addrWithInternalKey(
3✔
1199
                                info.DeliveryScript.Val,
3✔
1200
                        )
3✔
1201
                        if err != nil {
3✔
1202
                                shutdownInfoErr = fmt.Errorf("unable to make "+
×
1203
                                        "delivery addr: %w", err)
×
1204
                                return
×
1205
                        }
×
1206
                        chanCloser, err := p.createChanCloser(
3✔
1207
                                lnChan, addr, feePerKw, nil, info.Closer(),
3✔
1208
                        )
3✔
1209
                        if err != nil {
3✔
1210
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1211
                                        "create chan closer: %w", err)
×
1212

×
1213
                                return
×
1214
                        }
×
1215

1216
                        chanID := lnwire.NewChanIDFromOutPoint(
3✔
1217
                                lnChan.State().FundingOutpoint,
3✔
1218
                        )
3✔
1219

3✔
1220
                        p.activeChanCloses[chanID] = chanCloser
3✔
1221

3✔
1222
                        // Create the Shutdown message.
3✔
1223
                        shutdown, err := chanCloser.ShutdownChan()
3✔
1224
                        if err != nil {
3✔
1225
                                delete(p.activeChanCloses, chanID)
×
1226
                                shutdownInfoErr = err
×
1227

×
1228
                                return
×
1229
                        }
×
1230

1231
                        shutdownMsg = fn.Some(*shutdown)
3✔
1232
                })
1233
                if shutdownInfoErr != nil {
3✔
1234
                        return nil, shutdownInfoErr
×
1235
                }
×
1236

1237
                // Subscribe to the set of on-chain events for this channel.
1238
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
3✔
1239
                        chanPoint,
3✔
1240
                )
3✔
1241
                if err != nil {
3✔
1242
                        return nil, err
×
1243
                }
×
1244

1245
                err = p.addLink(
3✔
1246
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
3✔
1247
                        true, shutdownMsg,
3✔
1248
                )
3✔
1249
                if err != nil {
3✔
1250
                        return nil, fmt.Errorf("unable to add link %v to "+
×
1251
                                "switch: %v", chanPoint, err)
×
1252
                }
×
1253

1254
                p.activeChannels.Store(chanID, lnChan)
3✔
1255
        }
1256

1257
        return msgs, nil
3✔
1258
}
1259

1260
// addLink creates and adds a new ChannelLink from the specified channel.
1261
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1262
        lnChan *lnwallet.LightningChannel,
1263
        forwardingPolicy *models.ForwardingPolicy,
1264
        chainEvents *contractcourt.ChainEventSubscription,
1265
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
3✔
1266

3✔
1267
        // onChannelFailure will be called by the link in case the channel
3✔
1268
        // fails for some reason.
3✔
1269
        onChannelFailure := func(chanID lnwire.ChannelID,
3✔
1270
                shortChanID lnwire.ShortChannelID,
3✔
1271
                linkErr htlcswitch.LinkFailureError) {
6✔
1272

3✔
1273
                failure := linkFailureReport{
3✔
1274
                        chanPoint:   *chanPoint,
3✔
1275
                        chanID:      chanID,
3✔
1276
                        shortChanID: shortChanID,
3✔
1277
                        linkErr:     linkErr,
3✔
1278
                }
3✔
1279

3✔
1280
                select {
3✔
1281
                case p.linkFailures <- failure:
3✔
1282
                case <-p.quit:
×
1283
                case <-p.cfg.Quit:
×
1284
                }
1285
        }
1286

1287
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
6✔
1288
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
3✔
1289
        }
3✔
1290

1291
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
6✔
1292
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
3✔
1293
        }
3✔
1294

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

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

3✔
1350
        // With the channel link created, we'll now notify the htlc switch so
3✔
1351
        // this channel can be used to dispatch local payments and also
3✔
1352
        // passively forward payments.
3✔
1353
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
3✔
1354
}
1355

1356
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1357
// one confirmed public channel exists with them.
1358
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
3✔
1359
        defer p.wg.Done()
3✔
1360

3✔
1361
        hasConfirmedPublicChan := false
3✔
1362
        for _, channel := range channels {
6✔
1363
                if channel.IsPending {
6✔
1364
                        continue
3✔
1365
                }
1366
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
6✔
1367
                        continue
3✔
1368
                }
1369

1370
                hasConfirmedPublicChan = true
3✔
1371
                break
3✔
1372
        }
1373
        if !hasConfirmedPublicChan {
6✔
1374
                return
3✔
1375
        }
3✔
1376

1377
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
3✔
1378
        if err != nil {
3✔
1379
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1380
                return
×
1381
        }
×
1382

1383
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
3✔
1384
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1385
        }
×
1386
}
1387

1388
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1389
// have any active channels with them.
1390
func (p *Brontide) maybeSendChannelUpdates() {
3✔
1391
        defer p.wg.Done()
3✔
1392

3✔
1393
        // If we don't have any active channels, then we can exit early.
3✔
1394
        if p.activeChannels.Len() == 0 {
6✔
1395
                return
3✔
1396
        }
3✔
1397

1398
        maybeSendUpd := func(cid lnwire.ChannelID,
3✔
1399
                lnChan *lnwallet.LightningChannel) error {
6✔
1400

3✔
1401
                // Nil channels are pending, so we'll skip them.
3✔
1402
                if lnChan == nil {
6✔
1403
                        return nil
3✔
1404
                }
3✔
1405

1406
                dbChan := lnChan.State()
3✔
1407
                scid := func() lnwire.ShortChannelID {
6✔
1408
                        switch {
3✔
1409
                        // Otherwise if it's a zero conf channel and confirmed,
1410
                        // then we need to use the "real" scid.
1411
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
3✔
1412
                                return dbChan.ZeroConfRealScid()
3✔
1413

1414
                        // Otherwise, we can use the normal scid.
1415
                        default:
3✔
1416
                                return dbChan.ShortChanID()
3✔
1417
                        }
1418
                }()
1419

1420
                // Now that we know the channel is in a good state, we'll try
1421
                // to fetch the update to send to the remote peer. If the
1422
                // channel is pending, and not a zero conf channel, we'll get
1423
                // an error here which we'll ignore.
1424
                chanUpd, err := p.cfg.FetchLastChanUpdate(scid)
3✔
1425
                if err != nil {
6✔
1426
                        p.log.Debugf("Unable to fetch channel update for "+
3✔
1427
                                "ChannelPoint(%v), scid=%v: %v",
3✔
1428
                                dbChan.FundingOutpoint, dbChan.ShortChanID, err)
3✔
1429

3✔
1430
                        return nil
3✔
1431
                }
3✔
1432

1433
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
3✔
1434
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
3✔
1435

3✔
1436
                // We'll send it as a normal message instead of using the lazy
3✔
1437
                // queue to prioritize transmission of the fresh update.
3✔
1438
                if err := p.SendMessage(false, chanUpd); err != nil {
3✔
1439
                        err := fmt.Errorf("unable to send channel update for "+
×
1440
                                "ChannelPoint(%v), scid=%v: %w",
×
1441
                                dbChan.FundingOutpoint, dbChan.ShortChanID(),
×
1442
                                err)
×
1443
                        p.log.Errorf(err.Error())
×
1444

×
1445
                        return err
×
1446
                }
×
1447

1448
                return nil
3✔
1449
        }
1450

1451
        p.activeChannels.ForEach(maybeSendUpd)
3✔
1452
}
1453

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

1471
        select {
3✔
1472
        case <-ready:
3✔
1473
        case <-p.quit:
2✔
1474
        }
1475

1476
        p.wg.Wait()
3✔
1477
}
1478

1479
// Disconnect terminates the connection with the remote peer. Additionally, a
1480
// signal is sent to the server and htlcSwitch indicating the resources
1481
// allocated to the peer can now be cleaned up.
1482
func (p *Brontide) Disconnect(reason error) {
3✔
1483
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
6✔
1484
                return
3✔
1485
        }
3✔
1486

1487
        // Make sure initialization has completed before we try to tear things
1488
        // down.
1489
        //
1490
        // NOTE: We only read the `startReady` chan if the peer has been
1491
        // started, otherwise we will skip reading it as this chan won't be
1492
        // closed, hence blocks forever.
1493
        if atomic.LoadInt32(&p.started) == 1 {
6✔
1494
                p.log.Debugf("Started, waiting on startReady signal")
3✔
1495

3✔
1496
                select {
3✔
1497
                case <-p.startReady:
3✔
1498
                case <-p.quit:
×
1499
                        return
×
1500
                }
1501
        }
1502

1503
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
3✔
1504
        p.storeError(err)
3✔
1505

3✔
1506
        p.log.Infof(err.Error())
3✔
1507

3✔
1508
        // Stop PingManager before closing TCP connection.
3✔
1509
        p.pingManager.Stop()
3✔
1510

3✔
1511
        // Ensure that the TCP connection is properly closed before continuing.
3✔
1512
        p.cfg.Conn.Close()
3✔
1513

3✔
1514
        close(p.quit)
3✔
1515

3✔
1516
        // If our msg router isn't global (local to this instance), then we'll
3✔
1517
        // stop it. Otherwise, we'll leave it running.
3✔
1518
        if !p.globalMsgRouter {
6✔
1519
                p.msgRouter.WhenSome(func(router msgmux.Router) {
6✔
1520
                        router.Stop()
3✔
1521
                })
3✔
1522
        }
1523
}
1524

1525
// String returns the string representation of this peer.
1526
func (p *Brontide) String() string {
3✔
1527
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
3✔
1528
}
3✔
1529

1530
// readNextMessage reads, and returns the next message on the wire along with
1531
// any additional raw payload.
1532
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
3✔
1533
        noiseConn := p.cfg.Conn
3✔
1534
        err := noiseConn.SetReadDeadline(time.Time{})
3✔
1535
        if err != nil {
3✔
1536
                return nil, err
×
1537
        }
×
1538

1539
        pktLen, err := noiseConn.ReadNextHeader()
3✔
1540
        if err != nil {
6✔
1541
                return nil, fmt.Errorf("read next header: %w", err)
3✔
1542
        }
3✔
1543

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

1566
                // The ReadNextBody method will actually end up re-using the
1567
                // buffer, so within this closure, we can continue to use
1568
                // rawMsg as it's just a slice into the buf from the buffer
1569
                // pool.
1570
                rawMsg, readErr := noiseConn.ReadNextBody(buf[:pktLen])
3✔
1571
                if readErr != nil {
3✔
1572
                        return fmt.Errorf("read next body: %w", readErr)
×
1573
                }
×
1574
                msgLen = uint64(len(rawMsg))
3✔
1575

3✔
1576
                // Next, create a new io.Reader implementation from the raw
3✔
1577
                // message, and use this to decode the message directly from.
3✔
1578
                msgReader := bytes.NewReader(rawMsg)
3✔
1579
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
3✔
1580
                if err != nil {
6✔
1581
                        return err
3✔
1582
                }
3✔
1583

1584
                // At this point, rawMsg and buf will be returned back to the
1585
                // buffer pool for re-use.
1586
                return nil
3✔
1587
        })
1588
        atomic.AddUint64(&p.bytesReceived, msgLen)
3✔
1589
        if err != nil {
6✔
1590
                return nil, err
3✔
1591
        }
3✔
1592

1593
        p.logWireMessage(nextMsg, true)
3✔
1594

3✔
1595
        return nextMsg, nil
3✔
1596
}
1597

1598
// msgStream implements a goroutine-safe, in-order stream of messages to be
1599
// delivered via closure to a receiver. These messages MUST be in order due to
1600
// the nature of the lightning channel commitment and gossiper state machines.
1601
// TODO(conner): use stream handler interface to abstract out stream
1602
// state/logging.
1603
type msgStream struct {
1604
        streamShutdown int32 // To be used atomically.
1605

1606
        peer *Brontide
1607

1608
        apply func(lnwire.Message)
1609

1610
        startMsg string
1611
        stopMsg  string
1612

1613
        msgCond *sync.Cond
1614
        msgs    []lnwire.Message
1615

1616
        mtx sync.Mutex
1617

1618
        producerSema chan struct{}
1619

1620
        wg   sync.WaitGroup
1621
        quit chan struct{}
1622
}
1623

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

3✔
1632
        stream := &msgStream{
3✔
1633
                peer:         p,
3✔
1634
                apply:        apply,
3✔
1635
                startMsg:     startMsg,
3✔
1636
                stopMsg:      stopMsg,
3✔
1637
                producerSema: make(chan struct{}, bufSize),
3✔
1638
                quit:         make(chan struct{}),
3✔
1639
        }
3✔
1640
        stream.msgCond = sync.NewCond(&stream.mtx)
3✔
1641

3✔
1642
        // Before we return the active stream, we'll populate the producer's
3✔
1643
        // semaphore channel. We'll use this to ensure that the producer won't
3✔
1644
        // attempt to allocate memory in the queue for an item until it has
3✔
1645
        // sufficient extra space.
3✔
1646
        for i := uint32(0); i < bufSize; i++ {
6✔
1647
                stream.producerSema <- struct{}{}
3✔
1648
        }
3✔
1649

1650
        return stream
3✔
1651
}
1652

1653
// Start starts the chanMsgStream.
1654
func (ms *msgStream) Start() {
3✔
1655
        ms.wg.Add(1)
3✔
1656
        go ms.msgConsumer()
3✔
1657
}
3✔
1658

1659
// Stop stops the chanMsgStream.
1660
func (ms *msgStream) Stop() {
3✔
1661
        // TODO(roasbeef): signal too?
3✔
1662

3✔
1663
        close(ms.quit)
3✔
1664

3✔
1665
        // Now that we've closed the channel, we'll repeatedly signal the msg
3✔
1666
        // consumer until we've detected that it has exited.
3✔
1667
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
6✔
1668
                ms.msgCond.Signal()
3✔
1669
                time.Sleep(time.Millisecond * 100)
3✔
1670
        }
3✔
1671

1672
        ms.wg.Wait()
3✔
1673
}
1674

1675
// msgConsumer is the main goroutine that streams messages from the peer's
1676
// readHandler directly to the target channel.
1677
func (ms *msgStream) msgConsumer() {
3✔
1678
        defer ms.wg.Done()
3✔
1679
        defer peerLog.Tracef(ms.stopMsg)
3✔
1680
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
3✔
1681

3✔
1682
        peerLog.Tracef(ms.startMsg)
3✔
1683

3✔
1684
        for {
6✔
1685
                // First, we'll check our condition. If the queue of messages
3✔
1686
                // is empty, then we'll wait until a new item is added.
3✔
1687
                ms.msgCond.L.Lock()
3✔
1688
                for len(ms.msgs) == 0 {
6✔
1689
                        ms.msgCond.Wait()
3✔
1690

3✔
1691
                        // If we woke up in order to exit, then we'll do so.
3✔
1692
                        // Otherwise, we'll check the message queue for any new
3✔
1693
                        // items.
3✔
1694
                        select {
3✔
1695
                        case <-ms.peer.quit:
3✔
1696
                                ms.msgCond.L.Unlock()
3✔
1697
                                return
3✔
1698
                        case <-ms.quit:
3✔
1699
                                ms.msgCond.L.Unlock()
3✔
1700
                                return
3✔
1701
                        default:
3✔
1702
                        }
1703
                }
1704

1705
                // Grab the message off the front of the queue, shifting the
1706
                // slice's reference down one in order to remove the message
1707
                // from the queue.
1708
                msg := ms.msgs[0]
3✔
1709
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
3✔
1710
                ms.msgs = ms.msgs[1:]
3✔
1711

3✔
1712
                ms.msgCond.L.Unlock()
3✔
1713

3✔
1714
                ms.apply(msg)
3✔
1715

3✔
1716
                // We've just successfully processed an item, so we'll signal
3✔
1717
                // to the producer that a new slot in the buffer. We'll use
3✔
1718
                // this to bound the size of the buffer to avoid allowing it to
3✔
1719
                // grow indefinitely.
3✔
1720
                select {
3✔
1721
                case ms.producerSema <- struct{}{}:
3✔
1722
                case <-ms.peer.quit:
3✔
1723
                        return
3✔
1724
                case <-ms.quit:
3✔
1725
                        return
3✔
1726
                }
1727
        }
1728
}
1729

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

1746
        // Next, we'll lock the condition, and add the message to the end of
1747
        // the message queue.
1748
        ms.msgCond.L.Lock()
3✔
1749
        ms.msgs = append(ms.msgs, msg)
3✔
1750
        ms.msgCond.L.Unlock()
3✔
1751

3✔
1752
        // With the message added, we signal to the msgConsumer that there are
3✔
1753
        // additional messages to consume.
3✔
1754
        ms.msgCond.Signal()
3✔
1755
}
1756

1757
// waitUntilLinkActive waits until the target link is active and returns a
1758
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1759
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1760
func waitUntilLinkActive(p *Brontide,
1761
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
3✔
1762

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

3✔
1765
        // Subscribe to receive channel events.
3✔
1766
        //
3✔
1767
        // NOTE: If the link is already active by SubscribeChannelEvents, then
3✔
1768
        // GetLink will retrieve the link and we can send messages. If the link
3✔
1769
        // becomes active between SubscribeChannelEvents and GetLink, then GetLink
3✔
1770
        // will retrieve the link. If the link becomes active after GetLink, then
3✔
1771
        // we will get an ActiveLinkEvent notification and retrieve the link. If
3✔
1772
        // the call to GetLink is before SubscribeChannelEvents, however, there
3✔
1773
        // will be a race condition.
3✔
1774
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
3✔
1775
        if err != nil {
4✔
1776
                // If we have a non-nil error, then the server is shutting down and we
1✔
1777
                // can exit here and return nil. This means no message will be delivered
1✔
1778
                // to the link.
1✔
1779
                return nil
1✔
1780
        }
1✔
1781
        defer sub.Cancel()
3✔
1782

3✔
1783
        // The link may already be active by this point, and we may have missed the
3✔
1784
        // ActiveLinkEvent. Check if the link exists.
3✔
1785
        link := p.fetchLinkFromKeyAndCid(cid)
3✔
1786
        if link != nil {
6✔
1787
                return link
3✔
1788
        }
3✔
1789

1790
        // If the link is nil, we must wait for it to be active.
1791
        for {
6✔
1792
                select {
3✔
1793
                // A new event has been sent by the ChannelNotifier. We first check
1794
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1795
                // that the event is for this channel. Otherwise, we discard the
1796
                // message.
1797
                case e := <-sub.Updates():
3✔
1798
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
3✔
1799
                        if !ok {
6✔
1800
                                // Ignore this notification.
3✔
1801
                                continue
3✔
1802
                        }
1803

1804
                        chanPoint := event.ChannelPoint
3✔
1805

3✔
1806
                        // Check whether the retrieved chanPoint matches the target
3✔
1807
                        // channel id.
3✔
1808
                        if !cid.IsChanPoint(chanPoint) {
3✔
1809
                                continue
×
1810
                        }
1811

1812
                        // The link shouldn't be nil as we received an
1813
                        // ActiveLinkEvent. If it is nil, we return nil and the
1814
                        // calling function should catch it.
1815
                        return p.fetchLinkFromKeyAndCid(cid)
3✔
1816

1817
                case <-p.quit:
3✔
1818
                        return nil
3✔
1819
                }
1820
        }
1821
}
1822

1823
// newChanMsgStream is used to create a msgStream between the peer and
1824
// particular channel link in the htlcswitch. We utilize additional
1825
// synchronization with the fundingManager to ensure we don't attempt to
1826
// dispatch a message to a channel before it is fully active. A reference to the
1827
// channel this stream forwards to is held in scope to prevent unnecessary
1828
// lookups.
1829
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
3✔
1830
        var chanLink htlcswitch.ChannelUpdateHandler
3✔
1831

3✔
1832
        apply := func(msg lnwire.Message) {
6✔
1833
                // This check is fine because if the link no longer exists, it will
3✔
1834
                // be removed from the activeChannels map and subsequent messages
3✔
1835
                // shouldn't reach the chan msg stream.
3✔
1836
                if chanLink == nil {
6✔
1837
                        chanLink = waitUntilLinkActive(p, cid)
3✔
1838

3✔
1839
                        // If the link is still not active and the calling function
3✔
1840
                        // errored out, just return.
3✔
1841
                        if chanLink == nil {
6✔
1842
                                p.log.Warnf("Link=%v is not active", cid)
3✔
1843
                                return
3✔
1844
                        }
3✔
1845
                }
1846

1847
                // In order to avoid unnecessarily delivering message
1848
                // as the peer is exiting, we'll check quickly to see
1849
                // if we need to exit.
1850
                select {
3✔
1851
                case <-p.quit:
×
1852
                        return
×
1853
                default:
3✔
1854
                }
1855

1856
                chanLink.HandleChannelUpdate(msg)
3✔
1857
        }
1858

1859
        return newMsgStream(p,
3✔
1860
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
3✔
1861
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
3✔
1862
                msgStreamSize,
3✔
1863
                apply,
3✔
1864
        )
3✔
1865
}
1866

1867
// newDiscMsgStream is used to setup a msgStream between the peer and the
1868
// authenticated gossiper. This stream should be used to forward all remote
1869
// channel announcements.
1870
func newDiscMsgStream(p *Brontide) *msgStream {
3✔
1871
        apply := func(msg lnwire.Message) {
6✔
1872
                // TODO(yy): `ProcessRemoteAnnouncement` returns an error chan
3✔
1873
                // and we need to process it.
3✔
1874
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(msg, p)
3✔
1875
        }
3✔
1876

1877
        return newMsgStream(
3✔
1878
                p,
3✔
1879
                "Update stream for gossiper created",
3✔
1880
                "Update stream for gossiper exited",
3✔
1881
                msgStreamSize,
3✔
1882
                apply,
3✔
1883
        )
3✔
1884
}
1885

1886
// readHandler is responsible for reading messages off the wire in series, then
1887
// properly dispatching the handling of the message to the proper subsystem.
1888
//
1889
// NOTE: This method MUST be run as a goroutine.
1890
func (p *Brontide) readHandler() {
3✔
1891
        defer p.wg.Done()
3✔
1892

3✔
1893
        // We'll stop the timer after a new messages is received, and also
3✔
1894
        // reset it after we process the next message.
3✔
1895
        idleTimer := time.AfterFunc(idleTimeout, func() {
3✔
1896
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
1897
                        p, idleTimeout)
×
1898
                p.Disconnect(err)
×
1899
        })
×
1900

1901
        // Initialize our negotiated gossip sync method before reading messages
1902
        // off the wire. When using gossip queries, this ensures a gossip
1903
        // syncer is active by the time query messages arrive.
1904
        //
1905
        // TODO(conner): have peer store gossip syncer directly and bypass
1906
        // gossiper?
1907
        p.initGossipSync()
3✔
1908

3✔
1909
        discStream := newDiscMsgStream(p)
3✔
1910
        discStream.Start()
3✔
1911
        defer discStream.Stop()
3✔
1912
out:
3✔
1913
        for atomic.LoadInt32(&p.disconnect) == 0 {
6✔
1914
                nextMsg, err := p.readNextMessage()
3✔
1915
                if !idleTimer.Stop() {
3✔
1916
                        select {
×
1917
                        case <-idleTimer.C:
×
1918
                        default:
×
1919
                        }
1920
                }
1921
                if err != nil {
6✔
1922
                        p.log.Infof("unable to read message from peer: %v", err)
3✔
1923

3✔
1924
                        // If we could not read our peer's message due to an
3✔
1925
                        // unknown type or invalid alias, we continue processing
3✔
1926
                        // as normal. We store unknown message and address
3✔
1927
                        // types, as they may provide debugging insight.
3✔
1928
                        switch e := err.(type) {
3✔
1929
                        // If this is just a message we don't yet recognize,
1930
                        // we'll continue processing as normal as this allows
1931
                        // us to introduce new messages in a forwards
1932
                        // compatible manner.
1933
                        case *lnwire.UnknownMessage:
3✔
1934
                                p.storeError(e)
3✔
1935
                                idleTimer.Reset(idleTimeout)
3✔
1936
                                continue
3✔
1937

1938
                        // If they sent us an address type that we don't yet
1939
                        // know of, then this isn't a wire error, so we'll
1940
                        // simply continue parsing the remainder of their
1941
                        // messages.
1942
                        case *lnwire.ErrUnknownAddrType:
×
1943
                                p.storeError(e)
×
1944
                                idleTimer.Reset(idleTimeout)
×
1945
                                continue
×
1946

1947
                        // If the NodeAnnouncement has an invalid alias, then
1948
                        // we'll log that error above and continue so we can
1949
                        // continue to read messages from the peer. We do not
1950
                        // store this error because it is of little debugging
1951
                        // value.
1952
                        case *lnwire.ErrInvalidNodeAlias:
×
1953
                                idleTimer.Reset(idleTimeout)
×
1954
                                continue
×
1955

1956
                        // If the error we encountered wasn't just a message we
1957
                        // didn't recognize, then we'll stop all processing as
1958
                        // this is a fatal error.
1959
                        default:
3✔
1960
                                break out
3✔
1961
                        }
1962
                }
1963

1964
                // If a message router is active, then we'll try to have it
1965
                // handle this message. If it can, then we're able to skip the
1966
                // rest of the message handling logic.
1967
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
6✔
1968
                        return r.RouteMsg(msgmux.PeerMsg{
3✔
1969
                                PeerPub: *p.IdentityKey(),
3✔
1970
                                Message: nextMsg,
3✔
1971
                        })
3✔
1972
                })
3✔
1973

1974
                // No error occurred, and the message was handled by the
1975
                // router.
1976
                if err == nil {
3✔
1977
                        continue
×
1978
                }
1979

1980
                var (
3✔
1981
                        targetChan   lnwire.ChannelID
3✔
1982
                        isLinkUpdate bool
3✔
1983
                )
3✔
1984

3✔
1985
                switch msg := nextMsg.(type) {
3✔
1986
                case *lnwire.Pong:
×
1987
                        // When we receive a Pong message in response to our
×
1988
                        // last ping message, we send it to the pingManager
×
1989
                        p.pingManager.ReceivedPong(msg)
×
1990

1991
                case *lnwire.Ping:
×
1992
                        // First, we'll store their latest ping payload within
×
1993
                        // the relevant atomic variable.
×
1994
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
1995

×
1996
                        // Next, we'll send over the amount of specified pong
×
1997
                        // bytes.
×
1998
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
×
1999
                        p.queueMsg(pong, nil)
×
2000

2001
                case *lnwire.OpenChannel,
2002
                        *lnwire.AcceptChannel,
2003
                        *lnwire.FundingCreated,
2004
                        *lnwire.FundingSigned,
2005
                        *lnwire.ChannelReady:
3✔
2006

3✔
2007
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2008

2009
                case *lnwire.Shutdown:
3✔
2010
                        select {
3✔
2011
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
2012
                        case <-p.quit:
×
2013
                                break out
×
2014
                        }
2015
                case *lnwire.ClosingSigned:
3✔
2016
                        select {
3✔
2017
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
2018
                        case <-p.quit:
×
2019
                                break out
×
2020
                        }
2021

2022
                case *lnwire.Warning:
×
2023
                        targetChan = msg.ChanID
×
2024
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2025

2026
                case *lnwire.Error:
3✔
2027
                        targetChan = msg.ChanID
3✔
2028
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
3✔
2029

2030
                case *lnwire.ChannelReestablish:
3✔
2031
                        targetChan = msg.ChanID
3✔
2032
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2033

3✔
2034
                        // If we failed to find the link in question, and the
3✔
2035
                        // message received was a channel sync message, then
3✔
2036
                        // this might be a peer trying to resync closed channel.
3✔
2037
                        // In this case we'll try to resend our last channel
3✔
2038
                        // sync message, such that the peer can recover funds
3✔
2039
                        // from the closed channel.
3✔
2040
                        if !isLinkUpdate {
6✔
2041
                                err := p.resendChanSyncMsg(targetChan)
3✔
2042
                                if err != nil {
6✔
2043
                                        // TODO(halseth): send error to peer?
3✔
2044
                                        p.log.Errorf("resend failed: %v",
3✔
2045
                                                err)
3✔
2046
                                }
3✔
2047
                        }
2048

2049
                // For messages that implement the LinkUpdater interface, we
2050
                // will consider them as link updates and send them to
2051
                // chanStream. These messages will be queued inside chanStream
2052
                // if the channel is not active yet.
2053
                case lnwire.LinkUpdater:
3✔
2054
                        targetChan = msg.TargetChanID()
3✔
2055
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2056

3✔
2057
                        // Log an error if we don't have this channel. This
3✔
2058
                        // means the peer has sent us a message with unknown
3✔
2059
                        // channel ID.
3✔
2060
                        if !isLinkUpdate {
6✔
2061
                                p.log.Errorf("Unknown channel ID: %v found "+
3✔
2062
                                        "in received msg=%s", targetChan,
3✔
2063
                                        nextMsg.MsgType())
3✔
2064
                        }
3✔
2065

2066
                case *lnwire.ChannelUpdate1,
2067
                        *lnwire.ChannelAnnouncement1,
2068
                        *lnwire.NodeAnnouncement,
2069
                        *lnwire.AnnounceSignatures1,
2070
                        *lnwire.GossipTimestampRange,
2071
                        *lnwire.QueryShortChanIDs,
2072
                        *lnwire.QueryChannelRange,
2073
                        *lnwire.ReplyChannelRange,
2074
                        *lnwire.ReplyShortChanIDsEnd:
3✔
2075

3✔
2076
                        discStream.AddMsg(msg)
3✔
2077

2078
                case *lnwire.Custom:
3✔
2079
                        err := p.handleCustomMessage(msg)
3✔
2080
                        if err != nil {
3✔
2081
                                p.storeError(err)
×
2082
                                p.log.Errorf("%v", err)
×
2083
                        }
×
2084

2085
                default:
×
2086
                        // If the message we received is unknown to us, store
×
2087
                        // the type to track the failure.
×
2088
                        err := fmt.Errorf("unknown message type %v received",
×
2089
                                uint16(msg.MsgType()))
×
2090
                        p.storeError(err)
×
2091

×
2092
                        p.log.Errorf("%v", err)
×
2093
                }
2094

2095
                if isLinkUpdate {
6✔
2096
                        // If this is a channel update, then we need to feed it
3✔
2097
                        // into the channel's in-order message stream.
3✔
2098
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
3✔
2099
                }
3✔
2100

2101
                idleTimer.Reset(idleTimeout)
3✔
2102
        }
2103

2104
        p.Disconnect(errors.New("read handler closed"))
3✔
2105

3✔
2106
        p.log.Trace("readHandler for peer done")
3✔
2107
}
2108

2109
// handleCustomMessage handles the given custom message if a handler is
2110
// registered.
2111
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
3✔
2112
        if p.cfg.HandleCustomMessage == nil {
3✔
2113
                return fmt.Errorf("no custom message handler for "+
×
2114
                        "message type %v", uint16(msg.MsgType()))
×
2115
        }
×
2116

2117
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
3✔
2118
}
2119

2120
// isLoadedFromDisk returns true if the provided channel ID is loaded from
2121
// disk.
2122
//
2123
// NOTE: only returns true for pending channels.
2124
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
3✔
2125
        // If this is a newly added channel, no need to reestablish.
3✔
2126
        _, added := p.addedChannels.Load(chanID)
3✔
2127
        if added {
6✔
2128
                return false
3✔
2129
        }
3✔
2130

2131
        // Return false if the channel is unknown.
2132
        channel, ok := p.activeChannels.Load(chanID)
3✔
2133
        if !ok {
3✔
2134
                return false
×
2135
        }
×
2136

2137
        // During startup, we will use a nil value to mark a pending channel
2138
        // that's loaded from disk.
2139
        return channel == nil
3✔
2140
}
2141

2142
// isActiveChannel returns true if the provided channel id is active, otherwise
2143
// returns false.
2144
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
3✔
2145
        // The channel would be nil if,
3✔
2146
        // - the channel doesn't exist, or,
3✔
2147
        // - the channel exists, but is pending. In this case, we don't
3✔
2148
        //   consider this channel active.
3✔
2149
        channel, _ := p.activeChannels.Load(chanID)
3✔
2150

3✔
2151
        return channel != nil
3✔
2152
}
3✔
2153

2154
// isPendingChannel returns true if the provided channel ID is pending, and
2155
// returns false if the channel is active or unknown.
2156
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
3✔
2157
        // Return false if the channel is unknown.
3✔
2158
        channel, ok := p.activeChannels.Load(chanID)
3✔
2159
        if !ok {
6✔
2160
                return false
3✔
2161
        }
3✔
2162

UNCOV
2163
        return channel == nil
×
2164
}
2165

2166
// hasChannel returns true if the peer has a pending/active channel specified
2167
// by the channel ID.
2168
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
3✔
2169
        _, ok := p.activeChannels.Load(chanID)
3✔
2170
        return ok
3✔
2171
}
3✔
2172

2173
// storeError stores an error in our peer's buffer of recent errors with the
2174
// current timestamp. Errors are only stored if we have at least one active
2175
// channel with the peer to mitigate a dos vector where a peer costlessly
2176
// connects to us and spams us with errors.
2177
func (p *Brontide) storeError(err error) {
3✔
2178
        var haveChannels bool
3✔
2179

3✔
2180
        p.activeChannels.Range(func(_ lnwire.ChannelID,
3✔
2181
                channel *lnwallet.LightningChannel) bool {
6✔
2182

3✔
2183
                // Pending channels will be nil in the activeChannels map.
3✔
2184
                if channel == nil {
6✔
2185
                        // Return true to continue the iteration.
3✔
2186
                        return true
3✔
2187
                }
3✔
2188

2189
                haveChannels = true
3✔
2190

3✔
2191
                // Return false to break the iteration.
3✔
2192
                return false
3✔
2193
        })
2194

2195
        // If we do not have any active channels with the peer, we do not store
2196
        // errors as a dos mitigation.
2197
        if !haveChannels {
6✔
2198
                p.log.Trace("no channels with peer, not storing err")
3✔
2199
                return
3✔
2200
        }
3✔
2201

2202
        p.cfg.ErrorBuffer.Add(
3✔
2203
                &TimestampedError{Timestamp: time.Now(), Error: err},
3✔
2204
        )
3✔
2205
}
2206

2207
// handleWarningOrError processes a warning or error msg and returns true if
2208
// msg should be forwarded to the associated channel link. False is returned if
2209
// any necessary forwarding of msg was already handled by this method. If msg is
2210
// an error from a peer with an active channel, we'll store it in memory.
2211
//
2212
// NOTE: This method should only be called from within the readHandler.
2213
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
2214
        msg lnwire.Message) bool {
3✔
2215

3✔
2216
        if errMsg, ok := msg.(*lnwire.Error); ok {
6✔
2217
                p.storeError(errMsg)
3✔
2218
        }
3✔
2219

2220
        switch {
3✔
2221
        // Connection wide messages should be forwarded to all channel links
2222
        // with this peer.
2223
        case chanID == lnwire.ConnectionWideID:
×
2224
                for _, chanStream := range p.activeMsgStreams {
×
2225
                        chanStream.AddMsg(msg)
×
2226
                }
×
2227

2228
                return false
×
2229

2230
        // If the channel ID for the message corresponds to a pending channel,
2231
        // then the funding manager will handle it.
2232
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
3✔
2233
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2234
                return false
3✔
2235

2236
        // If not we hand the message to the channel link for this channel.
2237
        case p.isActiveChannel(chanID):
3✔
2238
                return true
3✔
2239

2240
        default:
3✔
2241
                return false
3✔
2242
        }
2243
}
2244

2245
// messageSummary returns a human-readable string that summarizes a
2246
// incoming/outgoing message. Not all messages will have a summary, only those
2247
// which have additional data that can be informative at a glance.
2248
func messageSummary(msg lnwire.Message) string {
3✔
2249
        switch msg := msg.(type) {
3✔
2250
        case *lnwire.Init:
3✔
2251
                // No summary.
3✔
2252
                return ""
3✔
2253

2254
        case *lnwire.OpenChannel:
3✔
2255
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
3✔
2256
                        "push_amt=%v, reserve=%v, flags=%v",
3✔
2257
                        msg.PendingChannelID[:], msg.ChainHash,
3✔
2258
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
3✔
2259
                        msg.ChannelReserve, msg.ChannelFlags)
3✔
2260

2261
        case *lnwire.AcceptChannel:
3✔
2262
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
3✔
2263
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
3✔
2264
                        msg.MinAcceptDepth)
3✔
2265

2266
        case *lnwire.FundingCreated:
3✔
2267
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
3✔
2268
                        msg.PendingChannelID[:], msg.FundingPoint)
3✔
2269

2270
        case *lnwire.FundingSigned:
3✔
2271
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
3✔
2272

2273
        case *lnwire.ChannelReady:
3✔
2274
                return fmt.Sprintf("chan_id=%v, next_point=%x",
3✔
2275
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
3✔
2276

2277
        case *lnwire.Shutdown:
3✔
2278
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
3✔
2279
                        msg.Address[:])
3✔
2280

2281
        case *lnwire.ClosingComplete:
×
2282
                return fmt.Sprintf("chan_id=%v, fee_sat=%v, locktime=%v",
×
2283
                        msg.ChannelID, msg.FeeSatoshis, msg.LockTime)
×
2284

2285
        case *lnwire.ClosingSig:
×
2286
                return fmt.Sprintf("chan_id=%v", msg.ChannelID)
×
2287

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

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

3✔
2298
                                blindingPoint = b.Val.SerializeCompressed()
3✔
2299
                        },
3✔
2300
                )
2301

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

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

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

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

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

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

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

2332
        case *lnwire.Error:
3✔
2333
                return fmt.Sprintf("%v", msg.Error())
3✔
2334

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2397
        case *lnwire.Custom:
3✔
2398
                return fmt.Sprintf("type=%d", msg.Type)
3✔
2399
        }
2400

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

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

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

2422
                preposition := "to"
3✔
2423
                if read {
6✔
2424
                        preposition = "from"
3✔
2425
                }
3✔
2426

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

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

2438
        prefix := "readMessage from peer"
3✔
2439
        if !read {
6✔
2440
                prefix = "writeMessage to peer"
3✔
2441
        }
3✔
2442

2443
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
3✔
2444
}
2445

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

2463
        noiseConn := p.cfg.Conn
3✔
2464

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

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

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

2486
                return err
3✔
2487
        }
2488

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

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

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

2516
        return flushMsg()
3✔
2517
}
2518

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

2534
        var exitErr error
3✔
2535

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

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

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

×
2565
                                goto retry
×
2566
                        }
2567

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

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

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

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

2596
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2597
        // disconnect.
2598
        p.wg.Done()
3✔
2599

3✔
2600
        p.Disconnect(exitErr)
3✔
2601

3✔
2602
        p.log.Trace("writeHandler for peer done")
3✔
2603
}
2604

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

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

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

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

2630
                if elem != nil {
6✔
2631
                        front := elem.Value.(outgoingMsg)
3✔
2632

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

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

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

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

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

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

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

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

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

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

2730
                snapshot := activeChan.StateSnapshot()
3✔
2731
                snapshots = append(snapshots, snapshot)
3✔
2732

3✔
2733
                return nil
3✔
2734
        })
2735

2736
        return snapshots
3✔
2737
}
2738

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

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

3✔
2758
        return txscript.PayToAddrScript(deliveryAddr)
3✔
2759
}
2760

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

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

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

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

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

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

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

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

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

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

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

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

3✔
2849
                                // Exit if the channel is nil as it's a pending
3✔
2850
                                // channel.
3✔
2851
                                if lc == nil {
6✔
2852
                                        return nil
3✔
2853
                                }
3✔
2854

2855
                                lc.ResetState()
3✔
2856

3✔
2857
                                return nil
3✔
2858
                        })
2859

2860
                        break out
3✔
2861
                }
2862
        }
2863
}
2864

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

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

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

3✔
2883
                switch {
3✔
2884
                // No error occurred, continue to request the next channel.
2885
                case err == nil:
3✔
2886
                        continue
3✔
2887

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

3✔
2894
                        continue
3✔
2895

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

×
2913
                                continue
×
2914
                        }
2915

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

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

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

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

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

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

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

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

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

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

2997
        p.activeChanCloses[chanID] = chanCloser
3✔
2998

3✔
2999
        return chanCloser, nil
3✔
3000
}
3001

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

3✔
3008
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
3✔
3009
                lnChan *lnwallet.LightningChannel) bool {
6✔
3010

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

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

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

3031
                activePublicChans = append(
3✔
3032
                        activePublicChans, dbChan.FundingOutpoint,
3✔
3033
                )
3✔
3034

3✔
3035
                return true
3✔
3036
        })
3037

3038
        return activePublicChans
3✔
3039
}
3040

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

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

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

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

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

3076
                return nil
×
3077
        }
3078

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

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

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

3104
                                continue
×
3105
                        }
3106

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

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

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

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

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

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

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

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

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

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

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

3187
        var deliveryScript []byte
×
3188

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

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

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

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

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

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

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

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

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

3258
        return shutdownMsg, nil
×
3259
}
3260

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

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

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

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

3306
        return chanCloser, nil
3✔
3307
}
3308

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

3✔
3314
        channel, ok := p.activeChannels.Load(chanID)
3✔
3315

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

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

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

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

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

3376
                p.activeChanCloses[chanID] = chanCloser
3✔
3377

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

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

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

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

3411
                link.OnCommitOnce(htlcswitch.Outgoing, func() {
6✔
3412
                        p.queueMsg(shutdownMsg, nil)
3✔
3413
                })
3✔
3414

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
3528
        var chanLink htlcswitch.ChannelUpdateHandler
3✔
3529

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

3540
        return chanLink
3✔
3541
}
3542

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

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

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

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

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

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

3580
        closingTxid := closingTx.TxHash()
3✔
3581

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

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

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

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

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

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

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

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

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

3✔
3656
        p.activeChannels.Delete(chanID)
3✔
3657

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

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

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

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

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

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

3701
        return nil
3✔
3702
}
3703

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

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

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

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

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

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

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

3756
        msg := lnwire.NewInitMessage(
3✔
3757
                legacyFeatures.RawFeatureVector,
3✔
3758
                features.RawFeatureVector,
3✔
3759
        )
3✔
3760

3✔
3761
        return p.writeMessage(msg)
3✔
3762
}
3763

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

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

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

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

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

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

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

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

3✔
3805
        return nil
3✔
3806
}
3807

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

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

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

3849
                if priority {
6✔
3850
                        p.queueMsg(msg, errChan)
3✔
3851
                } else {
6✔
3852
                        p.queueMsgLazy(msg, errChan)
3✔
3853
                }
3✔
3854
        }
3855

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

3869
        return nil
3✔
3870
}
3871

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

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

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

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

3✔
3900
        errChan := make(chan error, 1)
3✔
3901
        newChanMsg := &newChannelMsg{
3✔
3902
                channel: newChan,
3✔
3903
                err:     errChan,
3✔
3904
        }
3✔
3905

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

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

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

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

3✔
3937
        select {
3✔
3938
        case p.newPendingChannel <- newChanMsg:
3✔
3939

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

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

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

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

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

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

3✔
3972
        select {
3✔
3973
        case p.removePendingChannel <- newChanMsg:
3✔
3974
        case <-p.quit:
×
3975
                return lnpeer.ErrPeerExiting
×
3976
        }
3977

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

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

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

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

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

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

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

4021
        handleErr := func(err error) {
4✔
4022
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
4023
                p.log.Error(err)
1✔
4024

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

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

1✔
4034
                p.Disconnect(err)
1✔
4035
        }
4036

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

4047
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
3✔
4048
                if err != nil {
3✔
4049
                        handleErr(err)
×
4050
                        return
×
4051
                }
×
4052

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

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

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

4077
                beginNegotiation := func() {
6✔
4078
                        oClosingSigned, err := chanCloser.BeginNegotiation()
3✔
4079
                        if err != nil {
3✔
4080
                                handleErr(err)
×
4081
                                return
×
4082
                        }
×
4083

4084
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
6✔
4085
                                p.queueMsg(&msg, nil)
3✔
4086
                        })
3✔
4087
                }
4088

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

4102
        case *lnwire.ClosingSigned:
3✔
4103
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
3✔
4104
                if err != nil {
4✔
4105
                        handleErr(err)
1✔
4106
                        return
1✔
4107
                }
1✔
4108

4109
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
6✔
4110
                        p.queueMsg(&msg, nil)
3✔
4111
                })
3✔
4112

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4201
        return pingBytes
×
4202
}
4203

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

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

4225
        p.channelEventClient = sub
3✔
4226

3✔
4227
        return nil
3✔
4228
}
4229

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

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

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

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

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

4260
        p.log.Infof("Processing retransmitted ChannelReady for "+
3✔
4261
                "ChannelPoint(%v)", chanPoint)
3✔
4262

3✔
4263
        nextRevoke := c.RemoteNextRevocation
3✔
4264

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

4270
        return nil
3✔
4271
}
4272

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

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

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

4295
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
3✔
4296
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
4297
        })
×
4298
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
3✔
4299
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
4300
        })
×
4301
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
3✔
4302
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
4303
        })
×
4304

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

4315
        // Store the channel in the activeChannels map.
4316
        p.activeChannels.Store(chanID, lnChan)
3✔
4317

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

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

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

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

4346
        return nil
3✔
4347
}
4348

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

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

3✔
4364
                // Handle it and close the err chan on the request.
3✔
4365
                close(req.err)
3✔
4366

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

4373
                return
3✔
4374
        }
4375

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

×
4382
                return
×
4383
        }
×
4384

4385
        // Close the err chan if everything went fine.
4386
        close(req.err)
3✔
4387
}
4388

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

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

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

×
UNCOV
4406
                return
×
UNCOV
4407
        }
×
4408

4409
        // The channel has already been added, we will do nothing and return.
4410
        if p.isPendingChannel(chanID) {
3✔
UNCOV
4411
                p.log.Infof("Channel(%v) is already added, ignoring "+
×
UNCOV
4412
                        "pending channel request", chanID)
×
UNCOV
4413

×
UNCOV
4414
                return
×
UNCOV
4415
        }
×
4416

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

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

3✔
4430
        chanID := req.channelID
3✔
4431

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

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

4447
        // Remove the record of this pending channel.
4448
        p.activeChannels.Delete(chanID)
3✔
4449
        p.addedChannels.Delete(chanID)
3✔
4450
}
4451

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

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

3✔
4465
                // Stop the stream when quit.
3✔
4466
                go func() {
6✔
4467
                        <-p.quit
3✔
4468
                        chanStream.Stop()
3✔
4469
                }()
3✔
4470
        }
4471

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

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

UNCOV
4486
        return timeout
×
4487
}
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