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

lightningnetwork / lnd / 10909621672

17 Sep 2024 07:18PM UTC coverage: 58.705% (+0.2%) from 58.519%
10909621672

Pull #9111

github

web-flow
Fix links to resolve issue in Builder's Guide (https and redirect)

There are some links in this document that cause issues for pull request [#670](https://github.com/lightninglabs/docs.lightning.engineering/pull/670) in the Builder's Guide Repo.
Pull Request #9111: Fix links to resolve issue in Builder's Guide (https and redirect)

128053 of 218129 relevant lines covered (58.71%)

28251.8 hits per line

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

78.52
/peer/brontide.go
1
package peer
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

120
        err chan error
121
}
122

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

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

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

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

148
// TimestampedError is a timestamped error that is used to store the most recent
149
// errors we have experienced with our peers.
150
type TimestampedError struct {
151
        Error     error
152
        Timestamp time.Time
153
}
154

155
// Config defines configuration fields that are necessary for a peer object
156
// to function.
157
type Config struct {
158
        // Conn is the underlying network connection for this peer.
159
        Conn MessageConn
160

161
        // ConnReq stores information related to the persistent connection request
162
        // for this peer.
163
        ConnReq *connmgr.ConnReq
164

165
        // PubKeyBytes is the serialized, compressed public key of this peer.
166
        PubKeyBytes [33]byte
167

168
        // Addr is the network address of the peer.
169
        Addr *lnwire.NetAddress
170

171
        // Inbound indicates whether or not the peer is an inbound peer.
172
        Inbound bool
173

174
        // Features is the set of features that we advertise to the remote party.
175
        Features *lnwire.FeatureVector
176

177
        // LegacyFeatures is the set of features that we advertise to the remote
178
        // peer for backwards compatibility. Nodes that have not implemented
179
        // flat features will still be able to read our feature bits from the
180
        // legacy global field, but we will also advertise everything in the
181
        // default features field.
182
        LegacyFeatures *lnwire.FeatureVector
183

184
        // OutgoingCltvRejectDelta defines the number of blocks before expiry of
185
        // an htlc where we don't offer it anymore.
186
        OutgoingCltvRejectDelta uint32
187

188
        // ChanActiveTimeout specifies the duration the peer will wait to request
189
        // a channel reenable, beginning from the time the peer was started.
190
        ChanActiveTimeout time.Duration
191

192
        // ErrorBuffer stores a set of errors related to a peer. It contains error
193
        // messages that our peer has recently sent us over the wire and records of
194
        // unknown messages that were sent to us so that we can have a full track
195
        // record of the communication errors we have had with our peer. If we
196
        // choose to disconnect from a peer, it also stores the reason we had for
197
        // disconnecting.
198
        ErrorBuffer *queue.CircularBuffer
199

200
        // WritePool is the task pool that manages reuse of write buffers. Write
201
        // tasks are submitted to the pool in order to conserve the total number of
202
        // write buffers allocated at any one time, and decouple write buffer
203
        // allocation from the peer life cycle.
204
        WritePool *pool.Write
205

206
        // ReadPool is the task pool that manages reuse of read buffers.
207
        ReadPool *pool.Read
208

209
        // Switch is a pointer to the htlcswitch. It is used to setup, get, and
210
        // tear-down ChannelLinks.
211
        Switch messageSwitch
212

213
        // InterceptSwitch is a pointer to the InterceptableSwitch, a wrapper around
214
        // the regular Switch. We only export it here to pass ForwardPackets to the
215
        // ChannelLinkConfig.
216
        InterceptSwitch *htlcswitch.InterceptableSwitch
217

218
        // ChannelDB is used to fetch opened channels, and closed channels.
219
        ChannelDB *channeldb.ChannelStateDB
220

221
        // ChannelGraph is a pointer to the channel graph which is used to
222
        // query information about the set of known active channels.
223
        ChannelGraph *channeldb.ChannelGraph
224

225
        // ChainArb is used to subscribe to channel events, update contract signals,
226
        // and force close channels.
227
        ChainArb *contractcourt.ChainArbitrator
228

229
        // AuthGossiper is needed so that the Brontide impl can register with the
230
        // gossiper and process remote channel announcements.
231
        AuthGossiper *discovery.AuthenticatedGossiper
232

233
        // ChanStatusMgr is used to set or un-set the disabled bit in channel
234
        // updates.
235
        ChanStatusMgr *netann.ChanStatusManager
236

237
        // ChainIO is used to retrieve the best block.
238
        ChainIO lnwallet.BlockChainIO
239

240
        // FeeEstimator is used to compute our target ideal fee-per-kw when
241
        // initializing the coop close process.
242
        FeeEstimator chainfee.Estimator
243

244
        // Signer is used when creating *lnwallet.LightningChannel instances.
245
        Signer input.Signer
246

247
        // SigPool is used when creating *lnwallet.LightningChannel instances.
248
        SigPool *lnwallet.SigPool
249

250
        // Wallet is used to publish transactions and generates delivery
251
        // scripts during the coop close process.
252
        Wallet *lnwallet.LightningWallet
253

254
        // ChainNotifier is used to receive confirmations of a coop close
255
        // transaction.
256
        ChainNotifier chainntnfs.ChainNotifier
257

258
        // BestBlockView is used to efficiently query for up-to-date
259
        // blockchain state information
260
        BestBlockView chainntnfs.BestBlockView
261

262
        // RoutingPolicy is used to set the forwarding policy for links created by
263
        // the Brontide.
264
        RoutingPolicy models.ForwardingPolicy
265

266
        // Sphinx is used when setting up ChannelLinks so they can decode sphinx
267
        // onion blobs.
268
        Sphinx *hop.OnionProcessor
269

270
        // WitnessBeacon is used when setting up ChannelLinks so they can add any
271
        // preimages that they learn.
272
        WitnessBeacon contractcourt.WitnessBeacon
273

274
        // Invoices is passed to the ChannelLink on creation and handles all
275
        // invoice-related logic.
276
        Invoices *invoices.InvoiceRegistry
277

278
        // ChannelNotifier is used by the link to notify other sub-systems about
279
        // channel-related events and by the Brontide to subscribe to
280
        // ActiveLinkEvents.
281
        ChannelNotifier *channelnotifier.ChannelNotifier
282

283
        // HtlcNotifier is used when creating a ChannelLink.
284
        HtlcNotifier *htlcswitch.HtlcNotifier
285

286
        // TowerClient is used to backup revoked states.
287
        TowerClient wtclient.ClientManager
288

289
        // DisconnectPeer is used to disconnect this peer if the cooperative close
290
        // process fails.
291
        DisconnectPeer func(*btcec.PublicKey) error
292

293
        // GenNodeAnnouncement is used to send our node announcement to the remote
294
        // on startup.
295
        GenNodeAnnouncement func(...netann.NodeAnnModifier) (
296
                lnwire.NodeAnnouncement, error)
297

298
        // PrunePersistentPeerConnection is used to remove all internal state
299
        // related to this peer in the server.
300
        PrunePersistentPeerConnection func([33]byte)
301

302
        // FetchLastChanUpdate fetches our latest channel update for a target
303
        // channel.
304
        FetchLastChanUpdate func(lnwire.ShortChannelID) (*lnwire.ChannelUpdate,
305
                error)
306

307
        // FundingManager is an implementation of the funding.Controller interface.
308
        FundingManager funding.Controller
309

310
        // Hodl is used when creating ChannelLinks to specify HodlFlags as
311
        // breakpoints in dev builds.
312
        Hodl *hodl.Config
313

314
        // UnsafeReplay is used when creating ChannelLinks to specify whether or
315
        // not to replay adds on its commitment tx.
316
        UnsafeReplay bool
317

318
        // MaxOutgoingCltvExpiry is used when creating ChannelLinks and is the max
319
        // number of blocks that funds could be locked up for when forwarding
320
        // payments.
321
        MaxOutgoingCltvExpiry uint32
322

323
        // MaxChannelFeeAllocation is used when creating ChannelLinks and is the
324
        // maximum percentage of total funds that can be allocated to a channel's
325
        // commitment fee. This only applies for the initiator of the channel.
326
        MaxChannelFeeAllocation float64
327

328
        // MaxAnchorsCommitFeeRate is the maximum fee rate we'll use as an
329
        // initiator for anchor channel commitments.
330
        MaxAnchorsCommitFeeRate chainfee.SatPerKWeight
331

332
        // CoopCloseTargetConfs is the confirmation target that will be used
333
        // to estimate the fee rate to use during a cooperative channel
334
        // closure initiated by the remote peer.
335
        CoopCloseTargetConfs uint32
336

337
        // ServerPubKey is the serialized, compressed public key of our lnd node.
338
        // It is used to determine which policy (channel edge) to pass to the
339
        // ChannelLink.
340
        ServerPubKey [33]byte
341

342
        // ChannelCommitInterval is the maximum time that is allowed to pass between
343
        // receiving a channel state update and signing the next commitment.
344
        // Setting this to a longer duration allows for more efficient channel
345
        // operations at the cost of latency.
346
        ChannelCommitInterval time.Duration
347

348
        // PendingCommitInterval is the maximum time that is allowed to pass
349
        // while waiting for the remote party to revoke a locally initiated
350
        // commitment state. Setting this to a longer duration if a slow
351
        // response is expected from the remote party or large number of
352
        // payments are attempted at the same time.
353
        PendingCommitInterval time.Duration
354

355
        // ChannelCommitBatchSize is the maximum number of channel state updates
356
        // that is accumulated before signing a new commitment.
357
        ChannelCommitBatchSize uint32
358

359
        // HandleCustomMessage is called whenever a custom message is received
360
        // from the peer.
361
        HandleCustomMessage func(peer [33]byte, msg *lnwire.Custom) error
362

363
        // GetAliases is passed to created links so the Switch and link can be
364
        // aware of the channel's aliases.
365
        GetAliases func(base lnwire.ShortChannelID) []lnwire.ShortChannelID
366

367
        // RequestAlias allows the Brontide struct to request an alias to send
368
        // to the peer.
369
        RequestAlias func() (lnwire.ShortChannelID, error)
370

371
        // AddLocalAlias persists an alias to an underlying alias store.
372
        AddLocalAlias func(alias, base lnwire.ShortChannelID,
373
                gossip, liveUpdate bool) error
374

375
        // AuxLeafStore is an optional store that can be used to store auxiliary
376
        // leaves for certain custom channel types.
377
        AuxLeafStore fn.Option[lnwallet.AuxLeafStore]
378

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

385
        // Adds the option to disable forwarding payments in blinded routes
386
        // by failing back any blinding-related payloads as if they were
387
        // invalid.
388
        DisallowRouteBlinding bool
389

390
        // MaxFeeExposure limits the number of outstanding fees in a channel.
391
        // This value will be passed to created links.
392
        MaxFeeExposure lnwire.MilliSatoshi
393

394
        // MsgRouter is an optional instance of the main message router that
395
        // the peer will use. If None, then a new default version will be used
396
        // in place.
397
        MsgRouter fn.Option[msgmux.Router]
398

399
        // Quit is the server's quit channel. If this is closed, we halt operation.
400
        Quit chan struct{}
401
}
402

403
// Brontide is an active peer on the Lightning Network. This struct is responsible
404
// for managing any channel state related to this peer. To do so, it has
405
// several helper goroutines to handle events such as HTLC timeouts, new
406
// funding workflow, and detecting an uncooperative closure of any active
407
// channels.
408
// TODO(roasbeef): proper reconnection logic.
409
type Brontide struct {
410
        // MUST be used atomically.
411
        started    int32
412
        disconnect int32
413

414
        // MUST be used atomically.
415
        bytesReceived uint64
416
        bytesSent     uint64
417

418
        // isTorConnection is a flag that indicates whether or not we believe
419
        // the remote peer is a tor connection. It is not always possible to
420
        // know this with certainty but we have heuristics we use that should
421
        // catch most cases.
422
        //
423
        // NOTE: We judge the tor-ness of a connection by if the remote peer has
424
        // ".onion" in the address OR if it's connected over localhost.
425
        // This will miss cases where our peer is connected to our clearnet
426
        // address over the tor network (via exit nodes). It will also misjudge
427
        // actual localhost connections as tor. We need to include this because
428
        // inbound connections to our tor address will appear to come from the
429
        // local socks5 proxy. This heuristic is only used to expand the timeout
430
        // window for peers so it is OK to misjudge this. If you use this field
431
        // for any other purpose you should seriously consider whether or not
432
        // this heuristic is good enough for your use case.
433
        isTorConnection bool
434

435
        pingManager *PingManager
436

437
        // lastPingPayload stores an unsafe pointer wrapped as an atomic
438
        // variable which points to the last payload the remote party sent us
439
        // as their ping.
440
        //
441
        // MUST be used atomically.
442
        lastPingPayload atomic.Value
443

444
        cfg Config
445

446
        // activeSignal when closed signals that the peer is now active and
447
        // ready to process messages.
448
        activeSignal chan struct{}
449

450
        // startTime is the time this peer connection was successfully established.
451
        // It will be zero for peers that did not successfully call Start().
452
        startTime time.Time
453

454
        // sendQueue is the channel which is used to queue outgoing messages to be
455
        // written onto the wire. Note that this channel is unbuffered.
456
        sendQueue chan outgoingMsg
457

458
        // outgoingQueue is a buffered channel which allows second/third party
459
        // objects to queue messages to be sent out on the wire.
460
        outgoingQueue chan outgoingMsg
461

462
        // activeChannels is a map which stores the state machines of all
463
        // active channels. Channels are indexed into the map by the txid of
464
        // the funding transaction which opened the channel.
465
        //
466
        // NOTE: On startup, pending channels are stored as nil in this map.
467
        // Confirmed channels have channel data populated in the map. This means
468
        // that accesses to this map should nil-check the LightningChannel to
469
        // see if this is a pending channel or not. The tradeoff here is either
470
        // having two maps everywhere (one for pending, one for confirmed chans)
471
        // or having an extra nil-check per access.
472
        activeChannels *lnutils.SyncMap[
473
                lnwire.ChannelID, *lnwallet.LightningChannel]
474

475
        // addedChannels tracks any new channels opened during this peer's
476
        // lifecycle. We use this to filter out these new channels when the time
477
        // comes to request a reenable for active channels, since they will have
478
        // waited a shorter duration.
479
        addedChannels *lnutils.SyncMap[lnwire.ChannelID, struct{}]
480

481
        // newActiveChannel is used by the fundingManager to send fully opened
482
        // channels to the source peer which handled the funding workflow.
483
        newActiveChannel chan *newChannelMsg
484

485
        // newPendingChannel is used by the fundingManager to send pending open
486
        // channels to the source peer which handled the funding workflow.
487
        newPendingChannel chan *newChannelMsg
488

489
        // removePendingChannel is used by the fundingManager to cancel pending
490
        // open channels to the source peer when the funding flow is failed.
491
        removePendingChannel chan *newChannelMsg
492

493
        // activeMsgStreams is a map from channel id to the channel streams that
494
        // proxy messages to individual, active links.
495
        activeMsgStreams map[lnwire.ChannelID]*msgStream
496

497
        // activeChanCloses is a map that keeps track of all the active
498
        // cooperative channel closures. Any channel closing messages are directed
499
        // to one of these active state machines. Once the channel has been closed,
500
        // the state machine will be deleted from the map.
501
        activeChanCloses map[lnwire.ChannelID]*chancloser.ChanCloser
502

503
        // localCloseChanReqs is a channel in which any local requests to close
504
        // a particular channel are sent over.
505
        localCloseChanReqs chan *htlcswitch.ChanClose
506

507
        // linkFailures receives all reported channel failures from the switch,
508
        // and instructs the channelManager to clean remaining channel state.
509
        linkFailures chan linkFailureReport
510

511
        // chanCloseMsgs is a channel that any message related to channel
512
        // closures are sent over. This includes lnwire.Shutdown message as
513
        // well as lnwire.ClosingSigned messages.
514
        chanCloseMsgs chan *closeMsg
515

516
        // remoteFeatures is the feature vector received from the peer during
517
        // the connection handshake.
518
        remoteFeatures *lnwire.FeatureVector
519

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

526
        // channelEventClient is the channel event subscription client that's
527
        // used to assist retry enabling the channels. This client is only
528
        // created when the reenableTimeout is no greater than 1 minute. Once
529
        // created, it is canceled once the reenabling has been finished.
530
        //
531
        // NOTE: we choose to create the client conditionally to avoid
532
        // potentially holding lots of un-consumed events.
533
        channelEventClient *subscribe.Client
534

535
        // msgRouter is an instance of the msgmux.Router which is used to send
536
        // off new wire messages for handing.
537
        msgRouter fn.Option[msgmux.Router]
538

539
        // globalMsgRouter is a flag that indicates whether we have a global
540
        // msg router. If so, then we don't worry about stopping the msg router
541
        // when a peer disconnects.
542
        globalMsgRouter bool
543

544
        startReady chan struct{}
545
        quit       chan struct{}
546
        wg         sync.WaitGroup
547

548
        // log is a peer-specific logging instance.
549
        log btclog.Logger
550
}
551

552
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer interface.
553
var _ lnpeer.Peer = (*Brontide)(nil)
554

555
// NewBrontide creates a new Brontide from a peer.Config struct.
556
func NewBrontide(cfg Config) *Brontide {
28✔
557
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
28✔
558

28✔
559
        // We have a global message router if one was passed in via the config.
28✔
560
        // In this case, we don't need to attempt to tear it down when the peer
28✔
561
        // is stopped.
28✔
562
        globalMsgRouter := cfg.MsgRouter.IsSome()
28✔
563

28✔
564
        // We'll either use the msg router instance passed in, or create a new
28✔
565
        // blank instance.
28✔
566
        msgRouter := cfg.MsgRouter.Alt(fn.Some[msgmux.Router](
28✔
567
                msgmux.NewMultiMsgRouter(),
28✔
568
        ))
28✔
569

28✔
570
        p := &Brontide{
28✔
571
                cfg:           cfg,
28✔
572
                activeSignal:  make(chan struct{}),
28✔
573
                sendQueue:     make(chan outgoingMsg),
28✔
574
                outgoingQueue: make(chan outgoingMsg),
28✔
575
                addedChannels: &lnutils.SyncMap[lnwire.ChannelID, struct{}]{},
28✔
576
                activeChannels: &lnutils.SyncMap[
28✔
577
                        lnwire.ChannelID, *lnwallet.LightningChannel,
28✔
578
                ]{},
28✔
579
                newActiveChannel:     make(chan *newChannelMsg, 1),
28✔
580
                newPendingChannel:    make(chan *newChannelMsg, 1),
28✔
581
                removePendingChannel: make(chan *newChannelMsg),
28✔
582

28✔
583
                activeMsgStreams:   make(map[lnwire.ChannelID]*msgStream),
28✔
584
                activeChanCloses:   make(map[lnwire.ChannelID]*chancloser.ChanCloser),
28✔
585
                localCloseChanReqs: make(chan *htlcswitch.ChanClose),
28✔
586
                linkFailures:       make(chan linkFailureReport),
28✔
587
                chanCloseMsgs:      make(chan *closeMsg),
28✔
588
                resentChanSyncMsg:  make(map[lnwire.ChannelID]struct{}),
28✔
589
                startReady:         make(chan struct{}),
28✔
590
                quit:               make(chan struct{}),
28✔
591
                log:                build.NewPrefixLog(logPrefix, peerLog),
28✔
592
                msgRouter:          msgRouter,
28✔
593
                globalMsgRouter:    globalMsgRouter,
28✔
594
        }
28✔
595

28✔
596
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
31✔
597
                remoteAddr := cfg.Conn.RemoteAddr().String()
3✔
598
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
3✔
599
                        strings.Contains(remoteAddr, "127.0.0.1")
3✔
600
        }
3✔
601

602
        var (
28✔
603
                lastBlockHeader           *wire.BlockHeader
28✔
604
                lastSerializedBlockHeader [wire.MaxBlockHeaderPayload]byte
28✔
605
        )
28✔
606
        newPingPayload := func() []byte {
30✔
607
                // We query the BestBlockHeader from our BestBlockView each time
2✔
608
                // this is called, and update our serialized block header if
2✔
609
                // they differ.  Over time, we'll use this to disseminate the
2✔
610
                // latest block header between all our peers, which can later be
2✔
611
                // used to cross-check our own view of the network to mitigate
2✔
612
                // various types of eclipse attacks.
2✔
613
                header, err := p.cfg.BestBlockView.BestBlockHeader()
2✔
614
                if err != nil && header == lastBlockHeader {
2✔
615
                        return lastSerializedBlockHeader[:]
×
616
                }
×
617

618
                buf := bytes.NewBuffer(lastSerializedBlockHeader[0:0])
2✔
619
                err = header.Serialize(buf)
2✔
620
                if err == nil {
4✔
621
                        lastBlockHeader = header
2✔
622
                } else {
2✔
623
                        p.log.Warn("unable to serialize current block" +
×
624
                                "header for ping payload generation." +
×
625
                                "This should be impossible and means" +
×
626
                                "there is an implementation bug.")
×
627
                }
×
628

629
                return lastSerializedBlockHeader[:]
2✔
630
        }
631

