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

lightningnetwork / lnd / 10418626636

16 Aug 2024 10:36AM UTC coverage: 58.722% (+0.2%) from 58.558%
10418626636

Pull #9011

github

ziggie1984
docs: update release-notes.
Pull Request #9011: Fix TimeStamp issue in the Gossip Syncer

58 of 70 new or added lines in 3 files covered. (82.86%)

117 existing lines in 15 files now uncovered.

126269 of 215030 relevant lines covered (58.72%)

28151.42 hits per line

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

78.88
/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/netann"
46
        "github.com/lightningnetwork/lnd/pool"
47
        "github.com/lightningnetwork/lnd/queue"
48
        "github.com/lightningnetwork/lnd/subscribe"
49
        "github.com/lightningnetwork/lnd/ticker"
50
        "github.com/lightningnetwork/lnd/tlv"
51
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
52
)
53

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

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

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

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

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

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

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

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

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

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

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

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

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

119
        err chan error
120
}
121

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

380
        // Adds the option to disable forwarding payments in blinded routes
381
        // by failing back any blinding-related payloads as if they were
382
        // invalid.
383
        DisallowRouteBlinding bool
384

385
        // MaxFeeExposure limits the number of outstanding fees in a channel.
386
        // This value will be passed to created links.
387
        MaxFeeExposure lnwire.MilliSatoshi
388

389
        // Quit is the server's quit channel. If this is closed, we halt operation.
390
        Quit chan struct{}
391
}
392

393
// Brontide is an active peer on the Lightning Network. This struct is responsible
394
// for managing any channel state related to this peer. To do so, it has
395
// several helper goroutines to handle events such as HTLC timeouts, new
396
// funding workflow, and detecting an uncooperative closure of any active
397
// channels.
398
// TODO(roasbeef): proper reconnection logic.
399
type Brontide struct {
400
        // MUST be used atomically.
401
        started    int32
402
        disconnect int32
403

404
        // MUST be used atomically.
405
        bytesReceived uint64
406
        bytesSent     uint64
407

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

425
        pingManager *PingManager
426

427
        // lastPingPayload stores an unsafe pointer wrapped as an atomic
428
        // variable which points to the last payload the remote party sent us
429
        // as their ping.
430
        //
431
        // MUST be used atomically.
432
        lastPingPayload atomic.Value
433

434
        cfg Config
435

436
        // activeSignal when closed signals that the peer is now active and
437
        // ready to process messages.
438
        activeSignal chan struct{}
439

440
        // startTime is the time this peer connection was successfully established.
441
        // It will be zero for peers that did not successfully call Start().
442
        startTime time.Time
443

444
        // sendQueue is the channel which is used to queue outgoing messages to be
445
        // written onto the wire. Note that this channel is unbuffered.
446
        sendQueue chan outgoingMsg
447

448
        // outgoingQueue is a buffered channel which allows second/third party
449
        // objects to queue messages to be sent out on the wire.
450
        outgoingQueue chan outgoingMsg
451

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

465
        // addedChannels tracks any new channels opened during this peer's
466
        // lifecycle. We use this to filter out these new channels when the time
467
        // comes to request a reenable for active channels, since they will have
468
        // waited a shorter duration.
469
        addedChannels *lnutils.SyncMap[lnwire.ChannelID, struct{}]
470

471
        // newActiveChannel is used by the fundingManager to send fully opened
472
        // channels to the source peer which handled the funding workflow.
473
        newActiveChannel chan *newChannelMsg
474

475
        // newPendingChannel is used by the fundingManager to send pending open
476
        // channels to the source peer which handled the funding workflow.
477
        newPendingChannel chan *newChannelMsg
478

479
        // removePendingChannel is used by the fundingManager to cancel pending
480
        // open channels to the source peer when the funding flow is failed.
481
        removePendingChannel chan *newChannelMsg
482

483
        // activeMsgStreams is a map from channel id to the channel streams that
484
        // proxy messages to individual, active links.
485
        activeMsgStreams map[lnwire.ChannelID]*msgStream
486

487
        // activeChanCloses is a map that keeps track of all the active
488
        // cooperative channel closures. Any channel closing messages are directed
489
        // to one of these active state machines. Once the channel has been closed,
490
        // the state machine will be deleted from the map.
491
        activeChanCloses map[lnwire.ChannelID]*chancloser.ChanCloser
492

493
        // localCloseChanReqs is a channel in which any local requests to close
494
        // a particular channel are sent over.
495
        localCloseChanReqs chan *htlcswitch.ChanClose
496

497
        // linkFailures receives all reported channel failures from the switch,
498
        // and instructs the channelManager to clean remaining channel state.
499
        linkFailures chan linkFailureReport
500

501
        // chanCloseMsgs is a channel that any message related to channel
502
        // closures are sent over. This includes lnwire.Shutdown message as
503
        // well as lnwire.ClosingSigned messages.
504
        chanCloseMsgs chan *closeMsg
505

506
        // remoteFeatures is the feature vector received from the peer during
507
        // the connection handshake.
508
        remoteFeatures *lnwire.FeatureVector
509

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

516
        // channelEventClient is the channel event subscription client that's
517
        // used to assist retry enabling the channels. This client is only
518
        // created when the reenableTimeout is no greater than 1 minute. Once
519
        // created, it is canceled once the reenabling has been finished.
520
        //
521
        // NOTE: we choose to create the client conditionally to avoid
522
        // potentially holding lots of un-consumed events.
523
        channelEventClient *subscribe.Client
524

525
        startReady chan struct{}
526
        quit       chan struct{}
527
        wg         sync.WaitGroup
528

529
        // log is a peer-specific logging instance.
530
        log btclog.Logger
531
}
532

533
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer interface.
534
var _ lnpeer.Peer = (*Brontide)(nil)
535

536
// NewBrontide creates a new Brontide from a peer.Config struct.
537
func NewBrontide(cfg Config) *Brontide {
28✔
538
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
28✔
539

28✔
540
        p := &Brontide{
28✔
541
                cfg:           cfg,
28✔
542
                activeSignal:  make(chan struct{}),
28✔
543
                sendQueue:     make(chan outgoingMsg),
28✔
544
                outgoingQueue: make(chan outgoingMsg),
28✔
545
                addedChannels: &lnutils.SyncMap[lnwire.ChannelID, struct{}]{},
28✔
546
                activeChannels: &lnutils.SyncMap[
28✔
547
                        lnwire.ChannelID, *lnwallet.LightningChannel,
28✔
548
                ]{},
28✔
549
                newActiveChannel:     make(chan *newChannelMsg, 1),
28✔
550
                newPendingChannel:    make(chan *newChannelMsg, 1),
28✔
551
                removePendingChannel: make(chan *newChannelMsg),
28✔
552

28✔
553
                activeMsgStreams:   make(map[lnwire.ChannelID]*msgStream),
28✔
554
                activeChanCloses:   make(map[lnwire.ChannelID]*chancloser.ChanCloser),
28✔
555
                localCloseChanReqs: make(chan *htlcswitch.ChanClose),
28✔
556
                linkFailures:       make(chan linkFailureReport),
28✔
557
                chanCloseMsgs:      make(chan *closeMsg),
28✔
558
                resentChanSyncMsg:  make(map[lnwire.ChannelID]struct{}),
28✔
559
                startReady:         make(chan struct{}),
28✔
560
                quit:               make(chan struct{}),
28✔
561
                log:                build.NewPrefixLog(logPrefix, peerLog),
28✔
562
        }
28✔
563

28✔
564
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
31✔
565
                remoteAddr := cfg.Conn.RemoteAddr().String()
3✔
566
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
3✔
567
                        strings.Contains(remoteAddr, "127.0.0.1")
3✔
568
        }
3✔
569

570
        var (
28✔
571
                lastBlockHeader           *wire.BlockHeader
28✔
572
                lastSerializedBlockHeader [wire.MaxBlockHeaderPayload]byte
28✔
573
        )
28✔
574
        newPingPayload := func() []byte {
30✔
575
                // We query the BestBlockHeader from our BestBlockView each time
2✔
576
                // this is called, and update our serialized block header if
2✔
577
                // they differ.  Over time, we'll use this to disseminate the
2✔
578
                // latest block header between all our peers, which can later be
2✔
579
                // used to cross-check our own view of the network to mitigate
2✔
580
                // various types of eclipse attacks.
2✔
581
                header, err := p.cfg.BestBlockView.BestBlockHeader()
2✔
582
                if err != nil && header == lastBlockHeader {
2✔
583
                        return lastSerializedBlockHeader[:]
×
584
                }
×
585

586
                buf := bytes.NewBuffer(lastSerializedBlockHeader[0:0])
2✔
587
                err = header.Serialize(buf)
2✔
588
                if err == nil {
4✔
589
                        lastBlockHeader = header
2✔
590
                } else {
2✔
591
                        p.log.Warn("unable to serialize current block" +
×
592
                                "header for ping payload generation." +
×
593
                                "This should be impossible and means" +
×
594
                                "there is an implementation bug.")
×
595
                }
×
596

597
                return lastSerializedBlockHeader[:]
2✔
598
        }
599

600
        // TODO(roasbeef): make dynamic in order to create fake cover traffic.
601
        //
602
        // NOTE(proofofkeags): this was changed to be dynamic to allow better
603
        // pong identification, however, more thought is needed to make this
604
        // actually usable as a traffic decoy.
605
        randPongSize := func() uint16 {
30✔
606
                return uint16(
2✔
607
                        // We don't need cryptographic randomness here.
2✔
608
                        /* #nosec */
2✔
609
                        rand.Intn(pongSizeCeiling) + 1,
2✔
610
                )
2✔
611
        }
2✔
612

613
        p.pingManager = NewPingManager(&PingManagerConfig{
28✔
614
                NewPingPayload:   newPingPayload,
28✔
615
                NewPongSize:      randPongSize,
28✔
616
                IntervalDuration: p.scaleTimeout(pingInterval),
28✔
617
                TimeoutDuration:  p.scaleTimeout(pingTimeout),
28✔
618
                SendPing: func(ping *lnwire.Ping) {
30✔
619
                        p.queueMsg(ping, nil)
2✔
620
                },
2✔
621
                OnPongFailure: func(err error) {
×
622
                        eStr := "pong response failure for %s: %v " +
×
623
                                "-- disconnecting"
×
624
                        p.log.Warnf(eStr, p, err)
×
625
                        go p.Disconnect(fmt.Errorf(eStr, p, err))
×
626
                },
×
627
        })
628

629
        return p
28✔
630
}
631

632
// Start starts all helper goroutines the peer needs for normal operations.  In
633
// the case this peer has already been started, then this function is a noop.
634
func (p *Brontide) Start() error {
6✔
635
        if atomic.AddInt32(&p.started, 1) != 1 {
6✔
636
                return nil
×
637
        }
×
638

639
        // Once we've finished starting up the peer, we'll signal to other
640
        // goroutines that the they can move forward to tear down the peer, or
641
        // carry out other relevant changes.
642
        defer close(p.startReady)
6✔
643

6✔
644
        p.log.Tracef("starting with conn[%v->%v]",
6✔
645
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
6✔
646

6✔
647
        // Fetch and then load all the active channels we have with this remote
6✔
648
        // peer from the database.
6✔
649
        activeChans, err := p.cfg.ChannelDB.FetchOpenChannels(
6✔
650
                p.cfg.Addr.IdentityKey,
6✔
651
        )
6✔
652
        if err != nil {
6✔
653
                p.log.Errorf("Unable to fetch active chans "+
×
654
                        "for peer: %v", err)
×
655
                return err
×
656
        }
×
657

658
        if len(activeChans) == 0 {
10✔
659
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
4✔
660
        }
4✔
661

662
        // Quickly check if we have any existing legacy channels with this
663
        // peer.
664
        haveLegacyChan := false
6✔
665
        for _, c := range activeChans {
11✔
666
                if c.ChanType.IsTweakless() {
10✔
667
                        continue
5✔
668
                }
669

670
                haveLegacyChan = true
3✔
671
                break
3✔
672
        }
673

674
        // Exchange local and global features, the init message should be very
675
        // first between two nodes.
676
        if err := p.sendInitMsg(haveLegacyChan); err != nil {
6✔
677
                return fmt.Errorf("unable to send init msg: %w", err)
×
678
        }
×
679

680
        // Before we launch any of the helper goroutines off the peer struct,
681
        // we'll first ensure proper adherence to the p2p protocol. The init
682
        // message MUST be sent before any other message.
683
        readErr := make(chan error, 1)
6✔
684
        msgChan := make(chan lnwire.Message, 1)
6✔
685
        p.wg.Add(1)
6✔
686
        go func() {
12✔
687
                defer p.wg.Done()
6✔
688

6✔
689
                msg, err := p.readNextMessage()
6✔
690
                if err != nil {
7✔
691
                        readErr <- err
1✔
692
                        msgChan <- nil
1✔
693
                        return
1✔
694
                }
1✔
695
                readErr <- nil
6✔
696
                msgChan <- msg
6✔
697
        }()
698

699
        select {
6✔
700
        // In order to avoid blocking indefinitely, we'll give the other peer
701
        // an upper timeout to respond before we bail out early.
702
        case <-time.After(handshakeTimeout):
×
703
                return fmt.Errorf("peer did not complete handshake within %v",
×
704
                        handshakeTimeout)
×
705
        case err := <-readErr:
6✔
706
                if err != nil {
7✔
707
                        return fmt.Errorf("unable to read init msg: %w", err)
1✔
708
                }
1✔
709
        }
710

711
        // Once the init message arrives, we can parse it so we can figure out
712
        // the negotiation of features for this session.
713
        msg := <-msgChan
6✔
714
        if msg, ok := msg.(*lnwire.Init); ok {
12✔
715
                if err := p.handleInitMsg(msg); err != nil {
6✔
716
                        p.storeError(err)
×
717
                        return err
×
718
                }
×
719
        } else {
×
720
                return errors.New("very first message between nodes " +
×
721
                        "must be init message")
×
722
        }
×
723

724
        // Next, load all the active channels we have with this peer,
725
        // registering them with the switch and launching the necessary
726
        // goroutines required to operate them.
727
        p.log.Debugf("Loaded %v active channels from database",
6✔
728
                len(activeChans))
6✔
729

6✔
730
        // Conditionally subscribe to channel events before loading channels so
6✔
731
        // we won't miss events. This subscription is used to listen to active
6✔
732
        // channel event when reenabling channels. Once the reenabling process
6✔
733
        // is finished, this subscription will be canceled.
6✔
734
        //
6✔
735
        // NOTE: ChannelNotifier must be started before subscribing events
6✔
736
        // otherwise we'd panic here.
6✔
737
        if err := p.attachChannelEventSubscription(); err != nil {
6✔
738
                return err
×
739
        }
×
740

741
        msgs, err := p.loadActiveChannels(activeChans)
6✔
742
        if err != nil {
6✔
743
                return fmt.Errorf("unable to load channels: %w", err)
×
744
        }
×
745

746
        p.startTime = time.Now()
6✔
747

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

5✔
755
                // Send the messages directly via writeMessage and bypass the
5✔
756
                // writeHandler goroutine.
5✔
757
                for _, msg := range msgs {
10✔
758
                        if err := p.writeMessage(msg); err != nil {
5✔
759
                                return fmt.Errorf("unable to send "+
×
760
                                        "reestablish msg: %v", err)
×
761
                        }
×
762
                }
763
        }
764

765
        err = p.pingManager.Start()
6✔
766
        if err != nil {
6✔
767
                return fmt.Errorf("could not start ping manager %w", err)
×
768
        }
×
769

770
        p.wg.Add(4)
6✔
771
        go p.queueHandler()
6✔
772
        go p.writeHandler()
6✔
773
        go p.channelManager()
6✔
774
        go p.readHandler()
6✔
775

6✔
776
        // Signal to any external processes that the peer is now active.
6✔
777
        close(p.activeSignal)
6✔
778

6✔
779
        // Node announcements don't propagate very well throughout the network
6✔
780
        // as there isn't a way to efficiently query for them through their
6✔
781
        // timestamp, mostly affecting nodes that were offline during the time
6✔
782
        // of broadcast. We'll resend our node announcement to the remote peer
6✔
783
        // as a best-effort delivery such that it can also propagate to their
6✔
784
        // peers. To ensure they can successfully process it in most cases,
6✔
785
        // we'll only resend it as long as we have at least one confirmed
6✔
786
        // advertised channel with the remote peer.
6✔
787
        //
6✔
788
        // TODO(wilmer): Remove this once we're able to query for node
6✔
789
        // announcements through their timestamps.
6✔
790
        p.wg.Add(2)
6✔
791
        go p.maybeSendNodeAnn(activeChans)
6✔
792
        go p.maybeSendChannelUpdates()
6✔
793

6✔
794
        return nil
6✔
795
}
796

797
// initGossipSync initializes either a gossip syncer or an initial routing
798
// dump, depending on the negotiated synchronization method.
799
func (p *Brontide) initGossipSync() {
6✔
800
        // If the remote peer knows of the new gossip queries feature, then
6✔
801
        // we'll create a new gossipSyncer in the AuthenticatedGossiper for it.
6✔
802
        if p.remoteFeatures.HasFeature(lnwire.GossipQueriesOptional) {
12✔
803
                p.log.Info("Negotiated chan series queries")
6✔
804

6✔
805
                if p.cfg.AuthGossiper == nil {
9✔
806
                        // This should only ever be hit in the unit tests.
3✔
807
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
3✔
808
                                "gossip sync.")
3✔
809
                        return
3✔
810
                }
3✔
811

812
                // Register the peer's gossip syncer with the gossiper.
813
                // This blocks synchronously to ensure the gossip syncer is
814
                // registered with the gossiper before attempting to read
815
                // messages from the remote peer.
816
                //
817
                // TODO(wilmer): Only sync updates from non-channel peers. This
818
                // requires an improved version of the current network
819
                // bootstrapper to ensure we can find and connect to non-channel
820
                // peers.
821
                p.cfg.AuthGossiper.InitSyncState(p)
3✔
822
        }
823
}
824

825
// taprootShutdownAllowed returns true if both parties have negotiated the
826
// shutdown-any-segwit feature.
827
func (p *Brontide) taprootShutdownAllowed() bool {
9✔
828
        return p.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
9✔
829
                p.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
9✔
830
}
9✔
831

832
// QuitSignal is a method that should return a channel which will be sent upon
833
// or closed once the backing peer exits. This allows callers using the
834
// interface to cancel any processing in the event the backing implementation
835
// exits.
836
//
837
// NOTE: Part of the lnpeer.Peer interface.
838
func (p *Brontide) QuitSignal() <-chan struct{} {
3✔
839
        return p.quit
3✔
840
}
3✔
841

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

6✔
849
        // Return a slice of messages to send to the peers in case the channel
6✔
850
        // cannot be loaded normally.
6✔
851
        var msgs []lnwire.Message
6✔
852

6✔
853
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
6✔
854