632
        // TODO(roasbeef): make dynamic in order to create fake cover traffic.
633
        //
634
        // NOTE(proofofkeags): this was changed to be dynamic to allow better
635
        // pong identification, however, more thought is needed to make this
636
        // actually usable as a traffic decoy.
637
        randPongSize := func() uint16 {
30✔
638
                return uint16(
2✔
639
                        // We don't need cryptographic randomness here.
2✔
640
                        /* #nosec */
2✔
641
                        rand.Intn(pongSizeCeiling) + 1,
2✔
642
                )
2✔
643
        }
2✔
644

645
        p.pingManager = NewPingManager(&PingManagerConfig{
28✔
646
                NewPingPayload:   newPingPayload,
28✔
647
                NewPongSize:      randPongSize,
28✔
648
                IntervalDuration: p.scaleTimeout(pingInterval),
28✔
649
                TimeoutDuration:  p.scaleTimeout(pingTimeout),
28✔
650
                SendPing: func(ping *lnwire.Ping) {
30✔
651
                        p.queueMsg(ping, nil)
2✔
652
                },
2✔
653
                OnPongFailure: func(err error) {
×
654
                        eStr := "pong response failure for %s: %v " +
×
655
                                "-- disconnecting"
×
656
                        p.log.Warnf(eStr, p, err)
×
657
                        go p.Disconnect(fmt.Errorf(eStr, p, err))
×
658
                },
×
659
        })
660

661
        return p
28✔
662
}
663

664
// Start starts all helper goroutines the peer needs for normal operations.  In
665
// the case this peer has already been started, then this function is a noop.
666
func (p *Brontide) Start() error {
6✔
667
        if atomic.AddInt32(&p.started, 1) != 1 {
6✔
668
                return nil
×
669
        }
×
670

671
        // Once we've finished starting up the peer, we'll signal to other
672
        // goroutines that the they can move forward to tear down the peer, or
673
        // carry out other relevant changes.
674
        defer close(p.startReady)
6✔
675

6✔
676
        p.log.Tracef("starting with conn[%v->%v]",
6✔
677
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
6✔
678

6✔
679
        // Fetch and then load all the active channels we have with this remote
6✔
680
        // peer from the database.
6✔
681
        activeChans, err := p.cfg.ChannelDB.FetchOpenChannels(
6✔
682
                p.cfg.Addr.IdentityKey,
6✔
683
        )
6✔
684
        if err != nil {
6✔
685
                p.log.Errorf("Unable to fetch active chans "+
×
686
                        "for peer: %v", err)
×
687
                return err
×
688
        }
×
689

690
        if len(activeChans) == 0 {
10✔
691
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
4✔
692
        }
4✔
693

694
        // Quickly check if we have any existing legacy channels with this
695
        // peer.
696
        haveLegacyChan := false
6✔
697
        for _, c := range activeChans {
11✔
698
                if c.ChanType.IsTweakless() {
10✔
699
                        continue
5✔
700
                }
701

702
                haveLegacyChan = true
3✔
703
                break
3✔
704
        }
705

706
        // Exchange local and global features, the init message should be very
707
        // first between two nodes.
708
        if err := p.sendInitMsg(haveLegacyChan); err != nil {
6✔
709
                return fmt.Errorf("unable to send init msg: %w", err)
×
710
        }
×
711

712
        // Before we launch any of the helper goroutines off the peer struct,
713
        // we'll first ensure proper adherence to the p2p protocol. The init
714
        // message MUST be sent before any other message.
715
        readErr := make(chan error, 1)
6✔
716
        msgChan := make(chan lnwire.Message, 1)
6✔
717
        p.wg.Add(1)
6✔
718
        go func() {
12✔
719
                defer p.wg.Done()
6✔
720

6✔
721
                msg, err := p.readNextMessage()
6✔
722
                if err != nil {
8✔
723
                        readErr <- err
2✔
724
                        msgChan <- nil
2✔
725
                        return
2✔
726
                }
2✔
727
                readErr <- nil
6✔
728
                msgChan <- msg
6✔
729
        }()
730

731
        select {
6✔
732
        // In order to avoid blocking indefinitely, we'll give the other peer
733
        // an upper timeout to respond before we bail out early.
734
        case <-time.After(handshakeTimeout):
×
735
                return fmt.Errorf("peer did not complete handshake within %v",
×
736
                        handshakeTimeout)
×
737
        case err := <-readErr:
6✔
738
                if err != nil {
8✔
739
                        return fmt.Errorf("unable to read init msg: %w", err)
2✔
740
                }
2✔
741
        }
742

743
        // Once the init message arrives, we can parse it so we can figure out
744
        // the negotiation of features for this session.
745
        msg := <-msgChan
6✔
746
        if msg, ok := msg.(*lnwire.Init); ok {
12✔
747
                if err := p.handleInitMsg(msg); err != nil {
6✔
748
                        p.storeError(err)
×
749
                        return err
×
750
                }
×
751
        } else {
×
752
                return errors.New("very first message between nodes " +
×
753
                        "must be init message")
×
754
        }
×
755

756
        // Next, load all the active channels we have with this peer,
757
        // registering them with the switch and launching the necessary
758
        // goroutines required to operate them.
759
        p.log.Debugf("Loaded %v active channels from database",
6✔
760
                len(activeChans))
6✔
761

6✔
762
        // Conditionally subscribe to channel events before loading channels so
6✔
763
        // we won't miss events. This subscription is used to listen to active
6✔
764
        // channel event when reenabling channels. Once the reenabling process
6✔
765
        // is finished, this subscription will be canceled.
6✔
766
        //
6✔
767
        // NOTE: ChannelNotifier must be started before subscribing events
6✔
768
        // otherwise we'd panic here.
6✔
769
        if err := p.attachChannelEventSubscription(); err != nil {
6✔
770
                return err
×
771
        }
×
772

773
        // Register the message router now as we may need to register some
774
        // endpoints while loading the channels below.
775
        p.msgRouter.WhenSome(func(router msgmux.Router) {
12✔
776
                router.Start()
6✔
777
        })
6✔
778

779
        msgs, err := p.loadActiveChannels(activeChans)
6✔
780
        if err != nil {
6✔
781
                return fmt.Errorf("unable to load channels: %w", err)
×
782
        }
×
783

784
        p.startTime = time.Now()
6✔
785

6✔
786
        // Before launching the writeHandler goroutine, we send any channel
6✔
787
        // sync messages that must be resent for borked channels. We do this to
6✔
788
        // avoid data races with WriteMessage & Flush calls.
6✔
789
        if len(msgs) > 0 {
11✔
790
                p.log.Infof("Sending %d channel sync messages to peer after "+
5✔
791
                        "loading active channels", len(msgs))
5✔
792

5✔
793
                // Send the messages directly via writeMessage and bypass the
5✔
794
                // writeHandler goroutine.
5✔
795
                for _, msg := range msgs {
10✔
796
                        if err := p.writeMessage(msg); err != nil {
5✔
797
                                return fmt.Errorf("unable to send "+
×
798
                                        "reestablish msg: %v", err)
×
799
                        }
×
800
                }
801
        }
802

803
        err = p.pingManager.Start()
6✔
804
        if err != nil {
6✔
805
                return fmt.Errorf("could not start ping manager %w", err)
×
806
        }
×
807

808
        p.wg.Add(4)
6✔
809
        go p.queueHandler()
6✔
810
        go p.writeHandler()
6✔
811
        go p.channelManager()
6✔
812
        go p.readHandler()
6✔
813

6✔
814
        // Signal to any external processes that the peer is now active.
6✔
815
        close(p.activeSignal)
6✔
816

6✔
817
        // Node announcements don't propagate very well throughout the network
6✔
818
        // as there isn't a way to efficiently query for them through their
6✔
819
        // timestamp, mostly affecting nodes that were offline during the time
6✔
820
        // of broadcast. We'll resend our node announcement to the remote peer
6✔
821
        // as a best-effort delivery such that it can also propagate to their
6✔
822
        // peers. To ensure they can successfully process it in most cases,
6✔
823
        // we'll only resend it as long as we have at least one confirmed
6✔
824
        // advertised channel with the remote peer.
6✔
825
        //
6✔
826
        // TODO(wilmer): Remove this once we're able to query for node
6✔
827
        // announcements through their timestamps.
6✔
828
        p.wg.Add(2)
6✔
829
        go p.maybeSendNodeAnn(activeChans)
6✔
830
        go p.maybeSendChannelUpdates()
6✔
831

6✔
832
        return nil
6✔
833
}
834

835
// initGossipSync initializes either a gossip syncer or an initial routing
836
// dump, depending on the negotiated synchronization method.
837
func (p *Brontide) initGossipSync() {
6✔
838
        // If the remote peer knows of the new gossip queries feature, then
6✔
839
        // we'll create a new gossipSyncer in the AuthenticatedGossiper for it.
6✔
840
        if p.remoteFeatures.HasFeature(lnwire.GossipQueriesOptional) {
12✔
841
                p.log.Info("Negotiated chan series queries")
6✔
842

6✔
843
                if p.cfg.AuthGossiper == nil {
9✔
844
                        // This should only ever be hit in the unit tests.
3✔
845
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
3✔
846
                                "gossip sync.")
3✔
847
                        return
3✔
848
                }
3✔
849

850
                // Register the peer's gossip syncer with the gossiper.
851
                // This blocks synchronously to ensure the gossip syncer is
852
                // registered with the gossiper before attempting to read
853
                // messages from the remote peer.
854
                //
855
                // TODO(wilmer): Only sync updates from non-channel peers. This
856
                // requires an improved version of the current network
857
                // bootstrapper to ensure we can find and connect to non-channel
858
                // peers.
859
                p.cfg.AuthGossiper.InitSyncState(p)
3✔
860
        }
861
}
862

863
// taprootShutdownAllowed returns true if both parties have negotiated the
864
// shutdown-any-segwit feature.
865
func (p *Brontide) taprootShutdownAllowed() bool {
9✔
866
        return p.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
9✔
867
                p.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
9✔
868
}
9✔
869

870
// QuitSignal is a method that should return a channel which will be sent upon
871
// or closed once the backing peer exits. This allows callers using the
872
// interface to cancel any processing in the event the backing implementation
873
// exits.
874
//
875
// NOTE: Part of the lnpeer.Peer interface.
876
func (p *Brontide) QuitSignal() <-chan struct{} {
3✔
877
        return p.quit
3✔
878
}
3✔
879

880
// loadActiveChannels creates indexes within the peer for tracking all active
881
// channels returned by the database. It returns a slice of channel reestablish
882
// messages that should be sent to the peer immediately, in case we have borked
883
// channels that haven't been closed yet.
884
func (p *Brontide) loadActiveChannels(chans []*channeldb.OpenChannel) (
885
        []lnwire.Message, error) {
6✔
886

6✔
887
        // Return a slice of messages to send to the peers in case the channel
6✔
888
        // cannot be loaded normally.
6✔
889
        var msgs []lnwire.Message
6✔
890

6✔
891
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
6✔
892

6✔
893
        for _, dbChan := range chans {
11✔
894
                hasScidFeature := dbChan.ChanType.HasScidAliasFeature()
5✔
895
                if scidAliasNegotiated && !hasScidFeature {
8✔
896
                        // We'll request and store an alias, making sure that a
3✔
897
                        // gossiper mapping is not created for the alias to the
3✔
898
                        // real SCID. This is done because the peer and funding
3✔
899
                        // manager are not aware of each other's states and if
3✔
900
                        // we did not do this, we would accept alias channel
3✔
901
                        // updates after 6 confirmations, which would be buggy.
3✔
902
                        // We'll queue a channel_ready message with the new
3✔
903
                        // alias. This should technically be done *after* the
3✔
904
                        // reestablish, but this behavior is pre-existing since
3✔
905
                        // the funding manager may already queue a
3✔
906
                        // channel_ready before the channel_reestablish.
3✔
907
                        if !dbChan.IsPending {
6✔
908
                                aliasScid, err := p.cfg.RequestAlias()
3✔
909
                                if err != nil {
3✔
910
                                        return nil, err
×
911
                                }
×
912

913
                                err = p.cfg.AddLocalAlias(
3✔
914
                                        aliasScid, dbChan.ShortChanID(), false,
3✔
915
                                        false,
3✔
916
                                )
3✔
917
                                if err != nil {
3✔
918
                                        return nil, err
×
919
                                }
×
920

921
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
922
                                        dbChan.FundingOutpoint,
3✔
923
                                )
3✔
924

3✔
925
                                // Fetch the second commitment point to send in
3✔
926
                                // the channel_ready message.
3✔
927
                                second, err := dbChan.SecondCommitmentPoint()
3✔
928
                                if err != nil {
3✔
929
                                        return nil, err
×
930
                                }
×
931

932
                                channelReadyMsg := lnwire.NewChannelReady(
3✔
933
                                        chanID, second,
3✔
934
                                )
3✔
935
                                channelReadyMsg.AliasScid = &aliasScid
3✔
936

3✔
937
                                msgs = append(msgs, channelReadyMsg)
3✔
938
                        }
939

940
                        // If we've negotiated the option-scid-alias feature
941
                        // and this channel does not have ScidAliasFeature set
942
                        // to true due to an upgrade where the feature bit was
943
                        // turned on, we'll update the channel's database
944
                        // state.
945
                        err := dbChan.MarkScidAliasNegotiated()
3✔
946
                        if err != nil {
3✔
947
                                return nil, err
×
948
                        }
×
949
                }
950

951
                var chanOpts []lnwallet.ChannelOpt
5✔
952
                p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
5✔
953
                        chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
954
                })
×
955
                lnChan, err := lnwallet.NewLightningChannel(
5✔
956
                        p.cfg.Signer, dbChan, p.cfg.SigPool, chanOpts...,
5✔
957
                )
5✔
958
                if err != nil {
5✔
959
                        return nil, fmt.Errorf("unable to create channel "+
×
960
                                "state machine: %w", err)
×
961
                }
×
962

963
                chanPoint := dbChan.FundingOutpoint
5✔
964

5✔
965
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
5✔
966

5✔
967
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
5✔
968
                        chanPoint, lnChan.IsPending())
5✔
969

5✔
970
                // Skip adding any permanently irreconcilable channels to the
5✔
971
                // htlcswitch.
5✔
972
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
5✔
973
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
10✔
974

5✔
975
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
5✔
976
                                "start.", chanPoint, dbChan.ChanStatus())
5✔
977

5✔
978
                        // To help our peer recover from a potential data loss,
5✔
979
                        // we resend our channel reestablish message if the
5✔
980
                        // channel is in a borked state. We won't process any
5✔
981
                        // channel reestablish message sent from the peer, but
5✔
982
                        // that's okay since the assumption is that we did when
5✔
983
                        // marking the channel borked.
5✔
984
                        chanSync, err := dbChan.ChanSyncMsg()
5✔
985
                        if err != nil {
5✔
986
                                p.log.Errorf("Unable to create channel "+
×
987
                                        "reestablish message for channel %v: "+
×
988
                                        "%v", chanPoint, err)
×
989
                                continue
×
990
                        }
991

992
                        msgs = append(msgs, chanSync)
5✔
993

5✔
994
                        // Check if this channel needs to have the cooperative
5✔
995
                        // close process restarted. If so, we'll need to send
5✔
996
                        // the Shutdown message that is returned.
5✔
997
                        if dbChan.HasChanStatus(
5✔
998
                                channeldb.ChanStatusCoopBroadcasted,
5✔
999
                        ) {
5✔
1000

×
1001
                                shutdownMsg, err := p.restartCoopClose(lnChan)
×
1002
                                if err != nil {
×
1003
                                        p.log.Errorf("Unable to restart "+
×
1004
                                                "coop close for channel: %v",
×
1005
                                                err)
×
1006
                                        continue
×
1007
                                }
1008

1009
                                if shutdownMsg == nil {
×
1010
                                        continue
×
1011
                                }
1012

1013
                                // Append the message to the set of messages to
1014
                                // send.
1015
                                msgs = append(msgs, shutdownMsg)
×
1016
                        }
1017

1018
                        continue
5✔
1019
                }
1020

1021
                // Before we register this new link with the HTLC Switch, we'll
1022
                // need to fetch its current link-layer forwarding policy from
1023
                // the database.
1024
                graph := p.cfg.ChannelGraph
3✔
1025
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
3✔
1026
                        &chanPoint,
3✔
1027
                )
3✔
1028
                if err != nil && !errors.Is(err, channeldb.ErrEdgeNotFound) {
3✔
1029
                        return nil, err
×
1030
                }
×
1031

1032
                // We'll filter out our policy from the directional channel
1033
                // edges based whom the edge connects to. If it doesn't connect
1034
                // to us, then we know that we were the one that advertised the
1035
                // policy.
1036
                //
1037
                // TODO(roasbeef): can add helper method to get policy for
1038
                // particular channel.
1039
                var selfPolicy *models.ChannelEdgePolicy
3✔
1040
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
3✔
1041
                        p.cfg.ServerPubKey[:]) {
6✔
1042

3✔
1043
                        selfPolicy = p1
3✔
1044
                } else {
6✔
1045
                        selfPolicy = p2
3✔
1046
                }
3✔
1047

1048
                // If we don't yet have an advertised routing policy, then
1049
                // we'll use the current default, otherwise we'll translate the
1050
                // routing policy into a forwarding policy.
1051
                var forwardingPolicy *models.ForwardingPolicy
3✔
1052
                if selfPolicy != nil {
6✔
1053
                        var inboundWireFee lnwire.Fee
3✔
1054
                        _, err := selfPolicy.ExtraOpaqueData.ExtractRecords(
3✔
1055
                                &inboundWireFee,
3✔
1056
                        )
3✔
1057
                        if err != nil {
3✔
1058
                                return nil, err
×
1059
                        }
×
1060

1061
                        inboundFee := models.NewInboundFeeFromWire(
3✔
1062
                                inboundWireFee,
3✔
1063
                        )
3✔
1064

3✔
1065
                        forwardingPolicy = &models.ForwardingPolicy{
3✔
1066
                                MinHTLCOut:    selfPolicy.MinHTLC,
3✔
1067
                                MaxHTLC:       selfPolicy.MaxHTLC,
3✔
1068
                                BaseFee:       selfPolicy.FeeBaseMSat,
3✔
1069
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
3✔
1070
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
3✔
1071

3✔
1072
                                InboundFee: inboundFee,
3✔
1073
                        }
3✔
1074
                } else {
3✔
1075
                        p.log.Warnf("Unable to find our forwarding policy "+
3✔
1076
                                "for channel %v, using default values",
3✔
1077
                                chanPoint)
3✔
1078
                        forwardingPolicy = &p.cfg.RoutingPolicy
3✔
1079
                }
3✔
1080

1081
                p.log.Tracef("Using link policy of: %v",
3✔
1082
                        spew.Sdump(forwardingPolicy))
3✔
1083

3✔
1084
                // If the channel is pending, set the value to nil in the
3✔
1085
                // activeChannels map. This is done to signify that the channel
3✔
1086
                // is pending. We don't add the link to the switch here - it's
3✔
1087
                // the funding manager's responsibility to spin up pending
3✔
1088
                // channels. Adding them here would just be extra work as we'll
3✔
1089
                // tear them down when creating + adding the final link.
3✔
1090
                if lnChan.IsPending() {
6✔
1091
                        p.activeChannels.Store(chanID, nil)
3✔
1092

3✔
1093
                        continue
3✔
1094
                }
1095

1096
                shutdownInfo, err := lnChan.State().ShutdownInfo()
3✔
1097
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
3✔
1098
                        return nil, err
×
1099
                }
×
1100

1101
                var (
3✔
1102
                        shutdownMsg     fn.Option[lnwire.Shutdown]
3✔
1103
                        shutdownInfoErr error
3✔
1104
                )
3✔
1105
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
6✔
1106
                        // Compute an ideal fee.
3✔
1107
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
1108
                                p.cfg.CoopCloseTargetConfs,
3✔
1109
                        )
3✔
1110
                        if err != nil {
3✔
1111
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1112
                                        "estimate fee: %w", err)
×
1113

×
1114
                                return
×
1115
                        }
×
1116

1117
                        chanCloser, err := p.createChanCloser(
3✔
1118
                                lnChan, info.DeliveryScript.Val, feePerKw, nil,
3✔
1119
                                info.Closer(),
3✔
1120
                        )
3✔
1121
                        if err != nil {
3✔
1122
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1123
                                        "create chan closer: %w", err)
×
1124

×
1125
                                return
×
1126
                        }
×
1127

1128
                        chanID := lnwire.NewChanIDFromOutPoint(
3✔
1129
                                lnChan.State().FundingOutpoint,
3✔
1130
                        )
3✔
1131

3✔
1132
                        p.activeChanCloses[chanID] = chanCloser
3✔
1133

3✔
1134
                        // Create the Shutdown message.
3✔
1135
                        shutdown, err := chanCloser.ShutdownChan()
3✔
1136
                        if err != nil {
3✔
1137
                                delete(p.activeChanCloses, chanID)
×
1138
                                shutdownInfoErr = err
×
1139

×
1140
                                return
×
1141
                        }
×
1142

1143
                        shutdownMsg = fn.Some(*shutdown)
3✔
1144
                })
1145
                if shutdownInfoErr != nil {
3✔
1146
                        return nil, shutdownInfoErr
×
1147
                }
×
1148

1149
                // Subscribe to the set of on-chain events for this channel.
1150
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
3✔
1151
                        chanPoint,
3✔
1152
                )
3✔
1153
                if err != nil {
3✔
1154
                        return nil, err
×
1155
                }
×
1156

1157
                err = p.addLink(
3✔
1158
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
3✔
1159
                        true, shutdownMsg,
3✔
1160
                )
3✔
1161
                if err != nil {
3✔
1162
                        return nil, fmt.Errorf("unable to add link %v to "+
×
1163
                                "switch: %v", chanPoint, err)
×
1164
                }
×
1165

1166
                p.activeChannels.Store(chanID, lnChan)
3✔
1167
        }
1168

1169
        return msgs, nil
6✔
1170
}
1171

1172
// addLink creates and adds a new ChannelLink from the specified channel.
1173
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1174
        lnChan *lnwallet.LightningChannel,
1175
        forwardingPolicy *models.ForwardingPolicy,
1176
        chainEvents *contractcourt.ChainEventSubscription,
1177
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
3✔
1178

3✔
1179
        // onChannelFailure will be called by the link in case the channel
3✔
1180
        // fails for some reason.
3✔
1181
        onChannelFailure := func(chanID lnwire.ChannelID,
3✔
1182
                shortChanID lnwire.ShortChannelID,
3✔
1183
                linkErr htlcswitch.LinkFailureError) {
6✔
1184

3✔
1185
                failure := linkFailureReport{
3✔
1186
                        chanPoint:   *chanPoint,
3✔
1187
                        chanID:      chanID,
3✔
1188
                        shortChanID: shortChanID,
3✔
1189
                        linkErr:     linkErr,
3✔
1190
                }
3✔
1191

3✔
1192
                select {
3✔
1193
                case p.linkFailures <- failure:
3✔
1194
                case <-p.quit:
×
1195
                case <-p.cfg.Quit:
1✔
1196
                }
1197
        }
1198

1199
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
6✔
1200
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
3✔
1201
        }
3✔
1202

1203
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
6✔
1204
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
3✔
1205
        }
3✔
1206

1207
        //nolint:lll
1208
        linkCfg := htlcswitch.ChannelLinkConfig{
3✔
1209
                Peer:                   p,
3✔
1210
                DecodeHopIterators:     p.cfg.Sphinx.DecodeHopIterators,
3✔
1211
                ExtractErrorEncrypter:  p.cfg.Sphinx.ExtractErrorEncrypter,
3✔
1212
                FetchLastChannelUpdate: p.cfg.FetchLastChanUpdate,
3✔
1213
                HodlMask:               p.cfg.Hodl.Mask(),
3✔
1214
                Registry:               p.cfg.Invoices,
3✔
1215
                BestHeight:             p.cfg.Switch.BestHeight,
3✔
1216
                Circuits:               p.cfg.Switch.CircuitModifier(),
3✔
1217
                ForwardPackets:         p.cfg.InterceptSwitch.ForwardPackets,
3✔
1218
                FwrdingPolicy:          *forwardingPolicy,
3✔
1219
                FeeEstimator:           p.cfg.FeeEstimator,
3✔
1220
                PreimageCache:          p.cfg.WitnessBeacon,
3✔
1221
                ChainEvents:            chainEvents,
3✔
1222
                UpdateContractSignals:  updateContractSignals,
3✔
1223
                NotifyContractUpdate:   notifyContractUpdate,
3✔
1224
                OnChannelFailure:       onChannelFailure,
3✔
1225
                SyncStates:             syncStates,
3✔
1226
                BatchTicker:            ticker.New(p.cfg.ChannelCommitInterval),
3✔
1227
                FwdPkgGCTicker:         ticker.New(time.Hour),
3✔
1228
                PendingCommitTicker: ticker.New(
3✔
1229
                        p.cfg.PendingCommitInterval,
3✔
1230
                ),
3✔
1231
                BatchSize:               p.cfg.ChannelCommitBatchSize,
3✔
1232
                UnsafeReplay:            p.cfg.UnsafeReplay,
3✔
1233
                MinUpdateTimeout:        htlcswitch.DefaultMinLinkFeeUpdateTimeout,
3✔
1234
                MaxUpdateTimeout:        htlcswitch.DefaultMaxLinkFeeUpdateTimeout,
3✔
1235
                OutgoingCltvRejectDelta: p.cfg.OutgoingCltvRejectDelta,
3✔
1236
                TowerClient:             p.cfg.TowerClient,
3✔
1237
                MaxOutgoingCltvExpiry:   p.cfg.MaxOutgoingCltvExpiry,
3✔
1238
                MaxFeeAllocation:        p.cfg.MaxChannelFeeAllocation,
3✔
1239
                MaxAnchorsCommitFeeRate: p.cfg.MaxAnchorsCommitFeeRate,
3✔
1240
                NotifyActiveLink:        p.cfg.ChannelNotifier.NotifyActiveLinkEvent,
3✔
1241
                NotifyActiveChannel:     p.cfg.ChannelNotifier.NotifyActiveChannelEvent,
3✔
1242
                NotifyInactiveChannel:   p.cfg.ChannelNotifier.NotifyInactiveChannelEvent,
3✔
1243
                NotifyInactiveLinkEvent: p.cfg.ChannelNotifier.NotifyInactiveLinkEvent,
3✔
1244
                HtlcNotifier:            p.cfg.HtlcNotifier,
3✔
1245
                GetAliases:              p.cfg.GetAliases,
3✔
1246
                PreviouslySentShutdown:  shutdownMsg,
3✔
1247
                DisallowRouteBlinding:   p.cfg.DisallowRouteBlinding,
3✔
1248
                MaxFeeExposure:          p.cfg.MaxFeeExposure,
3✔
1249
        }
3✔
1250

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

3✔
1258
        // With the channel link created, we'll now notify the htlc switch so
3✔
1259
        // this channel can be used to dispatch local payments and also
3✔
1260
        // passively forward payments.
3✔
1261
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
3✔
1262
}
1263

1264
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1265
// one confirmed public channel exists with them.
1266
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
6✔
1267
        defer p.wg.Done()
6✔
1268

6✔
1269
        hasConfirmedPublicChan := false
6✔
1270
        for _, channel := range channels {
11✔
1271
                if channel.IsPending {
8✔
1272
                        continue
3✔
1273
                }
1274
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
10✔
1275
                        continue
5✔
1276
                }
1277

1278
                hasConfirmedPublicChan = true
3✔
1279
                break
3✔
1280
        }
1281
        if !hasConfirmedPublicChan {
12✔
1282
                return
6✔
1283
        }
6✔
1284

1285
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
3✔
1286
        if err != nil {
3✔
1287
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1288
                return
×
1289
        }
×
1290

1291
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
3✔
1292
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1293
        }
×
1294
}
1295

1296
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1297
// have any active channels with them.
1298
func (p *Brontide) maybeSendChannelUpdates() {
6✔
1299
        defer p.wg.Done()
6✔
1300

6✔
1301
        // If we don't have any active channels, then we can exit early.
6✔
1302
        if p.activeChannels.Len() == 0 {
10✔
1303
                return
4✔
1304
        }
4✔
1305

1306
        maybeSendUpd := func(cid lnwire.ChannelID,
5✔
1307
                lnChan *lnwallet.LightningChannel) error {
10✔
1308

5✔
1309
                // Nil channels are pending, so we'll skip them.
5✔
1310
                if lnChan == nil {
8✔
1311
                        return nil
3✔
1312
                }
3✔
1313

1314
                dbChan := lnChan.State()
5✔
1315
                scid := func() lnwire.ShortChannelID {
10✔
1316
                        switch {
5✔
1317
                        // Otherwise if it's a zero conf channel and confirmed,
1318
                        // then we need to use the "real" scid.
1319
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
3✔
1320
                                return dbChan.ZeroConfRealScid()
3✔
1321

1322
                        // Otherwise, we can use the normal scid.
1323
                        default:
5✔
1324
                                return dbChan.ShortChanID()
5✔
1325
                        }
1326
                }()
1327

1328
                // Now that we know the channel is in a good state, we'll try
1329
                // to fetch the update to send to the remote peer. If the
1330
                // channel is pending, and not a zero conf channel, we'll get
1331
                // an error here which we'll ignore.
1332
                chanUpd, err := p.cfg.FetchLastChanUpdate(scid)
5✔
1333
                if err != nil {
8✔
1334
                        p.log.Debugf("Unable to fetch channel update for "+
3✔
1335
                                "ChannelPoint(%v), scid=%v: %v",
3✔
1336
                                dbChan.FundingOutpoint, dbChan.ShortChanID, err)
3✔
1337

3✔
1338
                        return nil
3✔
1339
                }
3✔
1340

1341
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
5✔
1342
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
5✔
1343

5✔
1344
                // We'll send it as a normal message instead of using the lazy
5✔
1345
                // queue to prioritize transmission of the fresh update.
5✔
1346
                if err := p.SendMessage(false, chanUpd); err != nil {
5✔
1347
                        err := fmt.Errorf("unable to send channel update for "+
×
1348
                                "ChannelPoint(%v), scid=%v: %w",
×
1349
                                dbChan.FundingOutpoint, dbChan.ShortChanID(),
×
1350
                                err)
×
1351
                        p.log.Errorf(err.Error())
×
1352

×
1353
                        return err
×
1354
                }
×
1355

1356
                return nil
5✔
1357
        }
1358

1359
        p.activeChannels.ForEach(maybeSendUpd)
5✔
1360
}
1361

1362
// WaitForDisconnect waits until the peer has disconnected. A peer may be
1363
// disconnected if the local or remote side terminates the connection, or an
1364
// irrecoverable protocol error has been encountered. This method will only
1365
// begin watching the peer's waitgroup after the ready channel or the peer's
1366
// quit channel are signaled. The ready channel should only be signaled if a
1367
// call to Start returns no error. Otherwise, if the peer fails to start,
1368
// calling Disconnect will signal the quit channel and the method will not
1369
// block, since no goroutines were spawned.
1370
func (p *Brontide) WaitForDisconnect(ready chan struct{}) {
3✔
1371
        // Before we try to call the `Wait` goroutine, we'll make sure the main
3✔
1372
        // set of goroutines are already active.
3✔
1373
        select {
3✔
1374
        case <-p.startReady:
3✔
1375
        case <-p.quit:
×
1376
                return
×
1377
        }
1378

1379
        select {
3✔
1380
        case <-ready:
3✔
1381
        case <-p.quit:
2✔
1382
        }
1383

1384
        p.wg.Wait()
3✔
1385
}
1386

1387
// Disconnect terminates the connection with the remote peer. Additionally, a
1388
// signal is sent to the server and htlcSwitch indicating the resources
1389
// allocated to the peer can now be cleaned up.
1390
func (p *Brontide) Disconnect(reason error) {
3✔
1391
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
6✔
1392
                return
3✔
1393
        }
3✔
1394

1395
        // Make sure initialization has completed before we try to tear things
1396
        // down.
1397
        select {
3✔
1398
        case <-p.startReady:
3✔
1399
        case <-p.quit:
×
1400
                return
×
1401
        }
1402

1403
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
3✔
1404
        p.storeError(err)
3✔
1405

3✔
1406
        p.log.Infof(err.Error())
3✔
1407

3✔
1408
        // Stop PingManager before closing TCP connection.
3✔
1409
        p.pingManager.Stop()
3✔
1410

3✔
1411
        // Ensure that the TCP connection is properly closed before continuing.
3✔
1412
        p.cfg.Conn.Close()
3✔
1413

3✔
1414
        close(p.quit)
3✔
1415

3✔
1416
        // If our msg router isn't global (local to this instance), then we'll
3✔
1417
        // stop it. Otherwise, we'll leave it running.
3✔
1418
        if !p.globalMsgRouter {
6✔
1419
                p.msgRouter.WhenSome(func(router msgmux.Router) {
6✔
1420
                        router.Stop()
3✔
1421
                })
3✔
1422
        }
1423
}
1424

1425
// String returns the string representation of this peer.
1426
func (p *Brontide) String() string {
3✔
1427
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
3✔
1428
}
3✔
1429

1430
// readNextMessage reads, and returns the next message on the wire along with
1431
// any additional raw payload.
1432
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
10✔
1433
        noiseConn := p.cfg.Conn
10✔
1434
        err := noiseConn.SetReadDeadline(time.Time{})
10✔
1435
        if err != nil {
10✔
1436
                return nil, err
×
1437
        }
×
1438

1439
        pktLen, err := noiseConn.ReadNextHeader()
10✔
1440
        if err != nil {
13✔
1441
                return nil, fmt.Errorf("read next header: %w", err)
3✔
1442
        }
3✔
1443

1444
        // First we'll read the next _full_ message. We do this rather than
1445
        // reading incrementally from the stream as the Lightning wire protocol
1446
        // is message oriented and allows nodes to pad on additional data to
1447
        // the message stream.
1448
        var (
7✔
1449
                nextMsg lnwire.Message
7✔
1450
                msgLen  uint64
7✔
1451
        )
7✔
1452
        err = p.cfg.ReadPool.Submit(func(buf *buffer.Read) error {
14✔
1453
                // Before reading the body of the message, set the read timeout
7✔
1454
                // accordingly to ensure we don't block other readers using the
7✔
1455
                // pool. We do so only after the task has been scheduled to
7✔
1456
                // ensure the deadline doesn't expire while the message is in
7✔
1457
                // the process of being scheduled.
7✔
1458
                readDeadline := time.Now().Add(
7✔
1459
                        p.scaleTimeout(readMessageTimeout),
7✔
1460
                )
7✔
1461
                readErr := noiseConn.SetReadDeadline(readDeadline)
7✔
1462
                if readErr != nil {
7✔
1463
                        return readErr
×
1464
                }
×
1465

1466
                // The ReadNextBody method will actually end up re-using the
1467
                // buffer, so within this closure, we can continue to use
1468
                // rawMsg as it's just a slice into the buf from the buffer
1469
                // pool.
1470
                rawMsg, readErr := noiseConn.ReadNextBody(buf[:pktLen])
7✔
1471
                if readErr != nil {
7✔
1472
                        return fmt.Errorf("read next body: %w", readErr)
×
1473
                }
×
1474
                msgLen = uint64(len(rawMsg))
7✔
1475

7✔
1476
                // Next, create a new io.Reader implementation from the raw
7✔
1477
                // message, and use this to decode the message directly from.
7✔
1478
                msgReader := bytes.NewReader(rawMsg)
7✔
1479
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
7✔
1480
                if err != nil {
10✔
1481
                        return err
3✔
1482
                }
3✔
1483

1484
                // At this point, rawMsg and buf will be returned back to the
1485
                // buffer pool for re-use.
1486
                return nil
7✔
1487
        })
1488
        atomic.AddUint64(&p.bytesReceived, msgLen)
7✔
1489
        if err != nil {
10✔
1490
                return nil, err
3✔
1491
        }
3✔
1492

1493
        p.logWireMessage(nextMsg, true)
7✔
1494

7✔
1495
        return nextMsg, nil
7✔
1496
}
1497

1498
// msgStream implements a goroutine-safe, in-order stream of messages to be
1499
// delivered via closure to a receiver. These messages MUST be in order due to
1500
// the nature of the lightning channel commitment and gossiper state machines.
1501
// TODO(conner): use stream handler interface to abstract out stream
1502
// state/logging.
1503
type msgStream struct {
1504
        streamShutdown int32 // To be used atomically.
1505

1506
        peer *Brontide
1507

1508
        apply func(lnwire.Message)
1509

1510
        startMsg string
1511
        stopMsg  string
1512

1513
        msgCond *sync.Cond
1514
        msgs    []lnwire.Message
1515

1516
        mtx sync.Mutex
1517

1518
        producerSema chan struct{}
1519

1520
        wg   sync.WaitGroup
1521
        quit chan struct{}
1522
}
1523

1524
// newMsgStream creates a new instance of a chanMsgStream for a particular
1525
// channel identified by its channel ID. bufSize is the max number of messages
1526
// that should be buffered in the internal queue. Callers should set this to a
1527
// sane value that avoids blocking unnecessarily, but doesn't allow an
1528
// unbounded amount of memory to be allocated to buffer incoming messages.
1529
func newMsgStream(p *Brontide, startMsg, stopMsg string, bufSize uint32,
1530
        apply func(lnwire.Message)) *msgStream {
6✔
1531

6✔
1532
        stream := &msgStream{
6✔
1533
                peer:         p,
6✔
1534
                apply:        apply,
6✔
1535
                startMsg:     startMsg,
6✔
1536
                stopMsg:      stopMsg,
6✔
1537
                producerSema: make(chan struct{}, bufSize),
6✔
1538
                quit:         make(chan struct{}),
6✔
1539
        }
6✔
1540
        stream.msgCond = sync.NewCond(&stream.mtx)
6✔
1541

6✔
1542
        // Before we return the active stream, we'll populate the producer's
6✔
1543
        // semaphore channel. We'll use this to ensure that the producer won't
6✔
1544
        // attempt to allocate memory in the queue for an item until it has
6✔
1545
        // sufficient extra space.
6✔
1546
        for i := uint32(0); i < bufSize; i++ {
3,009✔
1547
                stream.producerSema <- struct{}{}
3,003✔
1548
        }
3,003✔
1549

1550
        return stream
6✔
1551
}
1552

1553
// Start starts the chanMsgStream.
1554
func (ms *msgStream) Start() {
6✔
1555
        ms.wg.Add(1)
6✔
1556
        go ms.msgConsumer()
6✔
1557
}
6✔
1558

1559
// Stop stops the chanMsgStream.
1560
func (ms *msgStream) Stop() {
3✔
1561
        // TODO(roasbeef): signal too?
3✔
1562

3✔
1563
        close(ms.quit)
3✔
1564

3✔
1565
        // Now that we've closed the channel, we'll repeatedly signal the msg
3✔
1566
        // consumer until we've detected that it has exited.
3✔
1567
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
6✔
1568
                ms.msgCond.Signal()
3✔
1569
                time.Sleep(time.Millisecond * 100)
3✔
1570
        }
3✔
1571

1572
        ms.wg.Wait()
3✔
1573
}
1574

1575
// msgConsumer is the main goroutine that streams messages from the peer's
1576
// readHandler directly to the target channel.
1577
func (ms *msgStream) msgConsumer() {
6✔
1578
        defer ms.wg.Done()
6✔
1579
        defer peerLog.Tracef(ms.stopMsg)
6✔
1580
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
6✔
1581

6✔
1582
        peerLog.Tracef(ms.startMsg)
6✔
1583

6✔
1584
        for {
12✔
1585
                // First, we'll check our condition. If the queue of messages
6✔
1586
                // is empty, then we'll wait until a new item is added.
6✔
1587
                ms.msgCond.L.Lock()
6✔
1588
                for len(ms.msgs) == 0 {
12✔
1589
                        ms.msgCond.Wait()
6✔
1590

6✔
1591
                        // If we woke up in order to exit, then we'll do so.
6✔
1592
                        // Otherwise, we'll check the message queue for any new
6✔
1593
                        // items.
6✔
1594
                        select {
6✔
1595
                        case <-ms.peer.quit:
3✔
1596
                                ms.msgCond.L.Unlock()
3✔
1597
                                return
3✔
1598
                        case <-ms.quit:
3✔
1599
                                ms.msgCond.L.Unlock()
3✔
1600
                                return
3✔
1601
                        default:
3✔
1602
                        }
1603
                }
1604

1605
                // Grab the message off the front of the queue, shifting the
1606
                // slice's reference down one in order to remove the message
1607
                // from the queue.
1608
                msg := ms.msgs[0]
3✔
1609
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
3✔
1610
                ms.msgs = ms.msgs[1:]
3✔
1611

3✔
1612
                ms.msgCond.L.Unlock()
3✔
1613

3✔
1614
                ms.apply(msg)
3✔
1615

3✔
1616
                // We've just successfully processed an item, so we'll signal
3✔
1617
                // to the producer that a new slot in the buffer. We'll use
3✔
1618
                // this to bound the size of the buffer to avoid allowing it to
3✔
1619
                // grow indefinitely.
3✔
1620
                select {
3✔
1621
                case ms.producerSema <- struct{}{}:
3✔
1622
                case <-ms.peer.quit:
3✔
1623
                        return
3✔
1624
                case <-ms.quit:
3✔
1625
                        return
3✔
1626
                }
1627
        }
1628
}
1629