6✔
855
        for _, dbChan := range chans {
11✔
856
                hasScidFeature := dbChan.ChanType.HasScidAliasFeature()
5✔
857
                if scidAliasNegotiated && !hasScidFeature {
8✔
858
                        // We'll request and store an alias, making sure that a
3✔
859
                        // gossiper mapping is not created for the alias to the
3✔
860
                        // real SCID. This is done because the peer and funding
3✔
861
                        // manager are not aware of each other's states and if
3✔
862
                        // we did not do this, we would accept alias channel
3✔
863
                        // updates after 6 confirmations, which would be buggy.
3✔
864
                        // We'll queue a channel_ready message with the new
3✔
865
                        // alias. This should technically be done *after* the
3✔
866
                        // reestablish, but this behavior is pre-existing since
3✔
867
                        // the funding manager may already queue a
3✔
868
                        // channel_ready before the channel_reestablish.
3✔
869
                        if !dbChan.IsPending {
6✔
870
                                aliasScid, err := p.cfg.RequestAlias()
3✔
871
                                if err != nil {
3✔
872
                                        return nil, err
×
873
                                }
×
874

875
                                err = p.cfg.AddLocalAlias(
3✔
876
                                        aliasScid, dbChan.ShortChanID(), false,
3✔
877
                                )
3✔
878
                                if err != nil {
3✔
879
                                        return nil, err
×
880
                                }
×
881

882
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
883
                                        dbChan.FundingOutpoint,
3✔
884
                                )
3✔
885

3✔
886
                                // Fetch the second commitment point to send in
3✔
887
                                // the channel_ready message.
3✔
888
                                second, err := dbChan.SecondCommitmentPoint()
3✔
889
                                if err != nil {
3✔
890
                                        return nil, err
×
891
                                }
×
892

893
                                channelReadyMsg := lnwire.NewChannelReady(
3✔
894
                                        chanID, second,
3✔
895
                                )
3✔
896
                                channelReadyMsg.AliasScid = &aliasScid
3✔
897

3✔
898
                                msgs = append(msgs, channelReadyMsg)
3✔
899
                        }
900

901
                        // If we've negotiated the option-scid-alias feature
902
                        // and this channel does not have ScidAliasFeature set
903
                        // to true due to an upgrade where the feature bit was
904
                        // turned on, we'll update the channel's database
905
                        // state.
906
                        err := dbChan.MarkScidAliasNegotiated()
3✔
907
                        if err != nil {
3✔
908
                                return nil, err
×
909
                        }
×
910
                }
911

912
                lnChan, err := lnwallet.NewLightningChannel(
5✔
913
                        p.cfg.Signer, dbChan, p.cfg.SigPool,
5✔
914
                )
5✔
915
                if err != nil {
5✔
916
                        return nil, err
×
917
                }
×
918

919
                chanPoint := dbChan.FundingOutpoint
5✔
920

5✔
921
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
5✔
922

5✔
923
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
5✔
924
                        chanPoint, lnChan.IsPending())
5✔
925

5✔
926
                // Skip adding any permanently irreconcilable channels to the
5✔
927
                // htlcswitch.
5✔
928
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
5✔
929
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
10✔
930

5✔
931
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
5✔
932
                                "start.", chanPoint, dbChan.ChanStatus())
5✔
933

5✔
934
                        // To help our peer recover from a potential data loss,
5✔
935
                        // we resend our channel reestablish message if the
5✔
936
                        // channel is in a borked state. We won't process any
5✔
937
                        // channel reestablish message sent from the peer, but
5✔
938
                        // that's okay since the assumption is that we did when
5✔
939
                        // marking the channel borked.
5✔
940
                        chanSync, err := dbChan.ChanSyncMsg()
5✔
941
                        if err != nil {
5✔
942
                                p.log.Errorf("Unable to create channel "+
×
943
                                        "reestablish message for channel %v: "+
×
944
                                        "%v", chanPoint, err)
×
945
                                continue
×
946
                        }
947

948
                        msgs = append(msgs, chanSync)
5✔
949

5✔
950
                        // Check if this channel needs to have the cooperative
5✔
951
                        // close process restarted. If so, we'll need to send
5✔
952
                        // the Shutdown message that is returned.
5✔
953
                        if dbChan.HasChanStatus(
5✔
954
                                channeldb.ChanStatusCoopBroadcasted,
5✔
955
                        ) {
5✔
956

×
957
                                shutdownMsg, err := p.restartCoopClose(lnChan)
×
958
                                if err != nil {
×
959
                                        p.log.Errorf("Unable to restart "+
×
960
                                                "coop close for channel: %v",
×
961
                                                err)
×
962
                                        continue
×
963
                                }
964

965
                                if shutdownMsg == nil {
×
966
                                        continue
×
967
                                }
968

969
                                // Append the message to the set of messages to
970
                                // send.
971
                                msgs = append(msgs, shutdownMsg)
×
972
                        }
973

974
                        continue
5✔
975
                }
976

977
                // Before we register this new link with the HTLC Switch, we'll
978
                // need to fetch its current link-layer forwarding policy from
979
                // the database.
980
                graph := p.cfg.ChannelGraph
3✔
981
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
3✔
982
                        &chanPoint,
3✔
983
                )
3✔
984
                if err != nil && !errors.Is(err, channeldb.ErrEdgeNotFound) {
3✔
985
                        return nil, err
×
986
                }
×
987

988
                // We'll filter out our policy from the directional channel
989
                // edges based whom the edge connects to. If it doesn't connect
990
                // to us, then we know that we were the one that advertised the
991
                // policy.
992
                //
993
                // TODO(roasbeef): can add helper method to get policy for
994
                // particular channel.
995
                var selfPolicy *models.ChannelEdgePolicy
3✔
996
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
3✔
997
                        p.cfg.ServerPubKey[:]) {
6✔
998

3✔
999
                        selfPolicy = p1
3✔
1000
                } else {
6✔
1001
                        selfPolicy = p2
3✔
1002
                }
3✔
1003

1004
                // If we don't yet have an advertised routing policy, then
1005
                // we'll use the current default, otherwise we'll translate the
1006
                // routing policy into a forwarding policy.
1007
                var forwardingPolicy *models.ForwardingPolicy
3✔
1008
                if selfPolicy != nil {
6✔
1009
                        var inboundWireFee lnwire.Fee
3✔
1010
                        _, err := selfPolicy.ExtraOpaqueData.ExtractRecords(
3✔
1011
                                &inboundWireFee,
3✔
1012
                        )
3✔
1013
                        if err != nil {
3✔
1014
                                return nil, err
×
1015
                        }
×
1016

1017
                        inboundFee := models.NewInboundFeeFromWire(
3✔
1018
                                inboundWireFee,
3✔
1019
                        )
3✔
1020

3✔
1021
                        forwardingPolicy = &models.ForwardingPolicy{
3✔
1022
                                MinHTLCOut:    selfPolicy.MinHTLC,
3✔
1023
                                MaxHTLC:       selfPolicy.MaxHTLC,
3✔
1024
                                BaseFee:       selfPolicy.FeeBaseMSat,
3✔
1025
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
3✔
1026
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
3✔
1027

3✔
1028
                                InboundFee: inboundFee,
3✔
1029
                        }
3✔
1030
                } else {
3✔
1031
                        p.log.Warnf("Unable to find our forwarding policy "+
3✔
1032
                                "for channel %v, using default values",
3✔
1033
                                chanPoint)
3✔
1034
                        forwardingPolicy = &p.cfg.RoutingPolicy
3✔
1035
                }
3✔
1036

1037
                p.log.Tracef("Using link policy of: %v",
3✔
1038
                        spew.Sdump(forwardingPolicy))
3✔
1039

3✔
1040
                // If the channel is pending, set the value to nil in the
3✔
1041
                // activeChannels map. This is done to signify that the channel
3✔
1042
                // is pending. We don't add the link to the switch here - it's
3✔
1043
                // the funding manager's responsibility to spin up pending
3✔
1044
                // channels. Adding them here would just be extra work as we'll
3✔
1045
                // tear them down when creating + adding the final link.
3✔
1046
                if lnChan.IsPending() {
6✔
1047
                        p.activeChannels.Store(chanID, nil)
3✔
1048

3✔
1049
                        continue
3✔
1050
                }
1051

1052
                shutdownInfo, err := lnChan.State().ShutdownInfo()
3✔
1053
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
3✔
1054
                        return nil, err
×
1055
                }
×
1056

1057
                var (
3✔
1058
                        shutdownMsg     fn.Option[lnwire.Shutdown]
3✔
1059
                        shutdownInfoErr error
3✔
1060
                )
3✔
1061
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
6✔
1062
                        // Compute an ideal fee.
3✔
1063
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
1064
                                p.cfg.CoopCloseTargetConfs,
3✔
1065
                        )
3✔
1066
                        if err != nil {
3✔
1067
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1068
                                        "estimate fee: %w", err)
×
1069

×
1070
                                return
×
1071
                        }
×
1072

1073
                        chanCloser, err := p.createChanCloser(
3✔
1074
                                lnChan, info.DeliveryScript.Val, feePerKw, nil,
3✔
1075
                                info.Closer(),
3✔
1076
                        )
3✔
1077
                        if err != nil {
3✔
1078
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1079
                                        "create chan closer: %w", err)
×
1080

×
1081
                                return
×
1082
                        }
×
1083

1084
                        chanID := lnwire.NewChanIDFromOutPoint(
3✔
1085
                                lnChan.State().FundingOutpoint,
3✔
1086
                        )
3✔
1087

3✔
1088
                        p.activeChanCloses[chanID] = chanCloser
3✔
1089

3✔
1090
                        // Create the Shutdown message.
3✔
1091
                        shutdown, err := chanCloser.ShutdownChan()
3✔
1092
                        if err != nil {
3✔
1093
                                delete(p.activeChanCloses, chanID)
×
1094
                                shutdownInfoErr = err
×
1095

×
1096
                                return
×
1097
                        }
×
1098

1099
                        shutdownMsg = fn.Some(*shutdown)
3✔
1100
                })
1101
                if shutdownInfoErr != nil {
3✔
1102
                        return nil, shutdownInfoErr
×
1103
                }
×
1104

1105
                // Subscribe to the set of on-chain events for this channel.
1106
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
3✔
1107
                        chanPoint,
3✔
1108
                )
3✔
1109
                if err != nil {
3✔
1110
                        return nil, err
×
1111
                }
×
1112

1113
                err = p.addLink(
3✔
1114
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
3✔
1115
                        true, shutdownMsg,
3✔
1116
                )
3✔
1117
                if err != nil {
3✔
1118
                        return nil, fmt.Errorf("unable to add link %v to "+
×
1119
                                "switch: %v", chanPoint, err)
×
1120
                }
×
1121

1122
                p.activeChannels.Store(chanID, lnChan)
3✔
1123
        }
1124

1125
        return msgs, nil
6✔
1126
}
1127

1128
// addLink creates and adds a new ChannelLink from the specified channel.
1129
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1130
        lnChan *lnwallet.LightningChannel,
1131
        forwardingPolicy *models.ForwardingPolicy,
1132
        chainEvents *contractcourt.ChainEventSubscription,
1133
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
3✔
1134

3✔
1135
        // onChannelFailure will be called by the link in case the channel
3✔
1136
        // fails for some reason.
3✔
1137
        onChannelFailure := func(chanID lnwire.ChannelID,
3✔
1138
                shortChanID lnwire.ShortChannelID,
3✔
1139
                linkErr htlcswitch.LinkFailureError) {
6✔
1140

3✔
1141
                failure := linkFailureReport{
3✔
1142
                        chanPoint:   *chanPoint,
3✔
1143
                        chanID:      chanID,
3✔
1144
                        shortChanID: shortChanID,
3✔
1145
                        linkErr:     linkErr,
3✔
1146
                }
3✔
1147

3✔
1148
                select {
3✔
1149
                case p.linkFailures <- failure:
3✔
1150
                case <-p.quit:
×
1151
                case <-p.cfg.Quit:
×
1152
                }
1153
        }
1154

1155
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
6✔
1156
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
3✔
1157
        }
3✔
1158

1159
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
6✔
1160
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
3✔
1161
        }
3✔
1162

1163
        //nolint:lll
1164
        linkCfg := htlcswitch.ChannelLinkConfig{
3✔
1165
                Peer:                   p,
3✔
1166
                DecodeHopIterators:     p.cfg.Sphinx.DecodeHopIterators,
3✔
1167
                ExtractErrorEncrypter:  p.cfg.Sphinx.ExtractErrorEncrypter,
3✔
1168
                FetchLastChannelUpdate: p.cfg.FetchLastChanUpdate,
3✔
1169
                HodlMask:               p.cfg.Hodl.Mask(),
3✔
1170
                Registry:               p.cfg.Invoices,
3✔
1171
                BestHeight:             p.cfg.Switch.BestHeight,
3✔
1172
                Circuits:               p.cfg.Switch.CircuitModifier(),
3✔
1173
                ForwardPackets:         p.cfg.InterceptSwitch.ForwardPackets,
3✔
1174
                FwrdingPolicy:          *forwardingPolicy,
3✔
1175
                FeeEstimator:           p.cfg.FeeEstimator,
3✔
1176
                PreimageCache:          p.cfg.WitnessBeacon,
3✔
1177
                ChainEvents:            chainEvents,
3✔
1178
                UpdateContractSignals:  updateContractSignals,
3✔
1179
                NotifyContractUpdate:   notifyContractUpdate,
3✔
1180
                OnChannelFailure:       onChannelFailure,
3✔
1181
                SyncStates:             syncStates,
3✔
1182
                BatchTicker:            ticker.New(p.cfg.ChannelCommitInterval),
3✔
1183
                FwdPkgGCTicker:         ticker.New(time.Hour),
3✔
1184
                PendingCommitTicker: ticker.New(
3✔
1185
                        p.cfg.PendingCommitInterval,
3✔
1186
                ),
3✔
1187
                BatchSize:               p.cfg.ChannelCommitBatchSize,
3✔
1188
                UnsafeReplay:            p.cfg.UnsafeReplay,
3✔
1189
                MinUpdateTimeout:        htlcswitch.DefaultMinLinkFeeUpdateTimeout,
3✔
1190
                MaxUpdateTimeout:        htlcswitch.DefaultMaxLinkFeeUpdateTimeout,
3✔
1191
                OutgoingCltvRejectDelta: p.cfg.OutgoingCltvRejectDelta,
3✔
1192
                TowerClient:             p.cfg.TowerClient,
3✔
1193
                MaxOutgoingCltvExpiry:   p.cfg.MaxOutgoingCltvExpiry,
3✔
1194
                MaxFeeAllocation:        p.cfg.MaxChannelFeeAllocation,
3✔
1195
                MaxAnchorsCommitFeeRate: p.cfg.MaxAnchorsCommitFeeRate,
3✔
1196
                NotifyActiveLink:        p.cfg.ChannelNotifier.NotifyActiveLinkEvent,
3✔
1197
                NotifyActiveChannel:     p.cfg.ChannelNotifier.NotifyActiveChannelEvent,
3✔
1198
                NotifyInactiveChannel:   p.cfg.ChannelNotifier.NotifyInactiveChannelEvent,
3✔
1199
                NotifyInactiveLinkEvent: p.cfg.ChannelNotifier.NotifyInactiveLinkEvent,
3✔
1200
                HtlcNotifier:            p.cfg.HtlcNotifier,
3✔
1201
                GetAliases:              p.cfg.GetAliases,
3✔
1202
                PreviouslySentShutdown:  shutdownMsg,
3✔
1203
                DisallowRouteBlinding:   p.cfg.DisallowRouteBlinding,
3✔
1204
                MaxFeeExposure:          p.cfg.MaxFeeExposure,
3✔
1205
        }
3✔
1206

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

3✔
1214
        // With the channel link created, we'll now notify the htlc switch so
3✔
1215
        // this channel can be used to dispatch local payments and also
3✔
1216
        // passively forward payments.
3✔
1217
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
3✔
1218
}
1219

1220
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1221
// one confirmed public channel exists with them.
1222
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
6✔
1223
        defer p.wg.Done()
6✔
1224

6✔
1225
        hasConfirmedPublicChan := false
6✔
1226
        for _, channel := range channels {
11✔
1227
                if channel.IsPending {
8✔
1228
                        continue
3✔
1229
                }
1230
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
10✔
1231
                        continue
5✔
1232
                }
1233

1234
                hasConfirmedPublicChan = true
3✔
1235
                break
3✔
1236
        }
1237
        if !hasConfirmedPublicChan {
12✔
1238
                return
6✔
1239
        }
6✔
1240

1241
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
3✔
1242
        if err != nil {
3✔
1243
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1244
                return
×
1245
        }
×
1246

1247
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
3✔
1248
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1249
        }
×
1250
}
1251

1252
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1253
// have any active channels with them.
1254
func (p *Brontide) maybeSendChannelUpdates() {
6✔
1255
        defer p.wg.Done()
6✔
1256

6✔
1257
        // If we don't have any active channels, then we can exit early.
6✔
1258
        if p.activeChannels.Len() == 0 {
10✔
1259
                return
4✔
1260
        }
4✔
1261

1262
        maybeSendUpd := func(cid lnwire.ChannelID,
5✔
1263
                lnChan *lnwallet.LightningChannel) error {
10✔
1264

5✔
1265
                // Nil channels are pending, so we'll skip them.
5✔
1266
                if lnChan == nil {
8✔
1267
                        return nil
3✔
1268
                }
3✔
1269

1270
                dbChan := lnChan.State()
5✔
1271
                scid := func() lnwire.ShortChannelID {
10✔
1272
                        switch {
5✔
1273
                        // Otherwise if it's a zero conf channel and confirmed,
1274
                        // then we need to use the "real" scid.
1275
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
3✔
1276
                                return dbChan.ZeroConfRealScid()
3✔
1277

1278
                        // Otherwise, we can use the normal scid.
1279
                        default:
5✔
1280
                                return dbChan.ShortChanID()
5✔
1281
                        }
1282
                }()
1283

1284
                // Now that we know the channel is in a good state, we'll try
1285
                // to fetch the update to send to the remote peer. If the
1286
                // channel is pending, and not a zero conf channel, we'll get
1287
                // an error here which we'll ignore.
1288
                chanUpd, err := p.cfg.FetchLastChanUpdate(scid)
5✔
1289
                if err != nil {
8✔
1290
                        p.log.Debugf("Unable to fetch channel update for "+
3✔
1291
                                "ChannelPoint(%v), scid=%v: %v",
3✔
1292
                                dbChan.FundingOutpoint, dbChan.ShortChanID, err)
3✔
1293

3✔
1294
                        return nil
3✔
1295
                }
3✔
1296

1297
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
5✔
1298
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
5✔
1299

5✔
1300
                // We'll send it as a normal message instead of using the lazy
5✔
1301
                // queue to prioritize transmission of the fresh update.
5✔
1302
                if err := p.SendMessage(false, chanUpd); err != nil {
5✔
1303
                        err := fmt.Errorf("unable to send channel update for "+
×
1304
                                "ChannelPoint(%v), scid=%v: %w",
×
1305
                                dbChan.FundingOutpoint, dbChan.ShortChanID(),
×
1306
                                err)
×
1307
                        p.log.Errorf(err.Error())
×
1308

×
1309
                        return err
×
1310
                }
×
1311

1312
                return nil
5✔
1313
        }
1314

1315
        p.activeChannels.ForEach(maybeSendUpd)
5✔
1316
}
1317