1630
// AddMsg adds a new message to the msgStream. This function is safe for
1631
// concurrent access.
1632
func (ms *msgStream) AddMsg(msg lnwire.Message) {
3✔
1633
        // First, we'll attempt to receive from the producerSema struct. This
3✔
1634
        // acts as a semaphore to prevent us from indefinitely buffering
3✔
1635
        // incoming items from the wire. Either the msg queue isn't full, and
3✔
1636
        // we'll not block, or the queue is full, and we'll block until either
3✔
1637
        // we're signalled to quit, or a slot is freed up.
3✔
1638
        select {
3✔
1639
        case <-ms.producerSema:
3✔
1640
        case <-ms.peer.quit:
×
1641
                return
×
1642
        case <-ms.quit:
×
1643
                return
×
1644
        }
1645

1646
        // Next, we'll lock the condition, and add the message to the end of
1647
        // the message queue.
1648
        ms.msgCond.L.Lock()
3✔
1649
        ms.msgs = append(ms.msgs, msg)
3✔
1650
        ms.msgCond.L.Unlock()
3✔
1651

3✔
1652
        // With the message added, we signal to the msgConsumer that there are
3✔
1653
        // additional messages to consume.
3✔
1654
        ms.msgCond.Signal()
3✔
1655
}
1656

1657
// waitUntilLinkActive waits until the target link is active and returns a
1658
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1659
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1660
func waitUntilLinkActive(p *Brontide,
1661
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
3✔
1662

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

3✔
1665
        // Subscribe to receive channel events.
3✔
1666
        //
3✔
1667
        // NOTE: If the link is already active by SubscribeChannelEvents, then
3✔
1668
        // GetLink will retrieve the link and we can send messages. If the link
3✔
1669
        // becomes active between SubscribeChannelEvents and GetLink, then GetLink
3✔
1670
        // will retrieve the link. If the link becomes active after GetLink, then
3✔
1671
        // we will get an ActiveLinkEvent notification and retrieve the link. If
3✔
1672
        // the call to GetLink is before SubscribeChannelEvents, however, there
3✔
1673
        // will be a race condition.
3✔
1674
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
3✔
1675
        if err != nil {
6✔
1676
                // If we have a non-nil error, then the server is shutting down and we
3✔
1677
                // can exit here and return nil. This means no message will be delivered
3✔
1678
                // to the link.
3✔
1679
                return nil
3✔
1680
        }
3✔
1681
        defer sub.Cancel()
3✔
1682

3✔
1683
        // The link may already be active by this point, and we may have missed the
3✔
1684
        // ActiveLinkEvent. Check if the link exists.
3✔
1685
        link := p.fetchLinkFromKeyAndCid(cid)
3✔
1686
        if link != nil {
6✔
1687
                return link
3✔
1688
        }
3✔
1689

1690
        // If the link is nil, we must wait for it to be active.
1691
        for {
6✔
1692
                select {
3✔
1693
                // A new event has been sent by the ChannelNotifier. We first check
1694
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1695
                // that the event is for this channel. Otherwise, we discard the
1696
                // message.
1697
                case e := <-sub.Updates():
3✔
1698
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
3✔
1699
                        if !ok {
6✔
1700
                                // Ignore this notification.
3✔
1701
                                continue
3✔
1702
                        }
1703

1704
                        chanPoint := event.ChannelPoint
3✔
1705

3✔
1706
                        // Check whether the retrieved chanPoint matches the target
3✔
1707
                        // channel id.
3✔
1708
                        if !cid.IsChanPoint(chanPoint) {
3✔
1709
                                continue
×
1710
                        }
1711

1712
                        // The link shouldn't be nil as we received an
1713
                        // ActiveLinkEvent. If it is nil, we return nil and the
1714
                        // calling function should catch it.
1715
                        return p.fetchLinkFromKeyAndCid(cid)
3✔
1716

1717
                case <-p.quit:
3✔
1718
                        return nil
3✔
1719
                }
1720
        }
1721
}
1722

1723
// newChanMsgStream is used to create a msgStream between the peer and
1724
// particular channel link in the htlcswitch. We utilize additional
1725
// synchronization with the fundingManager to ensure we don't attempt to
1726
// dispatch a message to a channel before it is fully active. A reference to the
1727
// channel this stream forwards to is held in scope to prevent unnecessary
1728
// lookups.
1729
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
3✔
1730
        var chanLink htlcswitch.ChannelUpdateHandler
3✔
1731

3✔
1732
        apply := func(msg lnwire.Message) {
6✔
1733
                // This check is fine because if the link no longer exists, it will
3✔
1734
                // be removed from the activeChannels map and subsequent messages
3✔
1735
                // shouldn't reach the chan msg stream.
3✔
1736
                if chanLink == nil {
6✔
1737
                        chanLink = waitUntilLinkActive(p, cid)
3✔
1738

3✔
1739
                        // If the link is still not active and the calling function
3✔
1740
                        // errored out, just return.
3✔
1741
                        if chanLink == nil {
6✔
1742
                                p.log.Warnf("Link=%v is not active")
3✔
1743
                                return
3✔
1744
                        }
3✔
1745
                }
1746

1747
                // In order to avoid unnecessarily delivering message
1748
                // as the peer is exiting, we'll check quickly to see
1749
                // if we need to exit.
1750
                select {
3✔
1751
                case <-p.quit:
×
1752
                        return
×
1753
                default:
3✔
1754
                }
1755

1756
                chanLink.HandleChannelUpdate(msg)
3✔
1757
        }
1758

1759
        return newMsgStream(p,
3✔
1760
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
3✔
1761
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
3✔
1762
                1000,
3✔
1763
                apply,
3✔
1764
        )
3✔
1765
}
1766

1767
// newDiscMsgStream is used to setup a msgStream between the peer and the
1768
// authenticated gossiper. This stream should be used to forward all remote
1769
// channel announcements.
1770
func newDiscMsgStream(p *Brontide) *msgStream {
6✔
1771
        apply := func(msg lnwire.Message) {
9✔
1772
                // TODO(yy): `ProcessRemoteAnnouncement` returns an error chan
3✔
1773
                // and we need to process it.
3✔
1774
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(msg, p)
3✔
1775
        }
3✔
1776

1777
        return newMsgStream(
6✔
1778
                p,
6✔
1779
                "Update stream for gossiper created",
6✔
1780
                "Update stream for gossiper exited",
6✔
1781
                1000,
6✔
1782
                apply,
6✔
1783
        )
6✔
1784
}
1785

1786
// readHandler is responsible for reading messages off the wire in series, then
1787
// properly dispatching the handling of the message to the proper subsystem.
1788
//
1789
// NOTE: This method MUST be run as a goroutine.
1790
func (p *Brontide) readHandler() {
6✔
1791
        defer p.wg.Done()
6✔
1792

6✔
1793
        // We'll stop the timer after a new messages is received, and also
6✔
1794
        // reset it after we process the next message.
6✔
1795
        idleTimer := time.AfterFunc(idleTimeout, func() {
6✔
1796
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
1797
                        p, idleTimeout)
×
1798
                p.Disconnect(err)
×
1799
        })
×
1800

1801
        // Initialize our negotiated gossip sync method before reading messages
1802
        // off the wire. When using gossip queries, this ensures a gossip
1803
        // syncer is active by the time query messages arrive.
1804
        //
1805
        // TODO(conner): have peer store gossip syncer directly and bypass
1806
        // gossiper?
1807
        p.initGossipSync()
6✔
1808

6✔
1809
        discStream := newDiscMsgStream(p)
6✔
1810
        discStream.Start()
6✔
1811
        defer discStream.Stop()
6✔
1812
out:
6✔
1813
        for atomic.LoadInt32(&p.disconnect) == 0 {
13✔
1814
                nextMsg, err := p.readNextMessage()
7✔
1815
                if !idleTimer.Stop() {
7✔
1816
                        select {
×
1817
                        case <-idleTimer.C:
×
1818
                        default:
×
1819
                        }
1820
                }
1821
                if err != nil {
7✔
1822
                        p.log.Infof("unable to read message from peer: %v", err)
3✔
1823

3✔
1824
                        // If we could not read our peer's message due to an
3✔
1825
                        // unknown type or invalid alias, we continue processing
3✔
1826
                        // as normal. We store unknown message and address
3✔
1827
                        // types, as they may provide debugging insight.
3✔
1828
                        switch e := err.(type) {
3✔
1829
                        // If this is just a message we don't yet recognize,
1830
                        // we'll continue processing as normal as this allows
1831
                        // us to introduce new messages in a forwards
1832
                        // compatible manner.
1833
                        case *lnwire.UnknownMessage:
3✔
1834
                                p.storeError(e)
3✔
1835
                                idleTimer.Reset(idleTimeout)
3✔
1836
                                continue
3✔
1837

1838
                        // If they sent us an address type that we don't yet
1839
                        // know of, then this isn't a wire error, so we'll
1840
                        // simply continue parsing the remainder of their
1841
                        // messages.
1842
                        case *lnwire.ErrUnknownAddrType:
×
1843
                                p.storeError(e)
×
1844
                                idleTimer.Reset(idleTimeout)
×
1845
                                continue
×
1846

1847
                        // If the NodeAnnouncement has an invalid alias, then
1848
                        // we'll log that error above and continue so we can
1849
                        // continue to read messages from the peer. We do not
1850
                        // store this error because it is of little debugging
1851
                        // value.
1852
                        case *lnwire.ErrInvalidNodeAlias:
×
1853
                                idleTimer.Reset(idleTimeout)
×
1854
                                continue
×
1855

1856
                        // If the error we encountered wasn't just a message we
1857
                        // didn't recognize, then we'll stop all processing as
1858
                        // this is a fatal error.
1859
                        default:
3✔
1860
                                break out
3✔
1861
                        }
1862
                }
1863

1864
                // If a message router is active, then we'll try to have it
1865
                // handle this message. If it can, then we're able to skip the
1866
                // rest of the message handling logic.
1867
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
8✔
1868
                        return r.RouteMsg(msgmux.PeerMsg{
4✔
1869
                                PeerPub: *p.IdentityKey(),
4✔
1870
                                Message: nextMsg,
4✔
1871
                        })
4✔
1872
                })
4✔
1873

1874
                // No error occurred, and the message was handled by the
1875
                // router.
1876
                if err == nil {
4✔
1877
                        continue
×
1878
                }
1879

1880
                var (
4✔
1881
                        targetChan   lnwire.ChannelID
4✔
1882
                        isLinkUpdate bool
4✔
1883
                )
4✔
1884

4✔
1885
                switch msg := nextMsg.(type) {
4✔
1886
                case *lnwire.Pong:
2✔
1887
                        // When we receive a Pong message in response to our
2✔
1888
                        // last ping message, we send it to the pingManager
2✔
1889
                        p.pingManager.ReceivedPong(msg)
2✔
1890

1891
                case *lnwire.Ping:
2✔
1892
                        // First, we'll store their latest ping payload within
2✔
1893
                        // the relevant atomic variable.
2✔
1894
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
2✔
1895

2✔
1896
                        // Next, we'll send over the amount of specified pong
2✔
1897
                        // bytes.
2✔
1898
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
2✔
1899
                        p.queueMsg(pong, nil)
2✔
1900

1901
                case *lnwire.OpenChannel,
1902
                        *lnwire.AcceptChannel,
1903
                        *lnwire.FundingCreated,
1904
                        *lnwire.FundingSigned,
1905
                        *lnwire.ChannelReady:
3✔
1906

3✔
1907
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
1908

1909
                case *lnwire.Shutdown:
3✔
1910
                        select {
3✔
1911
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
1912
                        case <-p.quit:
×
1913
                                break out
×
1914
                        }
1915
                case *lnwire.ClosingSigned:
3✔
1916
                        select {
3✔
1917
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
1918
                        case <-p.quit:
×
1919
                                break out
×
1920
                        }
1921

1922
                case *lnwire.Warning:
×
1923
                        targetChan = msg.ChanID
×
1924
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
1925

1926
                case *lnwire.Error:
3✔
1927
                        targetChan = msg.ChanID
3✔
1928
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
3✔
1929

1930
                case *lnwire.ChannelReestablish:
3✔
1931
                        targetChan = msg.ChanID
3✔
1932
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
1933

3✔
1934
                        // If we failed to find the link in question, and the
3✔
1935
                        // message received was a channel sync message, then
3✔
1936
                        // this might be a peer trying to resync closed channel.
3✔
1937
                        // In this case we'll try to resend our last channel
3✔
1938
                        // sync message, such that the peer can recover funds
3✔
1939
                        // from the closed channel.
3✔
1940
                        if !isLinkUpdate {
6✔
1941
                                err := p.resendChanSyncMsg(targetChan)
3✔
1942
                                if err != nil {
6✔
1943
                                        // TODO(halseth): send error to peer?
3✔
1944
                                        p.log.Errorf("resend failed: %v",
3✔
1945
                                                err)
3✔
1946
                                }
3✔
1947
                        }
1948

1949
                // For messages that implement the LinkUpdater interface, we
1950
                // will consider them as link updates and send them to
1951
                // chanStream. These messages will be queued inside chanStream
1952
                // if the channel is not active yet.
1953
                case lnwire.LinkUpdater:
3✔
1954
                        targetChan = msg.TargetChanID()
3✔
1955
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
1956

3✔
1957
                        // Log an error if we don't have this channel. This
3✔
1958
                        // means the peer has sent us a message with unknown
3✔
1959
                        // channel ID.
3✔
1960
                        if !isLinkUpdate {
6✔
1961
                                p.log.Errorf("Unknown channel ID: %v found "+
3✔
1962
                                        "in received msg=%s", targetChan,
3✔
1963
                                        nextMsg.MsgType())
3✔
1964
                        }
3✔
1965

1966
                case *lnwire.ChannelUpdate,
1967
                        *lnwire.ChannelAnnouncement,
1968
                        *lnwire.NodeAnnouncement,
1969
                        *lnwire.AnnounceSignatures,
1970
                        *lnwire.GossipTimestampRange,
1971
                        *lnwire.QueryShortChanIDs,
1972
                        *lnwire.QueryChannelRange,
1973
                        *lnwire.ReplyChannelRange,
1974
                        *lnwire.ReplyShortChanIDsEnd:
3✔
1975

3✔
1976
                        discStream.AddMsg(msg)
3✔
1977

1978
                case *lnwire.Custom:
4✔
1979
                        err := p.handleCustomMessage(msg)
4✔
1980
                        if err != nil {
4✔
1981
                                p.storeError(err)
×
1982
                                p.log.Errorf("%v", err)
×
1983
                        }
×
1984

1985
                default:
×
1986
                        // If the message we received is unknown to us, store
×
1987
                        // the type to track the failure.
×
1988
                        err := fmt.Errorf("unknown message type %v received",
×
1989
                                uint16(msg.MsgType()))
×
1990
                        p.storeError(err)
×
1991

×
1992
                        p.log.Errorf("%v", err)
×
1993
                }
1994

1995
                if isLinkUpdate {
7✔
1996
                        // If this is a channel update, then we need to feed it
3✔
1997
                        // into the channel's in-order message stream.
3✔
1998
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
3✔
1999
                }
3✔
2000

2001
                idleTimer.Reset(idleTimeout)
4✔
2002
        }
2003

2004
        p.Disconnect(errors.New("read handler closed"))
3✔
2005

3✔
2006
        p.log.Trace("readHandler for peer done")
3✔
2007
}
2008

2009
// handleCustomMessage handles the given custom message if a handler is
2010
// registered.
2011
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
4✔
2012
        if p.cfg.HandleCustomMessage == nil {
4✔
2013
                return fmt.Errorf("no custom message handler for "+
×
2014
                        "message type %v", uint16(msg.MsgType()))
×
2015
        }
×
2016

2017
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
4✔
2018
}
2019

2020
// isLoadedFromDisk returns true if the provided channel ID is loaded from
2021
// disk.
2022
//
2023
// NOTE: only returns true for pending channels.
2024
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
3✔
2025
        // If this is a newly added channel, no need to reestablish.
3✔
2026
        _, added := p.addedChannels.Load(chanID)
3✔
2027
        if added {
6✔
2028
                return false
3✔
2029
        }
3✔
2030

2031
        // Return false if the channel is unknown.
2032
        channel, ok := p.activeChannels.Load(chanID)
3✔
2033
        if !ok {
3✔
2034
                return false
×
2035
        }
×
2036

2037
        // During startup, we will use a nil value to mark a pending channel
2038
        // that's loaded from disk.
2039
        return channel == nil
3✔
2040
}
2041

2042
// isActiveChannel returns true if the provided channel id is active, otherwise
2043
// returns false.
2044
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
11✔
2045
        // The channel would be nil if,
11✔
2046
        // - the channel doesn't exist, or,
11✔
2047
        // - the channel exists, but is pending. In this case, we don't
11✔
2048
        //   consider this channel active.
11✔
2049
        channel, _ := p.activeChannels.Load(chanID)
11✔
2050

11✔
2051
        return channel != nil
11✔
2052
}
11✔
2053

2054
// isPendingChannel returns true if the provided channel ID is pending, and
2055
// returns false if the channel is active or unknown.
2056
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
9✔
2057
        // Return false if the channel is unknown.
9✔
2058
        channel, ok := p.activeChannels.Load(chanID)
9✔
2059
        if !ok {
15✔
2060
                return false
6✔
2061
        }
6✔
2062

2063
        return channel == nil
3✔
2064
}
2065

2066
// hasChannel returns true if the peer has a pending/active channel specified
2067
// by the channel ID.
2068
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
3✔
2069
        _, ok := p.activeChannels.Load(chanID)
3✔
2070
        return ok
3✔
2071
}
3✔
2072

2073
// storeError stores an error in our peer's buffer of recent errors with the
2074
// current timestamp. Errors are only stored if we have at least one active
2075
// channel with the peer to mitigate a dos vector where a peer costlessly
2076
// connects to us and spams us with errors.
2077
func (p *Brontide) storeError(err error) {
3✔
2078
        var haveChannels bool
3✔
2079

3✔
2080
        p.activeChannels.Range(func(_ lnwire.ChannelID,
3✔
2081
                channel *lnwallet.LightningChannel) bool {
6✔
2082

3✔
2083
                // Pending channels will be nil in the activeChannels map.
3✔
2084
                if channel == nil {
6✔
2085
                        // Return true to continue the iteration.
3✔
2086
                        return true
3✔
2087
                }
3✔
2088

2089
                haveChannels = true
3✔
2090

3✔
2091
                // Return false to break the iteration.
3✔
2092
                return false
3✔
2093
        })
2094

2095
        // If we do not have any active channels with the peer, we do not store
2096
        // errors as a dos mitigation.
2097
        if !haveChannels {
6✔
2098
                p.log.Trace("no channels with peer, not storing err")
3✔
2099
                return
3✔
2100
        }
3✔
2101

2102
        p.cfg.ErrorBuffer.Add(
3✔
2103
                &TimestampedError{Timestamp: time.Now(), Error: err},
3✔
2104
        )
3✔
2105
}
2106

2107
// handleWarningOrError processes a warning or error msg and returns true if
2108
// msg should be forwarded to the associated channel link. False is returned if
2109
// any necessary forwarding of msg was already handled by this method. If msg is
2110
// an error from a peer with an active channel, we'll store it in memory.
2111
//
2112
// NOTE: This method should only be called from within the readHandler.
2113
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
2114
        msg lnwire.Message) bool {
3✔
2115

3✔
2116
        if errMsg, ok := msg.(*lnwire.Error); ok {
6✔
2117
                p.storeError(errMsg)
3✔
2118
        }
3✔
2119

2120
        switch {
3✔
2121
        // Connection wide messages should be forwarded to all channel links
2122
        // with this peer.
2123
        case chanID == lnwire.ConnectionWideID:
×
2124
                for _, chanStream := range p.activeMsgStreams {
×
2125
                        chanStream.AddMsg(msg)
×
2126
                }
×
2127

2128
                return false
×
2129

2130
        // If the channel ID for the message corresponds to a pending channel,
2131
        // then the funding manager will handle it.
2132
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
3✔
2133
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2134
                return false
3✔
2135

2136
        // If not we hand the message to the channel link for this channel.
2137
        case p.isActiveChannel(chanID):
3✔
2138
                return true
3✔
2139

2140
        default:
3✔
2141
                return false
3✔
2142
        }
2143
}
2144

2145
// messageSummary returns a human-readable string that summarizes a
2146
// incoming/outgoing message. Not all messages will have a summary, only those
2147
// which have additional data that can be informative at a glance.
2148
func messageSummary(msg lnwire.Message) string {
3✔
2149
        switch msg := msg.(type) {
3✔
2150
        case *lnwire.Init:
3✔
2151
                // No summary.
3✔
2152
                return ""
3✔
2153

2154
        case *lnwire.OpenChannel:
3✔
2155
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
3✔
2156
                        "push_amt=%v, reserve=%v, flags=%v",
3✔
2157
                        msg.PendingChannelID[:], msg.ChainHash,
3✔
2158
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
3✔
2159
                        msg.ChannelReserve, msg.ChannelFlags)
3✔
2160

2161
        case *lnwire.AcceptChannel:
3✔
2162
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
3✔
2163
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
3✔
2164
                        msg.MinAcceptDepth)
3✔
2165

2166
        case *lnwire.FundingCreated:
3✔
2167
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
3✔
2168
                        msg.PendingChannelID[:], msg.FundingPoint)
3✔
2169

2170
        case *lnwire.FundingSigned:
3✔
2171
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
3✔
2172

2173
        case *lnwire.ChannelReady:
3✔
2174
                return fmt.Sprintf("chan_id=%v, next_point=%x",
3✔
2175
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
3✔
2176

2177
        case *lnwire.Shutdown:
3✔
2178
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
3✔
2179
                        msg.Address[:])
3✔
2180

2181
        case *lnwire.ClosingSigned:
3✔
2182
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
3✔
2183
                        msg.FeeSatoshis)
3✔
2184

2185
        case *lnwire.UpdateAddHTLC:
3✔
2186
                var blindingPoint []byte
3✔
2187
                msg.BlindingPoint.WhenSome(
3✔
2188
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
3✔
2189
                                *btcec.PublicKey]) {
6✔
2190

3✔
2191
                                blindingPoint = b.Val.SerializeCompressed()
3✔
2192
                        },
3✔
2193
                )
2194

2195
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
3✔
2196
                        "hash=%x, blinding_point=%x, custom_records=%v",
3✔
2197
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
3✔
2198
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
3✔
2199

2200
        case *lnwire.UpdateFailHTLC:
3✔
2201
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
3✔
2202
                        msg.ID, msg.Reason)
3✔
2203

2204
        case *lnwire.UpdateFulfillHTLC:
3✔
2205
                return fmt.Sprintf("chan_id=%v, id=%v, pre_image=%x, "+
3✔
2206
                        "custom_records=%v", msg.ChanID, msg.ID,
3✔
2207
                        msg.PaymentPreimage[:], msg.CustomRecords)
3✔
2208

2209
        case *lnwire.CommitSig:
3✔
2210
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
3✔
2211
                        len(msg.HtlcSigs))
3✔
2212

2213
        case *lnwire.RevokeAndAck:
3✔
2214
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
3✔
2215
                        msg.ChanID, msg.Revocation[:],
3✔
2216
                        msg.NextRevocationKey.SerializeCompressed())
3✔
2217

2218
        case *lnwire.UpdateFailMalformedHTLC:
3✔
2219
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
3✔
2220
                        msg.ChanID, msg.ID, msg.FailureCode)
3✔
2221

2222
        case *lnwire.Warning:
×
2223
                return fmt.Sprintf("%v", msg.Warning())
×
2224

2225
        case *lnwire.Error:
3✔
2226
                return fmt.Sprintf("%v", msg.Error())
3✔
2227

2228
        case *lnwire.AnnounceSignatures:
3✔
2229
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
3✔
2230
                        msg.ShortChannelID.ToUint64())
3✔
2231

2232
        case *lnwire.ChannelAnnouncement:
3✔
2233
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
3✔
2234
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
3✔
2235

2236
        case *lnwire.ChannelUpdate:
3✔
2237
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
3✔
2238
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
3✔
2239
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
3✔
2240
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
3✔
2241

2242
        case *lnwire.NodeAnnouncement:
3✔
2243
                return fmt.Sprintf("node=%x, update_time=%v",
3✔
2244
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
3✔
2245

2246
        case *lnwire.Ping:
2✔
2247
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
2✔
2248

2249
        case *lnwire.Pong:
2✔
2250
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
2✔
2251

2252
        case *lnwire.UpdateFee:
×
2253
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2254
                        msg.ChanID, int64(msg.FeePerKw))
×
2255

2256
        case *lnwire.ChannelReestablish:
3✔
2257
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
3✔
2258
                        "remote_tail_height=%v", msg.ChanID,
3✔
2259
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
3✔
2260

2261
        case *lnwire.ReplyShortChanIDsEnd:
3✔
2262
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
3✔
2263
                        msg.Complete)
3✔
2264

2265
        case *lnwire.ReplyChannelRange:
3✔
2266
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
3✔
2267
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
3✔
2268
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
3✔
2269
                        msg.EncodingType)
3✔
2270

2271
        case *lnwire.QueryShortChanIDs:
3✔
2272
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
3✔
2273
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
3✔
2274

2275
        case *lnwire.QueryChannelRange:
3✔
2276
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
3✔
2277
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
3✔
2278
                        msg.LastBlockHeight())
3✔
2279

2280
        case *lnwire.GossipTimestampRange:
3✔
2281
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
3✔
2282
                        "stamp_range=%v", msg.ChainHash,
3✔
2283
                        time.Unix(int64(msg.FirstTimestamp), 0),
3✔
2284
                        msg.TimestampRange)
3✔
2285

2286
        case *lnwire.Stfu:
×
2287
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
×
2288
                        msg.Initiator)
×
2289

2290
        case *lnwire.Custom:
3✔
2291
                return fmt.Sprintf("type=%d", msg.Type)
3✔
2292
        }
2293

2294
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2295
}
2296

2297
// logWireMessage logs the receipt or sending of particular wire message. This
2298
// function is used rather than just logging the message in order to produce
2299
// less spammy log messages in trace mode by setting the 'Curve" parameter to
2300
// nil. Doing this avoids printing out each of the field elements in the curve
2301
// parameters for secp256k1.
2302
func (p *Brontide) logWireMessage(msg lnwire.Message, read bool) {
20✔
2303
        summaryPrefix := "Received"
20✔
2304
        if !read {
36✔
2305
                summaryPrefix = "Sending"
16✔
2306
        }
16✔
2307

2308
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
23✔
2309
                // Debug summary of message.
3✔
2310
                summary := messageSummary(msg)
3✔
2311
                if len(summary) > 0 {
6✔
2312
                        summary = "(" + summary + ")"
3✔
2313
                }
3✔
2314

2315
                preposition := "to"
3✔
2316
                if read {
6✔
2317
                        preposition = "from"
3✔
2318
                }
3✔
2319

2320
                var msgType string
3✔
2321
                if msg.MsgType() < lnwire.CustomTypeStart {
6✔
2322
                        msgType = msg.MsgType().String()
3✔
2323
                } else {
6✔
2324
                        msgType = "custom"
3✔
2325
                }
3✔
2326

2327
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
3✔
2328
                        msgType, summary, preposition, p)
3✔
2329
        }))
2330

2331
        prefix := "readMessage from peer"
20✔
2332
        if !read {
36✔
2333
                prefix = "writeMessage to peer"
16✔
2334
        }
16✔
2335

2336
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
20✔
2337
}
2338

2339
// writeMessage writes and flushes the target lnwire.Message to the remote peer.
2340
// If the passed message is nil, this method will only try to flush an existing
2341
// message buffered on the connection. It is safe to call this method again
2342
// with a nil message iff a timeout error is returned. This will continue to
2343
// flush the pending message to the wire.
2344
//
2345
// NOTE:
2346
// Besides its usage in Start, this function should not be used elsewhere
2347
// except in writeHandler. If multiple goroutines call writeMessage at the same
2348
// time, panics can occur because WriteMessage and Flush don't use any locking
2349
// internally.
2350
func (p *Brontide) writeMessage(msg lnwire.Message) error {
16✔
2351
        // Only log the message on the first attempt.
16✔
2352
        if msg != nil {
32✔
2353
                p.logWireMessage(msg, false)
16✔
2354
        }
16✔
2355

2356
        noiseConn := p.cfg.Conn
16✔
2357

16✔
2358
        flushMsg := func() error {
32✔
2359
                // Ensure the write deadline is set before we attempt to send
16✔
2360
                // the message.
16✔
2361
                writeDeadline := time.Now().Add(
16✔
2362
                        p.scaleTimeout(writeMessageTimeout),
16✔
2363
                )
16✔
2364
                err := noiseConn.SetWriteDeadline(writeDeadline)
16✔
2365
                if err != nil {
16✔
2366
                        return err
×
2367
                }
×
2368

2369
                // Flush the pending message to the wire. If an error is
2370
                // encountered, e.g. write timeout, the number of bytes written
2371
                // so far will be returned.
2372
                n, err := noiseConn.Flush()
16✔
2373

16✔
2374
                // Record the number of bytes written on the wire, if any.
16✔
2375
                if n > 0 {
19✔
2376
                        atomic.AddUint64(&p.bytesSent, uint64(n))
3✔
2377
                }
3✔
2378

2379
                return err
16✔
2380
        }
2381

2382
        // If the current message has already been serialized, encrypted, and
2383
        // buffered on the underlying connection we will skip straight to
2384
        // flushing it to the wire.
2385
        if msg == nil {
16✔
2386
                return flushMsg()
×
2387
        }
×
2388

2389
        // Otherwise, this is a new message. We'll acquire a write buffer to
2390
        // serialize the message and buffer the ciphertext on the connection.
2391
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
32✔
2392
                // Using a buffer allocated by the write pool, encode the
16✔
2393
                // message directly into the buffer.
16✔
2394
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
16✔
2395
                if writeErr != nil {
16✔
2396
                        return writeErr
×
2397
                }
×
2398

2399
                // Finally, write the message itself in a single swoop. This
2400
                // will buffer the ciphertext on the underlying connection. We
2401
                // will defer flushing the message until the write pool has been
2402
                // released.
2403
                return noiseConn.WriteMessage(buf.Bytes())
16✔
2404
        })
2405
        if err != nil {
16✔
2406
                return err
×
2407
        }
×
2408

2409
        return flushMsg()
16✔
2410
}
2411

2412
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2413
// queue, and writing them out to the wire. This goroutine coordinates with the
2414
// queueHandler in order to ensure the incoming message queue is quickly
2415
// drained.
2416
//
2417
// NOTE: This method MUST be run as a goroutine.
2418
func (p *Brontide) writeHandler() {
6✔
2419
        // We'll stop the timer after a new messages is sent, and also reset it
6✔
2420
        // after we process the next message.
6✔
2421
        idleTimer := time.AfterFunc(idleTimeout, func() {
8✔
2422
                err := fmt.Errorf("peer %s no write for %s -- disconnecting",
2✔
2423
                        p, idleTimeout)
2✔
2424
                p.Disconnect(err)
2✔
2425
        })
2✔
2426

2427
        var exitErr error
6✔
2428

6✔
2429
out:
6✔
2430
        for {
16✔
2431
                select {
10✔
2432
                case outMsg := <-p.sendQueue:
7✔
2433
                        // Record the time at which we first attempt to send the
7✔
2434
                        // message.
7✔
2435
                        startTime := time.Now()
7✔
2436

7✔
2437
                retry:
7✔
2438
                        // Write out the message to the socket. If a timeout
2439
                        // error is encountered, we will catch this and retry
2440
                        // after backing off in case the remote peer is just
2441
                        // slow to process messages from the wire.
2442
                        err := p.writeMessage(outMsg.msg)
7✔
2443
                        if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
7✔
2444
                                p.log.Debugf("Write timeout detected for "+
×
2445
                                        "peer, first write for message "+
×
2446
                                        "attempted %v ago",
×
2447
                                        time.Since(startTime))
×
2448

×
2449
                                // If we received a timeout error, this implies
×
2450
                                // that the message was buffered on the
×
2451
                                // connection successfully and that a flush was
×
2452
                                // attempted. We'll set the message to nil so
×
2453
                                // that on a subsequent pass we only try to
×
2454
                                // flush the buffered message, and forgo
×
2455
                                // reserializing or reencrypting it.
×
2456
                                outMsg.msg = nil
×
2457

×
2458
                                goto retry
×
2459
                        }
2460

2461
                        // The write succeeded, reset the idle timer to prevent
2462
                        // us from disconnecting the peer.
2463
                        if !idleTimer.Stop() {
7✔
2464
                                select {
×
2465
                                case <-idleTimer.C:
×
2466
                                default:
×
2467
                                }
2468
                        }
2469
                        idleTimer.Reset(idleTimeout)
7✔
2470

7✔
2471
                        // If the peer requested a synchronous write, respond
7✔
2472
                        // with the error.
7✔
2473
                        if outMsg.errChan != nil {
11✔
2474
                                outMsg.errChan <- err
4✔
2475
                        }
4✔
2476

2477
                        if err != nil {
7✔
2478
                                exitErr = fmt.Errorf("unable to write "+
×
2479
                                        "message: %v", err)
×
2480
                                break out
×
2481
                        }
2482

2483
                case <-p.quit:
3✔
2484
                        exitErr = lnpeer.ErrPeerExiting
3✔
2485
                        break out
3✔
2486
                }
2487
        }
2488

2489
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2490
        // disconnect.
2491
        p.wg.Done()
3✔
2492

3✔
2493
        p.Disconnect(exitErr)
3✔
2494

3✔
2495
        p.log.Trace("writeHandler for peer done")
3✔
2496
}
2497

2498
// queueHandler is responsible for accepting messages from outside subsystems
2499
// to be eventually sent out on the wire by the writeHandler.
2500
//
2501
// NOTE: This method MUST be run as a goroutine.
2502
func (p *Brontide) queueHandler() {
6✔
2503
        defer p.wg.Done()
6✔
2504

6✔
2505
        // priorityMsgs holds an in order list of messages deemed high-priority
6✔
2506
        // to be added to the sendQueue. This predominately includes messages
6✔
2507
        // from the funding manager and htlcswitch.
6✔
2508
        priorityMsgs := list.New()
6✔
2509

6✔
2510
        // lazyMsgs holds an in order list of messages deemed low-priority to be
6✔
2511
        // added to the sendQueue only after all high-priority messages have
6✔
2512
        // been queued. This predominately includes messages from the gossiper.
6✔
2513
        lazyMsgs := list.New()
6✔
2514

6✔
2515
        for {
20✔
2516
                // Examine the front of the priority queue, if it is empty check
14✔
2517
                // the low priority queue.
14✔
2518
                elem := priorityMsgs.Front()
14✔
2519
                if elem == nil {
25✔
2520
                        elem = lazyMsgs.Front()
11✔
2521
                }
11✔
2522

2523
                if elem != nil {
21✔
2524
                        front := elem.Value.(outgoingMsg)
7✔
2525

7✔
2526
                        // There's an element on the queue, try adding
7✔
2527
                        // it to the sendQueue. We also watch for
7✔
2528
                        // messages on the outgoingQueue, in case the
7✔
2529
                        // writeHandler cannot accept messages on the
7✔
2530
                        // sendQueue.
7✔
2531
                        select {
7✔
2532
                        case p.sendQueue <- front:
7✔
2533
                                if front.priority {
13✔
2534
                                        priorityMsgs.Remove(elem)
6✔
2535
                                } else {
10✔
2536
                                        lazyMsgs.Remove(elem)
4✔
2537
                                }
4✔
2538
                        case msg := <-p.outgoingQueue:
3✔
2539
                                if msg.priority {
6✔
2540
                                        priorityMsgs.PushBack(msg)
3✔
2541
                                } else {
6✔
2542
                                        lazyMsgs.PushBack(msg)
3✔
2543
                                }
3✔
2544
                        case <-p.quit:
×
2545
                                return
×
2546
                        }
2547
                } else {
10✔
2548
                        // If there weren't any messages to send to the
10✔
2549
                        // writeHandler, then we'll accept a new message
10✔
2550
                        // into the queue from outside sub-systems.
10✔
2551
                        select {
10✔
2552
                        case msg := <-p.outgoingQueue:
7✔
2553
                                if msg.priority {
13✔
2554
                                        priorityMsgs.PushBack(msg)
6✔
2555
                                } else {
10✔
2556
                                        lazyMsgs.PushBack(msg)
4✔
2557
                                }
4✔
2558
                        case <-p.quit:
3✔
2559
                                return
3✔
2560
                        }
2561
                }
2562
        }
2563
}
2564

2565
// PingTime returns the estimated ping time to the peer in microseconds.
2566
func (p *Brontide) PingTime() int64 {
3✔
2567
        return p.pingManager.GetPingTimeMicroSeconds()
3✔
2568
}
3✔
2569

2570
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2571
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2572
// or failed to write, and nil otherwise.
2573
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
28✔
2574
        p.queue(true, msg, errChan)
28✔
2575
}
28✔
2576

2577
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2578
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2579
// queue or failed to write, and nil otherwise.
2580
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
4✔
2581
        p.queue(false, msg, errChan)
4✔
2582
}
4✔
2583

2584
// queue sends a given message to the queueHandler using the passed priority. If
2585
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2586
// failed to write, and nil otherwise.
2587
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2588
        errChan chan error) {
29✔
2589

29✔
2590
        select {
29✔
2591
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
28✔
2592
        case <-p.quit:
3✔
2593
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
3✔
2594
                        spew.Sdump(msg))
3✔
2595
                if errChan != nil {
3✔
2596
                        errChan <- lnpeer.ErrPeerExiting
×
2597
                }
×
2598
        }
2599
}
2600

2601
// ChannelSnapshots returns a slice of channel snapshots detailing all
2602
// currently active channels maintained with the remote peer.
2603
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
3✔
2604
        snapshots := make(
3✔
2605
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
3✔
2606
        )
3✔
2607

3✔
2608
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2609
                activeChan *lnwallet.LightningChannel) error {
6✔
2610

3✔
2611
                // If the activeChan is nil, then we skip it as the channel is
3✔
2612
                // pending.
3✔
2613
                if activeChan == nil {
6✔
2614
                        return nil
3✔
2615
                }
3✔
2616

2617
                // We'll only return a snapshot for channels that are
2618
                // *immediately* available for routing payments over.
2619
                if activeChan.RemoteNextRevocation() == nil {
6✔
2620
                        return nil
3✔
2621
                }
3✔
2622

2623
                snapshot := activeChan.StateSnapshot()
3✔
2624
                snapshots = append(snapshots, snapshot)
3✔
2625

3✔
2626
                return nil
3✔
2627
        })
2628

2629
        return snapshots
3✔
2630
}
2631

2632
// genDeliveryScript returns a new script to be used to send our funds to in
2633
// the case of a cooperative channel close negotiation.
2634
func (p *Brontide) genDeliveryScript() ([]byte, error) {
9✔
2635
        // We'll send a normal p2wkh address unless we've negotiated the
9✔
2636
        // shutdown-any-segwit feature.
9✔
2637
        addrType := lnwallet.WitnessPubKey
9✔
2638
        if p.taprootShutdownAllowed() {
12✔
2639
                addrType = lnwallet.TaprootPubkey
3✔
2640
        }
3✔
2641

2642
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
9✔
2643
                addrType, false, lnwallet.DefaultAccountName,
9✔
2644
        )
9✔
2645
        if err != nil {
9✔
2646
                return nil, err
×
2647
        }
×
2648
        p.log.Infof("Delivery addr for channel close: %v",
9✔
2649
                deliveryAddr)
9✔
2650

9✔
2651
        return txscript.PayToAddrScript(deliveryAddr)
9✔
2652
}
2653

2654
// channelManager is goroutine dedicated to handling all requests/signals
2655
// pertaining to the opening, cooperative closing, and force closing of all
2656
// channels maintained with the remote peer.
2657
//
2658
// NOTE: This method MUST be run as a goroutine.
2659
func (p *Brontide) channelManager() {
20✔
2660
        defer p.wg.Done()
20✔
2661

20✔
2662
        // reenableTimeout will fire once after the configured channel status
20✔
2663
        // interval has elapsed. This will trigger us to sign new channel
20✔
2664
        // updates and broadcast them with the "disabled" flag unset.
20✔
2665
        reenableTimeout := time.After(p.cfg.ChanActiveTimeout)
20✔
2666

20✔
2667
out:
20✔
2668
        for {
61✔
2669
                select {
41✔
2670
                // A new pending channel has arrived which means we are about
2671
                // to complete a funding workflow and is waiting for the final
2672
                // `ChannelReady` messages to be exchanged. We will add this
2673
                // channel to the `activeChannels` with a nil value to indicate
2674
                // this is a pending channel.
2675
                case req := <-p.newPendingChannel:
4✔
2676
                        p.handleNewPendingChannel(req)
4✔
2677

2678
                // A new channel has arrived which means we've just completed a
2679
                // funding workflow. We'll initialize the necessary local
2680
                // state, and notify the htlc switch of a new link.
2681
                case req := <-p.newActiveChannel:
3✔
2682
                        p.handleNewActiveChannel(req)
3✔
2683

2684
                // The funding flow for a pending channel is failed, we will
2685
                // remove it from Brontide.
2686
                case req := <-p.removePendingChannel:
4✔
2687
                        p.handleRemovePendingChannel(req)
4✔
2688

2689
                // We've just received a local request to close an active
2690
                // channel. It will either kick of a cooperative channel
2691
                // closure negotiation, or be a notification of a breached
2692
                // contract that should be abandoned.
2693
                case req := <-p.localCloseChanReqs:
10✔
2694
                        p.handleLocalCloseReq(req)
10✔
2695

2696
                // We've received a link failure from a link that was added to
2697
                // the switch. This will initiate the teardown of the link, and
2698
                // initiate any on-chain closures if necessary.
2699
                case failure := <-p.linkFailures:
3✔
2700
                        p.handleLinkFailure(failure)
3✔
2701

2702
                // We've received a new cooperative channel closure related
2703
                // message from the remote peer, we'll use this message to
2704
                // advance the chan closer state machine.
2705
                case closeMsg := <-p.chanCloseMsgs:
16✔
2706
                        p.handleCloseMsg(closeMsg)
16✔
2707

2708
                // The channel reannounce delay has elapsed, broadcast the
2709
                // reenabled channel updates to the network. This should only
2710
                // fire once, so we set the reenableTimeout channel to nil to
2711
                // mark it for garbage collection. If the peer is torn down
2712
                // before firing, reenabling will not be attempted.
2713
                // TODO(conner): consolidate reenables timers inside chan status
2714
                // manager
2715
                case <-reenableTimeout:
3✔
2716
                        p.reenableActiveChannels()
3✔
2717

3✔
2718
                        // Since this channel will never fire again during the
3✔
2719
                        // lifecycle of the peer, we nil the channel to mark it
3✔
2720
                        // eligible for garbage collection, and make this
3✔
2721
                        // explicitly ineligible to receive in future calls to
3✔
2722
                        // select. This also shaves a few CPU cycles since the
3✔
2723
                        // select will ignore this case entirely.
3✔
2724
                        reenableTimeout = nil
3✔
2725

3✔
2726
                        // Once the reenabling is attempted, we also cancel the
3✔
2727
                        // channel event subscription to free up the overflow
3✔
2728
                        // queue used in channel notifier.
3✔
2729
                        //
3✔
2730
                        // NOTE: channelEventClient will be nil if the
3✔
2731
                        // reenableTimeout is greater than 1 minute.
3✔
2732
                        if p.channelEventClient != nil {
6✔
2733
                                p.channelEventClient.Cancel()
3✔
2734
                        }
3✔
2735

2736
                case <-p.quit:
3✔
2737
                        // As, we've been signalled to exit, we'll reset all
3✔
2738
                        // our active channel back to their default state.
3✔
2739
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2740
                                lc *lnwallet.LightningChannel) error {
6✔
2741

3✔
2742
                                // Exit if the channel is nil as it's a pending
3✔
2743
                                // channel.
3✔
2744
                                if lc == nil {
6✔
2745
                                        return nil
3✔
2746
                                }
3✔
2747

2748
                                lc.ResetState()
3✔
2749

3✔
2750
                                return nil
3✔
2751
                        })
2752

2753
                        break out
3✔
2754
                }