1318
// WaitForDisconnect waits until the peer has disconnected. A peer may be
1319
// disconnected if the local or remote side terminates the connection, or an
1320
// irrecoverable protocol error has been encountered. This method will only
1321
// begin watching the peer's waitgroup after the ready channel or the peer's
1322
// quit channel are signaled. The ready channel should only be signaled if a
1323
// call to Start returns no error. Otherwise, if the peer fails to start,
1324
// calling Disconnect will signal the quit channel and the method will not
1325
// block, since no goroutines were spawned.
1326
func (p *Brontide) WaitForDisconnect(ready chan struct{}) {
3✔
1327
        // Before we try to call the `Wait` goroutine, we'll make sure the main
3✔
1328
        // set of goroutines are already active.
3✔
1329
        select {
3✔
1330
        case <-p.startReady:
3✔
1331
        case <-p.quit:
×
1332
                return
×
1333
        }
1334

1335
        select {
3✔
1336
        case <-ready:
3✔
1337
        case <-p.quit:
1✔
1338
        }
1339

1340
        p.wg.Wait()
3✔
1341
}
1342

1343
// Disconnect terminates the connection with the remote peer. Additionally, a
1344
// signal is sent to the server and htlcSwitch indicating the resources
1345
// allocated to the peer can now be cleaned up.
1346
func (p *Brontide) Disconnect(reason error) {
4✔
1347
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
7✔
1348
                return
3✔
1349
        }
3✔
1350

1351
        // Make sure initialization has completed before we try to tear things
1352
        // down.
1353
        select {
4✔
1354
        case <-p.startReady:
3✔
1355
        case <-p.quit:
×
1356
                return
×
1357
        }
1358

1359
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
3✔
1360
        p.storeError(err)
3✔
1361

3✔
1362
        p.log.Infof(err.Error())
3✔
1363

3✔
1364
        // Stop PingManager before closing TCP connection.
3✔
1365
        p.pingManager.Stop()
3✔
1366

3✔
1367
        // Ensure that the TCP connection is properly closed before continuing.
3✔
1368
        p.cfg.Conn.Close()
3✔
1369

3✔
1370
        close(p.quit)
3✔
1371
}
1372

1373
// String returns the string representation of this peer.
1374
func (p *Brontide) String() string {
3✔
1375
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
3✔
1376
}
3✔
1377

1378
// readNextMessage reads, and returns the next message on the wire along with
1379
// any additional raw payload.
1380
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
10✔
1381
        noiseConn := p.cfg.Conn
10✔
1382
        err := noiseConn.SetReadDeadline(time.Time{})
10✔
1383
        if err != nil {
10✔
1384
                return nil, err
×
1385
        }
×
1386

1387
        pktLen, err := noiseConn.ReadNextHeader()
10✔
1388
        if err != nil {
13✔
1389
                return nil, fmt.Errorf("read next header: %w", err)
3✔
1390
        }
3✔
1391

1392
        // First we'll read the next _full_ message. We do this rather than
1393
        // reading incrementally from the stream as the Lightning wire protocol
1394
        // is message oriented and allows nodes to pad on additional data to
1395
        // the message stream.
1396
        var (
7✔
1397
                nextMsg lnwire.Message
7✔
1398
                msgLen  uint64
7✔
1399
        )
7✔
1400
        err = p.cfg.ReadPool.Submit(func(buf *buffer.Read) error {
14✔
1401
                // Before reading the body of the message, set the read timeout
7✔
1402
                // accordingly to ensure we don't block other readers using the
7✔
1403
                // pool. We do so only after the task has been scheduled to
7✔
1404
                // ensure the deadline doesn't expire while the message is in
7✔
1405
                // the process of being scheduled.
7✔
1406
                readDeadline := time.Now().Add(
7✔
1407
                        p.scaleTimeout(readMessageTimeout),
7✔
1408
                )
7✔
1409
                readErr := noiseConn.SetReadDeadline(readDeadline)
7✔
1410
                if readErr != nil {
7✔
1411
                        return readErr
×
1412
                }
×
1413

1414
                // The ReadNextBody method will actually end up re-using the
1415
                // buffer, so within this closure, we can continue to use
1416
                // rawMsg as it's just a slice into the buf from the buffer
1417
                // pool.
1418
                rawMsg, readErr := noiseConn.ReadNextBody(buf[:pktLen])
7✔
1419
                if readErr != nil {
7✔
1420
                        return fmt.Errorf("read next body: %w", readErr)
×
1421
                }
×
1422
                msgLen = uint64(len(rawMsg))
7✔
1423

7✔
1424
                // Next, create a new io.Reader implementation from the raw
7✔
1425
                // message, and use this to decode the message directly from.
7✔
1426
                msgReader := bytes.NewReader(rawMsg)
7✔
1427
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
7✔
1428
                if err != nil {
10✔
1429
                        return err
3✔
1430
                }
3✔
1431

1432
                // At this point, rawMsg and buf will be returned back to the
1433
                // buffer pool for re-use.
1434
                return nil
7✔
1435
        })
1436
        atomic.AddUint64(&p.bytesReceived, msgLen)
7✔
1437
        if err != nil {
10✔
1438
                return nil, err
3✔
1439
        }
3✔
1440

1441
        p.logWireMessage(nextMsg, true)
7✔
1442

7✔
1443
        return nextMsg, nil
7✔
1444
}
1445

1446
// msgStream implements a goroutine-safe, in-order stream of messages to be
1447
// delivered via closure to a receiver. These messages MUST be in order due to
1448
// the nature of the lightning channel commitment and gossiper state machines.
1449
// TODO(conner): use stream handler interface to abstract out stream
1450
// state/logging.
1451
type msgStream struct {
1452
        streamShutdown int32 // To be used atomically.
1453

1454
        peer *Brontide
1455

1456
        apply func(lnwire.Message)
1457

1458
        startMsg string
1459
        stopMsg  string
1460

1461
        msgCond *sync.Cond
1462
        msgs    []lnwire.Message
1463

1464
        mtx sync.Mutex
1465

1466
        producerSema chan struct{}
1467

1468
        wg   sync.WaitGroup
1469
        quit chan struct{}
1470
}
1471

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

6✔
1480
        stream := &msgStream{
6✔
1481
                peer:         p,
6✔
1482
                apply:        apply,
6✔
1483
                startMsg:     startMsg,
6✔
1484
                stopMsg:      stopMsg,
6✔
1485
                producerSema: make(chan struct{}, bufSize),
6✔
1486
                quit:         make(chan struct{}),
6✔
1487
        }
6✔
1488
        stream.msgCond = sync.NewCond(&stream.mtx)
6✔
1489

6✔
1490
        // Before we return the active stream, we'll populate the producer's
6✔
1491
        // semaphore channel. We'll use this to ensure that the producer won't
6✔
1492
        // attempt to allocate memory in the queue for an item until it has
6✔
1493
        // sufficient extra space.
6✔
1494
        for i := uint32(0); i < bufSize; i++ {
3,009✔
1495
                stream.producerSema <- struct{}{}
3,003✔
1496
        }
3,003✔
1497

1498
        return stream
6✔
1499
}
1500

1501
// Start starts the chanMsgStream.
1502
func (ms *msgStream) Start() {
6✔
1503
        ms.wg.Add(1)
6✔
1504
        go ms.msgConsumer()
6✔
1505
}
6✔
1506

1507
// Stop stops the chanMsgStream.
1508
func (ms *msgStream) Stop() {
3✔
1509
        // TODO(roasbeef): signal too?
3✔
1510

3✔
1511
        close(ms.quit)
3✔
1512

3✔
1513
        // Now that we've closed the channel, we'll repeatedly signal the msg
3✔
1514
        // consumer until we've detected that it has exited.
3✔
1515
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
6✔
1516
                ms.msgCond.Signal()
3✔
1517
                time.Sleep(time.Millisecond * 100)
3✔
1518
        }
3✔
1519

1520
        ms.wg.Wait()
3✔
1521
}
1522

1523
// msgConsumer is the main goroutine that streams messages from the peer's
1524
// readHandler directly to the target channel.
1525
func (ms *msgStream) msgConsumer() {
6✔
1526
        defer ms.wg.Done()
6✔
1527
        defer peerLog.Tracef(ms.stopMsg)
6✔
1528
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
6✔
1529

6✔
1530
        peerLog.Tracef(ms.startMsg)
6✔
1531

6✔
1532
        for {
12✔
1533
                // First, we'll check our condition. If the queue of messages
6✔
1534
                // is empty, then we'll wait until a new item is added.
6✔
1535
                ms.msgCond.L.Lock()
6✔
1536
                for len(ms.msgs) == 0 {
12✔
1537
                        ms.msgCond.Wait()
6✔
1538

6✔
1539
                        // If we woke up in order to exit, then we'll do so.
6✔
1540
                        // Otherwise, we'll check the message queue for any new
6✔
1541
                        // items.
6✔
1542
                        select {
6✔
1543
                        case <-ms.peer.quit:
3✔
1544
                                ms.msgCond.L.Unlock()
3✔
1545
                                return
3✔
1546
                        case <-ms.quit:
3✔
1547
                                ms.msgCond.L.Unlock()
3✔
1548
                                return
3✔
1549
                        default:
3✔
1550
                        }
1551
                }
1552

1553
                // Grab the message off the front of the queue, shifting the
1554
                // slice's reference down one in order to remove the message
1555
                // from the queue.
1556
                msg := ms.msgs[0]
3✔
1557
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
3✔
1558
                ms.msgs = ms.msgs[1:]
3✔
1559

3✔
1560
                ms.msgCond.L.Unlock()
3✔
1561

3✔
1562
                ms.apply(msg)
3✔
1563

3✔
1564
                // We've just successfully processed an item, so we'll signal
3✔
1565
                // to the producer that a new slot in the buffer. We'll use
3✔
1566
                // this to bound the size of the buffer to avoid allowing it to
3✔
1567
                // grow indefinitely.
3✔
1568
                select {
3✔
1569
                case ms.producerSema <- struct{}{}:
3✔
1570
                case <-ms.peer.quit:
3✔
1571
                        return
3✔
1572
                case <-ms.quit:
3✔
1573
                        return
3✔
1574
                }
1575
        }
1576
}
1577

1578
// AddMsg adds a new message to the msgStream. This function is safe for
1579
// concurrent access.
1580
func (ms *msgStream) AddMsg(msg lnwire.Message) {
3✔
1581
        // First, we'll attempt to receive from the producerSema struct. This
3✔
1582
        // acts as a semaphore to prevent us from indefinitely buffering
3✔
1583
        // incoming items from the wire. Either the msg queue isn't full, and
3✔
1584
        // we'll not block, or the queue is full, and we'll block until either
3✔
1585
        // we're signalled to quit, or a slot is freed up.
3✔
1586
        select {
3✔
1587
        case <-ms.producerSema:
3✔
1588
        case <-ms.peer.quit:
×
1589
                return
×
1590
        case <-ms.quit:
×
1591
                return
×
1592
        }
1593

1594
        // Next, we'll lock the condition, and add the message to the end of
1595
        // the message queue.
1596
        ms.msgCond.L.Lock()
3✔
1597
        ms.msgs = append(ms.msgs, msg)
3✔
1598
        ms.msgCond.L.Unlock()
3✔
1599

3✔
1600
        // With the message added, we signal to the msgConsumer that there are
3✔
1601
        // additional messages to consume.
3✔
1602
        ms.msgCond.Signal()
3✔
1603
}
1604

1605
// waitUntilLinkActive waits until the target link is active and returns a
1606
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1607
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1608
func waitUntilLinkActive(p *Brontide,
1609
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
3✔
1610

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

3✔
1613
        // Subscribe to receive channel events.
3✔
1614
        //
3✔
1615
        // NOTE: If the link is already active by SubscribeChannelEvents, then
3✔
1616
        // GetLink will retrieve the link and we can send messages. If the link
3✔
1617
        // becomes active between SubscribeChannelEvents and GetLink, then GetLink
3✔
1618
        // will retrieve the link. If the link becomes active after GetLink, then
3✔
1619
        // we will get an ActiveLinkEvent notification and retrieve the link. If
3✔
1620
        // the call to GetLink is before SubscribeChannelEvents, however, there
3✔
1621
        // will be a race condition.
3✔
1622
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
3✔
1623
        if err != nil {
6✔
1624
                // If we have a non-nil error, then the server is shutting down and we
3✔
1625
                // can exit here and return nil. This means no message will be delivered
3✔
1626
                // to the link.
3✔
1627
                return nil
3✔
1628
        }
3✔
1629
        defer sub.Cancel()
3✔
1630

3✔
1631
        // The link may already be active by this point, and we may have missed the
3✔
1632
        // ActiveLinkEvent. Check if the link exists.
3✔
1633
        link := p.fetchLinkFromKeyAndCid(cid)
3✔
1634
        if link != nil {
6✔
1635
                return link
3✔
1636
        }
3✔
1637

1638
        // If the link is nil, we must wait for it to be active.
1639
        for {
6✔
1640
                select {
3✔
1641
                // A new event has been sent by the ChannelNotifier. We first check
1642
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1643
                // that the event is for this channel. Otherwise, we discard the
1644
                // message.
1645
                case e := <-sub.Updates():
3✔
1646
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
3✔
1647
                        if !ok {
6✔
1648
                                // Ignore this notification.
3✔
1649
                                continue
3✔
1650
                        }
1651

1652
                        chanPoint := event.ChannelPoint
3✔
1653

3✔
1654
                        // Check whether the retrieved chanPoint matches the target
3✔
1655
                        // channel id.
3✔
1656
                        if !cid.IsChanPoint(chanPoint) {
3✔
1657
                                continue
×
1658
                        }
1659

1660
                        // The link shouldn't be nil as we received an
1661
                        // ActiveLinkEvent. If it is nil, we return nil and the
1662
                        // calling function should catch it.
1663
                        return p.fetchLinkFromKeyAndCid(cid)
3✔
1664

1665
                case <-p.quit:
3✔
1666
                        return nil
3✔
1667
                }
1668
        }
1669
}
1670

1671
// newChanMsgStream is used to create a msgStream between the peer and
1672
// particular channel link in the htlcswitch. We utilize additional
1673
// synchronization with the fundingManager to ensure we don't attempt to
1674
// dispatch a message to a channel before it is fully active. A reference to the
1675
// channel this stream forwards to is held in scope to prevent unnecessary
1676
// lookups.
1677
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
3✔
1678
        var chanLink htlcswitch.ChannelUpdateHandler
3✔
1679

3✔
1680
        apply := func(msg lnwire.Message) {
6✔
1681
                // This check is fine because if the link no longer exists, it will
3✔
1682
                // be removed from the activeChannels map and subsequent messages
3✔
1683
                // shouldn't reach the chan msg stream.
3✔
1684
                if chanLink == nil {
6✔
1685
                        chanLink = waitUntilLinkActive(p, cid)
3✔
1686

3✔
1687
                        // If the link is still not active and the calling function
3✔
1688
                        // errored out, just return.
3✔
1689
                        if chanLink == nil {
6✔
1690
                                p.log.Warnf("Link=%v is not active")
3✔
1691
                                return
3✔
1692
                        }
3✔
1693
                }
1694

1695
                // In order to avoid unnecessarily delivering message
1696
                // as the peer is exiting, we'll check quickly to see
1697
                // if we need to exit.
1698
                select {
3✔
1699
                case <-p.quit:
×
1700
                        return
×
1701
                default:
3✔
1702
                }
1703

1704
                chanLink.HandleChannelUpdate(msg)
3✔
1705
        }
1706

1707
        return newMsgStream(p,
3✔
1708
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
3✔
1709
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
3✔
1710
                1000,
3✔
1711
                apply,
3✔
1712
        )
3✔
1713
}
1714

1715
// newDiscMsgStream is used to setup a msgStream between the peer and the
1716
// authenticated gossiper. This stream should be used to forward all remote
1717
// channel announcements.
1718
func newDiscMsgStream(p *Brontide) *msgStream {
6✔
1719
        apply := func(msg lnwire.Message) {
9✔
1720
                // TODO(yy): `ProcessRemoteAnnouncement` returns an error chan
3✔
1721
                // and we need to process it.
3✔
1722
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(msg, p)
3✔
1723
        }
3✔
1724

1725
        return newMsgStream(
6✔
1726
                p,
6✔
1727
                "Update stream for gossiper created",
6✔
1728
                "Update stream for gossiper exited",
6✔
1729
                1000,
6✔
1730
                apply,
6✔
1731
        )
6✔
1732
}
1733

1734
// readHandler is responsible for reading messages off the wire in series, then
1735
// properly dispatching the handling of the message to the proper subsystem.
1736
//
1737
// NOTE: This method MUST be run as a goroutine.
1738
func (p *Brontide) readHandler() {
6✔
1739
        defer p.wg.Done()
6✔
1740

6✔
1741
        // We'll stop the timer after a new messages is received, and also
6✔
1742
        // reset it after we process the next message.
6✔
1743
        idleTimer := time.AfterFunc(idleTimeout, func() {
6✔
1744
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
1745
                        p, idleTimeout)
×
1746
                p.Disconnect(err)
×
1747
        })
×
1748

1749
        // Initialize our negotiated gossip sync method before reading messages
1750
        // off the wire. When using gossip queries, this ensures a gossip
1751
        // syncer is active by the time query messages arrive.
1752
        //
1753
        // TODO(conner): have peer store gossip syncer directly and bypass
1754
        // gossiper?
1755
        p.initGossipSync()
6✔
1756

6✔
1757
        discStream := newDiscMsgStream(p)
6✔
1758
        discStream.Start()
6✔
1759
        defer discStream.Stop()