2755
        }
2756
}
2757

2758
// reenableActiveChannels searches the index of channels maintained with this
2759
// peer, and reenables each public, non-pending channel. This is done at the
2760
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
2761
// No message will be sent if the channel is already enabled.
2762
func (p *Brontide) reenableActiveChannels() {
3✔
2763
        // First, filter all known channels with this peer for ones that are
3✔
2764
        // both public and not pending.
3✔
2765
        activePublicChans := p.filterChannelsToEnable()
3✔
2766

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

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

3✔
2776
                switch {
3✔
2777
                // No error occurred, continue to request the next channel.
2778
                case err == nil:
3✔
2779
                        continue
3✔
2780

2781
                // Cannot auto enable a manually disabled channel so we do
2782
                // nothing but proceed to the next channel.
2783
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
3✔
2784
                        p.log.Debugf("Channel(%v) was manually disabled, "+
3✔
2785
                                "ignoring automatic enable request", chanPoint)
3✔
2786

3✔
2787
                        continue
3✔
2788

2789
                // If the channel is reported as inactive, we will give it
2790
                // another chance. When handling the request, ChanStatusManager
2791
                // will check whether the link is active or not. One of the
2792
                // conditions is whether the link has been marked as
2793
                // reestablished, which happens inside a goroutine(htlcManager)
2794
                // after the link is started. And we may get a false negative
2795
                // saying the link is not active because that goroutine hasn't
2796
                // reached the line to mark the reestablishment. Thus we give
2797
                // it a second chance to send the request.
2798
                case errors.Is(err, netann.ErrEnableInactiveChan):
×
2799
                        // If we don't have a client created, it means we
×
2800
                        // shouldn't retry enabling the channel.
×
2801
                        if p.channelEventClient == nil {
×
2802
                                p.log.Errorf("Channel(%v) request enabling "+
×
2803
                                        "failed due to inactive link",
×
2804
                                        chanPoint)
×
2805

×
2806
                                continue
×
2807
                        }
2808

2809
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
2810
                                "ChanStatusManager reported inactive, retrying")
×
2811

×
2812
                        // Add the channel to the retry map.
×
2813
                        retryChans[chanPoint] = struct{}{}
×
2814
                }
2815
        }
2816

2817
        // Retry the channels if we have any.
2818
        if len(retryChans) != 0 {
3✔
2819
                p.retryRequestEnable(retryChans)
×
2820
        }
×
2821
}
2822

2823
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
2824
// for the target channel ID. If the channel isn't active an error is returned.
2825
// Otherwise, either an existing state machine will be returned, or a new one
2826
// will be created.
2827
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
2828
        *chancloser.ChanCloser, error) {
16✔
2829

16✔
2830
        chanCloser, found := p.activeChanCloses[chanID]
16✔
2831
        if found {
29✔
2832
                // An entry will only be found if the closer has already been
13✔
2833
                // created for a non-pending channel or for a channel that had
13✔
2834
                // previously started the shutdown process but the connection
13✔
2835
                // was restarted.
13✔
2836
                return chanCloser, nil
13✔
2837
        }
13✔
2838

2839
        // First, we'll ensure that we actually know of the target channel. If
2840
        // not, we'll ignore this message.
2841
        channel, ok := p.activeChannels.Load(chanID)
6✔
2842

6✔
2843
        // If the channel isn't in the map or the channel is nil, return
6✔
2844
        // ErrChannelNotFound as the channel is pending.
6✔
2845
        if !ok || channel == nil {
9✔
2846
                return nil, ErrChannelNotFound
3✔
2847
        }
3✔
2848

2849
        // We'll create a valid closing state machine in order to respond to
2850
        // the initiated cooperative channel closure. First, we set the
2851
        // delivery script that our funds will be paid out to. If an upfront
2852
        // shutdown script was set, we will use it. Otherwise, we get a fresh
2853
        // delivery script.
2854
        //
2855
        // TODO: Expose option to allow upfront shutdown script from watch-only
2856
        // accounts.
2857
        deliveryScript := channel.LocalUpfrontShutdownScript()
6✔
2858
        if len(deliveryScript) == 0 {
12✔
2859
                var err error
6✔
2860
                deliveryScript, err = p.genDeliveryScript()
6✔
2861
                if err != nil {
6✔
2862
                        p.log.Errorf("unable to gen delivery script: %v",
×
2863
                                err)
×
2864
                        return nil, fmt.Errorf("close addr unavailable")
×
2865
                }
×
2866
        }
2867

2868
        // In order to begin fee negotiations, we'll first compute our target
2869
        // ideal fee-per-kw.
2870
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
6✔
2871
                p.cfg.CoopCloseTargetConfs,
6✔
2872
        )
6✔
2873
        if err != nil {
6✔
2874
                p.log.Errorf("unable to query fee estimator: %v", err)
×
2875
                return nil, fmt.Errorf("unable to estimate fee")
×
2876
        }
×
2877

2878
        chanCloser, err = p.createChanCloser(
6✔
2879
                channel, deliveryScript, feePerKw, nil, lntypes.Remote,
6✔
2880
        )
6✔
2881
        if err != nil {
6✔
2882
                p.log.Errorf("unable to create chan closer: %v", err)
×
2883
                return nil, fmt.Errorf("unable to create chan closer")
×
2884
        }
×
2885

2886
        p.activeChanCloses[chanID] = chanCloser
6✔
2887

6✔
2888
        return chanCloser, nil
6✔
2889
}
2890

2891
// filterChannelsToEnable filters a list of channels to be enabled upon start.
2892
// The filtered channels are active channels that's neither private nor
2893
// pending.
2894
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
3✔
2895
        var activePublicChans []wire.OutPoint
3✔
2896

3✔
2897
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
3✔
2898
                lnChan *lnwallet.LightningChannel) bool {
6✔
2899

3✔
2900
                // If the lnChan is nil, continue as this is a pending channel.
3✔
2901
                if lnChan == nil {
3✔
2902
                        return true
×
2903
                }
×
2904

2905
                dbChan := lnChan.State()
3✔
2906
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
2907
                if !isPublic || dbChan.IsPending {
3✔
2908
                        return true
×
2909
                }
×
2910

2911
                // We'll also skip any channels added during this peer's
2912
                // lifecycle since they haven't waited out the timeout. Their
2913
                // first announcement will be enabled, and the chan status
2914
                // manager will begin monitoring them passively since they exist
2915
                // in the database.
2916
                if _, ok := p.addedChannels.Load(chanID); ok {
6✔
2917
                        return true
3✔
2918
                }
3✔
2919

2920
                activePublicChans = append(
3✔
2921
                        activePublicChans, dbChan.FundingOutpoint,
3✔
2922
                )
3✔
2923

3✔
2924
                return true
3✔
2925
        })
2926

2927
        return activePublicChans
3✔
2928
}
2929

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

×
2937
        // retryEnable is a helper closure that sends an enable request and
×
2938
        // removes the channel from the map if it's matched.
×
2939
        retryEnable := func(chanPoint wire.OutPoint) error {
×
2940
                // If this is an active channel event, check whether it's in
×
2941
                // our targeted channels map.
×
2942
                _, found := activeChans[chanPoint]
×
2943

×
2944
                // If this channel is irrelevant, return nil so the loop can
×
2945
                // jump to next iteration.
×
2946
                if !found {
×
2947
                        return nil
×
2948
                }
×
2949

2950
                // Otherwise we've just received an active signal for a channel
2951
                // that's previously failed to be enabled, we send the request
2952
                // again.
2953
                //
2954
                // We only give the channel one more shot, so we delete it from
2955
                // our map first to keep it from being attempted again.
2956
                delete(activeChans, chanPoint)
×
2957

×
2958
                // Send the request.
×
2959
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
2960
                if err != nil {
×
2961
                        return fmt.Errorf("request enabling channel %v "+
×
2962
                                "failed: %w", chanPoint, err)
×
2963
                }
×
2964

2965
                return nil
×
2966
        }
2967

2968
        for {
×
2969
                // If activeChans is empty, we've done processing all the
×
2970
                // channels.
×
2971
                if len(activeChans) == 0 {
×
2972
                        p.log.Debug("Finished retry enabling channels")
×
2973
                        return
×
2974
                }
×
2975

2976
                select {
×
2977
                // A new event has been sent by the ChannelNotifier. We now
2978
                // check whether it's an active or inactive channel event.
2979
                case e := <-p.channelEventClient.Updates():
×
2980
                        // If this is an active channel event, try enable the
×
2981
                        // channel then jump to the next iteration.
×
2982
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
2983
                        if ok {
×
2984
                                chanPoint := *active.ChannelPoint
×
2985

×
2986
                                // If we received an error for this particular
×
2987
                                // channel, we log an error and won't quit as
×
2988
                                // we still want to retry other channels.
×
2989
                                if err := retryEnable(chanPoint); err != nil {
×
2990
                                        p.log.Errorf("Retry failed: %v", err)
×
2991
                                }
×
2992

2993
                                continue
×
2994
                        }
2995

2996
                        // Otherwise check for inactive link event, and jump to
2997
                        // next iteration if it's not.
2998
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
2999
                        if !ok {
×
3000
                                continue
×
3001
                        }
3002

3003
                        // Found an inactive link event, if this is our
3004
                        // targeted channel, remove it from our map.
3005
                        chanPoint := *inactive.ChannelPoint
×
3006
                        _, found := activeChans[chanPoint]
×
3007
                        if !found {
×
3008
                                continue
×
3009
                        }
3010

3011
                        delete(activeChans, chanPoint)
×
3012
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3013
                                "inactive link event", chanPoint)
×
3014

3015
                case <-p.quit:
×
3016
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3017
                        return
×
3018
                }
3019
        }
3020
}
3021

3022
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3023
// a suitable script to close out to. This may be nil if neither script is
3024
// set. If both scripts are set, this function will error if they do not match.
3025
func chooseDeliveryScript(upfront,
3026
        requested lnwire.DeliveryAddress) (lnwire.DeliveryAddress, error) {
15✔
3027

15✔
3028
        // If no upfront shutdown script was provided, return the user
15✔
3029
        // requested address (which may be nil).
15✔
3030
        if len(upfront) == 0 {
24✔
3031
                return requested, nil
9✔
3032
        }
9✔
3033

3034
        // If an upfront shutdown script was provided, and the user did not
3035
        // request a custom shutdown script, return the upfront address.
3036
        if len(requested) == 0 {
14✔
3037
                return upfront, nil
5✔
3038
        }
5✔
3039

3040
        // If both an upfront shutdown script and a custom close script were
3041
        // provided, error if the user provided shutdown script does not match
3042
        // the upfront shutdown script (because closing out to a different
3043
        // script would violate upfront shutdown).
3044
        if !bytes.Equal(upfront, requested) {
6✔
3045
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
3046
        }
2✔
3047

3048
        // The user requested script matches the upfront shutdown script, so we
3049
        // can return it without error.
3050
        return upfront, nil
2✔
3051
}
3052

3053
// restartCoopClose checks whether we need to restart the cooperative close
3054
// process for a given channel.
3055
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3056
        *lnwire.Shutdown, error) {
×
3057

×
3058
        // If this channel has status ChanStatusCoopBroadcasted and does not
×
3059
        // have a closing transaction, then the cooperative close process was
×
3060
        // started but never finished. We'll re-create the chanCloser state
×
3061
        // machine and resend Shutdown. BOLT#2 requires that we retransmit
×
3062
        // Shutdown exactly, but doing so would mean persisting the RPC
×
3063
        // provided close script. Instead use the LocalUpfrontShutdownScript
×
3064
        // or generate a script.
×
3065
        c := lnChan.State()
×
3066
        _, err := c.BroadcastedCooperative()
×
3067
        if err != nil && err != channeldb.ErrNoCloseTx {
×
3068
                // An error other than ErrNoCloseTx was encountered.
×
3069
                return nil, err
×
3070
        } else if err == nil {
×
3071
                // This channel has already completed the coop close
×
3072
                // negotiation.
×
3073
                return nil, nil
×
3074
        }
×
3075

3076
        var deliveryScript []byte
×
3077

×
3078
        shutdownInfo, err := c.ShutdownInfo()
×
3079
        switch {
×
3080
        // We have previously stored the delivery script that we need to use
3081
        // in the shutdown message. Re-use this script.
3082
        case err == nil:
×
3083
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
×
3084
                        deliveryScript = info.DeliveryScript.Val
×
3085
                })
×
3086

3087
        // An error other than ErrNoShutdownInfo was returned
3088
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3089
                return nil, err
×
3090

3091
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3092
                deliveryScript = c.LocalShutdownScript
×
3093
                if len(deliveryScript) == 0 {
×
3094
                        var err error
×
3095
                        deliveryScript, err = p.genDeliveryScript()
×
3096
                        if err != nil {
×
3097
                                p.log.Errorf("unable to gen delivery script: "+
×
3098
                                        "%v", err)
×
3099

×
3100
                                return nil, fmt.Errorf("close addr unavailable")
×
3101
                        }
×
3102
                }
3103
        }
3104

3105
        // Compute an ideal fee.
3106
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
3107
                p.cfg.CoopCloseTargetConfs,
×
3108
        )
×
3109
        if err != nil {
×
3110
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3111
                return nil, fmt.Errorf("unable to estimate fee")
×
3112
        }
×
3113

3114
        // Determine whether we or the peer are the initiator of the coop
3115
        // close attempt by looking at the channel's status.
3116
        closingParty := lntypes.Remote
×
3117
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3118
                closingParty = lntypes.Local
×
3119
        }
×
3120

3121
        chanCloser, err := p.createChanCloser(
×
3122
                lnChan, deliveryScript, feePerKw, nil, closingParty,
×
3123
        )
×
3124
        if err != nil {
×
3125
                p.log.Errorf("unable to create chan closer: %v", err)
×
3126
                return nil, fmt.Errorf("unable to create chan closer")
×
3127
        }
×
3128

3129
        // This does not need a mutex even though it is in a different
3130
        // goroutine since this is done before the channelManager goroutine is
3131
        // created.
3132
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
×
3133
        p.activeChanCloses[chanID] = chanCloser
×
3134

×
3135
        // Create the Shutdown message.
×
3136
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3137
        if err != nil {
×
3138
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3139
                delete(p.activeChanCloses, chanID)
×
3140
                return nil, err
×
3141
        }
×
3142

3143
        return shutdownMsg, nil
×
3144
}
3145

3146
// createChanCloser constructs a ChanCloser from the passed parameters and is
3147
// used to de-duplicate code.
3148
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3149
        deliveryScript lnwire.DeliveryAddress, fee chainfee.SatPerKWeight,
3150
        req *htlcswitch.ChanClose,
3151
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
12✔
3152

12✔
3153
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
12✔
3154
        if err != nil {
12✔
3155
                p.log.Errorf("unable to obtain best block: %v", err)
×
3156
                return nil, fmt.Errorf("cannot obtain best block")
×
3157
        }
×
3158

3159
        // The req will only be set if we initiated the co-op closing flow.
3160
        var maxFee chainfee.SatPerKWeight
12✔
3161
        if req != nil {
21✔
3162
                maxFee = req.MaxFee
9✔
3163
        }
9✔
3164

3165
        chanCloser := chancloser.NewChanCloser(
12✔
3166
                chancloser.ChanCloseCfg{
12✔
3167
                        Channel:      channel,
12✔
3168
                        MusigSession: NewMusigChanCloser(channel),
12✔
3169
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
12✔
3170
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
12✔
3171
                        DisableChannel: func(op wire.OutPoint) error {
24✔
3172
                                return p.cfg.ChanStatusMgr.RequestDisable(
12✔
3173
                                        op, false,
12✔
3174
                                )
12✔
3175
                        },
12✔
3176
                        MaxFee: maxFee,
3177
                        Disconnect: func() error {
×
3178
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
3179
                        },
×
3180
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3181
                        Quit:        p.quit,
3182
                },
3183
                deliveryScript,
3184
                fee,
3185
                uint32(startingHeight),
3186
                req,
3187
                closer,
3188
        )
3189

3190
        return chanCloser, nil
12✔
3191
}
3192

3193
// handleLocalCloseReq kicks-off the workflow to execute a cooperative or
3194
// forced unilateral closure of the channel initiated by a local subsystem.
3195
func (p *Brontide) handleLocalCloseReq(req *htlcswitch.ChanClose) {
10✔
3196
        chanID := lnwire.NewChanIDFromOutPoint(*req.ChanPoint)
10✔
3197

10✔
3198
        channel, ok := p.activeChannels.Load(chanID)
10✔
3199

10✔
3200
        // Though this function can't be called for pending channels, we still
10✔
3201
        // check whether channel is nil for safety.
10✔
3202
        if !ok || channel == nil {
10✔
3203
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
×
3204
                        "unknown", chanID)
×
3205
                p.log.Errorf(err.Error())
×
3206
                req.Err <- err
×
3207
                return
×
3208
        }
×
3209

3210
        switch req.CloseType {
10✔
3211
        // A type of CloseRegular indicates that the user has opted to close
3212
        // out this channel on-chain, so we execute the cooperative channel
3213
        // closure workflow.
3214
        case contractcourt.CloseRegular:
10✔
3215
                // First, we'll choose a delivery address that we'll use to send the
10✔
3216
                // funds to in the case of a successful negotiation.
10✔
3217

10✔
3218
                // An upfront shutdown and user provided script are both optional,
10✔
3219
                // but must be equal if both set  (because we cannot serve a request
10✔
3220
                // to close out to a script which violates upfront shutdown). Get the
10✔
3221
                // appropriate address to close out to (which may be nil if neither
10✔
3222
                // are set) and error if they are both set and do not match.
10✔
3223
                deliveryScript, err := chooseDeliveryScript(
10✔
3224
                        channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
10✔
3225
                )
10✔
3226
                if err != nil {
11✔
3227
                        p.log.Errorf("cannot close channel %v: %v", req.ChanPoint, err)
1✔
3228
                        req.Err <- err
1✔
3229
                        return
1✔
3230
                }
1✔
3231

3232
                // If neither an upfront address or a user set address was
3233
                // provided, generate a fresh script.
3234
                if len(deliveryScript) == 0 {
15✔
3235
                        deliveryScript, err = p.genDeliveryScript()
6✔
3236
                        if err != nil {
6✔
3237
                                p.log.Errorf(err.Error())
×
3238
                                req.Err <- err
×
3239
                                return
×
3240
                        }
×
3241
                }
3242

3243
                chanCloser, err := p.createChanCloser(
9✔
3244
                        channel, deliveryScript, req.TargetFeePerKw, req,
9✔
3245
                        lntypes.Local,
9✔
3246
                )
9✔
3247
                if err != nil {
9✔
3248
                        p.log.Errorf(err.Error())
×
3249
                        req.Err <- err
×
3250
                        return
×
3251
                }
×
3252

3253
                p.activeChanCloses[chanID] = chanCloser
9✔
3254

9✔
3255
                // Finally, we'll initiate the channel shutdown within the
9✔
3256
                // chanCloser, and send the shutdown message to the remote
9✔
3257
                // party to kick things off.
9✔
3258
                shutdownMsg, err := chanCloser.ShutdownChan()
9✔
3259
                if err != nil {
9✔
3260
                        p.log.Errorf(err.Error())
×
3261
                        req.Err <- err
×
3262
                        delete(p.activeChanCloses, chanID)
×
3263

×
3264
                        // As we were unable to shutdown the channel, we'll
×
3265
                        // return it back to its normal state.
×
3266
                        channel.ResetState()
×
3267
                        return
×
3268
                }
×
3269

3270
                link := p.fetchLinkFromKeyAndCid(chanID)
9✔
3271
                if link == nil {
9✔
3272
                        // If the link is nil then it means it was already
×
3273
                        // removed from the switch or it never existed in the
×
3274
                        // first place. The latter case is handled at the
×
3275
                        // beginning of this function, so in the case where it
×
3276
                        // has already been removed, we can skip adding the
×
3277
                        // commit hook to queue a Shutdown message.
×
3278
                        p.log.Warnf("link not found during attempted closure: "+
×
3279
                                "%v", chanID)
×
3280
                        return
×
3281
                }
×
3282

3283
                if !link.DisableAdds(htlcswitch.Outgoing) {
9✔
3284
                        p.log.Warnf("Outgoing link adds already "+
×
3285
                                "disabled: %v", link.ChanID())
×
3286
                }
×
3287

3288
                link.OnCommitOnce(htlcswitch.Outgoing, func() {
18✔
3289
                        p.queueMsg(shutdownMsg, nil)
9✔
3290
                })
9✔
3291

3292
        // A type of CloseBreach indicates that the counterparty has breached
3293
        // the channel therefore we need to clean up our local state.
3294
        case contractcourt.CloseBreach:
1✔
3295
                // TODO(roasbeef): no longer need with newer beach logic?
1✔
3296
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
1✔
3297
                        "channel", req.ChanPoint)