6✔
1760
out:
6✔
1761
        for atomic.LoadInt32(&p.disconnect) == 0 {
13✔
1762
                nextMsg, err := p.readNextMessage()
7✔
1763
                if !idleTimer.Stop() {
7✔
1764
                        select {
×
1765
                        case <-idleTimer.C:
×
1766
                        default:
×
1767
                        }
1768
                }
1769
                if err != nil {
7✔
1770
                        p.log.Infof("unable to read message from peer: %v", err)
3✔
1771

3✔
1772
                        // If we could not read our peer's message due to an
3✔
1773
                        // unknown type or invalid alias, we continue processing
3✔
1774
                        // as normal. We store unknown message and address
3✔
1775
                        // types, as they may provide debugging insight.
3✔
1776
                        switch e := err.(type) {
3✔
1777
                        // If this is just a message we don't yet recognize,
1778
                        // we'll continue processing as normal as this allows
1779
                        // us to introduce new messages in a forwards
1780
                        // compatible manner.
1781
                        case *lnwire.UnknownMessage:
3✔
1782
                                p.storeError(e)
3✔
1783
                                idleTimer.Reset(idleTimeout)
3✔
1784
                                continue
3✔
1785

1786
                        // If they sent us an address type that we don't yet
1787
                        // know of, then this isn't a wire error, so we'll
1788
                        // simply continue parsing the remainder of their
1789
                        // messages.
1790
                        case *lnwire.ErrUnknownAddrType:
×
1791
                                p.storeError(e)
×
1792
                                idleTimer.Reset(idleTimeout)
×
1793
                                continue
×
1794

1795
                        // If the NodeAnnouncement has an invalid alias, then
1796
                        // we'll log that error above and continue so we can
1797
                        // continue to read messages from the peer. We do not
1798
                        // store this error because it is of little debugging
1799
                        // value.
1800
                        case *lnwire.ErrInvalidNodeAlias:
×
1801
                                idleTimer.Reset(idleTimeout)
×
1802
                                continue
×
1803

1804
                        // If the error we encountered wasn't just a message we
1805
                        // didn't recognize, then we'll stop all processing as
1806
                        // this is a fatal error.
1807
                        default:
3✔
1808
                                break out
3✔
1809
                        }
1810
                }
1811

1812
                var (
4✔
1813
                        targetChan   lnwire.ChannelID
4✔
1814
                        isLinkUpdate bool
4✔
1815
                )
4✔
1816

4✔
1817
                switch msg := nextMsg.(type) {
4✔
1818
                case *lnwire.Pong:
2✔
1819
                        // When we receive a Pong message in response to our
2✔
1820
                        // last ping message, we send it to the pingManager
2✔
1821
                        p.pingManager.ReceivedPong(msg)
2✔
1822

1823
                case *lnwire.Ping:
2✔
1824
                        // First, we'll store their latest ping payload within
2✔
1825
                        // the relevant atomic variable.
2✔
1826
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
2✔
1827

2✔
1828
                        // Next, we'll send over the amount of specified pong
2✔
1829
                        // bytes.
2✔
1830
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
2✔
1831
                        p.queueMsg(pong, nil)
2✔
1832

1833
                case *lnwire.OpenChannel,
1834
                        *lnwire.AcceptChannel,
1835
                        *lnwire.FundingCreated,
1836
                        *lnwire.FundingSigned,
1837
                        *lnwire.ChannelReady:
3✔
1838

3✔
1839
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
1840

1841
                case *lnwire.Shutdown:
3✔
1842
                        select {
3✔
1843
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
1844
                        case <-p.quit:
×
1845
                                break out
×
1846
                        }
1847
                case *lnwire.ClosingSigned:
3✔
1848
                        select {
3✔
1849
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
1850
                        case <-p.quit:
×
1851
                                break out
×
1852
                        }
1853

1854
                case *lnwire.Warning:
×
1855
                        targetChan = msg.ChanID
×
1856
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
1857

1858
                case *lnwire.Error:
3✔
1859
                        targetChan = msg.ChanID
3✔
1860
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
3✔
1861

1862
                case *lnwire.ChannelReestablish:
3✔
1863
                        targetChan = msg.ChanID
3✔
1864
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
1865

3✔
1866
                        // If we failed to find the link in question, and the
3✔
1867
                        // message received was a channel sync message, then
3✔
1868
                        // this might be a peer trying to resync closed channel.
3✔
1869
                        // In this case we'll try to resend our last channel
3✔
1870
                        // sync message, such that the peer can recover funds
3✔
1871
                        // from the closed channel.
3✔
1872
                        if !isLinkUpdate {
6✔
1873
                                err := p.resendChanSyncMsg(targetChan)
3✔
1874
                                if err != nil {
6✔
1875
                                        // TODO(halseth): send error to peer?
3✔
1876
                                        p.log.Errorf("resend failed: %v",
3✔
1877
                                                err)
3✔
1878
                                }
3✔
1879
                        }
1880

1881
                // For messages that implement the LinkUpdater interface, we
1882
                // will consider them as link updates and send them to
1883
                // chanStream. These messages will be queued inside chanStream
1884
                // if the channel is not active yet.
1885
                case lnwire.LinkUpdater:
3✔
1886
                        targetChan = msg.TargetChanID()
3✔
1887
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
1888

3✔
1889
                        // Log an error if we don't have this channel. This
3✔
1890
                        // means the peer has sent us a message with unknown
3✔
1891
                        // channel ID.
3✔
1892
                        if !isLinkUpdate {
6✔
1893
                                p.log.Errorf("Unknown channel ID: %v found "+
3✔
1894
                                        "in received msg=%s", targetChan,
3✔
1895
                                        nextMsg.MsgType())
3✔
1896
                        }
3✔
1897

1898
                case *lnwire.ChannelUpdate,
1899
                        *lnwire.ChannelAnnouncement,
1900
                        *lnwire.NodeAnnouncement,
1901
                        *lnwire.AnnounceSignatures,
1902
                        *lnwire.GossipTimestampRange,
1903
                        *lnwire.QueryShortChanIDs,
1904
                        *lnwire.QueryChannelRange,
1905
                        *lnwire.ReplyChannelRange,
1906
                        *lnwire.ReplyShortChanIDsEnd:
3✔
1907

3✔
1908
                        discStream.AddMsg(msg)
3✔
1909

1910
                case *lnwire.Custom:
4✔
1911
                        err := p.handleCustomMessage(msg)
4✔
1912
                        if err != nil {
4✔
1913
                                p.storeError(err)
×
1914
                                p.log.Errorf("%v", err)
×
1915
                        }
×
1916

1917
                default:
×
1918
                        // If the message we received is unknown to us, store
×
1919
                        // the type to track the failure.
×
1920
                        err := fmt.Errorf("unknown message type %v received",
×
1921
                                uint16(msg.MsgType()))
×
1922
                        p.storeError(err)
×
1923

×
1924
                        p.log.Errorf("%v", err)
×
1925
                }
1926

1927
                if isLinkUpdate {
7✔
1928
                        // If this is a channel update, then we need to feed it
3✔
1929
                        // into the channel's in-order message stream.
3✔
1930
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
3✔
1931
                }
3✔
1932

1933
                idleTimer.Reset(idleTimeout)
4✔
1934
        }
1935

1936
        p.Disconnect(errors.New("read handler closed"))
3✔
1937

3✔
1938
        p.log.Trace("readHandler for peer done")
3✔
1939
}
1940

1941
// handleCustomMessage handles the given custom message if a handler is
1942
// registered.
1943
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
4✔
1944
        if p.cfg.HandleCustomMessage == nil {
4✔
1945
                return fmt.Errorf("no custom message handler for "+
×
1946
                        "message type %v", uint16(msg.MsgType()))
×
1947
        }
×
1948

1949
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
4✔
1950
}
1951

1952
// isLoadedFromDisk returns true if the provided channel ID is loaded from
1953
// disk.
1954
//
1955
// NOTE: only returns true for pending channels.
1956
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
3✔
1957
        // If this is a newly added channel, no need to reestablish.
3✔
1958
        _, added := p.addedChannels.Load(chanID)
3✔
1959
        if added {
6✔
1960
                return false
3✔
1961
        }
3✔
1962

1963
        // Return false if the channel is unknown.
1964
        channel, ok := p.activeChannels.Load(chanID)
3✔
1965
        if !ok {
3✔
1966
                return false
×
1967
        }
×
1968

1969
        // During startup, we will use a nil value to mark a pending channel
1970
        // that's loaded from disk.
1971
        return channel == nil
3✔
1972
}
1973

1974
// isActiveChannel returns true if the provided channel id is active, otherwise
1975
// returns false.
1976
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
11✔
1977
        // The channel would be nil if,
11✔
1978
        // - the channel doesn't exist, or,
11✔
1979
        // - the channel exists, but is pending. In this case, we don't
11✔
1980
        //   consider this channel active.
11✔
1981
        channel, _ := p.activeChannels.Load(chanID)
11✔
1982

11✔
1983
        return channel != nil
11✔
1984
}
11✔
1985

1986
// isPendingChannel returns true if the provided channel ID is pending, and
1987
// returns false if the channel is active or unknown.
1988
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
9✔
1989
        // Return false if the channel is unknown.
9✔
1990
        channel, ok := p.activeChannels.Load(chanID)
9✔
1991
        if !ok {
15✔
1992
                return false
6✔
1993
        }
6✔
1994

1995
        return channel == nil
3✔
1996
}
1997

1998
// hasChannel returns true if the peer has a pending/active channel specified
1999
// by the channel ID.
2000
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
3✔
2001
        _, ok := p.activeChannels.Load(chanID)
3✔
2002
        return ok
3✔
2003
}
3✔
2004

2005
// storeError stores an error in our peer's buffer of recent errors with the
2006
// current timestamp. Errors are only stored if we have at least one active
2007
// channel with the peer to mitigate a dos vector where a peer costlessly
2008
// connects to us and spams us with errors.
2009
func (p *Brontide) storeError(err error) {
3✔
2010
        var haveChannels bool
3✔
2011

3✔
2012
        p.activeChannels.Range(func(_ lnwire.ChannelID,
3✔
2013
                channel *lnwallet.LightningChannel) bool {
6✔
2014

3✔
2015
                // Pending channels will be nil in the activeChannels map.
3✔
2016
                if channel == nil {
6✔
2017
                        // Return true to continue the iteration.
3✔
2018
                        return true
3✔
2019
                }
3✔
2020

2021
                haveChannels = true
3✔
2022

3✔
2023
                // Return false to break the iteration.
3✔
2024
                return false
3✔
2025
        })
2026

2027
        // If we do not have any active channels with the peer, we do not store
2028
        // errors as a dos mitigation.
2029
        if !haveChannels {
6✔
2030
                p.log.Trace("no channels with peer, not storing err")
3✔
2031
                return
3✔
2032
        }
3✔
2033

2034
        p.cfg.ErrorBuffer.Add(
3✔
2035
                &TimestampedError{Timestamp: time.Now(), Error: err},
3✔
2036
        )
3✔
2037
}
2038

2039
// handleWarningOrError processes a warning or error msg and returns true if
2040
// msg should be forwarded to the associated channel link. False is returned if
2041
// any necessary forwarding of msg was already handled by this method. If msg is
2042
// an error from a peer with an active channel, we'll store it in memory.
2043
//
2044
// NOTE: This method should only be called from within the readHandler.
2045
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
2046
        msg lnwire.Message) bool {
3✔
2047

3✔
2048
        if errMsg, ok := msg.(*lnwire.Error); ok {
6✔
2049
                p.storeError(errMsg)
3✔
2050
        }
3✔
2051

2052
        switch {
3✔
2053
        // Connection wide messages should be forwarded to all channel links
2054
        // with this peer.
2055
        case chanID == lnwire.ConnectionWideID:
×
2056
                for _, chanStream := range p.activeMsgStreams {
×
2057
                        chanStream.AddMsg(msg)
×
2058
                }
×
2059

2060
                return false
×
2061

2062
        // If the channel ID for the message corresponds to a pending channel,
2063
        // then the funding manager will handle it.
2064
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
3✔
2065
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2066
                return false
3✔
2067

2068
        // If not we hand the message to the channel link for this channel.
2069
        case p.isActiveChannel(chanID):
3✔
2070
                return true
3✔
2071

2072
        default:
3✔
2073
                return false
3✔
2074
        }
2075
}
2076

2077
// messageSummary returns a human-readable string that summarizes a
2078
// incoming/outgoing message. Not all messages will have a summary, only those
2079
// which have additional data that can be informative at a glance.
2080
func messageSummary(msg lnwire.Message) string {
3✔
2081
        switch msg := msg.(type) {
3✔
2082
        case *lnwire.Init:
3✔
2083
                // No summary.
3✔
2084
                return ""
3✔
2085

2086
        case *lnwire.OpenChannel:
3✔
2087
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
3✔
2088
                        "push_amt=%v, reserve=%v, flags=%v",
3✔
2089
                        msg.PendingChannelID[:], msg.ChainHash,
3✔
2090
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
3✔
2091
                        msg.ChannelReserve, msg.ChannelFlags)
3✔
2092

2093
        case *lnwire.AcceptChannel:
3✔
2094
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
3✔
2095
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
3✔
2096
                        msg.MinAcceptDepth)
3✔
2097

2098
        case *lnwire.FundingCreated:
3✔
2099
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
3✔
2100
                        msg.PendingChannelID[:], msg.FundingPoint)
3✔
2101

2102
        case *lnwire.FundingSigned:
3✔
2103
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
3✔
2104

2105
        case *lnwire.ChannelReady:
3✔
2106
                return fmt.Sprintf("chan_id=%v, next_point=%x",
3✔
2107
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
3✔
2108

2109
        case *lnwire.Shutdown:
3✔
2110
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
3✔
2111
                        msg.Address[:])
3✔
2112

2113
        case *lnwire.ClosingSigned:
3✔
2114
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
3✔
2115
                        msg.FeeSatoshis)
3✔
2116

2117
        case *lnwire.UpdateAddHTLC:
3✔
2118
                var blindingPoint []byte
3✔
2119
                msg.BlindingPoint.WhenSome(
3✔
2120
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
3✔
2121
                                *btcec.PublicKey]) {
6✔
2122

3✔
2123
                                blindingPoint = b.Val.SerializeCompressed()
3✔
2124
                        },
3✔
2125
                )
2126

2127
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
3✔
2128
                        "hash=%x, blinding_point=%x", msg.ChanID, msg.ID,
3✔
2129
                        msg.Amount, msg.Expiry, msg.PaymentHash[:],
3✔
2130
                        blindingPoint)
3✔
2131

2132
        case *lnwire.UpdateFailHTLC:
3✔
2133
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
3✔
2134
                        msg.ID, msg.Reason)
3✔
2135

2136
        case *lnwire.UpdateFulfillHTLC:
3✔
2137
                return fmt.Sprintf("chan_id=%v, id=%v, pre_image=%x",
3✔
2138
                        msg.ChanID, msg.ID, msg.PaymentPreimage[:])
3✔
2139

2140
        case *lnwire.CommitSig:
3✔
2141
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
3✔
2142
                        len(msg.HtlcSigs))
3✔
2143

2144
        case *lnwire.RevokeAndAck:
3✔
2145
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
3✔
2146
                        msg.ChanID, msg.Revocation[:],
3✔
2147
                        msg.NextRevocationKey.SerializeCompressed())
3✔
2148

2149
        case *lnwire.UpdateFailMalformedHTLC:
3✔
2150
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
3✔
2151
                        msg.ChanID, msg.ID, msg.FailureCode)
3✔
2152

2153
        case *lnwire.Warning:
×
2154
                return fmt.Sprintf("%v", msg.Warning())
×
2155

2156
        case *lnwire.Error:
3✔
2157
                return fmt.Sprintf("%v", msg.Error())
3✔
2158

2159
        case *lnwire.AnnounceSignatures:
3✔
2160
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
3✔
2161
                        msg.ShortChannelID.ToUint64())
3✔
2162

2163
        case *lnwire.ChannelAnnouncement:
3✔
2164
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
3✔
2165
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
3✔
2166

2167
        case *lnwire.ChannelUpdate:
3✔
2168
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
3✔
2169
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
3✔
2170
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
3✔
2171
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
3✔
2172

2173
        case *lnwire.NodeAnnouncement:
3✔
2174
                return fmt.Sprintf("node=%x, update_time=%v",
3✔
2175
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
3✔
2176

2177
        case *lnwire.Ping:
2✔
2178
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
2✔
2179

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

2183
        case *lnwire.UpdateFee:
×
2184
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2185
                        msg.ChanID, int64(msg.FeePerKw))
×
2186

2187
        case *lnwire.ChannelReestablish:
3✔
2188
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
3✔
2189
                        "remote_tail_height=%v", msg.ChanID,
3✔
2190
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
3✔
2191

2192
        case *lnwire.ReplyShortChanIDsEnd:
3✔
2193
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
3✔
2194
                        msg.Complete)
3✔
2195

2196
        case *lnwire.ReplyChannelRange:
3✔
2197
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
3✔
2198
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
3✔
2199
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
3✔
2200
                        msg.EncodingType)
3✔
2201

2202
        case *lnwire.QueryShortChanIDs:
3✔
2203
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
3✔
2204
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
3✔
2205

2206
        case *lnwire.QueryChannelRange:
3✔
2207
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
3✔
2208
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
3✔
2209
                        msg.LastBlockHeight())
3✔
2210

2211
        case *lnwire.GossipTimestampRange:
3✔
2212
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
3✔
2213
                        "stamp_range=%v", msg.ChainHash,
3✔
2214
                        time.Unix(int64(msg.FirstTimestamp), 0),
3✔
2215
                        msg.TimestampRange)
3✔
2216

2217
        case *lnwire.Stfu:
×
2218
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
×
2219
                        msg.Initiator)
×
2220

2221
        case *lnwire.Custom:
3✔
2222
                return fmt.Sprintf("type=%d", msg.Type)
3✔
2223
        }
2224

2225
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2226
}
2227

2228
// logWireMessage logs the receipt or sending of particular wire message. This
2229
// function is used rather than just logging the message in order to produce
2230
// less spammy log messages in trace mode by setting the 'Curve" parameter to
2231
// nil. Doing this avoids printing out each of the field elements in the curve
2232
// parameters for secp256k1.
2233
func (p *Brontide) logWireMessage(msg lnwire.Message, read bool) {
20✔
2234
        summaryPrefix := "Received"
20✔
2235
        if !read {
36✔
2236
                summaryPrefix = "Sending"
16✔
2237
        }
16✔
2238

2239
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
23✔
2240
                // Debug summary of message.
3✔
2241
                summary := messageSummary(msg)
3✔
2242
                if len(summary) > 0 {
6✔
2243
                        summary = "(" + summary + ")"
3✔
2244
                }
3✔
2245

2246
                preposition := "to"
3✔
2247
                if read {
6✔
2248
                        preposition = "from"
3✔
2249
                }
3✔
2250

2251
                var msgType string
3✔
2252
                if msg.MsgType() < lnwire.CustomTypeStart {
6✔
2253
                        msgType = msg.MsgType().String()
3✔
2254
                } else {
6✔
2255
                        msgType = "custom"
3✔
2256
                }
3✔
2257

2258
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
3✔
2259
                        msgType, summary, preposition, p)
3✔
2260
        }))
2261

2262
        prefix := "readMessage from peer"
20✔
2263
        if !read {
36✔
2264
                prefix = "writeMessage to peer"
16✔
2265
        }
16✔
2266

2267
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
20✔
2268
}
2269