1✔
3298
                p.WipeChannel(req.ChanPoint)
1✔
3299
        }
3300
}
3301

3302
// linkFailureReport is sent to the channelManager whenever a link reports a
3303
// link failure, and is forced to exit. The report houses the necessary
3304
// information to clean up the channel state, send back the error message, and
3305
// force close if necessary.
3306
type linkFailureReport struct {
3307
        chanPoint   wire.OutPoint
3308
        chanID      lnwire.ChannelID
3309
        shortChanID lnwire.ShortChannelID
3310
        linkErr     htlcswitch.LinkFailureError
3311
}
3312

3313
// handleLinkFailure processes a link failure report when a link in the switch
3314
// fails. It facilitates the removal of all channel state within the peer,
3315
// force closing the channel depending on severity, and sending the error
3316
// message back to the remote party.
3317
func (p *Brontide) handleLinkFailure(failure linkFailureReport) {
3✔
3318
        // Retrieve the channel from the map of active channels. We do this to
3✔
3319
        // have access to it even after WipeChannel remove it from the map.
3✔
3320
        chanID := lnwire.NewChanIDFromOutPoint(failure.chanPoint)
3✔
3321
        lnChan, _ := p.activeChannels.Load(chanID)
3✔
3322

3✔
3323
        // We begin by wiping the link, which will remove it from the switch,
3✔
3324
        // such that it won't be attempted used for any more updates.
3✔
3325
        //
3✔
3326
        // TODO(halseth): should introduce a way to atomically stop/pause the
3✔
3327
        // link and cancel back any adds in its mailboxes such that we can
3✔
3328
        // safely force close without the link being added again and updates
3✔
3329
        // being applied.
3✔
3330
        p.WipeChannel(&failure.chanPoint)
3✔
3331

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

3✔
3337
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
3✔
3338
                        failure.chanPoint,
3✔
3339
                )
3✔
3340
                if err != nil {
6✔
3341
                        p.log.Errorf("unable to force close "+
3✔
3342
                                "link(%v): %v", failure.shortChanID, err)
3✔
3343
                } else {
6✔
3344
                        p.log.Infof("channel(%v) force "+
3✔
3345
                                "closed with txid %v",
3✔
3346
                                failure.shortChanID, closeTx.TxHash())
3✔
3347
                }
3✔
3348
        }
3349

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

×
3355
                if err := lnChan.State().MarkBorked(); err != nil {
×
3356
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
3357
                                failure.shortChanID, err)
×
3358
                }
×
3359
        }
3360

3361
        // Send an error to the peer, why we failed the channel.
3362
        if failure.linkErr.ShouldSendToPeer() {
6✔
3363
                // If SendData is set, send it to the peer. If not, we'll use
3✔
3364
                // the standard error messages in the payload. We only include
3✔
3365
                // sendData in the cases where the error data does not contain
3✔
3366
                // sensitive information.
3✔
3367
                data := []byte(failure.linkErr.Error())
3✔
3368
                if failure.linkErr.SendData != nil {
3✔
3369
                        data = failure.linkErr.SendData
×
3370
                }
×
3371

3372
                var networkMsg lnwire.Message
3✔
3373
                if failure.linkErr.Warning {
3✔
3374
                        networkMsg = &lnwire.Warning{
×
3375
                                ChanID: failure.chanID,
×
3376
                                Data:   data,
×
3377
                        }
×
3378
                } else {
3✔
3379
                        networkMsg = &lnwire.Error{
3✔
3380
                                ChanID: failure.chanID,
3✔
3381
                                Data:   data,
3✔
3382
                        }
3✔
3383
                }
3✔
3384

3385
                err := p.SendMessage(true, networkMsg)
3✔
3386
                if err != nil {
3✔
3387
                        p.log.Errorf("unable to send msg to "+
×
3388
                                "remote peer: %v", err)
×
3389
                }
×
3390
        }
3391

3392
        // If the failure action is disconnect, then we'll execute that now. If
3393
        // we had to send an error above, it was a sync call, so we expect the
3394
        // message to be flushed on the wire by now.
3395
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
3✔
3396
                p.Disconnect(fmt.Errorf("link requested disconnect"))
×
3397
        }
×
3398
}
3399

3400
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
3401
// public key and the channel id.
3402
func (p *Brontide) fetchLinkFromKeyAndCid(
3403
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
22✔
3404

22✔
3405
        var chanLink htlcswitch.ChannelUpdateHandler
22✔
3406

22✔
3407
        // We don't need to check the error here, and can instead just loop
22✔
3408
        // over the slice and return nil.
22✔
3409
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
22✔
3410
        for _, link := range links {
43✔
3411
                if link.ChanID() == cid {
42✔
3412
                        chanLink = link
21✔
3413
                        break
21✔
3414
                }
3415
        }
3416

3417
        return chanLink
22✔
3418
}
3419

3420
// finalizeChanClosure performs the final clean up steps once the cooperative
3421
// closure transaction has been fully broadcast. The finalized closing state
3422
// machine should be passed in. Once the transaction has been sufficiently
3423
// confirmed, the channel will be marked as fully closed within the database,
3424
// and any clients will be notified of updates to the closing state.
3425
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
7✔
3426
        closeReq := chanCloser.CloseRequest()
7✔
3427

7✔
3428
        // First, we'll clear all indexes related to the channel in question.
7✔
3429
        chanPoint := chanCloser.Channel().ChannelPoint()
7✔
3430
        p.WipeChannel(&chanPoint)
7✔
3431

7✔
3432
        // Also clear the activeChanCloses map of this channel.
7✔
3433
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
7✔
3434
        delete(p.activeChanCloses, cid)
7✔
3435

7✔
3436
        // Next, we'll launch a goroutine which will request to be notified by
7✔
3437
        // the ChainNotifier once the closure transaction obtains a single
7✔
3438
        // confirmation.
7✔
3439
        notifier := p.cfg.ChainNotifier
7✔
3440

7✔
3441
        // If any error happens during waitForChanToClose, forward it to
7✔
3442
        // closeReq. If this channel closure is not locally initiated, closeReq
7✔
3443
        // will be nil, so just ignore the error.
7✔
3444
        errChan := make(chan error, 1)
7✔
3445
        if closeReq != nil {
12✔
3446
                errChan = closeReq.Err
5✔
3447
        }
5✔
3448

3449
        closingTx, err := chanCloser.ClosingTx()
7✔
3450
        if err != nil {
7✔
3451
                if closeReq != nil {
×
3452
                        p.log.Error(err)
×
3453
                        closeReq.Err <- err
×
3454
                }
×
3455
        }
3456

3457
        closingTxid := closingTx.TxHash()
7✔
3458

7✔
3459
        // If this is a locally requested shutdown, update the caller with a
7✔
3460
        // new event detailing the current pending state of this request.
7✔
3461
        if closeReq != nil {
12✔
3462
                closeReq.Updates <- &PendingUpdate{
5✔
3463
                        Txid: closingTxid[:],
5✔
3464
                }
5✔
3465
        }
5✔
3466

3467
        go WaitForChanToClose(chanCloser.NegotiationHeight(), notifier, errChan,
7✔
3468
                &chanPoint, &closingTxid, closingTx.TxOut[0].PkScript, func() {
14✔
3469
                        // Respond to the local subsystem which requested the
7✔
3470
                        // channel closure.
7✔
3471
                        if closeReq != nil {
12✔
3472
                                closeReq.Updates <- &ChannelCloseUpdate{
5✔
3473
                                        ClosingTxid: closingTxid[:],
5✔
3474
                                        Success:     true,
5✔
3475
                                }
5✔
3476
                        }
5✔
3477
                })
3478
}
3479

3480
// WaitForChanToClose uses the passed notifier to wait until the channel has
3481
// been detected as closed on chain and then concludes by executing the
3482
// following actions: the channel point will be sent over the settleChan, and
3483
// finally the callback will be executed. If any error is encountered within
3484
// the function, then it will be sent over the errChan.
3485
func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
3486
        errChan chan error, chanPoint *wire.OutPoint,
3487
        closingTxID *chainhash.Hash, closeScript []byte, cb func()) {
7✔
3488

7✔
3489
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
7✔
3490
                "with txid: %v", chanPoint, closingTxID)
7✔
3491

7✔
3492
        // TODO(roasbeef): add param for num needed confs
7✔
3493
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
7✔
3494
                closingTxID, closeScript, 1, bestHeight,
7✔
3495
        )
7✔
3496
        if err != nil {
7✔
3497
                if errChan != nil {
×
3498
                        errChan <- err
×
3499
                }
×
3500
                return
×
3501
        }
3502

3503
        // In the case that the ChainNotifier is shutting down, all subscriber
3504
        // notification channels will be closed, generating a nil receive.
3505
        height, ok := <-confNtfn.Confirmed
7✔
3506
        if !ok {
10✔
3507
                return
3✔
3508
        }
3✔
3509

3510
        // The channel has been closed, remove it from any active indexes, and
3511
        // the database state.
3512
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
7✔
3513
                "height %v", chanPoint, height.BlockHeight)
7✔
3514

7✔
3515
        // Finally, execute the closure call back to mark the confirmation of
7✔
3516
        // the transaction closing the contract.
7✔
3517
        cb()
7✔
3518
}
3519

3520
// WipeChannel removes the passed channel point from all indexes associated with
3521
// the peer and the switch.
3522
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
7✔
3523
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
7✔
3524

7✔
3525
        p.activeChannels.Delete(chanID)
7✔
3526

7✔
3527
        // Instruct the HtlcSwitch to close this link as the channel is no
7✔
3528
        // longer active.
7✔
3529
        p.cfg.Switch.RemoveLink(chanID)
7✔
3530
}
7✔
3531

3532
// handleInitMsg handles the incoming init message which contains global and
3533
// local feature vectors. If feature vectors are incompatible then disconnect.
3534
func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
6✔
3535
        // First, merge any features from the legacy global features field into
6✔
3536
        // those presented in the local features fields.
6✔
3537
        err := msg.Features.Merge(msg.GlobalFeatures)
6✔
3538
        if err != nil {
6✔
3539
                return fmt.Errorf("unable to merge legacy global features: %w",
×
3540
                        err)
×
3541
        }
×
3542

3543
        // Then, finalize the remote feature vector providing the flattened
3544
        // feature bit namespace.
3545
        p.remoteFeatures = lnwire.NewFeatureVector(
6✔
3546
                msg.Features, lnwire.Features,
6✔
3547
        )
6✔
3548

6✔
3549
        // Now that we have their features loaded, we'll ensure that they
6✔
3550
        // didn't set any required bits that we don't know of.
6✔
3551
        err = feature.ValidateRequired(p.remoteFeatures)
6✔
3552
        if err != nil {
6✔
3553
                return fmt.Errorf("invalid remote features: %w", err)
×
3554
        }
×
3555

3556
        // Ensure the remote party's feature vector contains all transitive
3557
        // dependencies. We know ours are correct since they are validated
3558
        // during the feature manager's instantiation.
3559
        err = feature.ValidateDeps(p.remoteFeatures)
6✔
3560
        if err != nil {
6✔
3561
                return fmt.Errorf("invalid remote features: %w", err)
×
3562
        }
×
3563

3564
        // Now that we know we understand their requirements, we'll check to
3565
        // see if they don't support anything that we deem to be mandatory.
3566
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
6✔
3567
                return fmt.Errorf("data loss protection required")
×
3568
        }
×
3569

3570
        return nil
6✔
3571
}
3572

3573
// LocalFeatures returns the set of global features that has been advertised by
3574
// the local node. This allows sub-systems that use this interface to gate their
3575
// behavior off the set of negotiated feature bits.
3576
//
3577
// NOTE: Part of the lnpeer.Peer interface.
3578
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
3✔
3579
        return p.cfg.Features
3✔
3580
}
3✔
3581

3582
// RemoteFeatures returns the set of global features that has been advertised by
3583
// the remote node. This allows sub-systems that use this interface to gate
3584
// their behavior off the set of negotiated feature bits.
3585
//
3586
// NOTE: Part of the lnpeer.Peer interface.
3587
func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector {
9✔
3588
        return p.remoteFeatures
9✔
3589
}
9✔
3590

3591
// hasNegotiatedScidAlias returns true if we've negotiated the
3592
// option-scid-alias feature bit with the peer.
3593
func (p *Brontide) hasNegotiatedScidAlias() bool {
6✔
3594
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
6✔
3595
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
6✔
3596
        return peerHas && localHas
6✔
3597
}
6✔
3598

3599
// sendInitMsg sends the Init message to the remote peer. This message contains
3600
// our currently supported local and global features.
3601
func (p *Brontide) sendInitMsg(legacyChan bool) error {
10✔
3602
        features := p.cfg.Features.Clone()
10✔
3603
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
10✔
3604

10✔
3605
        // If we have a legacy channel open with a peer, we downgrade static
10✔
3606
        // remote required to optional in case the peer does not understand the
10✔
3607
        // required feature bit. If we do not do this, the peer will reject our
10✔
3608
        // connection because it does not understand a required feature bit, and
10✔
3609
        // our channel will be unusable.
10✔
3610
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
11✔
3611
                p.log.Infof("Legacy channel open with peer, " +
1✔
3612
                        "downgrading static remote required feature bit to " +
1✔
3613
                        "optional")
1✔
3614

1✔
3615
                // Unset and set in both the local and global features to
1✔
3616
                // ensure both sets are consistent and merge able by old and
1✔
3617
                // new nodes.
1✔
3618
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3619
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3620

1✔
3621
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
3622
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
3623
        }
1✔
3624

3625
        msg := lnwire.NewInitMessage(
10✔
3626
                legacyFeatures.RawFeatureVector,
10✔
3627
                features.RawFeatureVector,
10✔
3628
        )
10✔
3629

10✔
3630
        return p.writeMessage(msg)
10✔
3631
}
3632

3633
// resendChanSyncMsg will attempt to find a channel sync message for the closed
3634
// channel and resend it to our peer.
3635
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
3✔
3636
        // If we already re-sent the mssage for this channel, we won't do it
3✔
3637
        // again.
3✔
3638
        if _, ok := p.resentChanSyncMsg[cid]; ok {
4✔
3639
                return nil
1✔
3640
        }
1✔
3641

3642
        // Check if we have any channel sync messages stored for this channel.
3643
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
3✔
3644
        if err != nil {
6✔
3645
                return fmt.Errorf("unable to fetch channel sync messages for "+
3✔
3646
                        "peer %v: %v", p, err)
3✔
3647
        }
3✔
3648

3649
        if c.LastChanSyncMsg == nil {
3✔
3650
                return fmt.Errorf("no chan sync message stored for channel %v",
×
3651
                        cid)
×
3652
        }
×
3653

3654
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
3✔
3655
                return fmt.Errorf("ignoring channel reestablish from "+
×
3656
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
3657
        }
×
3658

3659
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
3✔
3660
                "peer", cid)
3✔
3661

3✔
3662
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
3✔
3663
                return fmt.Errorf("failed resending channel sync "+
×
3664
                        "message to peer %v: %v", p, err)
×
3665
        }
×
3666

3667
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
3✔
3668
                cid)
3✔
3669

3✔
3670
        // Note down that we sent the message, so we won't resend it again for
3✔
3671
        // this connection.
3✔
3672
        p.resentChanSyncMsg[cid] = struct{}{}
3✔
3673

3✔
3674
        return nil
3✔
3675
}
3676

3677
// SendMessage sends a variadic number of high-priority messages to the remote
3678
// peer. The first argument denotes if the method should block until the
3679
// messages have been sent to the remote peer or an error is returned,
3680
// otherwise it returns immediately after queuing.
3681
//
3682
// NOTE: Part of the lnpeer.Peer interface.
3683
func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error {
6✔
3684
        return p.sendMessage(sync, true, msgs...)
6✔
3685
}
6✔
3686

3687
// SendMessageLazy sends a variadic number of low-priority messages to the
3688
// remote peer. The first argument denotes if the method should block until
3689
// the messages have been sent to the remote peer or an error is returned,
3690
// otherwise it returns immediately after queueing.
3691
//
3692
// NOTE: Part of the lnpeer.Peer interface.
3693
func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
4✔
3694
        return p.sendMessage(sync, false, msgs...)
4✔
3695
}
4✔
3696

3697
// sendMessage queues a variadic number of messages using the passed priority
3698
// to the remote peer. If sync is true, this method will block until the
3699
// messages have been sent to the remote peer or an error is returned, otherwise
3700
// it returns immediately after queueing.
3701
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
7✔
3702
        // Add all incoming messages to the outgoing queue. A list of error
7✔
3703
        // chans is populated for each message if the caller requested a sync
7✔
3704
        // send.
7✔
3705
        var errChans []chan error
7✔
3706
        if sync {
11✔
3707
                errChans = make([]chan error, 0, len(msgs))
4✔
3708
        }
4✔
3709
        for _, msg := range msgs {
14✔
3710
                // If a sync send was requested, create an error chan to listen
7✔
3711
                // for an ack from the writeHandler.
7✔
3712
                var errChan chan error
7✔
3713
                if sync {
11✔
3714
                        errChan = make(chan error, 1)
4✔
3715
                        errChans = append(errChans, errChan)
4✔
3716
                }
4✔
3717

3718
                if priority {
13✔
3719
                        p.queueMsg(msg, errChan)
6✔
3720
                } else {
10✔
3721
                        p.queueMsgLazy(msg, errChan)
4✔
3722
                }
4✔
3723
        }
3724

3725
        // Wait for all replies from the writeHandler. For async sends, this
3726
        // will be a NOP as the list of error chans is nil.
3727
        for _, errChan := range errChans {
11✔
3728
                select {
4✔
3729
                case err := <-errChan:
4✔
3730
                        return err
4✔
3731
                case <-p.quit:
×
3732
                        return lnpeer.ErrPeerExiting
×
3733
                case <-p.cfg.Quit:
1✔
3734
                        return lnpeer.ErrPeerExiting
1✔
3735
                }
3736
        }
3737

3738
        return nil
6✔
3739
}
3740

3741
// PubKey returns the pubkey of the peer in compressed serialized format.
3742
//
3743
// NOTE: Part of the lnpeer.Peer interface.
3744
func (p *Brontide) PubKey() [33]byte {
5✔
3745
        return p.cfg.PubKeyBytes
5✔
3746
}
5✔
3747

3748
// IdentityKey returns the public key of the remote peer.
3749
//
3750
// NOTE: Part of the lnpeer.Peer interface.
3751
func (p *Brontide) IdentityKey() *btcec.PublicKey {
18✔
3752
        return p.cfg.Addr.IdentityKey
18✔
3753
}
18✔
3754

3755
// Address returns the network address of the remote peer.
3756
//
3757
// NOTE: Part of the lnpeer.Peer interface.
3758
func (p *Brontide) Address() net.Addr {
3✔
3759
        return p.cfg.Addr.Address
3✔
3760
}
3✔
3761

3762
// AddNewChannel adds a new channel to the peer. The channel should fail to be
3763
// added if the cancel channel is closed.
3764
//
3765
// NOTE: Part of the lnpeer.Peer interface.
3766
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
3767
        cancel <-chan struct{}) error {
3✔
3768

3✔
3769
        errChan := make(chan error, 1)
3✔
3770
        newChanMsg := &newChannelMsg{
3✔
3771
                channel: newChan,
3✔
3772
                err:     errChan,
3✔
3773
        }
3✔
3774

3✔
3775
        select {
3✔
3776
        case p.newActiveChannel <- newChanMsg:
3✔
3777
        case <-cancel:
×
3778
                return errors.New("canceled adding new channel")
×
3779
        case <-p.quit:
×
3780
                return lnpeer.ErrPeerExiting
×
3781
        }
3782

3783
        // We pause here to wait for the peer to recognize the new channel
3784
        // before we close the channel barrier corresponding to the channel.
3785
        select {
3✔
3786
        case err := <-errChan:
3✔
3787
                return err
3✔
3788
        case <-p.quit:
×
3789
                return lnpeer.ErrPeerExiting
×
3790
        }
3791
}
3792