2270
// writeMessage writes and flushes the target lnwire.Message to the remote peer.
2271
// If the passed message is nil, this method will only try to flush an existing
2272
// message buffered on the connection. It is safe to call this method again
2273
// with a nil message iff a timeout error is returned. This will continue to
2274
// flush the pending message to the wire.
2275
//
2276
// NOTE:
2277
// Besides its usage in Start, this function should not be used elsewhere
2278
// except in writeHandler. If multiple goroutines call writeMessage at the same
2279
// time, panics can occur because WriteMessage and Flush don't use any locking
2280
// internally.
2281
func (p *Brontide) writeMessage(msg lnwire.Message) error {
16✔
2282
        // Only log the message on the first attempt.
16✔
2283
        if msg != nil {
32✔
2284
                p.logWireMessage(msg, false)
16✔
2285
        }
16✔
2286

2287
        noiseConn := p.cfg.Conn
16✔
2288

16✔
2289
        flushMsg := func() error {
32✔
2290
                // Ensure the write deadline is set before we attempt to send
16✔
2291
                // the message.
16✔
2292
                writeDeadline := time.Now().Add(
16✔
2293
                        p.scaleTimeout(writeMessageTimeout),
16✔
2294
                )
16✔
2295
                err := noiseConn.SetWriteDeadline(writeDeadline)
16✔
2296
                if err != nil {
16✔
2297
                        return err
×
2298
                }
×
2299

2300
                // Flush the pending message to the wire. If an error is
2301
                // encountered, e.g. write timeout, the number of bytes written
2302
                // so far will be returned.
2303
                n, err := noiseConn.Flush()
16✔
2304

16✔
2305
                // Record the number of bytes written on the wire, if any.
16✔
2306
                if n > 0 {
19✔
2307
                        atomic.AddUint64(&p.bytesSent, uint64(n))
3✔
2308
                }
3✔
2309

2310
                return err
16✔
2311
        }
2312

2313
        // If the current message has already been serialized, encrypted, and
2314
        // buffered on the underlying connection we will skip straight to
2315
        // flushing it to the wire.
2316
        if msg == nil {
16✔
2317
                return flushMsg()
×
2318
        }
×
2319

2320
        // Otherwise, this is a new message. We'll acquire a write buffer to
2321
        // serialize the message and buffer the ciphertext on the connection.
2322
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
32✔
2323
                // Using a buffer allocated by the write pool, encode the
16✔
2324
                // message directly into the buffer.
16✔
2325
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
16✔
2326
                if writeErr != nil {
16✔
2327
                        return writeErr
×
2328
                }
×
2329

2330
                // Finally, write the message itself in a single swoop. This
2331
                // will buffer the ciphertext on the underlying connection. We
2332
                // will defer flushing the message until the write pool has been
2333
                // released.
2334
                return noiseConn.WriteMessage(buf.Bytes())
16✔
2335
        })
2336
        if err != nil {
16✔
2337
                return err
×
2338
        }
×
2339

2340
        return flushMsg()
16✔
2341
}
2342

2343
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2344
// queue, and writing them out to the wire. This goroutine coordinates with the
2345
// queueHandler in order to ensure the incoming message queue is quickly
2346
// drained.
2347
//
2348
// NOTE: This method MUST be run as a goroutine.
2349
func (p *Brontide) writeHandler() {
6✔
2350
        // We'll stop the timer after a new messages is sent, and also reset it
6✔
2351
        // after we process the next message.
6✔
2352
        idleTimer := time.AfterFunc(idleTimeout, func() {
8✔
2353
                err := fmt.Errorf("peer %s no write for %s -- disconnecting",
2✔
2354
                        p, idleTimeout)
2✔
2355
                p.Disconnect(err)
2✔
2356
        })
2✔
2357

2358
        var exitErr error
6✔
2359

6✔
2360
out:
6✔
2361
        for {
16✔
2362
                select {
10✔
2363
                case outMsg := <-p.sendQueue:
7✔
2364
                        // Record the time at which we first attempt to send the
7✔
2365
                        // message.
7✔
2366
                        startTime := time.Now()
7✔
2367

7✔
2368
                retry:
7✔
2369
                        // Write out the message to the socket. If a timeout
2370
                        // error is encountered, we will catch this and retry
2371
                        // after backing off in case the remote peer is just
2372
                        // slow to process messages from the wire.
2373
                        err := p.writeMessage(outMsg.msg)
7✔
2374
                        if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
7✔
2375
                                p.log.Debugf("Write timeout detected for "+
×
2376
                                        "peer, first write for message "+
×
2377
                                        "attempted %v ago",
×
2378
                                        time.Since(startTime))
×
2379

×
2380
                                // If we received a timeout error, this implies
×
2381
                                // that the message was buffered on the
×
2382
                                // connection successfully and that a flush was
×
2383
                                // attempted. We'll set the message to nil so
×
2384
                                // that on a subsequent pass we only try to
×
2385
                                // flush the buffered message, and forgo
×
2386
                                // reserializing or reencrypting it.
×
2387
                                outMsg.msg = nil
×
2388

×
2389
                                goto retry
×
2390
                        }
2391

2392
                        // The write succeeded, reset the idle timer to prevent
2393
                        // us from disconnecting the peer.
2394
                        if !idleTimer.Stop() {
7✔
2395
                                select {
×
2396
                                case <-idleTimer.C:
×
2397
                                default:
×
2398
                                }
2399
                        }
2400
                        idleTimer.Reset(idleTimeout)
7✔
2401

7✔
2402
                        // If the peer requested a synchronous write, respond
7✔
2403
                        // with the error.
7✔
2404
                        if outMsg.errChan != nil {
11✔
2405
                                outMsg.errChan <- err
4✔
2406
                        }
4✔
2407

2408
                        if err != nil {
7✔
2409
                                exitErr = fmt.Errorf("unable to write "+
×
2410
                                        "message: %v", err)
×
2411
                                break out
×
2412
                        }
2413

2414
                case <-p.quit:
3✔
2415
                        exitErr = lnpeer.ErrPeerExiting
3✔
2416
                        break out
3✔
2417
                }
2418
        }
2419

2420
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2421
        // disconnect.
2422
        p.wg.Done()
3✔
2423

3✔
2424
        p.Disconnect(exitErr)
3✔
2425

3✔
2426
        p.log.Trace("writeHandler for peer done")
3✔
2427
}
2428

2429
// queueHandler is responsible for accepting messages from outside subsystems
2430
// to be eventually sent out on the wire by the writeHandler.
2431
//
2432
// NOTE: This method MUST be run as a goroutine.
2433
func (p *Brontide) queueHandler() {
6✔
2434
        defer p.wg.Done()
6✔
2435

6✔
2436
        // priorityMsgs holds an in order list of messages deemed high-priority
6✔
2437
        // to be added to the sendQueue. This predominately includes messages
6✔
2438
        // from the funding manager and htlcswitch.
6✔
2439
        priorityMsgs := list.New()
6✔
2440

6✔
2441
        // lazyMsgs holds an in order list of messages deemed low-priority to be
6✔
2442
        // added to the sendQueue only after all high-priority messages have
6✔
2443
        // been queued. This predominately includes messages from the gossiper.
6✔
2444
        lazyMsgs := list.New()
6✔
2445

6✔
2446
        for {
20✔
2447
                // Examine the front of the priority queue, if it is empty check
14✔
2448
                // the low priority queue.
14✔
2449
                elem := priorityMsgs.Front()
14✔
2450
                if elem == nil {
25✔
2451
                        elem = lazyMsgs.Front()
11✔
2452
                }
11✔
2453

2454
                if elem != nil {
21✔
2455
                        front := elem.Value.(outgoingMsg)
7✔
2456

7✔
2457
                        // There's an element on the queue, try adding
7✔
2458
                        // it to the sendQueue. We also watch for
7✔
2459
                        // messages on the outgoingQueue, in case the
7✔
2460
                        // writeHandler cannot accept messages on the
7✔
2461
                        // sendQueue.
7✔
2462
                        select {
7✔
2463
                        case p.sendQueue <- front:
7✔
2464
                                if front.priority {
13✔
2465
                                        priorityMsgs.Remove(elem)
6✔
2466
                                } else {
10✔
2467
                                        lazyMsgs.Remove(elem)
4✔
2468
                                }
4✔
2469
                        case msg := <-p.outgoingQueue:
3✔
2470
                                if msg.priority {
6✔
2471
                                        priorityMsgs.PushBack(msg)
3✔
2472
                                } else {
6✔
2473
                                        lazyMsgs.PushBack(msg)
3✔
2474
                                }
3✔
2475
                        case <-p.quit:
×
2476
                                return
×
2477
                        }
2478
                } else {
10✔
2479
                        // If there weren't any messages to send to the
10✔
2480
                        // writeHandler, then we'll accept a new message
10✔
2481
                        // into the queue from outside sub-systems.
10✔
2482
                        select {
10✔
2483
                        case msg := <-p.outgoingQueue:
7✔
2484
                                if msg.priority {
13✔
2485
                                        priorityMsgs.PushBack(msg)
6✔
2486
                                } else {
10✔
2487
                                        lazyMsgs.PushBack(msg)
4✔
2488
                                }
4✔
2489
                        case <-p.quit:
3✔
2490
                                return
3✔
2491
                        }
2492
                }
2493
        }
2494
}
2495

2496
// PingTime returns the estimated ping time to the peer in microseconds.
2497
func (p *Brontide) PingTime() int64 {
3✔
2498
        return p.pingManager.GetPingTimeMicroSeconds()
3✔
2499
}
3✔
2500

2501
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2502
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2503
// or failed to write, and nil otherwise.
2504
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
27✔
2505
        p.queue(true, msg, errChan)
27✔
2506
}
27✔
2507

2508
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2509
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2510
// queue or failed to write, and nil otherwise.
2511
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
4✔
2512
        p.queue(false, msg, errChan)
4✔
2513
}
4✔
2514

2515
// queue sends a given message to the queueHandler using the passed priority. If
2516
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2517
// failed to write, and nil otherwise.
2518
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2519
        errChan chan error) {
28✔
2520

28✔
2521
        select {
28✔
2522
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
28✔
2523
        case <-p.quit:
3✔
2524
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
3✔
2525
                        spew.Sdump(msg))
3✔
2526
                if errChan != nil {
3✔
2527
                        errChan <- lnpeer.ErrPeerExiting
×
2528
                }
×
2529
        }
2530
}
2531

2532
// ChannelSnapshots returns a slice of channel snapshots detailing all
2533
// currently active channels maintained with the remote peer.
2534
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
3✔
2535
        snapshots := make(
3✔
2536
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
3✔
2537
        )
3✔
2538

3✔
2539
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2540
                activeChan *lnwallet.LightningChannel) error {
6✔
2541

3✔
2542
                // If the activeChan is nil, then we skip it as the channel is
3✔
2543
                // pending.
3✔
2544
                if activeChan == nil {
6✔
2545
                        return nil
3✔
2546
                }
3✔
2547

2548
                // We'll only return a snapshot for channels that are
2549
                // *immediately* available for routing payments over.
2550
                if activeChan.RemoteNextRevocation() == nil {
6✔
2551
                        return nil
3✔
2552
                }
3✔
2553

2554
                snapshot := activeChan.StateSnapshot()
3✔
2555
                snapshots = append(snapshots, snapshot)
3✔
2556

3✔
2557
                return nil
3✔
2558
        })
2559

2560
        return snapshots
3✔
2561
}
2562

2563
// genDeliveryScript returns a new script to be used to send our funds to in
2564
// the case of a cooperative channel close negotiation.
2565
func (p *Brontide) genDeliveryScript() ([]byte, error) {
9✔
2566
        // We'll send a normal p2wkh address unless we've negotiated the
9✔
2567
        // shutdown-any-segwit feature.
9✔
2568
        addrType := lnwallet.WitnessPubKey
9✔
2569
        if p.taprootShutdownAllowed() {
12✔
2570
                addrType = lnwallet.TaprootPubkey
3✔
2571
        }
3✔
2572

2573
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
9✔
2574
                addrType, false, lnwallet.DefaultAccountName,
9✔
2575
        )
9✔
2576
        if err != nil {
9✔
2577
                return nil, err
×
2578
        }
×
2579
        p.log.Infof("Delivery addr for channel close: %v",
9✔
2580
                deliveryAddr)
9✔
2581

9✔
2582
        return txscript.PayToAddrScript(deliveryAddr)
9✔
2583
}
2584

2585
// channelManager is goroutine dedicated to handling all requests/signals
2586
// pertaining to the opening, cooperative closing, and force closing of all
2587
// channels maintained with the remote peer.
2588
//
2589
// NOTE: This method MUST be run as a goroutine.
2590
func (p *Brontide) channelManager() {
20✔
2591
        defer p.wg.Done()
20✔
2592

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

20✔
2598
out:
20✔
2599
        for {
61✔
2600
                select {
41✔
2601
                // A new pending channel has arrived which means we are about
2602
                // to complete a funding workflow and is waiting for the final
2603
                // `ChannelReady` messages to be exchanged. We will add this
2604
                // channel to the `activeChannels` with a nil value to indicate
2605
                // this is a pending channel.
2606
                case req := <-p.newPendingChannel:
4✔
2607
                        p.handleNewPendingChannel(req)
4✔
2608

2609
                // A new channel has arrived which means we've just completed a
2610
                // funding workflow. We'll initialize the necessary local
2611
                // state, and notify the htlc switch of a new link.
2612
                case req := <-p.newActiveChannel:
3✔
2613
                        p.handleNewActiveChannel(req)
3✔
2614

2615
                // The funding flow for a pending channel is failed, we will
2616
                // remove it from Brontide.
2617
                case req := <-p.removePendingChannel:
4✔
2618
                        p.handleRemovePendingChannel(req)
4✔
2619

2620
                // We've just received a local request to close an active
2621
                // channel. It will either kick of a cooperative channel
2622
                // closure negotiation, or be a notification of a breached
2623
                // contract that should be abandoned.
2624
                case req := <-p.localCloseChanReqs:
10✔
2625
                        p.handleLocalCloseReq(req)
10✔
2626

2627
                // We've received a link failure from a link that was added to
2628
                // the switch. This will initiate the teardown of the link, and
2629
                // initiate any on-chain closures if necessary.
2630
                case failure := <-p.linkFailures:
3✔
2631
                        p.handleLinkFailure(failure)
3✔
2632

2633
                // We've received a new cooperative channel closure related
2634
                // message from the remote peer, we'll use this message to
2635
                // advance the chan closer state machine.
2636
                case closeMsg := <-p.chanCloseMsgs:
16✔
2637
                        p.handleCloseMsg(closeMsg)
16✔
2638

2639
                // The channel reannounce delay has elapsed, broadcast the
2640
                // reenabled channel updates to the network. This should only
2641
                // fire once, so we set the reenableTimeout channel to nil to
2642
                // mark it for garbage collection. If the peer is torn down
2643
                // before firing, reenabling will not be attempted.
2644
                // TODO(conner): consolidate reenables timers inside chan status
2645
                // manager
2646
                case <-reenableTimeout:
3✔
2647
                        p.reenableActiveChannels()
3✔
2648

3✔
2649
                        // Since this channel will never fire again during the
3✔
2650
                        // lifecycle of the peer, we nil the channel to mark it
3✔
2651
                        // eligible for garbage collection, and make this
3✔
2652
                        // explicitly ineligible to receive in future calls to
3✔
2653
                        // select. This also shaves a few CPU cycles since the
3✔
2654
                        // select will ignore this case entirely.
3✔
2655
                        reenableTimeout = nil
3✔
2656

3✔
2657
                        // Once the reenabling is attempted, we also cancel the
3✔
2658
                        // channel event subscription to free up the overflow
3✔
2659
                        // queue used in channel notifier.
3✔
2660
                        //
3✔
2661
                        // NOTE: channelEventClient will be nil if the
3✔
2662
                        // reenableTimeout is greater than 1 minute.
3✔
2663
                        if p.channelEventClient != nil {
6✔
2664
                                p.channelEventClient.Cancel()
3✔
2665
                        }
3✔
2666

2667
                case <-p.quit:
3✔
2668
                        // As, we've been signalled to exit, we'll reset all
3✔
2669
                        // our active channel back to their default state.
3✔
2670
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2671
                                lc *lnwallet.LightningChannel) error {
6✔
2672

3✔
2673
                                // Exit if the channel is nil as it's a pending
3✔
2674
                                // channel.
3✔
2675
                                if lc == nil {
6✔
2676
                                        return nil
3✔
2677
                                }
3✔
2678

2679
                                lc.ResetState()
3✔
2680

3✔
2681
                                return nil
3✔
2682
                        })
2683

2684
                        break out
3✔
2685
                }
2686
        }
2687
}
2688

2689
// reenableActiveChannels searches the index of channels maintained with this
2690
// peer, and reenables each public, non-pending channel. This is done at the
2691
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
2692
// No message will be sent if the channel is already enabled.
2693
func (p *Brontide) reenableActiveChannels() {
3✔
2694
        // First, filter all known channels with this peer for ones that are
3✔
2695
        // both public and not pending.
3✔
2696
        activePublicChans := p.filterChannelsToEnable()
3✔
2697

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

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

3✔
2707
                switch {
3✔
2708
                // No error occurred, continue to request the next channel.
2709
                case err == nil:
3✔
2710
                        continue
3✔
2711

2712
                // Cannot auto enable a manually disabled channel so we do
2713
                // nothing but proceed to the next channel.
2714
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
3✔
2715
                        p.log.Debugf("Channel(%v) was manually disabled, "+
3✔
2716
                                "ignoring automatic enable request", chanPoint)
3✔
2717

3✔
2718
                        continue
3✔
2719

2720
                // If the channel is reported as inactive, we will give it
2721
                // another chance. When handling the request, ChanStatusManager
2722
                // will check whether the link is active or not. One of the
2723
                // conditions is whether the link has been marked as
2724
                // reestablished, which happens inside a goroutine(htlcManager)
2725
                // after the link is started. And we may get a false negative
2726
                // saying the link is not active because that goroutine hasn't
2727
                // reached the line to mark the reestablishment. Thus we give
2728
                // it a second chance to send the request.
2729
                case errors.Is(err, netann.ErrEnableInactiveChan):
×
2730
                        // If we don't have a client created, it means we
×
2731
                        // shouldn't retry enabling the channel.
×
2732
                        if p.channelEventClient == nil {
×
2733
                                p.log.Errorf("Channel(%v) request enabling "+
×
2734
                                        "failed due to inactive link",
×
2735
                                        chanPoint)
×
2736

×
2737
                                continue
×
2738
                        }
2739

2740
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
2741
                                "ChanStatusManager reported inactive, retrying")
×
2742

×
2743
                        // Add the channel to the retry map.
×
2744
                        retryChans[chanPoint] = struct{}{}
×
2745
                }
2746
        }
2747

2748
        // Retry the channels if we have any.
2749
        if len(retryChans) != 0 {
3✔
2750
                p.retryRequestEnable(retryChans)
×
2751
        }
×
2752
}
2753

2754
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
2755
// for the target channel ID. If the channel isn't active an error is returned.
2756
// Otherwise, either an existing state machine will be returned, or a new one
2757
// will be created.
2758
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
2759
        *chancloser.ChanCloser, error) {
16✔
2760

16✔
2761
        chanCloser, found := p.activeChanCloses[chanID]
16✔
2762
        if found {
29✔
2763
                // An entry will only be found if the closer has already been
13✔
2764
                // created for a non-pending channel or for a channel that had
13✔
2765
                // previously started the shutdown process but the connection
13✔
2766
                // was restarted.
13✔
2767
                return chanCloser, nil
13✔
2768
        }
13✔
2769

2770
        // First, we'll ensure that we actually know of the target channel. If
2771
        // not, we'll ignore this message.
2772
        channel, ok := p.activeChannels.Load(chanID)
6✔
2773

6✔
2774
        // If the channel isn't in the map or the channel is nil, return
6✔
2775
        // ErrChannelNotFound as the channel is pending.
6✔
2776
        if !ok || channel == nil {
9✔
2777
                return nil, ErrChannelNotFound
3✔
2778
        }
3✔
2779

2780
        // We'll create a valid closing state machine in order to respond to
2781
        // the initiated cooperative channel closure. First, we set the
2782
        // delivery script that our funds will be paid out to. If an upfront
2783
        // shutdown script was set, we will use it. Otherwise, we get a fresh
2784
        // delivery script.
2785
        //
2786
        // TODO: Expose option to allow upfront shutdown script from watch-only
2787
        // accounts.
2788
        deliveryScript := channel.LocalUpfrontShutdownScript()
6✔
2789
        if len(deliveryScript) == 0 {
12✔
2790
                var err error
6✔
2791
                deliveryScript, err = p.genDeliveryScript()
6✔
2792
                if err != nil {
6✔
2793
                        p.log.Errorf("unable to gen delivery script: %v",
×
2794
                                err)
×
2795
                        return nil, fmt.Errorf("close addr unavailable")
×
2796
                }
×
2797
        }
2798

2799
        // In order to begin fee negotiations, we'll first compute our target
2800
        // ideal fee-per-kw.
2801
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
6✔
2802
                p.cfg.CoopCloseTargetConfs,
6✔
2803
        )