3793
// AddPendingChannel adds a pending open channel to the peer. The channel
3794
// should fail to be added if the cancel channel is closed.
3795
//
3796
// NOTE: Part of the lnpeer.Peer interface.
3797
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
3798
        cancel <-chan struct{}) error {
3✔
3799

3✔
3800
        errChan := make(chan error, 1)
3✔
3801
        newChanMsg := &newChannelMsg{
3✔
3802
                channelID: cid,
3✔
3803
                err:       errChan,
3✔
3804
        }
3✔
3805

3✔
3806
        select {
3✔
3807
        case p.newPendingChannel <- newChanMsg:
3✔
3808

3809
        case <-cancel:
×
3810
                return errors.New("canceled adding pending channel")
×
3811

3812
        case <-p.quit:
×
3813
                return lnpeer.ErrPeerExiting
×
3814
        }
3815

3816
        // We pause here to wait for the peer to recognize the new pending
3817
        // channel before we close the channel barrier corresponding to the
3818
        // channel.
3819
        select {
3✔
3820
        case err := <-errChan:
3✔
3821
                return err
3✔
3822

3823
        case <-cancel:
×
3824
                return errors.New("canceled adding pending channel")
×
3825

3826
        case <-p.quit:
×
3827
                return lnpeer.ErrPeerExiting
×
3828
        }
3829
}
3830

3831
// RemovePendingChannel removes a pending open channel from the peer.
3832
//
3833
// NOTE: Part of the lnpeer.Peer interface.
3834
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
3✔
3835
        errChan := make(chan error, 1)
3✔
3836
        newChanMsg := &newChannelMsg{
3✔
3837
                channelID: cid,
3✔
3838
                err:       errChan,
3✔
3839
        }
3✔
3840

3✔
3841
        select {
3✔
3842
        case p.removePendingChannel <- newChanMsg:
3✔
3843
        case <-p.quit:
×
3844
                return lnpeer.ErrPeerExiting
×
3845
        }
3846

3847
        // We pause here to wait for the peer to respond to the cancellation of
3848
        // the pending channel before we close the channel barrier
3849
        // corresponding to the channel.
3850
        select {
3✔
3851
        case err := <-errChan:
3✔
3852
                return err
3✔
3853

3854
        case <-p.quit:
×
3855
                return lnpeer.ErrPeerExiting
×
3856
        }
3857
}
3858

3859
// StartTime returns the time at which the connection was established if the
3860
// peer started successfully, and zero otherwise.
3861
func (p *Brontide) StartTime() time.Time {
3✔
3862
        return p.startTime
3✔
3863
}
3✔
3864

3865
// handleCloseMsg is called when a new cooperative channel closure related
3866
// message is received from the remote peer. We'll use this message to advance
3867
// the chan closer state machine.
3868
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
16✔
3869
        link := p.fetchLinkFromKeyAndCid(msg.cid)
16✔
3870

16✔
3871
        // We'll now fetch the matching closing state machine in order to continue,
16✔
3872
        // or finalize the channel closure process.
16✔
3873
        chanCloser, err := p.fetchActiveChanCloser(msg.cid)
16✔
3874
        if err != nil {
19✔
3875
                // If the channel is not known to us, we'll simply ignore this message.
3✔
3876
                if err == ErrChannelNotFound {
6✔
3877
                        return
3✔
3878
                }
3✔
3879

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

×
3882
                errMsg := &lnwire.Error{
×
3883
                        ChanID: msg.cid,
×
3884
                        Data:   lnwire.ErrorData(err.Error()),
×
3885
                }
×
3886
                p.queueMsg(errMsg, nil)
×
3887
                return
×
3888
        }
3889

3890
        handleErr := func(err error) {
16✔
3891
                err = fmt.Errorf("unable to process close msg: %w", err)
×
3892
                p.log.Error(err)
×
3893

×
3894
                // As the negotiations failed, we'll reset the channel state machine to
×
3895
                // ensure we act to on-chain events as normal.
×
3896
                chanCloser.Channel().ResetState()
×
3897

×
3898
                if chanCloser.CloseRequest() != nil {
×
3899
                        chanCloser.CloseRequest().Err <- err
×
3900
                }
×
3901
                delete(p.activeChanCloses, msg.cid)
×
3902

×
3903
                p.Disconnect(err)
×
3904
        }
3905

3906
        // Next, we'll process the next message using the target state machine.
3907
        // We'll either continue negotiation, or halt.
3908
        switch typed := msg.msg.(type) {
16✔
3909
        case *lnwire.Shutdown:
8✔
3910
                // Disable incoming adds immediately.
8✔
3911
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
8✔
3912
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
3913
                                link.ChanID())
×
3914
                }
×
3915

3916
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
8✔
3917
                if err != nil {
8✔
3918
                        handleErr(err)
×
3919
                        return
×
3920
                }
×
3921

3922
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
14✔
3923
                        // If the link is nil it means we can immediately queue
6✔
3924
                        // the Shutdown message since we don't have to wait for
6✔
3925
                        // commitment transaction synchronization.
6✔
3926
                        if link == nil {
7✔
3927
                                p.queueMsg(&msg, nil)
1✔
3928
                                return
1✔
3929
                        }
1✔
3930

3931
                        // Immediately disallow any new HTLC's from being added
3932
                        // in the outgoing direction.
3933
                        if !link.DisableAdds(htlcswitch.Outgoing) {
5✔
3934
                                p.log.Warnf("Outgoing link adds already "+
×
3935
                                        "disabled: %v", link.ChanID())
×
3936
                        }
×
3937

3938
                        // When we have a Shutdown to send, we defer it till the
3939
                        // next time we send a CommitSig to remain spec
3940
                        // compliant.
3941
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
10✔
3942
                                p.queueMsg(&msg, nil)
5✔
3943
                        })
5✔
3944
                })
3945

3946
                beginNegotiation := func() {
16✔
3947
                        oClosingSigned, err := chanCloser.BeginNegotiation()
8✔
3948
                        if err != nil {
8✔
3949
                                handleErr(err)
×
3950
                                return
×
3951
                        }
×
3952

3953
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
16✔
3954
                                p.queueMsg(&msg, nil)
8✔
3955
                        })
8✔
3956
                }
3957

3958
                if link == nil {
9✔
3959
                        beginNegotiation()
1✔
3960
                } else {
8✔
3961
                        // Now we register a flush hook to advance the
7✔
3962
                        // ChanCloser and possibly send out a ClosingSigned
7✔
3963
                        // when the link finishes draining.
7✔
3964
                        link.OnFlushedOnce(func() {
14✔
3965
                                // Remove link in goroutine to prevent deadlock.
7✔
3966
                                go p.cfg.Switch.RemoveLink(msg.cid)
7✔
3967
                                beginNegotiation()
7✔
3968
                        })
7✔
3969
                }
3970

3971
        case *lnwire.ClosingSigned:
11✔
3972
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
11✔
3973
                if err != nil {
11✔
3974
                        handleErr(err)
×
3975
                        return
×
3976
                }
×
3977

3978
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
22✔
3979
                        p.queueMsg(&msg, nil)
11✔
3980
                })
11✔
3981

3982
        default:
×
3983
                panic("impossible closeMsg type")
×
3984
        }
3985

3986
        // If we haven't finished close negotiations, then we'll continue as we
3987
        // can't yet finalize the closure.
3988
        if _, err := chanCloser.ClosingTx(); err != nil {
26✔
3989
                return
11✔
3990
        }
11✔
3991

3992
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
3993
        // the channel closure by notifying relevant sub-systems and launching a
3994
        // goroutine to wait for close tx conf.
3995
        p.finalizeChanClosure(chanCloser)
7✔
3996
}
3997

3998
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
3999
// the channelManager goroutine, which will shut down the link and possibly
4000
// close the channel.
4001
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
3✔
4002
        select {
3✔
4003
        case p.localCloseChanReqs <- req:
3✔
4004
                p.log.Info("Local close channel request is going to be " +
3✔
4005
                        "delivered to the peer")
3✔
4006
        case <-p.quit:
×
4007
                p.log.Info("Unable to deliver local close channel request " +
×
4008
                        "to peer")
×
4009
        }
4010
}
4011

4012
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
4013
func (p *Brontide) NetAddress() *lnwire.NetAddress {
3✔
4014
        return p.cfg.Addr
3✔
4015
}
3✔
4016

4017
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
4018
func (p *Brontide) Inbound() bool {
3✔
4019
        return p.cfg.Inbound
3✔
4020
}
3✔
4021

4022
// ConnReq is a getter for the Brontide's connReq in cfg.
4023
func (p *Brontide) ConnReq() *connmgr.ConnReq {
3✔
4024
        return p.cfg.ConnReq
3✔
4025
}
3✔
4026

4027
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
4028
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
3✔
4029
        return p.cfg.ErrorBuffer
3✔
4030
}
3✔
4031

4032
// SetAddress sets the remote peer's address given an address.
4033
func (p *Brontide) SetAddress(address net.Addr) {
×
4034
        p.cfg.Addr.Address = address
×
4035
}
×
4036

4037
// ActiveSignal returns the peer's active signal.
4038
func (p *Brontide) ActiveSignal() chan struct{} {
3✔
4039
        return p.activeSignal
3✔
4040
}
3✔
4041

4042
// Conn returns a pointer to the peer's connection struct.
4043
func (p *Brontide) Conn() net.Conn {
3✔
4044
        return p.cfg.Conn
3✔
4045
}
3✔
4046

4047
// BytesReceived returns the number of bytes received from the peer.
4048
func (p *Brontide) BytesReceived() uint64 {
3✔
4049
        return atomic.LoadUint64(&p.bytesReceived)
3✔
4050
}
3✔
4051

4052
// BytesSent returns the number of bytes sent to the peer.
4053
func (p *Brontide) BytesSent() uint64 {
3✔
4054
        return atomic.LoadUint64(&p.bytesSent)
3✔
4055
}
3✔
4056

4057
// LastRemotePingPayload returns the last payload the remote party sent as part
4058
// of their ping.
4059
func (p *Brontide) LastRemotePingPayload() []byte {
3✔
4060
        pingPayload := p.lastPingPayload.Load()
3✔
4061
        if pingPayload == nil {
6✔
4062
                return []byte{}
3✔
4063
        }
3✔
4064

4065
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
4066
        if !ok {
×
4067
                return nil
×
4068
        }
×
4069

4070
        return pingBytes
×
4071
}
4072

4073
// attachChannelEventSubscription creates a channel event subscription and
4074
// attaches to client to Brontide if the reenableTimeout is no greater than 1
4075
// minute.
4076
func (p *Brontide) attachChannelEventSubscription() error {
6✔
4077
        // If the timeout is greater than 1 minute, it's unlikely that the link
6✔
4078
        // hasn't yet finished its reestablishment. Return a nil without
6✔
4079
        // creating the client to specify that we don't want to retry.
6✔
4080
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
9✔
4081
                return nil
3✔
4082
        }
3✔
4083

4084
        // When the reenable timeout is less than 1 minute, it's likely the
4085
        // channel link hasn't finished its reestablishment yet. In that case,
4086
        // we'll give it a second chance by subscribing to the channel update
4087
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
4088
        // enabling the channel again.
4089
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
6✔
4090
        if err != nil {
6✔
4091
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
4092
        }
×
4093

4094
        p.channelEventClient = sub
6✔
4095

6✔
4096
        return nil
6✔
4097
}
4098

4099
// updateNextRevocation updates the existing channel's next revocation if it's
4100
// nil.
4101
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
6✔
4102
        chanPoint := c.FundingOutpoint
6✔
4103
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
6✔
4104

6✔
4105
        // Read the current channel.
6✔
4106
        currentChan, loaded := p.activeChannels.Load(chanID)
6✔
4107

6✔
4108
        // currentChan should exist, but we perform a check anyway to avoid nil
6✔
4109
        // pointer dereference.
6✔
4110
        if !loaded {
7✔
4111
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
4112
                        chanID)
1✔
4113
        }
1✔
4114

4115
        // currentChan should not be nil, but we perform a check anyway to
4116
        // avoid nil pointer dereference.
4117
        if currentChan == nil {
6✔
4118
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
4119
                        chanID)
1✔
4120
        }
1✔
4121

4122
        // If we're being sent a new channel, and our existing channel doesn't
4123
        // have the next revocation, then we need to update the current
4124
        // existing channel.
4125
        if currentChan.RemoteNextRevocation() != nil {
4✔
4126
                return nil
×
4127
        }
×
4128

4129
        p.log.Infof("Processing retransmitted ChannelReady for "+
4✔
4130
                "ChannelPoint(%v)", chanPoint)
4✔
4131

4✔
4132
        nextRevoke := c.RemoteNextRevocation
4✔
4133

4✔
4134
        err := currentChan.InitNextRevocation(nextRevoke)
4✔
4135
        if err != nil {
4✔
4136
                return fmt.Errorf("unable to init next revocation: %w", err)
×
4137
        }
×
4138

4139
        return nil
4✔
4140
}
4141

4142
// addActiveChannel adds a new active channel to the `activeChannels` map. It
4143
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
4144
// it and assembles it with a channel link.
4145
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
3✔
4146
        chanPoint := c.FundingOutpoint
3✔
4147
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4148

3✔
4149
        // If we've reached this point, there are two possible scenarios.  If
3✔
4150
        // the channel was in the active channels map as nil, then it was
3✔
4151
        // loaded from disk and we need to send reestablish. Else, it was not
3✔
4152
        // loaded from disk and we don't need to send reestablish as this is a
3✔
4153
        // fresh channel.
3✔
4154
        shouldReestablish := p.isLoadedFromDisk(chanID)
3✔
4155

3✔
4156
        chanOpts := c.ChanOpts
3✔
4157
        if shouldReestablish {
6✔
4158
                // If we have to do the reestablish dance for this channel,
3✔
4159
                // ensure that we don't try to call InitRemoteMusigNonces twice
3✔
4160
                // by calling SkipNonceInit.
3✔
4161
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
3✔
4162
        }
3✔
4163

4164
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
3✔
4165
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
4166
        })
×
4167

4168
        // If not already active, we'll add this channel to the set of active
4169
        // channels, so we can look it up later easily according to its channel
4170
        // ID.
4171
        lnChan, err := lnwallet.NewLightningChannel(
3✔
4172
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
3✔
4173
        )
3✔
4174
        if err != nil {
3✔
4175
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
4176
        }
×
4177

4178
        // Store the channel in the activeChannels map.
4179
        p.activeChannels.Store(chanID, lnChan)
3✔
4180

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

3✔
4183
        // Next, we'll assemble a ChannelLink along with the necessary items it
3✔
4184
        // needs to function.
3✔
4185
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
3✔
4186
        if err != nil {
3✔
4187
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
4188
                        err)
×
4189
        }
×
4190

4191
        // We'll query the channel DB for the new channel's initial forwarding
4192
        // policies to determine the policy we start out with.
4193
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
3✔
4194
        if err != nil {
3✔
4195
                return fmt.Errorf("unable to query for initial forwarding "+
×
4196
                        "policy: %v", err)
×
4197
        }
×
4198

4199
        // Create the link and add it to the switch.
4200
        err = p.addLink(
3✔
4201
                &chanPoint, lnChan, initialPolicy, chainEvents,
3✔
4202
                shouldReestablish, fn.None[lnwire.Shutdown](),
3✔
4203
        )
3✔
4204
        if err != nil {
3✔
4205
                return fmt.Errorf("can't register new channel link(%v) with "+
×
4206
                        "peer", chanPoint)
×
4207
        }
×
4208

4209
        return nil
3✔
4210
}
4211

4212
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
4213
// know this channel ID or not, we'll either add it to the `activeChannels` map
4214
// or init the next revocation for it.
4215
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
3✔
4216
        newChan := req.channel
3✔
4217
        chanPoint := newChan.FundingOutpoint
3✔
4218
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4219

3✔
4220
        // Only update RemoteNextRevocation if the channel is in the
3✔
4221
        // activeChannels map and if we added the link to the switch. Only
3✔
4222
        // active channels will be added to the switch.
3✔
4223
        if p.isActiveChannel(chanID) {
6✔
4224
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
3✔
4225
                        chanPoint)
3✔
4226

3✔
4227
                // Handle it and close the err chan on the request.
3✔
4228
                close(req.err)
3✔
4229

3✔
4230
                // Update the next revocation point.
3✔
4231
                err := p.updateNextRevocation(newChan.OpenChannel)
3✔
4232
                if err != nil {
3✔
4233
                        p.log.Errorf(err.Error())
×
4234
                }
×
4235

4236
                return
3✔
4237
        }
4238

4239
        // This is a new channel, we now add it to the map.
4240
        if err := p.addActiveChannel(req.channel); err != nil {
3✔
4241
                // Log and send back the error to the request.
×
4242
                p.log.Errorf(err.Error())
×
4243
                req.err <- err
×
4244

×
4245
                return
×
4246
        }
×
4247

4248
        // Close the err chan if everything went fine.
4249
        close(req.err)
3✔
4250
}
4251

4252
// handleNewPendingChannel takes a `newChannelMsg` request and add it to
4253
// `activeChannels` map with nil value. This pending channel will be saved as
4254
// it may become active in the future. Once active, the funding manager will
4255
// send it again via `AddNewChannel`, and we'd handle the link creation there.
4256
func (p *Brontide) handleNewPendingChannel(req *newChannelMsg) {
7✔
4257
        defer close(req.err)
7✔
4258

7✔
4259
        chanID := req.channelID
7✔
4260

7✔
4261
        // If we already have this channel, something is wrong with the funding
7✔
4262
        // flow as it will only be marked as active after `ChannelReady` is
7✔
4263
        // handled. In this case, we will do nothing but log an error, just in
7✔
4264
        // case this is a legit channel.
7✔
4265
        if p.isActiveChannel(chanID) {
8✔
4266
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
4267
                        "pending channel request", chanID)
1✔
4268

1✔
4269
                return
1✔
4270
        }
1✔
4271

4272
        // The channel has already been added, we will do nothing and return.
4273
        if p.isPendingChannel(chanID) {
7✔
4274
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
4275
                        "pending channel request", chanID)
1✔
4276

1✔
4277
                return
1✔
4278
        }
1✔
4279

4280
        // This is a new channel, we now add it to the map `activeChannels`
4281
        // with nil value and mark it as a newly added channel in
4282
        // `addedChannels`.
4283
        p.activeChannels.Store(chanID, nil)
5✔
4284
        p.addedChannels.Store(chanID, struct{}{})
5✔
4285
}
4286

4287
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
4288
// from `activeChannels` map. The request will be ignored if the channel is
4289
// considered active by Brontide. Noop if the channel ID cannot be found.
4290
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
7✔
4291
        defer close(req.err)
7✔
4292

7✔
4293
        chanID := req.channelID
7✔
4294

7✔
4295
        // If we already have this channel, something is wrong with the funding
7✔
4296
        // flow as it will only be marked as active after `ChannelReady` is
7✔
4297
        // handled. In this case, we will log an error and exit.
7✔
4298
        if p.isActiveChannel(chanID) {
8✔
4299
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
4300
                        chanID)
1✔
4301
                return
1✔
4302
        }
1✔
4303

4304
        // The channel has not been added yet, we will log a warning as there
4305
        // is an unexpected call from funding manager.
4306
        if !p.isPendingChannel(chanID) {
10✔
4307
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
4✔
4308
        }
4✔
4309

4310
        // Remove the record of this pending channel.
4311
        p.activeChannels.Delete(chanID)
6✔
4312
        p.addedChannels.Delete(chanID)
6✔
4313
}
4314

4315
// sendLinkUpdateMsg sends a message that updates the channel to the
4316
// channel's message stream.
4317
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
3✔
4318
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
3✔
4319

3✔
4320
        chanStream, ok := p.activeMsgStreams[cid]
3✔
4321
        if !ok {
6✔
4322
                // If a stream hasn't yet been created, then we'll do so, add
3✔
4323
                // it to the map, and finally start it.
3✔
4324
                chanStream = newChanMsgStream(p, cid)
3✔
4325
                p.activeMsgStreams[cid] = chanStream
3✔
4326
                chanStream.Start()
3✔
4327

3✔
4328
                // Stop the stream when quit.
3✔
4329
                go func() {
6✔
4330
                        <-p.quit
3✔
4331
                        chanStream.Stop()
3✔
4332
                }()
3✔
4333
        }
4334

4335
        // With the stream obtained, add the message to the stream so we can
4336
        // continue processing message.
4337
        chanStream.AddMsg(msg)
3✔
4338
}
4339

4340
// scaleTimeout multiplies the argument duration by a constant factor depending
4341
// on variious heuristics. Currently this is only used to check whether our peer
4342
// appears to be connected over Tor and relaxes the timout deadline. However,
4343
// this is subject to change and should be treated as opaque.
4344
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
70✔
4345
        if p.isTorConnection {
73✔
4346
                return timeout * time.Duration(torTimeoutMultiplier)
3✔
4347
        }
3✔
4348

4349
        return timeout
67✔
4350
}
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