6✔
2804
        if err != nil {
6✔
2805
                p.log.Errorf("unable to query fee estimator: %v", err)
×
2806
                return nil, fmt.Errorf("unable to estimate fee")
×
2807
        }
×
2808

2809
        chanCloser, err = p.createChanCloser(
6✔
2810
                channel, deliveryScript, feePerKw, nil, lntypes.Remote,
6✔
2811
        )
6✔
2812
        if err != nil {
6✔
2813
                p.log.Errorf("unable to create chan closer: %v", err)
×
2814
                return nil, fmt.Errorf("unable to create chan closer")
×
2815
        }
×
2816

2817
        p.activeChanCloses[chanID] = chanCloser
6✔
2818

6✔
2819
        return chanCloser, nil
6✔
2820
}
2821

2822
// filterChannelsToEnable filters a list of channels to be enabled upon start.
2823
// The filtered channels are active channels that's neither private nor
2824
// pending.
2825
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
3✔
2826
        var activePublicChans []wire.OutPoint
3✔
2827

3✔
2828
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
3✔
2829
                lnChan *lnwallet.LightningChannel) bool {
6✔
2830

3✔
2831
                // If the lnChan is nil, continue as this is a pending channel.
3✔
2832
                if lnChan == nil {
3✔
2833
                        return true
×
2834
                }
×
2835

2836
                dbChan := lnChan.State()
3✔
2837
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
2838
                if !isPublic || dbChan.IsPending {
3✔
2839
                        return true
×
2840
                }
×
2841

2842
                // We'll also skip any channels added during this peer's
2843
                // lifecycle since they haven't waited out the timeout. Their
2844
                // first announcement will be enabled, and the chan status
2845
                // manager will begin monitoring them passively since they exist
2846
                // in the database.
2847
                if _, ok := p.addedChannels.Load(chanID); ok {
6✔
2848
                        return true
3✔
2849
                }
3✔
2850

2851
                activePublicChans = append(
3✔
2852
                        activePublicChans, dbChan.FundingOutpoint,
3✔
2853
                )
3✔
2854

3✔
2855
                return true
3✔
2856
        })
2857

2858
        return activePublicChans
3✔
2859
}
2860

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

×
2868
        // retryEnable is a helper closure that sends an enable request and
×
2869
        // removes the channel from the map if it's matched.
×
2870
        retryEnable := func(chanPoint wire.OutPoint) error {
×
2871
                // If this is an active channel event, check whether it's in
×
2872
                // our targeted channels map.
×
2873
                _, found := activeChans[chanPoint]
×
2874

×
2875
                // If this channel is irrelevant, return nil so the loop can
×
2876
                // jump to next iteration.
×
2877
                if !found {
×
2878
                        return nil
×
2879
                }
×
2880

2881
                // Otherwise we've just received an active signal for a channel
2882
                // that's previously failed to be enabled, we send the request
2883
                // again.
2884
                //
2885
                // We only give the channel one more shot, so we delete it from
2886
                // our map first to keep it from being attempted again.
2887
                delete(activeChans, chanPoint)
×
2888

×
2889
                // Send the request.
×
2890
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
2891
                if err != nil {
×
2892
                        return fmt.Errorf("request enabling channel %v "+
×
2893
                                "failed: %w", chanPoint, err)
×
2894
                }
×
2895

2896
                return nil
×
2897
        }
2898

2899
        for {
×
2900
                // If activeChans is empty, we've done processing all the
×
2901
                // channels.
×
2902
                if len(activeChans) == 0 {
×
2903
                        p.log.Debug("Finished retry enabling channels")
×
2904
                        return
×
2905
                }
×
2906

2907
                select {
×
2908
                // A new event has been sent by the ChannelNotifier. We now
2909
                // check whether it's an active or inactive channel event.
2910
                case e := <-p.channelEventClient.Updates():
×
2911
                        // If this is an active channel event, try enable the
×
2912
                        // channel then jump to the next iteration.
×
2913
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
2914
                        if ok {
×
2915
                                chanPoint := *active.ChannelPoint
×
2916

×
2917
                                // If we received an error for this particular
×
2918
                                // channel, we log an error and won't quit as
×
2919
                                // we still want to retry other channels.
×
2920
                                if err := retryEnable(chanPoint); err != nil {
×
2921
                                        p.log.Errorf("Retry failed: %v", err)
×
2922
                                }
×
2923

2924
                                continue
×
2925
                        }
2926

2927
                        // Otherwise check for inactive link event, and jump to
2928
                        // next iteration if it's not.
2929
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
2930
                        if !ok {
×
2931
                                continue
×
2932
                        }
2933

2934
                        // Found an inactive link event, if this is our
2935
                        // targeted channel, remove it from our map.
2936
                        chanPoint := *inactive.ChannelPoint
×
2937
                        _, found := activeChans[chanPoint]
×
2938
                        if !found {
×
2939
                                continue
×
2940
                        }
2941

2942
                        delete(activeChans, chanPoint)
×
2943
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
2944
                                "inactive link event", chanPoint)
×
2945

2946
                case <-p.quit:
×
2947
                        p.log.Debugf("Peer shutdown during retry enabling")
×
2948
                        return
×
2949
                }
2950
        }
2951
}
2952

2953
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
2954
// a suitable script to close out to. This may be nil if neither script is
2955
// set. If both scripts are set, this function will error if they do not match.
2956
func chooseDeliveryScript(upfront,
2957
        requested lnwire.DeliveryAddress) (lnwire.DeliveryAddress, error) {
15✔
2958

15✔
2959
        // If no upfront shutdown script was provided, return the user
15✔
2960
        // requested address (which may be nil).
15✔
2961
        if len(upfront) == 0 {
24✔
2962
                return requested, nil
9✔
2963
        }
9✔
2964

2965
        // If an upfront shutdown script was provided, and the user did not
2966
        // request a custom shutdown script, return the upfront address.
2967
        if len(requested) == 0 {
14✔
2968
                return upfront, nil
5✔
2969
        }
5✔
2970

2971
        // If both an upfront shutdown script and a custom close script were
2972
        // provided, error if the user provided shutdown script does not match
2973
        // the upfront shutdown script (because closing out to a different
2974
        // script would violate upfront shutdown).
2975
        if !bytes.Equal(upfront, requested) {
6✔
2976
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
2977
        }
2✔
2978

2979
        // The user requested script matches the upfront shutdown script, so we
2980
        // can return it without error.
2981
        return upfront, nil
2✔
2982
}
2983

2984
// restartCoopClose checks whether we need to restart the cooperative close
2985
// process for a given channel.
2986
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
2987
        *lnwire.Shutdown, error) {
×
2988

×
2989
        // If this channel has status ChanStatusCoopBroadcasted and does not
×
2990
        // have a closing transaction, then the cooperative close process was
×
2991
        // started but never finished. We'll re-create the chanCloser state
×
2992
        // machine and resend Shutdown. BOLT#2 requires that we retransmit
×
2993
        // Shutdown exactly, but doing so would mean persisting the RPC
×
2994
        // provided close script. Instead use the LocalUpfrontShutdownScript
×
2995
        // or generate a script.
×
2996
        c := lnChan.State()
×
2997
        _, err := c.BroadcastedCooperative()
×
2998
        if err != nil && err != channeldb.ErrNoCloseTx {
×
2999
                // An error other than ErrNoCloseTx was encountered.
×
3000
                return nil, err
×
3001
        } else if err == nil {
×
3002
                // This channel has already completed the coop close
×
3003
                // negotiation.
×
3004
                return nil, nil
×
3005
        }
×
3006

3007
        var deliveryScript []byte
×
3008

×
3009
        shutdownInfo, err := c.ShutdownInfo()
×
3010
        switch {
×
3011
        // We have previously stored the delivery script that we need to use
3012
        // in the shutdown message. Re-use this script.
3013
        case err == nil:
×
3014
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
×
3015
                        deliveryScript = info.DeliveryScript.Val
×
3016
                })
×
3017

3018
        // An error other than ErrNoShutdownInfo was returned
3019
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3020
                return nil, err
×
3021

3022
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3023
                deliveryScript = c.LocalShutdownScript
×
3024
                if len(deliveryScript) == 0 {
×
3025
                        var err error
×
3026
                        deliveryScript, err = p.genDeliveryScript()
×
3027
                        if err != nil {
×
3028
                                p.log.Errorf("unable to gen delivery script: "+
×
3029
                                        "%v", err)
×
3030

×
3031
                                return nil, fmt.Errorf("close addr unavailable")
×
3032
                        }
×
3033
                }
3034
        }
3035

3036
        // Compute an ideal fee.
3037
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
3038
                p.cfg.CoopCloseTargetConfs,
×
3039
        )
×
3040
        if err != nil {
×
3041
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3042
                return nil, fmt.Errorf("unable to estimate fee")
×
3043
        }
×
3044

3045
        // Determine whether we or the peer are the initiator of the coop
3046
        // close attempt by looking at the channel's status.
3047
        closingParty := lntypes.Remote
×
3048
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3049
                closingParty = lntypes.Local
×
3050
        }
×
3051

3052
        chanCloser, err := p.createChanCloser(
×
3053
                lnChan, deliveryScript, feePerKw, nil, closingParty,
×
3054
        )
×
3055
        if err != nil {
×
3056
                p.log.Errorf("unable to create chan closer: %v", err)
×
3057
                return nil, fmt.Errorf("unable to create chan closer")
×
3058
        }
×
3059

3060
        // This does not need a mutex even though it is in a different
3061
        // goroutine since this is done before the channelManager goroutine is
3062
        // created.
3063
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
×
3064
        p.activeChanCloses[chanID] = chanCloser
×
3065

×
3066
        // Create the Shutdown message.
×
3067
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3068
        if err != nil {
×
3069
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3070
                delete(p.activeChanCloses, chanID)
×
3071
                return nil, err
×
3072
        }
×
3073

3074
        return shutdownMsg, nil
×
3075
}
3076

3077
// createChanCloser constructs a ChanCloser from the passed parameters and is
3078
// used to de-duplicate code.
3079
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3080
        deliveryScript lnwire.DeliveryAddress, fee chainfee.SatPerKWeight,
3081
        req *htlcswitch.ChanClose,
3082
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
12✔
3083

12✔
3084
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
12✔
3085
        if err != nil {
12✔
3086
                p.log.Errorf("unable to obtain best block: %v", err)
×
3087
                return nil, fmt.Errorf("cannot obtain best block")
×
3088
        }
×
3089

3090
        // The req will only be set if we initiated the co-op closing flow.
3091
        var maxFee chainfee.SatPerKWeight
12✔
3092
        if req != nil {
21✔
3093
                maxFee = req.MaxFee
9✔
3094
        }
9✔
3095

3096
        chanCloser := chancloser.NewChanCloser(
12✔
3097
                chancloser.ChanCloseCfg{
12✔
3098
                        Channel:      channel,
12✔
3099
                        MusigSession: NewMusigChanCloser(channel),
12✔
3100
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
12✔
3101
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
12✔
3102
                        DisableChannel: func(op wire.OutPoint) error {
24✔
3103
                                return p.cfg.ChanStatusMgr.RequestDisable(
12✔
3104
                                        op, false,
12✔
3105
                                )
12✔
3106
                        },
12✔
3107
                        MaxFee: maxFee,
3108
                        Disconnect: func() error {
×
3109
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
3110
                        },
×
3111
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3112
                        Quit:        p.quit,
3113
                },
3114
                deliveryScript,
3115
                fee,
3116
                uint32(startingHeight),
3117
                req,
3118
                closer,
3119
        )
3120

3121
        return chanCloser, nil
12✔
3122
}
3123

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

10✔
3129
        channel, ok := p.activeChannels.Load(chanID)
10✔
3130

10✔
3131
        // Though this function can't be called for pending channels, we still
10✔
3132
        // check whether channel is nil for safety.
10✔
3133
        if !ok || channel == nil {
10✔
3134
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
×
3135
                        "unknown", chanID)
×
3136
                p.log.Errorf(err.Error())
×
3137
                req.Err <- err
×
3138
                return
×
3139
        }
×
3140

3141
        switch req.CloseType {
10✔
3142
        // A type of CloseRegular indicates that the user has opted to close
3143
        // out this channel on-chain, so we execute the cooperative channel
3144
        // closure workflow.
3145
        case contractcourt.CloseRegular:
10✔
3146
                // First, we'll choose a delivery address that we'll use to send the
10✔
3147
                // funds to in the case of a successful negotiation.
10✔
3148

10✔
3149
                // An upfront shutdown and user provided script are both optional,
10✔
3150
                // but must be equal if both set  (because we cannot serve a request
10✔
3151
                // to close out to a script which violates upfront shutdown). Get the
10✔
3152
                // appropriate address to close out to (which may be nil if neither
10✔
3153
                // are set) and error if they are both set and do not match.
10✔
3154
                deliveryScript, err := chooseDeliveryScript(
10✔
3155
                        channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
10✔
3156
                )
10✔
3157
                if err != nil {
11✔
3158
                        p.log.Errorf("cannot close channel %v: %v", req.ChanPoint, err)
1✔
3159
                        req.Err <- err
1✔
3160
                        return
1✔
3161
                }
1✔
3162

3163
                // If neither an upfront address or a user set address was
3164
                // provided, generate a fresh script.
3165
                if len(deliveryScript) == 0 {
15✔
3166
                        deliveryScript, err = p.genDeliveryScript()
6✔
3167
                        if err != nil {
6✔
3168
                                p.log.Errorf(err.Error())
×
3169
                                req.Err <- err
×
3170
                                return
×
3171
                        }
×
3172
                }
3173

3174
                chanCloser, err := p.createChanCloser(
9✔
3175
                        channel, deliveryScript, req.TargetFeePerKw, req,
9✔
3176
                        lntypes.Local,
9✔
3177
                )
9✔
3178
                if err != nil {
9✔
3179
                        p.log.Errorf(err.Error())
×
3180
                        req.Err <- err
×
3181
                        return
×
3182
                }
×
3183

3184
                p.activeChanCloses[chanID] = chanCloser
9✔
3185

9✔
3186
                // Finally, we'll initiate the channel shutdown within the
9✔
3187
                // chanCloser, and send the shutdown message to the remote
9✔
3188
                // party to kick things off.
9✔
3189
                shutdownMsg, err := chanCloser.ShutdownChan()
9✔
3190
                if err != nil {
9✔
3191
                        p.log.Errorf(err.Error())
×
3192
                        req.Err <- err
×
3193
                        delete(p.activeChanCloses, chanID)
×
3194

×
3195
                        // As we were unable to shutdown the channel, we'll
×
3196
                        // return it back to its normal state.
×
3197
                        channel.ResetState()
×
3198
                        return
×
3199
                }
×
3200

3201
                link := p.fetchLinkFromKeyAndCid(chanID)
9✔
3202
                if link == nil {
9✔
3203
                        // If the link is nil then it means it was already
×
3204
                        // removed from the switch or it never existed in the
×
3205
                        // first place. The latter case is handled at the
×
3206
                        // beginning of this function, so in the case where it
×
3207
                        // has already been removed, we can skip adding the
×
3208
                        // commit hook to queue a Shutdown message.
×
3209
                        p.log.Warnf("link not found during attempted closure: "+
×
3210
                                "%v", chanID)
×
3211
                        return
×
3212
                }
×
3213

3214
                if !link.DisableAdds(htlcswitch.Outgoing) {
9✔
3215
                        p.log.Warnf("Outgoing link adds already "+
×
3216
                                "disabled: %v", link.ChanID())
×
3217
                }
×
3218

3219
                link.OnCommitOnce(htlcswitch.Outgoing, func() {
18✔
3220
                        p.queueMsg(shutdownMsg, nil)
9✔
3221
                })
9✔
3222

3223
        // A type of CloseBreach indicates that the counterparty has breached
3224
        // the channel therefore we need to clean up our local state.
UNCOV
3225
        case contractcourt.CloseBreach:
×
UNCOV
3226
                // TODO(roasbeef): no longer need with newer beach logic?
×
UNCOV
3227
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
×
UNCOV
3228
                        "channel", req.ChanPoint)
×
UNCOV
3229
                p.WipeChannel(req.ChanPoint)
×
3230
        }
3231
}
3232

3233
// linkFailureReport is sent to the channelManager whenever a link reports a
3234
// link failure, and is forced to exit. The report houses the necessary
3235
// information to clean up the channel state, send back the error message, and
3236
// force close if necessary.
3237
type linkFailureReport struct {
3238
        chanPoint   wire.OutPoint
3239
        chanID      lnwire.ChannelID
3240
        shortChanID lnwire.ShortChannelID
3241
        linkErr     htlcswitch.LinkFailureError
3242
}
3243

3244
// handleLinkFailure processes a link failure report when a link in the switch
3245
// fails. It facilitates the removal of all channel state within the peer,
3246
// force closing the channel depending on severity, and sending the error
3247
// message back to the remote party.
3248
func (p *Brontide) handleLinkFailure(failure linkFailureReport) {
3✔
3249
        // Retrieve the channel from the map of active channels. We do this to
3✔
3250
        // have access to it even after WipeChannel remove it from the map.
3✔
3251
        chanID := lnwire.NewChanIDFromOutPoint(failure.chanPoint)
3✔
3252
        lnChan, _ := p.activeChannels.Load(chanID)
3✔
3253

3✔
3254
        // We begin by wiping the link, which will remove it from the switch,
3✔
3255
        // such that it won't be attempted used for any more updates.
3✔
3256
        //
3✔
3257
        // TODO(halseth): should introduce a way to atomically stop/pause the
3✔
3258
        // link and cancel back any adds in its mailboxes such that we can
3✔
3259
        // safely force close without the link being added again and updates
3✔
3260
        // being applied.
3✔
3261
        p.WipeChannel(&failure.chanPoint)
3✔
3262

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

3✔
3268
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
3✔
3269
                        failure.chanPoint,
3✔
3270
                )
3✔
3271
                if err != nil {
6✔
3272
                        p.log.Errorf("unable to force close "+
3✔
3273
                                "link(%v): %v", failure.shortChanID, err)
3✔
3274
                } else {
6✔
3275
                        p.log.Infof("channel(%v) force "+
3✔
3276
                                "closed with txid %v",
3✔
3277
                                failure.shortChanID, closeTx.TxHash())
3✔
3278
                }
3✔
3279
        }
3280

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

×
3286
                if err := lnChan.State().MarkBorked(); err != nil {
×
3287
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
3288
                                failure.shortChanID, err)
×
3289
                }
×
3290
        }
3291

3292
        // Send an error to the peer, why we failed the channel.
3293
        if failure.linkErr.ShouldSendToPeer() {
6✔
3294
                // If SendData is set, send it to the peer. If not, we'll use
3✔
3295
                // the standard error messages in the payload. We only include
3✔
3296
                // sendData in the cases where the error data does not contain
3✔
3297
                // sensitive information.
3✔
3298
                data := []byte(failure.linkErr.Error())
3✔
3299
                if failure.linkErr.SendData != nil {
3✔
3300
                        data = failure.linkErr.SendData
×
3301
                }
×
3302

3303
                var networkMsg lnwire.Message
3✔
3304
                if failure.linkErr.Warning {
3✔
3305
                        networkMsg = &lnwire.Warning{
×
3306
                                ChanID: failure.chanID,
×
3307
                                Data:   data,
×
3308
                        }
×
3309
                } else {
3✔
3310
                        networkMsg = &lnwire.Error{
3✔
3311
                                ChanID: failure.chanID,
3✔
3312
                                Data:   data,
3✔
3313
                        }
3✔
3314
                }
3✔
3315

3316
                err := p.SendMessage(true, networkMsg)
3✔
3317
                if err != nil {
3✔
3318
                        p.log.Errorf("unable to send msg to "+
×
3319
                                "remote peer: %v", err)
×
3320
                }
×
3321
        }
3322

3323
        // If the failure action is disconnect, then we'll execute that now. If
3324
        // we had to send an error above, it was a sync call, so we expect the
3325
        // message to be flushed on the wire by now.
3326
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
3✔
3327
                p.Disconnect(fmt.Errorf("link requested disconnect"))
×
3328
        }
×
3329
}
3330

3331
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
3332
// public key and the channel id.
3333
func (p *Brontide) fetchLinkFromKeyAndCid(
3334
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
22✔
3335

22✔
3336
        var chanLink htlcswitch.ChannelUpdateHandler
22✔
3337

22✔
3338
        // We don't need to check the error here, and can instead just loop
22✔
3339
        // over the slice and return nil.
22✔
3340
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
22✔
3341
        for _, link := range links {
43✔
3342
                if link.ChanID() == cid {
42✔
3343
                        chanLink = link
21✔
3344
                        break
21✔
3345
                }
3346
        }
3347

3348
        return chanLink
22✔
3349
}
3350

3351
// finalizeChanClosure performs the final clean up steps once the cooperative
3352
// closure transaction has been fully broadcast. The finalized closing state
3353
// machine should be passed in. Once the transaction has been sufficiently
3354
// confirmed, the channel will be marked as fully closed within the database,
3355
// and any clients will be notified of updates to the closing state.
3356
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
7✔
3357
        closeReq := chanCloser.CloseRequest()
7✔
3358

7✔
3359
        // First, we'll clear all indexes related to the channel in question.
7✔
3360
        chanPoint := chanCloser.Channel().ChannelPoint()
7✔
3361
        p.WipeChannel(&chanPoint)
7✔
3362

7✔
3363
        // Also clear the activeChanCloses map of this channel.
7✔
3364
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
7✔
3365
        delete(p.activeChanCloses, cid)
7✔
3366

7✔
3367
        // Next, we'll launch a goroutine which will request to be notified by
7✔
3368
        // the ChainNotifier once the closure transaction obtains a single
7✔
3369
        // confirmation.
7✔
3370
        notifier := p.cfg.ChainNotifier
7✔
3371

7✔
3372
        // If any error happens during waitForChanToClose, forward it to
7✔
3373
        // closeReq. If this channel closure is not locally initiated, closeReq
7✔
3374
        // will be nil, so just ignore the error.
7✔
3375
        errChan := make(chan error, 1)
7✔
3376
        if closeReq != nil {
12✔
3377
                errChan = closeReq.Err
5✔
3378
        }
5✔
3379

3380
        closingTx, err := chanCloser.ClosingTx()
7✔
3381
        if err != nil {
7✔
3382
                if closeReq != nil {
×
3383
                        p.log.Error(err)
×
3384
                        closeReq.Err <- err
×
3385
                }
×
3386
        }
3387

3388
        closingTxid := closingTx.TxHash()
7✔
3389

7✔
3390
        // If this is a locally requested shutdown, update the caller with a
7✔
3391
        // new event detailing the current pending state of this request.
7✔
3392
        if closeReq != nil {
12✔
3393
                closeReq.Updates <- &PendingUpdate{
5✔
3394
                        Txid: closingTxid[:],
5✔
3395
                }
5✔
3396
        }
5✔
3397

3398
        go WaitForChanToClose(chanCloser.NegotiationHeight(), notifier, errChan,
7✔
3399
                &chanPoint, &closingTxid, closingTx.TxOut[0].PkScript, func() {
14✔
3400
                        // Respond to the local subsystem which requested the
7✔
3401
                        // channel closure.
7✔
3402
                        if closeReq != nil {
12✔
3403
                                closeReq.Updates <- &ChannelCloseUpdate{
5✔
3404
                                        ClosingTxid: closingTxid[:],
5✔
3405
                                        Success:     true,
5✔
3406
                                }
5✔
3407
                        }
5✔
3408
                })
3409
}
3410

3411
// WaitForChanToClose uses the passed notifier to wait until the channel has
3412
// been detected as closed on chain and then concludes by executing the
3413
// following actions: the channel point will be sent over the settleChan, and
3414
// finally the callback will be executed. If any error is encountered within
3415
// the function, then it will be sent over the errChan.
3416
func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
3417
        errChan chan error, chanPoint *wire.OutPoint,
3418
        closingTxID *chainhash.Hash, closeScript []byte, cb func()) {
7✔
3419

7✔
3420
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
7✔
3421
                "with txid: %v", chanPoint, closingTxID)
7✔
3422

7✔
3423
        // TODO(roasbeef): add param for num needed confs
7✔
3424
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
7✔
3425
                closingTxID, closeScript, 1, bestHeight,
7✔
3426
        )
7✔
3427
        if err != nil {
7✔
3428
                if errChan != nil {
×
3429
                        errChan <- err
×
3430
                }
×
3431
                return
×
3432
        }
3433

3434
        // In the case that the ChainNotifier is shutting down, all subscriber
3435
        // notification channels will be closed, generating a nil receive.
3436
        height, ok := <-confNtfn.Confirmed
7✔
3437
        if !ok {
10✔
3438
                return
3✔
3439
        }
3✔
3440

3441
        // The channel has been closed, remove it from any active indexes, and
3442
        // the database state.
3443
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
7✔
3444
                "height %v", chanPoint, height.BlockHeight)
7✔
3445

7✔
3446
        // Finally, execute the closure call back to mark the confirmation of
7✔
3447
        // the transaction closing the contract.
7✔
3448
        cb()
7✔
3449
}
3450

3451
// WipeChannel removes the passed channel point from all indexes associated with
3452
// the peer and the switch.
3453
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
7✔
3454
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
7✔
3455

7✔
3456
        p.activeChannels.Delete(chanID)
7✔
3457

7✔
3458
        // Instruct the HtlcSwitch to close this link as the channel is no
7✔
3459
        // longer active.
7✔
3460
        p.cfg.Switch.RemoveLink(chanID)
7✔
3461
}
7✔
3462

3463
// handleInitMsg handles the incoming init message which contains global and
3464
// local feature vectors. If feature vectors are incompatible then disconnect.
3465
func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
6✔
3466
        // First, merge any features from the legacy global features field into
6✔
3467
        // those presented in the local features fields.
6✔
3468
        err := msg.Features.Merge(msg.GlobalFeatures)
6✔
3469
        if err != nil {
6✔
3470
                return fmt.Errorf("unable to merge legacy global features: %w",
×
3471
                        err)
×
3472
        }
×
3473

3474
        // Then, finalize the remote feature vector providing the flattened
3475
        // feature bit namespace.
3476
        p.remoteFeatures = lnwire.NewFeatureVector(
6✔
3477
                msg.Features, lnwire.Features,
6✔
3478
        )
6✔
3479

6✔
3480
        // Now that we have their features loaded, we'll ensure that they
6✔
3481
        // didn't set any required bits that we don't know of.
6✔
3482
        err = feature.ValidateRequired(p.remoteFeatures)
6✔
3483
        if err != nil {
6✔
3484
                return fmt.Errorf("invalid remote features: %w", err)
×
3485
        }
×
3486

3487
        // Ensure the remote party's feature vector contains all transitive
3488
        // dependencies. We know ours are correct since they are validated
3489
        // during the feature manager's instantiation.
3490
        err = feature.ValidateDeps(p.remoteFeatures)
6✔
3491
        if err != nil {
6✔
3492
                return fmt.Errorf("invalid remote features: %w", err)
×
3493
        }
×
3494

3495
        // Now that we know we understand their requirements, we'll check to
3496
        // see if they don't support anything that we deem to be mandatory.
3497
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
6✔
3498
                return fmt.Errorf("data loss protection required")
×
3499
        }
×
3500

3501
        return nil
6✔
3502
}
3503

3504
// LocalFeatures returns the set of global features that has been advertised by
3505
// the local node. This allows sub-systems that use this interface to gate their
3506
// behavior off the set of negotiated feature bits.
3507
//
3508
// NOTE: Part of the lnpeer.Peer interface.
3509
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
3✔
3510
        return p.cfg.Features
3✔
3511
}
3✔
3512

3513
// RemoteFeatures returns the set of global features that has been advertised by
3514
// the remote node. This allows sub-systems that use this interface to gate
3515
// their behavior off the set of negotiated feature bits.
3516
//
3517
// NOTE: Part of the lnpeer.Peer interface.
3518
func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector {
9✔
3519
        return p.remoteFeatures
9✔
3520
}
9✔
3521

3522
// hasNegotiatedScidAlias returns true if we've negotiated the
3523
// option-scid-alias feature bit with the peer.
3524
func (p *Brontide) hasNegotiatedScidAlias() bool {
6✔
3525
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
6✔
3526
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
6✔
3527
        return peerHas && localHas
6✔
3528
}
6✔
3529

3530
// sendInitMsg sends the Init message to the remote peer. This message contains
3531
// our currently supported local and global features.
3532
func (p *Brontide) sendInitMsg(legacyChan bool) error {
10✔
3533
        features := p.cfg.Features.Clone()
10✔
3534
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
10✔
3535

10✔
3536
        // If we have a legacy channel open with a peer, we downgrade static
10✔
3537
        // remote required to optional in case the peer does not understand the
10✔
3538
        // required feature bit. If we do not do this, the peer will reject our
10✔
3539
        // connection because it does not understand a required feature bit, and
10✔
3540
        // our channel will be unusable.
10✔
3541
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
11✔
3542
                p.log.Infof("Legacy channel open with peer, " +
1✔
3543
                        "downgrading static remote required feature bit to " +
1✔
3544
                        "optional")
1✔
3545

1✔
3546
                // Unset and set in both the local and global features to
1✔
3547
                // ensure both sets are consistent and merge able by old and
1✔
3548
                // new nodes.
1✔
3549
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3550
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3551

1✔
3552
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
3553
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
3554
        }
1✔
3555

3556
        msg := lnwire.NewInitMessage(
10✔
3557
                legacyFeatures.RawFeatureVector,
10✔
3558
                features.RawFeatureVector,
10✔
3559
        )
10✔
3560

10✔
3561
        return p.writeMessage(msg)
10✔
3562
}
3563

3564
// resendChanSyncMsg will attempt to find a channel sync message for the closed
3565
// channel and resend it to our peer.
3566
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
3✔
3567
        // If we already re-sent the mssage for this channel, we won't do it
3✔
3568
        // again.
3✔
3569
        if _, ok := p.resentChanSyncMsg[cid]; ok {
3✔
UNCOV
3570
                return nil
×
UNCOV
3571
        }
×
3572

3573
        // Check if we have any channel sync messages stored for this channel.
3574
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
3✔
3575
        if err != nil {
6✔
3576
                return fmt.Errorf("unable to fetch channel sync messages for "+
3✔
3577
                        "peer %v: %v", p, err)
3✔
3578
        }
3✔
3579

3580
        if c.LastChanSyncMsg == nil {
3✔
3581
                return fmt.Errorf("no chan sync message stored for channel %v",
×
3582
                        cid)
×
3583
        }
×
3584

3585
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
3✔
3586
                return fmt.Errorf("ignoring channel reestablish from "+
×
3587
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
3588
        }
×
3589

3590
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
3✔
3591
                "peer", cid)
3✔
3592

3✔
3593
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
3✔
3594
                return fmt.Errorf("failed resending channel sync "+
×
3595
                        "message to peer %v: %v", p, err)
×
3596
        }
×
3597

3598
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
3✔
3599
                cid)
3✔
3600

3✔
3601
        // Note down that we sent the message, so we won't resend it again for
3✔
3602
        // this connection.
3✔
3603
        p.resentChanSyncMsg[cid] = struct{}{}
3✔
3604

3✔
3605
        return nil
3✔
3606
}
3607

3608
// SendMessage sends a variadic number of high-priority messages to the remote
3609
// peer. The first argument denotes if the method should block until the
3610
// messages have been sent to the remote peer or an error is returned,
3611
// otherwise it returns immediately after queuing.
3612
//
3613
// NOTE: Part of the lnpeer.Peer interface.
3614
func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error {
6✔
3615
        return p.sendMessage(sync, true, msgs...)
6✔
3616
}
6✔
3617

3618
// SendMessageLazy sends a variadic number of low-priority messages to the
3619
// remote peer. The first argument denotes if the method should block until
3620
// the messages have been sent to the remote peer or an error is returned,
3621
// otherwise it returns immediately after queueing.
3622
//
3623
// NOTE: Part of the lnpeer.Peer interface.
3624
func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
4✔
3625
        return p.sendMessage(sync, false, msgs...)
4✔
3626
}
4✔
3627

3628
// sendMessage queues a variadic number of messages using the passed priority
3629
// to the remote peer. If sync is true, this method will block until the
3630
// messages have been sent to the remote peer or an error is returned, otherwise
3631
// it returns immediately after queueing.
3632
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
7✔
3633
        // Add all incoming messages to the outgoing queue. A list of error
7✔
3634
        // chans is populated for each message if the caller requested a sync
7✔
3635
        // send.
7✔
3636
        var errChans []chan error
7✔
3637
        if sync {
11✔
3638
                errChans = make([]chan error, 0, len(msgs))
4✔
3639
        }
4✔
3640
        for _, msg := range msgs {
14✔
3641
                // If a sync send was requested, create an error chan to listen
7✔
3642
                // for an ack from the writeHandler.
7✔
3643
                var errChan chan error
7✔
3644
                if sync {
11✔
3645
                        errChan = make(chan error, 1)
4✔
3646
                        errChans = append(errChans, errChan)
4✔
3647
                }
4✔
3648

3649
                if priority {
13✔
3650
                        p.queueMsg(msg, errChan)
6✔
3651
                } else {
10✔
3652
                        p.queueMsgLazy(msg, errChan)
4✔
3653
                }
4✔
3654
        }
3655

3656
        // Wait for all replies from the writeHandler. For async sends, this
3657
        // will be a NOP as the list of error chans is nil.
3658
        for _, errChan := range errChans {
11✔
3659
                select {
4✔
3660
                case err := <-errChan:
4✔
3661
                        return err
4✔
3662
                case <-p.quit:
×
3663
                        return lnpeer.ErrPeerExiting
×
3664
                case <-p.cfg.Quit:
1✔
3665
                        return lnpeer.ErrPeerExiting
1✔
3666
                }
3667
        }
3668

3669
        return nil
6✔
3670
}
3671

3672
// PubKey returns the pubkey of the peer in compressed serialized format.
3673
//
3674
// NOTE: Part of the lnpeer.Peer interface.
3675
func (p *Brontide) PubKey() [33]byte {
5✔
3676
        return p.cfg.PubKeyBytes
5✔
3677
}
5✔
3678

3679
// IdentityKey returns the public key of the remote peer.
3680
//
3681
// NOTE: Part of the lnpeer.Peer interface.
3682
func (p *Brontide) IdentityKey() *btcec.PublicKey {
17✔
3683
        return p.cfg.Addr.IdentityKey
17✔
3684
}
17✔
3685

3686
// Address returns the network address of the remote peer.
3687
//
3688
// NOTE: Part of the lnpeer.Peer interface.
3689
func (p *Brontide) Address() net.Addr {
3✔
3690
        return p.cfg.Addr.Address
3✔
3691
}
3✔
3692

3693
// AddNewChannel adds a new channel to the peer. The channel should fail to be
3694
// added if the cancel channel is closed.
3695
//
3696
// NOTE: Part of the lnpeer.Peer interface.
3697
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
3698
        cancel <-chan struct{}) error {
3✔
3699

3✔
3700
        errChan := make(chan error, 1)
3✔
3701
        newChanMsg := &newChannelMsg{
3✔
3702
                channel: newChan,
3✔
3703
                err:     errChan,
3✔
3704
        }
3✔
3705

3✔
3706
        select {
3✔
3707
        case p.newActiveChannel <- newChanMsg:
3✔
3708
        case <-cancel:
×
3709
                return errors.New("canceled adding new channel")
×
3710
        case <-p.quit:
×
3711
                return lnpeer.ErrPeerExiting
×
3712
        }
3713

3714
        // We pause here to wait for the peer to recognize the new channel
3715
        // before we close the channel barrier corresponding to the channel.
3716
        select {
3✔
3717
        case err := <-errChan:
3✔
3718
                return err
3✔
3719
        case <-p.quit:
×
3720
                return lnpeer.ErrPeerExiting
×
3721
        }
3722
}
3723

3724
// AddPendingChannel adds a pending open channel to the peer. The channel
3725
// should fail to be added if the cancel channel is closed.
3726
//
3727
// NOTE: Part of the lnpeer.Peer interface.
3728
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
3729
        cancel <-chan struct{}) error {
3✔
3730

3✔
3731
        errChan := make(chan error, 1)
3✔
3732
        newChanMsg := &newChannelMsg{
3✔
3733
                channelID: cid,
3✔
3734
                err:       errChan,
3✔
3735
        }
3✔
3736

3✔
3737
        select {
3✔
3738
        case p.newPendingChannel <- newChanMsg:
3✔
3739

3740
        case <-cancel:
×
3741
                return errors.New("canceled adding pending channel")
×
3742

3743
        case <-p.quit:
×
3744
                return lnpeer.ErrPeerExiting
×
3745
        }
3746

3747
        // We pause here to wait for the peer to recognize the new pending
3748
        // channel before we close the channel barrier corresponding to the
3749
        // channel.
3750
        select {
3✔
3751
        case err := <-errChan:
3✔
3752
                return err
3✔
3753

3754
        case <-cancel:
×
3755
                return errors.New("canceled adding pending channel")
×
3756

3757
        case <-p.quit:
×
3758
                return lnpeer.ErrPeerExiting
×
3759
        }
3760
}
3761

3762
// RemovePendingChannel removes a pending open channel from the peer.
3763
//
3764
// NOTE: Part of the lnpeer.Peer interface.
3765
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
3✔
3766
        errChan := make(chan error, 1)
3✔
3767
        newChanMsg := &newChannelMsg{
3✔
3768
                channelID: cid,
3✔
3769
                err:       errChan,
3✔
3770
        }
3✔
3771

3✔
3772
        select {
3✔
3773
        case p.removePendingChannel <- newChanMsg:
3✔
3774
        case <-p.quit:
×
3775
                return lnpeer.ErrPeerExiting
×
3776
        }
3777

3778
        // We pause here to wait for the peer to respond to the cancellation of
3779
        // the pending channel before we close the channel barrier
3780
        // corresponding to the channel.
3781
        select {
3✔
3782
        case err := <-errChan:
3✔
3783
                return err
3✔
3784

3785
        case <-p.quit:
×
3786
                return lnpeer.ErrPeerExiting
×
3787
        }
3788
}
3789

3790
// StartTime returns the time at which the connection was established if the
3791
// peer started successfully, and zero otherwise.
3792
func (p *Brontide) StartTime() time.Time {
3✔
3793
        return p.startTime
3✔
3794
}
3✔
3795

3796
// handleCloseMsg is called when a new cooperative channel closure related
3797
// message is received from the remote peer. We'll use this message to advance
3798
// the chan closer state machine.
3799
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
16✔
3800
        link := p.fetchLinkFromKeyAndCid(msg.cid)
16✔
3801

16✔
3802
        // We'll now fetch the matching closing state machine in order to continue,
16✔
3803
        // or finalize the channel closure process.
16✔
3804
        chanCloser, err := p.fetchActiveChanCloser(msg.cid)
16✔
3805
        if err != nil {
19✔
3806
                // If the channel is not known to us, we'll simply ignore this message.
3✔
3807
                if err == ErrChannelNotFound {
6✔
3808
                        return
3✔
3809
                }
3✔
3810

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

×
3813
                errMsg := &lnwire.Error{
×
3814
                        ChanID: msg.cid,
×
3815
                        Data:   lnwire.ErrorData(err.Error()),
×
3816
                }
×
3817
                p.queueMsg(errMsg, nil)
×
3818
                return
×
3819
        }
3820

3821
        handleErr := func(err error) {
18✔
3822
                err = fmt.Errorf("unable to process close msg: %w", err)
2✔
3823
                p.log.Error(err)
2✔
3824

2✔
3825
                // As the negotiations failed, we'll reset the channel state machine to
2✔
3826
                // ensure we act to on-chain events as normal.
2✔
3827
                chanCloser.Channel().ResetState()
2✔
3828

2✔
3829
                if chanCloser.CloseRequest() != nil {
2✔
3830
                        chanCloser.CloseRequest().Err <- err
×
3831
                }
×
3832
                delete(p.activeChanCloses, msg.cid)
2✔
3833

2✔
3834
                p.Disconnect(err)
2✔
3835
        }
3836

3837
        // Next, we'll process the next message using the target state machine.
3838
        // We'll either continue negotiation, or halt.
3839
        switch typed := msg.msg.(type) {
16✔
3840
        case *lnwire.Shutdown:
8✔
3841
                // Disable incoming adds immediately.
8✔
3842
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
8✔
3843
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
3844
                                link.ChanID())
×
3845
                }
×
3846

3847
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
8✔
3848
                if err != nil {
8✔
3849
                        handleErr(err)
×
3850
                        return
×
3851
                }
×
3852

3853
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
14✔
3854
                        // If the link is nil it means we can immediately queue
6✔
3855
                        // the Shutdown message since we don't have to wait for
6✔
3856
                        // commitment transaction synchronization.
6✔
3857
                        if link == nil {
7✔
3858
                                p.queueMsg(&msg, nil)
1✔
3859
                                return
1✔
3860
                        }
1✔
3861

3862
                        // Immediately disallow any new HTLC's from being added
3863
                        // in the outgoing direction.
3864
                        if !link.DisableAdds(htlcswitch.Outgoing) {
5✔
3865
                                p.log.Warnf("Outgoing link adds already "+
×
3866
                                        "disabled: %v", link.ChanID())
×
3867
                        }
×
3868

3869
                        // When we have a Shutdown to send, we defer it till the
3870
                        // next time we send a CommitSig to remain spec
3871
                        // compliant.
3872
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
10✔
3873
                                p.queueMsg(&msg, nil)
5✔
3874
                        })
5✔
3875
                })
3876

3877
                beginNegotiation := func() {
16✔
3878
                        oClosingSigned, err := chanCloser.BeginNegotiation()
8✔
3879
                        if err != nil {
9✔
3880
                                handleErr(err)
1✔
3881
                                return
1✔
3882
                        }
1✔
3883

3884
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
14✔
3885
                                p.queueMsg(&msg, nil)
7✔
3886
                        })
7✔
3887
                }
3888

3889
                if link == nil {
9✔
3890
                        beginNegotiation()
1✔
3891
                } else {
8✔
3892
                        // Now we register a flush hook to advance the
7✔
3893
                        // ChanCloser and possibly send out a ClosingSigned
7✔
3894
                        // when the link finishes draining.
7✔
3895
                        link.OnFlushedOnce(func() {
14✔
3896
                                // Remove link in goroutine to prevent deadlock.
7✔
3897
                                go p.cfg.Switch.RemoveLink(msg.cid)
7✔
3898
                                beginNegotiation()
7✔
3899
                        })
7✔
3900
                }
3901

3902
        case *lnwire.ClosingSigned:
11✔
3903
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
11✔
3904
                if err != nil {
12✔
3905
                        handleErr(err)
1✔
3906
                        return
1✔
3907
                }
1✔
3908

3909
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
22✔
3910
                        p.queueMsg(&msg, nil)
11✔
3911
                })
11✔
3912

3913
        default:
×
3914
                panic("impossible closeMsg type")
×
3915
        }
3916

3917
        // If we haven't finished close negotiations, then we'll continue as we
3918
        // can't yet finalize the closure.
3919
        if _, err := chanCloser.ClosingTx(); err != nil {
26✔
3920
                return
11✔
3921
        }
11✔
3922

3923
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
3924
        // the channel closure by notifying relevant sub-systems and launching a
3925
        // goroutine to wait for close tx conf.
3926
        p.finalizeChanClosure(chanCloser)
7✔
3927
}
3928

3929
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
3930
// the channelManager goroutine, which will shut down the link and possibly
3931
// close the channel.
3932
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
3✔
3933
        select {
3✔
3934
        case p.localCloseChanReqs <- req:
3✔
3935
                p.log.Info("Local close channel request is going to be " +
3✔
3936
                        "delivered to the peer")
3✔
3937
        case <-p.quit:
×
3938
                p.log.Info("Unable to deliver local close channel request " +
×
3939
                        "to peer")
×
3940
        }
3941
}
3942

3943
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
3944
func (p *Brontide) NetAddress() *lnwire.NetAddress {
3✔
3945
        return p.cfg.Addr
3✔
3946
}
3✔
3947

3948
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
3949
func (p *Brontide) Inbound() bool {
3✔
3950
        return p.cfg.Inbound
3✔
3951
}
3✔
3952

3953
// ConnReq is a getter for the Brontide's connReq in cfg.
3954
func (p *Brontide) ConnReq() *connmgr.ConnReq {
3✔
3955
        return p.cfg.ConnReq
3✔
3956
}
3✔
3957

3958
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
3959
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
3✔
3960
        return p.cfg.ErrorBuffer
3✔
3961
}
3✔
3962

3963
// SetAddress sets the remote peer's address given an address.
3964
func (p *Brontide) SetAddress(address net.Addr) {
×
3965
        p.cfg.Addr.Address = address
×
3966
}
×
3967

3968
// ActiveSignal returns the peer's active signal.
3969
func (p *Brontide) ActiveSignal() chan struct{} {
3✔
3970
        return p.activeSignal
3✔
3971
}
3✔
3972

3973
// Conn returns a pointer to the peer's connection struct.
3974
func (p *Brontide) Conn() net.Conn {
3✔
3975
        return p.cfg.Conn
3✔
3976
}
3✔
3977

3978
// BytesReceived returns the number of bytes received from the peer.
3979
func (p *Brontide) BytesReceived() uint64 {
3✔
3980
        return atomic.LoadUint64(&p.bytesReceived)
3✔
3981
}
3✔
3982

3983
// BytesSent returns the number of bytes sent to the peer.
3984
func (p *Brontide) BytesSent() uint64 {
3✔
3985
        return atomic.LoadUint64(&p.bytesSent)
3✔
3986
}
3✔
3987

3988
// LastRemotePingPayload returns the last payload the remote party sent as part
3989
// of their ping.
3990
func (p *Brontide) LastRemotePingPayload() []byte {
3✔
3991
        pingPayload := p.lastPingPayload.Load()
3✔
3992
        if pingPayload == nil {
6✔
3993
                return []byte{}
3✔
3994
        }
3✔
3995

3996
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
1✔
3997
        if !ok {
1✔
3998
                return nil
×
3999
        }
×
4000

4001
        return pingBytes
1✔
4002
}
4003

4004
// attachChannelEventSubscription creates a channel event subscription and
4005
// attaches to client to Brontide if the reenableTimeout is no greater than 1
4006
// minute.
4007
func (p *Brontide) attachChannelEventSubscription() error {
6✔
4008
        // If the timeout is greater than 1 minute, it's unlikely that the link
6✔
4009
        // hasn't yet finished its reestablishment. Return a nil without
6✔
4010
        // creating the client to specify that we don't want to retry.
6✔
4011
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
9✔
4012
                return nil
3✔
4013
        }
3✔
4014

4015
        // When the reenable timeout is less than 1 minute, it's likely the
4016
        // channel link hasn't finished its reestablishment yet. In that case,
4017
        // we'll give it a second chance by subscribing to the channel update
4018
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
4019
        // enabling the channel again.
4020
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
6✔
4021
        if err != nil {
6✔
4022
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
4023
        }
×
4024

4025
        p.channelEventClient = sub
6✔
4026

6✔
4027
        return nil
6✔
4028
}
4029

4030
// updateNextRevocation updates the existing channel's next revocation if it's
4031
// nil.
4032
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
6✔
4033
        chanPoint := c.FundingOutpoint
6✔
4034
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
6✔
4035

6✔
4036
        // Read the current channel.
6✔
4037
        currentChan, loaded := p.activeChannels.Load(chanID)
6✔
4038

6✔
4039
        // currentChan should exist, but we perform a check anyway to avoid nil
6✔
4040
        // pointer dereference.
6✔
4041
        if !loaded {
7✔
4042
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
4043
                        chanID)
1✔
4044
        }
1✔
4045

4046
        // currentChan should not be nil, but we perform a check anyway to
4047
        // avoid nil pointer dereference.
4048
        if currentChan == nil {
6✔
4049
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
4050
                        chanID)
1✔
4051
        }
1✔
4052

4053
        // If we're being sent a new channel, and our existing channel doesn't
4054
        // have the next revocation, then we need to update the current
4055
        // existing channel.
4056
        if currentChan.RemoteNextRevocation() != nil {
4✔
4057
                return nil
×
4058
        }
×
4059

4060
        p.log.Infof("Processing retransmitted ChannelReady for "+
4✔
4061
                "ChannelPoint(%v)", chanPoint)
4✔
4062

4✔
4063
        nextRevoke := c.RemoteNextRevocation
4✔
4064

4✔
4065
        err := currentChan.InitNextRevocation(nextRevoke)
4✔
4066
        if err != nil {
4✔
4067
                return fmt.Errorf("unable to init next revocation: %w", err)
×
4068
        }
×
4069

4070
        return nil
4✔
4071
}
4072

4073
// addActiveChannel adds a new active channel to the `activeChannels` map. It
4074
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
4075
// it and assembles it with a channel link.
4076
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
3✔
4077
        chanPoint := c.FundingOutpoint
3✔
4078
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4079

3✔
4080
        // If we've reached this point, there are two possible scenarios.  If
3✔
4081
        // the channel was in the active channels map as nil, then it was
3✔
4082
        // loaded from disk and we need to send reestablish. Else, it was not
3✔
4083
        // loaded from disk and we don't need to send reestablish as this is a
3✔
4084
        // fresh channel.
3✔
4085
        shouldReestablish := p.isLoadedFromDisk(chanID)
3✔
4086

3✔
4087
        chanOpts := c.ChanOpts
3✔
4088
        if shouldReestablish {
6✔
4089
                // If we have to do the reestablish dance for this channel,
3✔
4090
                // ensure that we don't try to call InitRemoteMusigNonces twice
3✔
4091
                // by calling SkipNonceInit.
3✔
4092
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
3✔
4093
        }
3✔
4094

4095
        // If not already active, we'll add this channel to the set of active
4096
        // channels, so we can look it up later easily according to its channel
4097
        // ID.
4098
        lnChan, err := lnwallet.NewLightningChannel(
3✔
4099
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
3✔
4100
        )
3✔
4101
        if err != nil {
3✔
4102
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
4103
        }
×
4104

4105
        // Store the channel in the activeChannels map.
4106
        p.activeChannels.Store(chanID, lnChan)
3✔
4107

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

3✔
4110
        // Next, we'll assemble a ChannelLink along with the necessary items it
3✔
4111
        // needs to function.
3✔
4112
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
3✔
4113
        if err != nil {
3✔
4114
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
4115
                        err)
×
4116
        }
×
4117

4118
        // We'll query the channel DB for the new channel's initial forwarding
4119
        // policies to determine the policy we start out with.
4120
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
3✔
4121
        if err != nil {
3✔
4122
                return fmt.Errorf("unable to query for initial forwarding "+
×
4123
                        "policy: %v", err)
×
4124
        }
×
4125

4126
        // Create the link and add it to the switch.
4127
        err = p.addLink(
3✔
4128
                &chanPoint, lnChan, initialPolicy, chainEvents,
3✔
4129
                shouldReestablish, fn.None[lnwire.Shutdown](),
3✔
4130
        )
3✔
4131
        if err != nil {
3✔
4132
                return fmt.Errorf("can't register new channel link(%v) with "+
×
4133
                        "peer", chanPoint)
×
4134
        }
×
4135

4136
        return nil
3✔
4137
}
4138

4139
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
4140
// know this channel ID or not, we'll either add it to the `activeChannels` map
4141
// or init the next revocation for it.
4142
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
3✔
4143
        newChan := req.channel
3✔
4144
        chanPoint := newChan.FundingOutpoint
3✔
4145
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4146

3✔
4147
        // Only update RemoteNextRevocation if the channel is in the
3✔
4148
        // activeChannels map and if we added the link to the switch. Only
3✔
4149
        // active channels will be added to the switch.
3✔
4150
        if p.isActiveChannel(chanID) {
6✔
4151
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
3✔
4152
                        chanPoint)
3✔
4153

3✔
4154
                // Handle it and close the err chan on the request.
3✔
4155
                close(req.err)
3✔
4156

3✔
4157
                // Update the next revocation point.
3✔
4158
                err := p.updateNextRevocation(newChan.OpenChannel)
3✔
4159
                if err != nil {
3✔
4160
                        p.log.Errorf(err.Error())
×
4161
                }
×
4162

4163
                return
3✔
4164
        }
4165

4166
        // This is a new channel, we now add it to the map.
4167
        if err := p.addActiveChannel(req.channel); err != nil {
3✔
4168
                // Log and send back the error to the request.
×
4169
                p.log.Errorf(err.Error())
×
4170
                req.err <- err
×
4171

×
4172
                return
×
4173
        }
×
4174

4175
        // Close the err chan if everything went fine.
4176
        close(req.err)
3✔
4177
}
4178

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

7✔
4186
        chanID := req.channelID
7✔
4187

7✔
4188
        // If we already have this channel, something is wrong with the funding
7✔
4189
        // flow as it will only be marked as active after `ChannelReady` is
7✔
4190
        // handled. In this case, we will do nothing but log an error, just in
7✔
4191
        // case this is a legit channel.
7✔
4192
        if p.isActiveChannel(chanID) {
8✔
4193
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
4194
                        "pending channel request", chanID)
1✔
4195

1✔
4196
                return
1✔
4197
        }
1✔
4198

4199
        // The channel has already been added, we will do nothing and return.
4200
        if p.isPendingChannel(chanID) {
7✔
4201
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
4202
                        "pending channel request", chanID)
1✔
4203

1✔
4204
                return
1✔
4205
        }
1✔
4206

4207
        // This is a new channel, we now add it to the map `activeChannels`
4208
        // with nil value and mark it as a newly added channel in
4209
        // `addedChannels`.
4210
        p.activeChannels.Store(chanID, nil)
5✔
4211
        p.addedChannels.Store(chanID, struct{}{})
5✔
4212
}
4213

4214
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
4215
// from `activeChannels` map. The request will be ignored if the channel is
4216
// considered active by Brontide. Noop if the channel ID cannot be found.
4217
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
7✔
4218
        defer close(req.err)
7✔
4219

7✔
4220
        chanID := req.channelID
7✔
4221

7✔
4222
        // If we already have this channel, something is wrong with the funding
7✔
4223
        // flow as it will only be marked as active after `ChannelReady` is
7✔
4224
        // handled. In this case, we will log an error and exit.
7✔
4225
        if p.isActiveChannel(chanID) {
8✔
4226
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
4227
                        chanID)
1✔
4228
                return
1✔
4229
        }
1✔
4230

4231
        // The channel has not been added yet, we will log a warning as there
4232
        // is an unexpected call from funding manager.
4233
        if !p.isPendingChannel(chanID) {
10✔
4234
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
4✔
4235
        }
4✔
4236

4237
        // Remove the record of this pending channel.
4238
        p.activeChannels.Delete(chanID)
6✔
4239
        p.addedChannels.Delete(chanID)
6✔
4240
}
4241

4242
// sendLinkUpdateMsg sends a message that updates the channel to the
4243
// channel's message stream.
4244
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
3✔
4245
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
3✔
4246

3✔
4247
        chanStream, ok := p.activeMsgStreams[cid]
3✔
4248
        if !ok {
6✔
4249
                // If a stream hasn't yet been created, then we'll do so, add
3✔
4250
                // it to the map, and finally start it.
3✔
4251
                chanStream = newChanMsgStream(p, cid)
3✔
4252
                p.activeMsgStreams[cid] = chanStream
3✔
4253
                chanStream.Start()
3✔
4254

3✔
4255
                // Stop the stream when quit.
3✔
4256
                go func() {
6✔
4257
                        <-p.quit
3✔
4258
                        chanStream.Stop()
3✔
4259
                }()
3✔
4260
        }
4261

4262
        // With the stream obtained, add the message to the stream so we can
4263
        // continue processing message.
4264
        chanStream.AddMsg(msg)
3✔
4265
}
4266

4267
// scaleTimeout multiplies the argument duration by a constant factor depending
4268
// on variious heuristics. Currently this is only used to check whether our peer
4269
// appears to be connected over Tor and relaxes the timout deadline. However,
4270
// this is subject to change and should be treated as opaque.
4271
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
70✔
4272
        if p.isTorConnection {
73✔
4273
                return timeout * time.Duration(torTimeoutMultiplier)
3✔
4274
        }
3✔
4275

4276
        return timeout
67✔
4277
}
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