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

lightningnetwork / lnd / 11131178835

01 Oct 2024 06:21PM UTC coverage: 58.814%. Remained the same
11131178835

push

github

web-flow
Merge pull request #9001 from ellemouton/namespacedMC

routing: Namespaced Mission Control

211 of 257 new or added lines in 8 files covered. (82.1%)

71 existing lines in 15 files now uncovered.

130409 of 221731 relevant lines covered (58.81%)

28194.48 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

122
        err chan error
123
}
124

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

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

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

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

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

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

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

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

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

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

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

185
        // Addr is the network address of the peer.
186
        Addr *lnwire.NetAddress
187

188
        // Inbound indicates whether or not the peer is an inbound peer.
189
        Inbound bool
190

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

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

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

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

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

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

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

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

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

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

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

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

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

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

254
        // ChainIO is used to retrieve the best block.
255
        ChainIO lnwallet.BlockChainIO
256

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

261
        // Signer is used when creating *lnwallet.LightningChannel instances.
262
        Signer input.Signer
263

264
        // SigPool is used when creating *lnwallet.LightningChannel instances.
265
        SigPool *lnwallet.SigPool
266

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

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

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

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

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

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

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

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

300
        // HtlcNotifier is used when creating a ChannelLink.
301
        HtlcNotifier *htlcswitch.HtlcNotifier
302

303
        // TowerClient is used to backup revoked states.
304
        TowerClient wtclient.ClientManager
305

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

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

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

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

324
        // FundingManager is an implementation of the funding.Controller interface.
325
        FundingManager funding.Controller
326

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

411
        // MaxFeeExposure limits the number of outstanding fees in a channel.
412
        // This value will be passed to created links.
413
        MaxFeeExposure lnwire.MilliSatoshi
414

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

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

424
        // Quit is the server's quit channel. If this is closed, we halt operation.
425
        Quit chan struct{}
426
}
427

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

439
        // MUST be used atomically.
440
        bytesReceived uint64
441
        bytesSent     uint64
442

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

460
        pingManager *PingManager
461

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

469
        cfg Config
470

471
        // activeSignal when closed signals that the peer is now active and
472
        // ready to process messages.
473
        activeSignal chan struct{}
474

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

479
        // sendQueue is the channel which is used to queue outgoing messages to be
480
        // written onto the wire. Note that this channel is unbuffered.
481
        sendQueue chan outgoingMsg
482

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

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

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

506
        // newActiveChannel is used by the fundingManager to send fully opened
507
        // channels to the source peer which handled the funding workflow.
508
        newActiveChannel chan *newChannelMsg
509

510
        // newPendingChannel is used by the fundingManager to send pending open
511
        // channels to the source peer which handled the funding workflow.
512
        newPendingChannel chan *newChannelMsg
513

514
        // removePendingChannel is used by the fundingManager to cancel pending
515
        // open channels to the source peer when the funding flow is failed.
516
        removePendingChannel chan *newChannelMsg
517

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

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

528
        // localCloseChanReqs is a channel in which any local requests to close
529
        // a particular channel are sent over.
530
        localCloseChanReqs chan *htlcswitch.ChanClose
531

532
        // linkFailures receives all reported channel failures from the switch,
533
        // and instructs the channelManager to clean remaining channel state.
534
        linkFailures chan linkFailureReport
535

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

541
        // remoteFeatures is the feature vector received from the peer during
542
        // the connection handshake.
543
        remoteFeatures *lnwire.FeatureVector
544

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

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

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

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

569
        startReady chan struct{}
570
        quit       chan struct{}
571
        wg         sync.WaitGroup
572

573
        // log is a peer-specific logging instance.
574
        log btclog.Logger
575
}
576

577
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer interface.
578
var _ lnpeer.Peer = (*Brontide)(nil)
579

580
// NewBrontide creates a new Brontide from a peer.Config struct.
581
func NewBrontide(cfg Config) *Brontide {
29✔
582
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
29✔
583

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

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

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

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

29✔
621
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
33✔
622
                remoteAddr := cfg.Conn.RemoteAddr().String()
4✔
623
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
4✔
624
                        strings.Contains(remoteAddr, "127.0.0.1")
4✔
625
        }
4✔
626

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

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

654
                return lastSerializedBlockHeader[:]
3✔
655
        }
656

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

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

686
        return p
29✔
687
}
688

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

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

7✔
701
        p.log.Tracef("starting with conn[%v->%v]",
7✔
702
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
7✔
703

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

715
        if len(activeChans) == 0 {
12✔
716
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
5✔
717
        }
5✔
718

719
        // Quickly check if we have any existing legacy channels with this
720
        // peer.
721
        haveLegacyChan := false
7✔
722
        for _, c := range activeChans {
13✔
723
                if c.ChanType.IsTweakless() {
12✔
724
                        continue
6✔
725
                }
726

727
                haveLegacyChan = true
4✔
728
                break
4✔
729
        }
730

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

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

7✔
746
                msg, err := p.readNextMessage()
7✔
747
                if err != nil {
8✔
748
                        readErr <- err
1✔
749
                        msgChan <- nil
1✔
750
                        return
1✔
751
                }
1✔
752
                readErr <- nil
7✔
753
                msgChan <- msg
7✔
754
        }()
755

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

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

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

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

798
        // Register the message router now as we may need to register some
799
        // endpoints while loading the channels below.
800
        p.msgRouter.WhenSome(func(router msgmux.Router) {
14✔
801
                router.Start()
7✔
802
        })
7✔
803

804
        msgs, err := p.loadActiveChannels(activeChans)
7✔
805
        if err != nil {
7✔
806
                return fmt.Errorf("unable to load channels: %w", err)
×
807
        }
×
808

809
        p.startTime = time.Now()
7✔
810

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

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

828
        err = p.pingManager.Start()
7✔
829
        if err != nil {
7✔
830
                return fmt.Errorf("could not start ping manager %w", err)
×
831
        }
×
832

833
        p.wg.Add(4)
7✔
834
        go p.queueHandler()
7✔
835
        go p.writeHandler()
7✔
836
        go p.channelManager()
7✔
837
        go p.readHandler()
7✔
838

7✔
839
        // Signal to any external processes that the peer is now active.
7✔
840
        close(p.activeSignal)
7✔
841

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

7✔
857
        return nil
7✔
858
}
859

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

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

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

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

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

905
// internalKeyForAddr returns the internal key associated with a taproot
906
// address.
907
func internalKeyForAddr(wallet *lnwallet.LightningWallet,
908
        deliveryScript []byte) (fn.Option[btcec.PublicKey], error) {
13✔
909

13✔
910
        none := fn.None[btcec.PublicKey]()
13✔
911

13✔
912
        pkScript, err := txscript.ParsePkScript(deliveryScript)
13✔
913
        if err != nil {
13✔
914
                return none, err
×
915
        }
×
916
        addr, err := pkScript.Address(&wallet.Cfg.NetParams)
13✔
917
        if err != nil {
13✔
918
                return none, err
×
919
        }
×
920

921
        // If it's not a taproot address, we don't require to know the internal
922
        // key in the first place. So we don't return an error here, but also no
923
        // internal key.
924
        _, isTaproot := addr.(*btcutil.AddressTaproot)
13✔
925
        if !isTaproot {
26✔
926
                return none, nil
13✔
927
        }
13✔
928

929
        walletAddr, err := wallet.AddressInfo(addr)
4✔
930
        if err != nil {
4✔
931
                return none, err
×
932
        }
×
933

934
        // If the address isn't known to the wallet, we can't determine the
935
        // internal key.
936
        if walletAddr == nil {
4✔
937
                return none, nil
×
938
        }
×
939

940
        pubKeyAddr, ok := walletAddr.(waddrmgr.ManagedPubKeyAddress)
4✔
941
        if !ok {
4✔
942
                return none, fmt.Errorf("expected pubkey addr, got %T",
×
943
                        pubKeyAddr)
×
944
        }
×
945

946
        return fn.Some(*pubKeyAddr.PubKey()), nil
4✔
947
}
948

949
// addrWithInternalKey takes a delivery script, then attempts to supplement it
950
// with information related to the internal key for the addr, but only if it's
951
// a taproot addr.
952
func (p *Brontide) addrWithInternalKey(
953
        deliveryScript []byte) fn.Result[chancloser.DeliveryAddrWithKey] {
13✔
954

13✔
955
        // TODO(roasbeef): not compatible with external shutdown addr?
13✔
956
        // Currently, custom channels cannot be created with external upfront
13✔
957
        // shutdown addresses, so this shouldn't be an issue. We only require
13✔
958
        // the internal key for taproot addresses to be able to provide a non
13✔
959
        // inclusion proof of any scripts.
13✔
960

13✔
961
        internalKey, err := internalKeyForAddr(p.cfg.Wallet, deliveryScript)
13✔
962
        if err != nil {
13✔
963
                return fn.Err[chancloser.DeliveryAddrWithKey](err)
×
964
        }
×
965

966
        return fn.Ok(chancloser.DeliveryAddrWithKey{
13✔
967
                DeliveryAddress: deliveryScript,
13✔
968
                InternalKey:     internalKey,
13✔
969
        })
13✔
970
}
971

972
// loadActiveChannels creates indexes within the peer for tracking all active
973
// channels returned by the database. It returns a slice of channel reestablish
974
// messages that should be sent to the peer immediately, in case we have borked
975
// channels that haven't been closed yet.
976
func (p *Brontide) loadActiveChannels(chans []*channeldb.OpenChannel) (
977
        []lnwire.Message, error) {
7✔
978

7✔
979
        // Return a slice of messages to send to the peers in case the channel
7✔
980
        // cannot be loaded normally.
7✔
981
        var msgs []lnwire.Message
7✔
982

7✔
983
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
7✔
984

7✔
985
        for _, dbChan := range chans {
13✔
986
                hasScidFeature := dbChan.ChanType.HasScidAliasFeature()
6✔
987
                if scidAliasNegotiated && !hasScidFeature {
10✔
988
                        // We'll request and store an alias, making sure that a
4✔
989
                        // gossiper mapping is not created for the alias to the
4✔
990
                        // real SCID. This is done because the peer and funding
4✔
991
                        // manager are not aware of each other's states and if
4✔
992
                        // we did not do this, we would accept alias channel
4✔
993
                        // updates after 6 confirmations, which would be buggy.
4✔
994
                        // We'll queue a channel_ready message with the new
4✔
995
                        // alias. This should technically be done *after* the
4✔
996
                        // reestablish, but this behavior is pre-existing since
4✔
997
                        // the funding manager may already queue a
4✔
998
                        // channel_ready before the channel_reestablish.
4✔
999
                        if !dbChan.IsPending {
8✔
1000
                                aliasScid, err := p.cfg.RequestAlias()
4✔
1001
                                if err != nil {
4✔
1002
                                        return nil, err
×
1003
                                }
×
1004

1005
                                err = p.cfg.AddLocalAlias(
4✔
1006
                                        aliasScid, dbChan.ShortChanID(), false,
4✔
1007
                                        false,
4✔
1008
                                )
4✔
1009
                                if err != nil {
4✔
1010
                                        return nil, err
×
1011
                                }
×
1012

1013
                                chanID := lnwire.NewChanIDFromOutPoint(
4✔
1014
                                        dbChan.FundingOutpoint,
4✔
1015
                                )
4✔
1016

4✔
1017
                                // Fetch the second commitment point to send in
4✔
1018
                                // the channel_ready message.
4✔
1019
                                second, err := dbChan.SecondCommitmentPoint()
4✔
1020
                                if err != nil {
4✔
1021
                                        return nil, err
×
1022
                                }
×
1023

1024
                                channelReadyMsg := lnwire.NewChannelReady(
4✔
1025
                                        chanID, second,
4✔
1026
                                )
4✔
1027
                                channelReadyMsg.AliasScid = &aliasScid
4✔
1028

4✔
1029
                                msgs = append(msgs, channelReadyMsg)
4✔
1030
                        }
1031

1032
                        // If we've negotiated the option-scid-alias feature
1033
                        // and this channel does not have ScidAliasFeature set
1034
                        // to true due to an upgrade where the feature bit was
1035
                        // turned on, we'll update the channel's database
1036
                        // state.
1037
                        err := dbChan.MarkScidAliasNegotiated()
4✔
1038
                        if err != nil {
4✔
1039
                                return nil, err
×
1040
                        }
×
1041
                }
1042

1043
                var chanOpts []lnwallet.ChannelOpt
6✔
1044
                p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
6✔
1045
                        chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
1046
                })
×
1047
                p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
6✔
1048
                        chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
1049
                })
×
1050
                lnChan, err := lnwallet.NewLightningChannel(
6✔
1051
                        p.cfg.Signer, dbChan, p.cfg.SigPool, chanOpts...,
6✔
1052
                )
6✔
1053
                if err != nil {
6✔
1054
                        return nil, fmt.Errorf("unable to create channel "+
×
1055
                                "state machine: %w", err)
×
1056
                }
×
1057

1058
                chanPoint := dbChan.FundingOutpoint
6✔
1059

6✔
1060
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
6✔
1061

6✔
1062
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
6✔
1063
                        chanPoint, lnChan.IsPending())
6✔
1064

6✔
1065
                // Skip adding any permanently irreconcilable channels to the
6✔
1066
                // htlcswitch.
6✔
1067
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
6✔
1068
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
12✔
1069

6✔
1070
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
6✔
1071
                                "start.", chanPoint, dbChan.ChanStatus())
6✔
1072

6✔
1073
                        // To help our peer recover from a potential data loss,
6✔
1074
                        // we resend our channel reestablish message if the
6✔
1075
                        // channel is in a borked state. We won't process any
6✔
1076
                        // channel reestablish message sent from the peer, but
6✔
1077
                        // that's okay since the assumption is that we did when
6✔
1078
                        // marking the channel borked.
6✔
1079
                        chanSync, err := dbChan.ChanSyncMsg()
6✔
1080
                        if err != nil {
6✔
1081
                                p.log.Errorf("Unable to create channel "+
×
1082
                                        "reestablish message for channel %v: "+
×
1083
                                        "%v", chanPoint, err)
×
1084
                                continue
×
1085
                        }
1086

1087
                        msgs = append(msgs, chanSync)
6✔
1088

6✔
1089
                        // Check if this channel needs to have the cooperative
6✔
1090
                        // close process restarted. If so, we'll need to send
6✔
1091
                        // the Shutdown message that is returned.
6✔
1092
                        if dbChan.HasChanStatus(
6✔
1093
                                channeldb.ChanStatusCoopBroadcasted,
6✔
1094
                        ) {
6✔
1095

×
1096
                                shutdownMsg, err := p.restartCoopClose(lnChan)
×
1097
                                if err != nil {
×
1098
                                        p.log.Errorf("Unable to restart "+
×
1099
                                                "coop close for channel: %v",
×
1100
                                                err)
×
1101
                                        continue
×
1102
                                }
1103

1104
                                if shutdownMsg == nil {
×
1105
                                        continue
×
1106
                                }
1107

1108
                                // Append the message to the set of messages to
1109
                                // send.
1110
                                msgs = append(msgs, shutdownMsg)
×
1111
                        }
1112

1113
                        continue
6✔
1114
                }
1115

1116
                // Before we register this new link with the HTLC Switch, we'll
1117
                // need to fetch its current link-layer forwarding policy from
1118
                // the database.
1119
                graph := p.cfg.ChannelGraph
4✔
1120
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
4✔
1121
                        &chanPoint,
4✔
1122
                )
4✔
1123
                if err != nil && !errors.Is(err, channeldb.ErrEdgeNotFound) {
4✔
1124
                        return nil, err
×
1125
                }
×
1126

1127
                // We'll filter out our policy from the directional channel
1128
                // edges based whom the edge connects to. If it doesn't connect
1129
                // to us, then we know that we were the one that advertised the
1130
                // policy.
1131
                //
1132
                // TODO(roasbeef): can add helper method to get policy for
1133
                // particular channel.
1134
                var selfPolicy *models.ChannelEdgePolicy
4✔
1135
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
4✔
1136
                        p.cfg.ServerPubKey[:]) {
8✔
1137

4✔
1138
                        selfPolicy = p1
4✔
1139
                } else {
8✔
1140
                        selfPolicy = p2
4✔
1141
                }
4✔
1142

1143
                // If we don't yet have an advertised routing policy, then
1144
                // we'll use the current default, otherwise we'll translate the
1145
                // routing policy into a forwarding policy.
1146
                var forwardingPolicy *models.ForwardingPolicy
4✔
1147
                if selfPolicy != nil {
8✔
1148
                        var inboundWireFee lnwire.Fee
4✔
1149
                        _, err := selfPolicy.ExtraOpaqueData.ExtractRecords(
4✔
1150
                                &inboundWireFee,
4✔
1151
                        )
4✔
1152
                        if err != nil {
4✔
1153
                                return nil, err
×
1154
                        }
×
1155

1156
                        inboundFee := models.NewInboundFeeFromWire(
4✔
1157
                                inboundWireFee,
4✔
1158
                        )
4✔
1159

4✔
1160
                        forwardingPolicy = &models.ForwardingPolicy{
4✔
1161
                                MinHTLCOut:    selfPolicy.MinHTLC,
4✔
1162
                                MaxHTLC:       selfPolicy.MaxHTLC,
4✔
1163
                                BaseFee:       selfPolicy.FeeBaseMSat,
4✔
1164
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
4✔
1165
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
4✔
1166

4✔
1167
                                InboundFee: inboundFee,
4✔
1168
                        }
4✔
1169
                } else {
4✔
1170
                        p.log.Warnf("Unable to find our forwarding policy "+
4✔
1171
                                "for channel %v, using default values",
4✔
1172
                                chanPoint)
4✔
1173
                        forwardingPolicy = &p.cfg.RoutingPolicy
4✔
1174
                }
4✔
1175

1176
                p.log.Tracef("Using link policy of: %v",
4✔
1177
                        spew.Sdump(forwardingPolicy))
4✔
1178

4✔
1179
                // If the channel is pending, set the value to nil in the
4✔
1180
                // activeChannels map. This is done to signify that the channel
4✔
1181
                // is pending. We don't add the link to the switch here - it's
4✔
1182
                // the funding manager's responsibility to spin up pending
4✔
1183
                // channels. Adding them here would just be extra work as we'll
4✔
1184
                // tear them down when creating + adding the final link.
4✔
1185
                if lnChan.IsPending() {
8✔
1186
                        p.activeChannels.Store(chanID, nil)
4✔
1187

4✔
1188
                        continue
4✔
1189
                }
1190

1191
                shutdownInfo, err := lnChan.State().ShutdownInfo()
4✔
1192
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
4✔
1193
                        return nil, err
×
1194
                }
×
1195

1196
                var (
4✔
1197
                        shutdownMsg     fn.Option[lnwire.Shutdown]
4✔
1198
                        shutdownInfoErr error
4✔
1199
                )
4✔
1200
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
8✔
1201
                        // Compute an ideal fee.
4✔
1202
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
4✔
1203
                                p.cfg.CoopCloseTargetConfs,
4✔
1204
                        )
4✔
1205
                        if err != nil {
4✔
1206
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1207
                                        "estimate fee: %w", err)
×
1208

×
1209
                                return
×
1210
                        }
×
1211

1212
                        addr, err := p.addrWithInternalKey(
4✔
1213
                                info.DeliveryScript.Val,
4✔
1214
                        ).Unpack()
4✔
1215
                        if err != nil {
4✔
1216
                                shutdownInfoErr = fmt.Errorf("unable to make "+
×
1217
                                        "delivery addr: %w", err)
×
1218
                                return
×
1219
                        }
×
1220
                        chanCloser, err := p.createChanCloser(
4✔
1221
                                lnChan, addr, feePerKw, nil, info.Closer(),
4✔
1222
                        )
4✔
1223
                        if err != nil {
4✔
1224
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1225
                                        "create chan closer: %w", err)
×
1226

×
1227
                                return
×
1228
                        }
×
1229

1230
                        chanID := lnwire.NewChanIDFromOutPoint(
4✔
1231
                                lnChan.State().FundingOutpoint,
4✔
1232
                        )
4✔
1233

4✔
1234
                        p.activeChanCloses[chanID] = chanCloser
4✔
1235

4✔
1236
                        // Create the Shutdown message.
4✔
1237
                        shutdown, err := chanCloser.ShutdownChan()
4✔
1238
                        if err != nil {
4✔
1239
                                delete(p.activeChanCloses, chanID)
×
1240
                                shutdownInfoErr = err
×
1241

×
1242
                                return
×
1243
                        }
×
1244

1245
                        shutdownMsg = fn.Some(*shutdown)
4✔
1246
                })
1247
                if shutdownInfoErr != nil {
4✔
1248
                        return nil, shutdownInfoErr
×
1249
                }
×
1250

1251
                // Subscribe to the set of on-chain events for this channel.
1252
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
4✔
1253
                        chanPoint,
4✔
1254
                )
4✔
1255
                if err != nil {
4✔
1256
                        return nil, err
×
1257
                }
×
1258

1259
                err = p.addLink(
4✔
1260
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
4✔
1261
                        true, shutdownMsg,
4✔
1262
                )
4✔
1263
                if err != nil {
4✔
1264
                        return nil, fmt.Errorf("unable to add link %v to "+
×
1265
                                "switch: %v", chanPoint, err)
×
1266
                }
×
1267

1268
                p.activeChannels.Store(chanID, lnChan)
4✔
1269
        }
1270

1271
        return msgs, nil
7✔
1272
}
1273

1274
// addLink creates and adds a new ChannelLink from the specified channel.
1275
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1276
        lnChan *lnwallet.LightningChannel,
1277
        forwardingPolicy *models.ForwardingPolicy,
1278
        chainEvents *contractcourt.ChainEventSubscription,
1279
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
4✔
1280

4✔
1281
        // onChannelFailure will be called by the link in case the channel
4✔
1282
        // fails for some reason.
4✔
1283
        onChannelFailure := func(chanID lnwire.ChannelID,
4✔
1284
                shortChanID lnwire.ShortChannelID,
4✔
1285
                linkErr htlcswitch.LinkFailureError) {
8✔
1286

4✔
1287
                failure := linkFailureReport{
4✔
1288
                        chanPoint:   *chanPoint,
4✔
1289
                        chanID:      chanID,
4✔
1290
                        shortChanID: shortChanID,
4✔
1291
                        linkErr:     linkErr,
4✔
1292
                }
4✔
1293

4✔
1294
                select {
4✔
1295
                case p.linkFailures <- failure:
4✔
1296
                case <-p.quit:
×
1297
                case <-p.cfg.Quit:
×
1298
                }
1299
        }
1300

1301
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
8✔
1302
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
4✔
1303
        }
4✔
1304

1305
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
8✔
1306
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
4✔
1307
        }
4✔
1308

1309
        //nolint:lll
1310
        linkCfg := htlcswitch.ChannelLinkConfig{
4✔
1311
                Peer:                   p,
4✔
1312
                DecodeHopIterators:     p.cfg.Sphinx.DecodeHopIterators,
4✔
1313
                ExtractErrorEncrypter:  p.cfg.Sphinx.ExtractErrorEncrypter,
4✔
1314
                FetchLastChannelUpdate: p.cfg.FetchLastChanUpdate,
4✔
1315
                HodlMask:               p.cfg.Hodl.Mask(),
4✔
1316
                Registry:               p.cfg.Invoices,
4✔
1317
                BestHeight:             p.cfg.Switch.BestHeight,
4✔
1318
                Circuits:               p.cfg.Switch.CircuitModifier(),
4✔
1319
                ForwardPackets:         p.cfg.InterceptSwitch.ForwardPackets,
4✔
1320
                FwrdingPolicy:          *forwardingPolicy,
4✔
1321
                FeeEstimator:           p.cfg.FeeEstimator,
4✔
1322
                PreimageCache:          p.cfg.WitnessBeacon,
4✔
1323
                ChainEvents:            chainEvents,
4✔
1324
                UpdateContractSignals:  updateContractSignals,
4✔
1325
                NotifyContractUpdate:   notifyContractUpdate,
4✔
1326
                OnChannelFailure:       onChannelFailure,
4✔
1327
                SyncStates:             syncStates,
4✔
1328
                BatchTicker:            ticker.New(p.cfg.ChannelCommitInterval),
4✔
1329
                FwdPkgGCTicker:         ticker.New(time.Hour),
4✔
1330
                PendingCommitTicker: ticker.New(
4✔
1331
                        p.cfg.PendingCommitInterval,
4✔
1332
                ),
4✔
1333
                BatchSize:               p.cfg.ChannelCommitBatchSize,
4✔
1334
                UnsafeReplay:            p.cfg.UnsafeReplay,
4✔
1335
                MinUpdateTimeout:        htlcswitch.DefaultMinLinkFeeUpdateTimeout,
4✔
1336
                MaxUpdateTimeout:        htlcswitch.DefaultMaxLinkFeeUpdateTimeout,
4✔
1337
                OutgoingCltvRejectDelta: p.cfg.OutgoingCltvRejectDelta,
4✔
1338
                TowerClient:             p.cfg.TowerClient,
4✔
1339
                MaxOutgoingCltvExpiry:   p.cfg.MaxOutgoingCltvExpiry,
4✔
1340
                MaxFeeAllocation:        p.cfg.MaxChannelFeeAllocation,
4✔
1341
                MaxAnchorsCommitFeeRate: p.cfg.MaxAnchorsCommitFeeRate,
4✔
1342
                NotifyActiveLink:        p.cfg.ChannelNotifier.NotifyActiveLinkEvent,
4✔
1343
                NotifyActiveChannel:     p.cfg.ChannelNotifier.NotifyActiveChannelEvent,
4✔
1344
                NotifyInactiveChannel:   p.cfg.ChannelNotifier.NotifyInactiveChannelEvent,
4✔
1345
                NotifyInactiveLinkEvent: p.cfg.ChannelNotifier.NotifyInactiveLinkEvent,
4✔
1346
                HtlcNotifier:            p.cfg.HtlcNotifier,
4✔
1347
                GetAliases:              p.cfg.GetAliases,
4✔
1348
                PreviouslySentShutdown:  shutdownMsg,
4✔
1349
                DisallowRouteBlinding:   p.cfg.DisallowRouteBlinding,
4✔
1350
                MaxFeeExposure:          p.cfg.MaxFeeExposure,
4✔
1351
        }
4✔
1352

4✔
1353
        // Before adding our new link, purge the switch of any pending or live
4✔
1354
        // links going by the same channel id. If one is found, we'll shut it
4✔
1355
        // down to ensure that the mailboxes are only ever under the control of
4✔
1356
        // one link.
4✔
1357
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
4✔
1358
        p.cfg.Switch.RemoveLink(chanID)
4✔
1359

4✔
1360
        // With the channel link created, we'll now notify the htlc switch so
4✔
1361
        // this channel can be used to dispatch local payments and also
4✔
1362
        // passively forward payments.
4✔
1363
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
4✔
1364
}
1365

1366
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1367
// one confirmed public channel exists with them.
1368
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
7✔
1369
        defer p.wg.Done()
7✔
1370

7✔
1371
        hasConfirmedPublicChan := false
7✔
1372
        for _, channel := range channels {
13✔
1373
                if channel.IsPending {
10✔
1374
                        continue
4✔
1375
                }
1376
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
12✔
1377
                        continue
6✔
1378
                }
1379

1380
                hasConfirmedPublicChan = true
4✔
1381
                break
4✔
1382
        }
1383
        if !hasConfirmedPublicChan {
14✔
1384
                return
7✔
1385
        }
7✔
1386

1387
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
4✔
1388
        if err != nil {
4✔
1389
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1390
                return
×
1391
        }
×
1392

1393
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
4✔
1394
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1395
        }
×
1396
}
1397

1398
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1399
// have any active channels with them.
1400
func (p *Brontide) maybeSendChannelUpdates() {
7✔
1401
        defer p.wg.Done()
7✔
1402

7✔
1403
        // If we don't have any active channels, then we can exit early.
7✔
1404
        if p.activeChannels.Len() == 0 {
12✔
1405
                return
5✔
1406
        }
5✔
1407

1408
        maybeSendUpd := func(cid lnwire.ChannelID,
6✔
1409
                lnChan *lnwallet.LightningChannel) error {
12✔
1410

6✔
1411
                // Nil channels are pending, so we'll skip them.
6✔
1412
                if lnChan == nil {
10✔
1413
                        return nil
4✔
1414
                }
4✔
1415

1416
                dbChan := lnChan.State()
6✔
1417
                scid := func() lnwire.ShortChannelID {
12✔
1418
                        switch {
6✔
1419
                        // Otherwise if it's a zero conf channel and confirmed,
1420
                        // then we need to use the "real" scid.
1421
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
4✔
1422
                                return dbChan.ZeroConfRealScid()
4✔
1423

1424
                        // Otherwise, we can use the normal scid.
1425
                        default:
6✔
1426
                                return dbChan.ShortChanID()
6✔
1427
                        }
1428
                }()
1429

1430
                // Now that we know the channel is in a good state, we'll try
1431
                // to fetch the update to send to the remote peer. If the
1432
                // channel is pending, and not a zero conf channel, we'll get
1433
                // an error here which we'll ignore.
1434
                chanUpd, err := p.cfg.FetchLastChanUpdate(scid)
6✔
1435
                if err != nil {
10✔
1436
                        p.log.Debugf("Unable to fetch channel update for "+
4✔
1437
                                "ChannelPoint(%v), scid=%v: %v",
4✔
1438
                                dbChan.FundingOutpoint, dbChan.ShortChanID, err)
4✔
1439

4✔
1440
                        return nil
4✔
1441
                }
4✔
1442

1443
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
6✔
1444
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
6✔
1445

6✔
1446
                // We'll send it as a normal message instead of using the lazy
6✔
1447
                // queue to prioritize transmission of the fresh update.
6✔
1448
                if err := p.SendMessage(false, chanUpd); err != nil {
6✔
1449
                        err := fmt.Errorf("unable to send channel update for "+
×
1450
                                "ChannelPoint(%v), scid=%v: %w",
×
1451
                                dbChan.FundingOutpoint, dbChan.ShortChanID(),
×
1452
                                err)
×
1453
                        p.log.Errorf(err.Error())
×
1454

×
1455
                        return err
×
1456
                }
×
1457

1458
                return nil
6✔
1459
        }
1460

1461
        p.activeChannels.ForEach(maybeSendUpd)
6✔
1462
}
1463

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

1481
        select {
4✔
1482
        case <-ready:
4✔
1483
        case <-p.quit:
1✔
1484
        }
1485

1486
        p.wg.Wait()
4✔
1487
}
1488

1489
// Disconnect terminates the connection with the remote peer. Additionally, a
1490
// signal is sent to the server and htlcSwitch indicating the resources
1491
// allocated to the peer can now be cleaned up.
1492
func (p *Brontide) Disconnect(reason error) {
4✔
1493
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
8✔
1494
                return
4✔
1495
        }
4✔
1496

1497
        // Make sure initialization has completed before we try to tear things
1498
        // down.
1499
        select {
4✔
1500
        case <-p.startReady:
4✔
1501
        case <-p.quit:
×
1502
                return
×
1503
        }
1504

1505
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
4✔
1506
        p.storeError(err)
4✔
1507

4✔
1508
        p.log.Infof(err.Error())
4✔
1509

4✔
1510
        // Stop PingManager before closing TCP connection.
4✔
1511
        p.pingManager.Stop()
4✔
1512

4✔
1513
        // Ensure that the TCP connection is properly closed before continuing.
4✔
1514
        p.cfg.Conn.Close()
4✔
1515

4✔
1516
        close(p.quit)
4✔
1517

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

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

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

1541
        pktLen, err := noiseConn.ReadNextHeader()
11✔
1542
        if err != nil {
15✔
1543
                return nil, fmt.Errorf("read next header: %w", err)
4✔
1544
        }
4✔
1545

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

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

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

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

1595
        p.logWireMessage(nextMsg, true)
8✔
1596

8✔
1597
        return nextMsg, nil
8✔
1598
}
1599

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

1608
        peer *Brontide
1609

1610
        apply func(lnwire.Message)
1611

1612
        startMsg string
1613
        stopMsg  string
1614

1615
        msgCond *sync.Cond
1616
        msgs    []lnwire.Message
1617

1618
        mtx sync.Mutex
1619

1620
        producerSema chan struct{}
1621

1622
        wg   sync.WaitGroup
1623
        quit chan struct{}
1624
}
1625

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

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

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

1652
        return stream
7✔
1653
}
1654

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

1661
// Stop stops the chanMsgStream.
1662
func (ms *msgStream) Stop() {
4✔
1663
        // TODO(roasbeef): signal too?
4✔
1664

4✔
1665
        close(ms.quit)
4✔
1666

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

1674
        ms.wg.Wait()
4✔
1675
}
1676

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

7✔
1684
        peerLog.Tracef(ms.startMsg)
7✔
1685

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

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

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

4✔
1714
                ms.msgCond.L.Unlock()
4✔
1715

4✔
1716
                ms.apply(msg)
4✔
1717

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

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

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

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

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

4✔
1765
        p.log.Tracef("Waiting for link=%v to be active", cid)
4✔
1766

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

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

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

1806
                        chanPoint := event.ChannelPoint
4✔
1807

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

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

1819
                case <-p.quit:
4✔
1820
                        return nil
4✔
1821
                }
1822
        }
1823
}
1824

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

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

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

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

1858
                chanLink.HandleChannelUpdate(msg)
4✔
1859
        }
1860

1861
        return newMsgStream(p,
4✔
1862
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
4✔
1863
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
4✔
1864
                1000,
4✔
1865
                apply,
4✔
1866
        )
4✔
1867
}
1868

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

1879
        return newMsgStream(
7✔
1880
                p,
7✔
1881
                "Update stream for gossiper created",
7✔
1882
                "Update stream for gossiper exited",
7✔
1883
                1000,
7✔
1884
                apply,
7✔
1885
        )
7✔
1886
}
1887

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

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

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

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

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

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

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

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

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

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

1982
                var (
5✔
1983
                        targetChan   lnwire.ChannelID
5✔
1984
                        isLinkUpdate bool
5✔
1985
                )
5✔
1986

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

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

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

2003
                case *lnwire.OpenChannel,
2004
                        *lnwire.AcceptChannel,
2005
                        *lnwire.FundingCreated,
2006
                        *lnwire.FundingSigned,
2007
                        *lnwire.ChannelReady:
4✔
2008

4✔
2009
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
4✔
2010

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

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

2028
                case *lnwire.Error:
4✔
2029
                        targetChan = msg.ChanID
4✔
2030
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
4✔
2031

2032
                case *lnwire.ChannelReestablish:
4✔
2033
                        targetChan = msg.ChanID
4✔
2034
                        isLinkUpdate = p.hasChannel(targetChan)
4✔
2035

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

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

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

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

4✔
2078
                        discStream.AddMsg(msg)
4✔
2079

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

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

×
2094
                        p.log.Errorf("%v", err)
×
2095
                }
2096

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

2103
                idleTimer.Reset(idleTimeout)
5✔
2104
        }
2105

2106
        p.Disconnect(errors.New("read handler closed"))
4✔
2107

4✔
2108
        p.log.Trace("readHandler for peer done")
4✔
2109
}
2110

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

2119
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
5✔
2120
}
2121

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

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

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

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

12✔
2153
        return channel != nil
12✔
2154
}
12✔
2155

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

2165
        return channel == nil
3✔
2166
}
2167

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

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

4✔
2182
        p.activeChannels.Range(func(_ lnwire.ChannelID,
4✔
2183
                channel *lnwallet.LightningChannel) bool {
8✔
2184

4✔
2185
                // Pending channels will be nil in the activeChannels map.
4✔
2186
                if channel == nil {
8✔
2187
                        // Return true to continue the iteration.
4✔
2188
                        return true
4✔
2189
                }
4✔
2190

2191
                haveChannels = true
4✔
2192

4✔
2193
                // Return false to break the iteration.
4✔
2194
                return false
4✔
2195
        })
2196

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

2204
        p.cfg.ErrorBuffer.Add(
4✔
2205
                &TimestampedError{Timestamp: time.Now(), Error: err},
4✔
2206
        )
4✔
2207
}
2208

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

4✔
2218
        if errMsg, ok := msg.(*lnwire.Error); ok {
8✔
2219
                p.storeError(errMsg)
4✔
2220
        }
4✔
2221

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

2230
                return false
×
2231

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

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

2242
        default:
4✔
2243
                return false
4✔
2244
        }
2245
}
2246

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

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

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

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

2272
        case *lnwire.FundingSigned:
4✔
2273
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
4✔
2274

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

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

2283
        case *lnwire.ClosingSigned:
4✔
2284
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
4✔
2285
                        msg.FeeSatoshis)
4✔
2286

2287
        case *lnwire.UpdateAddHTLC:
4✔
2288
                var blindingPoint []byte
4✔
2289
                msg.BlindingPoint.WhenSome(
4✔
2290
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
4✔
2291
                                *btcec.PublicKey]) {
8✔
2292

4✔
2293
                                blindingPoint = b.Val.SerializeCompressed()
4✔
2294
                        },
4✔
2295
                )
2296

2297
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
4✔
2298
                        "hash=%x, blinding_point=%x, custom_records=%v",
4✔
2299
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
4✔
2300
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
4✔
2301

2302
        case *lnwire.UpdateFailHTLC:
4✔
2303
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
4✔
2304
                        msg.ID, msg.Reason)
4✔
2305

2306
        case *lnwire.UpdateFulfillHTLC:
4✔
2307
                return fmt.Sprintf("chan_id=%v, id=%v, pre_image=%x, "+
4✔
2308
                        "custom_records=%v", msg.ChanID, msg.ID,
4✔
2309
                        msg.PaymentPreimage[:], msg.CustomRecords)
4✔
2310

2311
        case *lnwire.CommitSig:
4✔
2312
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
4✔
2313
                        len(msg.HtlcSigs))
4✔
2314

2315
        case *lnwire.RevokeAndAck:
4✔
2316
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
4✔
2317
                        msg.ChanID, msg.Revocation[:],
4✔
2318
                        msg.NextRevocationKey.SerializeCompressed())
4✔
2319

2320
        case *lnwire.UpdateFailMalformedHTLC:
4✔
2321
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
4✔
2322
                        msg.ChanID, msg.ID, msg.FailureCode)
4✔
2323

2324
        case *lnwire.Warning:
×
2325
                return fmt.Sprintf("%v", msg.Warning())
×
2326

2327
        case *lnwire.Error:
4✔
2328
                return fmt.Sprintf("%v", msg.Error())
4✔
2329

2330
        case *lnwire.AnnounceSignatures1:
4✔
2331
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
4✔
2332
                        msg.ShortChannelID.ToUint64())
4✔
2333

2334
        case *lnwire.ChannelAnnouncement1:
4✔
2335
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
4✔
2336
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
4✔
2337

2338
        case *lnwire.ChannelUpdate1:
4✔
2339
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
4✔
2340
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
4✔
2341
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
4✔
2342
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
4✔
2343

2344
        case *lnwire.NodeAnnouncement:
4✔
2345
                return fmt.Sprintf("node=%x, update_time=%v",
4✔
2346
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
4✔
2347

2348
        case *lnwire.Ping:
3✔
2349
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
3✔
2350

2351
        case *lnwire.Pong:
3✔
2352
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
3✔
2353

2354
        case *lnwire.UpdateFee:
×
2355
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2356
                        msg.ChanID, int64(msg.FeePerKw))
×
2357

2358
        case *lnwire.ChannelReestablish:
4✔
2359
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
4✔
2360
                        "remote_tail_height=%v", msg.ChanID,
4✔
2361
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
4✔
2362

2363
        case *lnwire.ReplyShortChanIDsEnd:
4✔
2364
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
4✔
2365
                        msg.Complete)
4✔
2366

2367
        case *lnwire.ReplyChannelRange:
4✔
2368
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
4✔
2369
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
4✔
2370
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
4✔
2371
                        msg.EncodingType)
4✔
2372

2373
        case *lnwire.QueryShortChanIDs:
4✔
2374
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
4✔
2375
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
4✔
2376

2377
        case *lnwire.QueryChannelRange:
4✔
2378
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
4✔
2379
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
4✔
2380
                        msg.LastBlockHeight())
4✔
2381

2382
        case *lnwire.GossipTimestampRange:
4✔
2383
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
4✔
2384
                        "stamp_range=%v", msg.ChainHash,
4✔
2385
                        time.Unix(int64(msg.FirstTimestamp), 0),
4✔
2386
                        msg.TimestampRange)
4✔
2387

2388
        case *lnwire.Stfu:
×
2389
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
×
2390
                        msg.Initiator)
×
2391

2392
        case *lnwire.Custom:
4✔
2393
                return fmt.Sprintf("type=%d", msg.Type)
4✔
2394
        }
2395

2396
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2397
}
2398

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

2410
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
25✔
2411
                // Debug summary of message.
4✔
2412
                summary := messageSummary(msg)
4✔
2413
                if len(summary) > 0 {
8✔
2414
                        summary = "(" + summary + ")"
4✔
2415
                }
4✔
2416

2417
                preposition := "to"
4✔
2418
                if read {
8✔
2419
                        preposition = "from"
4✔
2420
                }
4✔
2421

2422
                var msgType string
4✔
2423
                if msg.MsgType() < lnwire.CustomTypeStart {
8✔
2424
                        msgType = msg.MsgType().String()
4✔
2425
                } else {
8✔
2426
                        msgType = "custom"
4✔
2427
                }
4✔
2428

2429
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
4✔
2430
                        msgType, summary, preposition, p)
4✔
2431
        }))
2432

2433
        prefix := "readMessage from peer"
21✔
2434
        if !read {
38✔
2435
                prefix = "writeMessage to peer"
17✔
2436
        }
17✔
2437

2438
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
21✔
2439
}
2440

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

2458
        noiseConn := p.cfg.Conn
17✔
2459

17✔
2460
        flushMsg := func() error {
34✔
2461
                // Ensure the write deadline is set before we attempt to send
17✔
2462
                // the message.
17✔
2463
                writeDeadline := time.Now().Add(
17✔
2464
                        p.scaleTimeout(writeMessageTimeout),
17✔
2465
                )
17✔
2466
                err := noiseConn.SetWriteDeadline(writeDeadline)
17✔
2467
                if err != nil {
17✔
2468
                        return err
×
2469
                }
×
2470

2471
                // Flush the pending message to the wire. If an error is
2472
                // encountered, e.g. write timeout, the number of bytes written
2473
                // so far will be returned.
2474
                n, err := noiseConn.Flush()
17✔
2475

17✔
2476
                // Record the number of bytes written on the wire, if any.
17✔
2477
                if n > 0 {
21✔
2478
                        atomic.AddUint64(&p.bytesSent, uint64(n))
4✔
2479
                }
4✔
2480

2481
                return err
17✔
2482
        }
2483

2484
        // If the current message has already been serialized, encrypted, and
2485
        // buffered on the underlying connection we will skip straight to
2486
        // flushing it to the wire.
2487
        if msg == nil {
17✔
2488
                return flushMsg()
×
2489
        }
×
2490

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

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

2511
        return flushMsg()
17✔
2512
}
2513

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

2529
        var exitErr error
7✔
2530

7✔
2531
out:
7✔
2532
        for {
18✔
2533
                select {
11✔
2534
                case outMsg := <-p.sendQueue:
8✔
2535
                        // Record the time at which we first attempt to send the
8✔
2536
                        // message.
8✔
2537
                        startTime := time.Now()
8✔
2538

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

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

×
2560
                                goto retry
×
2561
                        }
2562

2563
                        // The write succeeded, reset the idle timer to prevent
2564
                        // us from disconnecting the peer.
2565
                        if !idleTimer.Stop() {
8✔
2566
                                select {
×
2567
                                case <-idleTimer.C:
×
2568
                                default:
×
2569
                                }
2570
                        }
2571
                        idleTimer.Reset(idleTimeout)
8✔
2572

8✔
2573
                        // If the peer requested a synchronous write, respond
8✔
2574
                        // with the error.
8✔
2575
                        if outMsg.errChan != nil {
13✔
2576
                                outMsg.errChan <- err
5✔
2577
                        }
5✔
2578

2579
                        if err != nil {
8✔
2580
                                exitErr = fmt.Errorf("unable to write "+
×
2581
                                        "message: %v", err)
×
2582
                                break out
×
2583
                        }
2584

2585
                case <-p.quit:
4✔
2586
                        exitErr = lnpeer.ErrPeerExiting
4✔
2587
                        break out
4✔
2588
                }
2589
        }
2590

2591
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2592
        // disconnect.
2593
        p.wg.Done()
4✔
2594

4✔
2595
        p.Disconnect(exitErr)
4✔
2596

4✔
2597
        p.log.Trace("writeHandler for peer done")
4✔
2598
}
2599

2600
// queueHandler is responsible for accepting messages from outside subsystems
2601
// to be eventually sent out on the wire by the writeHandler.
2602
//
2603
// NOTE: This method MUST be run as a goroutine.
2604
func (p *Brontide) queueHandler() {
7✔
2605
        defer p.wg.Done()
7✔
2606

7✔
2607
        // priorityMsgs holds an in order list of messages deemed high-priority
7✔
2608
        // to be added to the sendQueue. This predominately includes messages
7✔
2609
        // from the funding manager and htlcswitch.
7✔
2610
        priorityMsgs := list.New()
7✔
2611

7✔
2612
        // lazyMsgs holds an in order list of messages deemed low-priority to be
7✔
2613
        // added to the sendQueue only after all high-priority messages have
7✔
2614
        // been queued. This predominately includes messages from the gossiper.
7✔
2615
        lazyMsgs := list.New()
7✔
2616

7✔
2617
        for {
22✔
2618
                // Examine the front of the priority queue, if it is empty check
15✔
2619
                // the low priority queue.
15✔
2620
                elem := priorityMsgs.Front()
15✔
2621
                if elem == nil {
27✔
2622
                        elem = lazyMsgs.Front()
12✔
2623
                }
12✔
2624

2625
                if elem != nil {
23✔
2626
                        front := elem.Value.(outgoingMsg)
8✔
2627

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

2667
// PingTime returns the estimated ping time to the peer in microseconds.
2668
func (p *Brontide) PingTime() int64 {
4✔
2669
        return p.pingManager.GetPingTimeMicroSeconds()
4✔
2670
}
4✔
2671

2672
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2673
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2674
// or failed to write, and nil otherwise.
2675
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
29✔
2676
        p.queue(true, msg, errChan)
29✔
2677
}
29✔
2678

2679
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2680
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2681
// queue or failed to write, and nil otherwise.
2682
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
5✔
2683
        p.queue(false, msg, errChan)
5✔
2684
}
5✔
2685

2686
// queue sends a given message to the queueHandler using the passed priority. If
2687
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2688
// failed to write, and nil otherwise.
2689
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2690
        errChan chan error) {
30✔
2691

30✔
2692
        select {
30✔
2693
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
29✔
2694
        case <-p.quit:
4✔
2695
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
4✔
2696
                        spew.Sdump(msg))
4✔
2697
                if errChan != nil {
4✔
2698
                        errChan <- lnpeer.ErrPeerExiting
×
2699
                }
×
2700
        }
2701
}
2702

2703
// ChannelSnapshots returns a slice of channel snapshots detailing all
2704
// currently active channels maintained with the remote peer.
2705
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
4✔
2706
        snapshots := make(
4✔
2707
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
4✔
2708
        )
4✔
2709

4✔
2710
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
4✔
2711
                activeChan *lnwallet.LightningChannel) error {
8✔
2712

4✔
2713
                // If the activeChan is nil, then we skip it as the channel is
4✔
2714
                // pending.
4✔
2715
                if activeChan == nil {
8✔
2716
                        return nil
4✔
2717
                }
4✔
2718

2719
                // We'll only return a snapshot for channels that are
2720
                // *immediately* available for routing payments over.
2721
                if activeChan.RemoteNextRevocation() == nil {
8✔
2722
                        return nil
4✔
2723
                }
4✔
2724

2725
                snapshot := activeChan.StateSnapshot()
4✔
2726
                snapshots = append(snapshots, snapshot)
4✔
2727

4✔
2728
                return nil
4✔
2729
        })
2730

2731
        return snapshots
4✔
2732
}
2733

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

2744
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
10✔
2745
                addrType, false, lnwallet.DefaultAccountName,
10✔
2746
        )
10✔
2747
        if err != nil {
10✔
2748
                return nil, err
×
2749
        }
×
2750
        p.log.Infof("Delivery addr for channel close: %v",
10✔
2751
                deliveryAddr)
10✔
2752

10✔
2753
        return txscript.PayToAddrScript(deliveryAddr)
10✔
2754
}
2755

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

21✔
2764
        // reenableTimeout will fire once after the configured channel status
21✔
2765
        // interval has elapsed. This will trigger us to sign new channel
21✔
2766
        // updates and broadcast them with the "disabled" flag unset.
21✔
2767
        reenableTimeout := time.After(p.cfg.ChanActiveTimeout)
21✔
2768

21✔
2769
out:
21✔
2770
        for {
63✔
2771
                select {
42✔
2772
                // A new pending channel has arrived which means we are about
2773
                // to complete a funding workflow and is waiting for the final
2774
                // `ChannelReady` messages to be exchanged. We will add this
2775
                // channel to the `activeChannels` with a nil value to indicate
2776
                // this is a pending channel.
2777
                case req := <-p.newPendingChannel:
5✔
2778
                        p.handleNewPendingChannel(req)
5✔
2779

2780
                // A new channel has arrived which means we've just completed a
2781
                // funding workflow. We'll initialize the necessary local
2782
                // state, and notify the htlc switch of a new link.
2783
                case req := <-p.newActiveChannel:
4✔
2784
                        p.handleNewActiveChannel(req)
4✔
2785

2786
                // The funding flow for a pending channel is failed, we will
2787
                // remove it from Brontide.
2788
                case req := <-p.removePendingChannel:
5✔
2789
                        p.handleRemovePendingChannel(req)
5✔
2790

2791
                // We've just received a local request to close an active
2792
                // channel. It will either kick of a cooperative channel
2793
                // closure negotiation, or be a notification of a breached
2794
                // contract that should be abandoned.
2795
                case req := <-p.localCloseChanReqs:
11✔
2796
                        p.handleLocalCloseReq(req)
11✔
2797

2798
                // We've received a link failure from a link that was added to
2799
                // the switch. This will initiate the teardown of the link, and
2800
                // initiate any on-chain closures if necessary.
2801
                case failure := <-p.linkFailures:
4✔
2802
                        p.handleLinkFailure(failure)
4✔
2803

2804
                // We've received a new cooperative channel closure related
2805
                // message from the remote peer, we'll use this message to
2806
                // advance the chan closer state machine.
2807
                case closeMsg := <-p.chanCloseMsgs:
17✔
2808
                        p.handleCloseMsg(closeMsg)
17✔
2809

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

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

4✔
2828
                        // Once the reenabling is attempted, we also cancel the
4✔
2829
                        // channel event subscription to free up the overflow
4✔
2830
                        // queue used in channel notifier.
4✔
2831
                        //
4✔
2832
                        // NOTE: channelEventClient will be nil if the
4✔
2833
                        // reenableTimeout is greater than 1 minute.
4✔
2834
                        if p.channelEventClient != nil {
8✔
2835
                                p.channelEventClient.Cancel()
4✔
2836
                        }
4✔
2837

2838
                case <-p.quit:
4✔
2839
                        // As, we've been signalled to exit, we'll reset all
4✔
2840
                        // our active channel back to their default state.
4✔
2841
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
4✔
2842
                                lc *lnwallet.LightningChannel) error {
8✔
2843

4✔
2844
                                // Exit if the channel is nil as it's a pending
4✔
2845
                                // channel.
4✔
2846
                                if lc == nil {
8✔
2847
                                        return nil
4✔
2848
                                }
4✔
2849

2850
                                lc.ResetState()
4✔
2851

4✔
2852
                                return nil
4✔
2853
                        })
2854

2855
                        break out
4✔
2856
                }
2857
        }
2858
}
2859

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

4✔
2869
        // Create a map to hold channels that needs to be retried.
4✔
2870
        retryChans := make(map[wire.OutPoint]struct{}, len(activePublicChans))
4✔
2871

4✔
2872
        // For each of the public, non-pending channels, set the channel
4✔
2873
        // disabled bit to false and send out a new ChannelUpdate. If this
4✔
2874
        // channel is already active, the update won't be sent.
4✔
2875
        for _, chanPoint := range activePublicChans {
8✔
2876
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
4✔
2877

4✔
2878
                switch {
4✔
2879
                // No error occurred, continue to request the next channel.
2880
                case err == nil:
4✔
2881
                        continue
4✔
2882

2883
                // Cannot auto enable a manually disabled channel so we do
2884
                // nothing but proceed to the next channel.
2885
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
4✔
2886
                        p.log.Debugf("Channel(%v) was manually disabled, "+
4✔
2887
                                "ignoring automatic enable request", chanPoint)
4✔
2888

4✔
2889
                        continue
4✔
2890

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

×
2908
                                continue
×
2909
                        }
2910

2911
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
2912
                                "ChanStatusManager reported inactive, retrying")
×
2913

×
2914
                        // Add the channel to the retry map.
×
2915
                        retryChans[chanPoint] = struct{}{}
×
2916
                }
2917
        }
2918

2919
        // Retry the channels if we have any.
2920
        if len(retryChans) != 0 {
4✔
2921
                p.retryRequestEnable(retryChans)
×
2922
        }
×
2923
}
2924

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

17✔
2932
        chanCloser, found := p.activeChanCloses[chanID]
17✔
2933
        if found {
31✔
2934
                // An entry will only be found if the closer has already been
14✔
2935
                // created for a non-pending channel or for a channel that had
14✔
2936
                // previously started the shutdown process but the connection
14✔
2937
                // was restarted.
14✔
2938
                return chanCloser, nil
14✔
2939
        }
14✔
2940

2941
        // First, we'll ensure that we actually know of the target channel. If
2942
        // not, we'll ignore this message.
2943
        channel, ok := p.activeChannels.Load(chanID)
7✔
2944

7✔
2945
        // If the channel isn't in the map or the channel is nil, return
7✔
2946
        // ErrChannelNotFound as the channel is pending.
7✔
2947
        if !ok || channel == nil {
11✔
2948
                return nil, ErrChannelNotFound
4✔
2949
        }
4✔
2950

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

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

2980
        addr, err := p.addrWithInternalKey(deliveryScript).Unpack()
7✔
2981
        if err != nil {
7✔
2982
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
2983
        }
×
2984
        chanCloser, err = p.createChanCloser(
7✔
2985
                channel, addr, feePerKw, nil, lntypes.Remote,
7✔
2986
        )
7✔
2987
        if err != nil {
7✔
2988
                p.log.Errorf("unable to create chan closer: %v", err)
×
2989
                return nil, fmt.Errorf("unable to create chan closer")
×
2990
        }
×
2991

2992
        p.activeChanCloses[chanID] = chanCloser
7✔
2993

7✔
2994
        return chanCloser, nil
7✔
2995
}
2996

2997
// filterChannelsToEnable filters a list of channels to be enabled upon start.
2998
// The filtered channels are active channels that's neither private nor
2999
// pending.
3000
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
4✔
3001
        var activePublicChans []wire.OutPoint
4✔
3002

4✔
3003
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
4✔
3004
                lnChan *lnwallet.LightningChannel) bool {
8✔
3005

4✔
3006
                // If the lnChan is nil, continue as this is a pending channel.
4✔
3007
                if lnChan == nil {
4✔
UNCOV
3008
                        return true
×
UNCOV
3009
                }
×
3010

3011
                dbChan := lnChan.State()
4✔
3012
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
4✔
3013
                if !isPublic || dbChan.IsPending {
4✔
3014
                        return true
×
3015
                }
×
3016

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

3026
                activePublicChans = append(
4✔
3027
                        activePublicChans, dbChan.FundingOutpoint,
4✔
3028
                )
4✔
3029

4✔
3030
                return true
4✔
3031
        })
3032

3033
        return activePublicChans
4✔
3034
}
3035

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

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

×
3050
                // If this channel is irrelevant, return nil so the loop can
×
3051
                // jump to next iteration.
×
3052
                if !found {
×
3053
                        return nil
×
3054
                }
×
3055

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

×
3064
                // Send the request.
×
3065
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3066
                if err != nil {
×
3067
                        return fmt.Errorf("request enabling channel %v "+
×
3068
                                "failed: %w", chanPoint, err)
×
3069
                }
×
3070

3071
                return nil
×
3072
        }
3073

3074
        for {
×
3075
                // If activeChans is empty, we've done processing all the
×
3076
                // channels.
×
3077
                if len(activeChans) == 0 {
×
3078
                        p.log.Debug("Finished retry enabling channels")
×
3079
                        return
×
3080
                }
×
3081

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

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

3099
                                continue
×
3100
                        }
3101

3102
                        // Otherwise check for inactive link event, and jump to
3103
                        // next iteration if it's not.
3104
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3105
                        if !ok {
×
3106
                                continue
×
3107
                        }
3108

3109
                        // Found an inactive link event, if this is our
3110
                        // targeted channel, remove it from our map.
3111
                        chanPoint := *inactive.ChannelPoint
×
3112
                        _, found := activeChans[chanPoint]
×
3113
                        if !found {
×
3114
                                continue
×
3115
                        }
3116

3117
                        delete(activeChans, chanPoint)
×
3118
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3119
                                "inactive link event", chanPoint)
×
3120

3121
                case <-p.quit:
×
3122
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3123
                        return
×
3124
                }
3125
        }
3126
}
3127

3128
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3129
// a suitable script to close out to. This may be nil if neither script is
3130
// set. If both scripts are set, this function will error if they do not match.
3131
func chooseDeliveryScript(upfront,
3132
        requested lnwire.DeliveryAddress) (lnwire.DeliveryAddress, error) {
16✔
3133

16✔
3134
        // If no upfront shutdown script was provided, return the user
16✔
3135
        // requested address (which may be nil).
16✔
3136
        if len(upfront) == 0 {
26✔
3137
                return requested, nil
10✔
3138
        }
10✔
3139

3140
        // If an upfront shutdown script was provided, and the user did not
3141
        // request a custom shutdown script, return the upfront address.
3142
        if len(requested) == 0 {
16✔
3143
                return upfront, nil
6✔
3144
        }
6✔
3145

3146
        // If both an upfront shutdown script and a custom close script were
3147
        // provided, error if the user provided shutdown script does not match
3148
        // the upfront shutdown script (because closing out to a different
3149
        // script would violate upfront shutdown).
3150
        if !bytes.Equal(upfront, requested) {
6✔
3151
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
3152
        }
2✔
3153

3154
        // The user requested script matches the upfront shutdown script, so we
3155
        // can return it without error.
3156
        return upfront, nil
2✔
3157
}
3158

3159
// restartCoopClose checks whether we need to restart the cooperative close
3160
// process for a given channel.
3161
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3162
        *lnwire.Shutdown, error) {
×
3163

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

3182
        var deliveryScript []byte
×
3183

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

3193
        // An error other than ErrNoShutdownInfo was returned
3194
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3195
                return nil, err
×
3196

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

×
3206
                                return nil, fmt.Errorf("close addr unavailable")
×
3207
                        }
×
3208
                }
3209
        }
3210

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

3220
        // Determine whether we or the peer are the initiator of the coop
3221
        // close attempt by looking at the channel's status.
3222
        closingParty := lntypes.Remote
×
3223
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3224
                closingParty = lntypes.Local
×
3225
        }
×
3226

3227
        addr, err := p.addrWithInternalKey(deliveryScript).Unpack()
×
3228
        if err != nil {
×
3229
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3230
        }
×
3231
        chanCloser, err := p.createChanCloser(
×
3232
                lnChan, addr, feePerKw, nil, closingParty,
×
3233
        )
×
3234
        if err != nil {
×
3235
                p.log.Errorf("unable to create chan closer: %v", err)
×
3236
                return nil, fmt.Errorf("unable to create chan closer")
×
3237
        }
×
3238

3239
        // This does not need a mutex even though it is in a different
3240
        // goroutine since this is done before the channelManager goroutine is
3241
        // created.
3242
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
×
3243
        p.activeChanCloses[chanID] = chanCloser
×
3244

×
3245
        // Create the Shutdown message.
×
3246
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3247
        if err != nil {
×
3248
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3249
                delete(p.activeChanCloses, chanID)
×
3250
                return nil, err
×
3251
        }
×
3252

3253
        return shutdownMsg, nil
×
3254
}
3255

3256
// createChanCloser constructs a ChanCloser from the passed parameters and is
3257
// used to de-duplicate code.
3258
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3259
        deliveryScript chancloser.DeliveryAddrWithKey,
3260
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3261
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
13✔
3262

13✔
3263
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
13✔
3264
        if err != nil {
13✔
3265
                p.log.Errorf("unable to obtain best block: %v", err)
×
3266
                return nil, fmt.Errorf("cannot obtain best block")
×
3267
        }
×
3268

3269
        // The req will only be set if we initiated the co-op closing flow.
3270
        var maxFee chainfee.SatPerKWeight
13✔
3271
        if req != nil {
23✔
3272
                maxFee = req.MaxFee
10✔
3273
        }
10✔
3274

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

3301
        return chanCloser, nil
13✔
3302
}
3303

3304
// handleLocalCloseReq kicks-off the workflow to execute a cooperative or
3305
// forced unilateral closure of the channel initiated by a local subsystem.
3306
func (p *Brontide) handleLocalCloseReq(req *htlcswitch.ChanClose) {
11✔
3307
        chanID := lnwire.NewChanIDFromOutPoint(*req.ChanPoint)
11✔
3308

11✔
3309
        channel, ok := p.activeChannels.Load(chanID)
11✔
3310

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

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

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

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

×
3360
                        return
×
3361
                }
×
3362
                chanCloser, err := p.createChanCloser(
10✔
3363
                        channel, addr, req.TargetFeePerKw, req, lntypes.Local,
10✔
3364
                )
10✔
3365
                if err != nil {
10✔
3366
                        p.log.Errorf(err.Error())
×
3367
                        req.Err <- err
×
3368
                        return
×
3369
                }
×
3370

3371
                p.activeChanCloses[chanID] = chanCloser
10✔
3372

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

×
3382
                        // As we were unable to shutdown the channel, we'll
×
3383
                        // return it back to its normal state.
×
3384
                        channel.ResetState()
×
3385
                        return
×
3386
                }
×
3387

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

3401
                if !link.DisableAdds(htlcswitch.Outgoing) {
10✔
3402
                        p.log.Warnf("Outgoing link adds already "+
×
3403
                                "disabled: %v", link.ChanID())
×
3404
                }
×
3405

3406
                link.OnCommitOnce(htlcswitch.Outgoing, func() {
20✔
3407
                        p.queueMsg(shutdownMsg, nil)
10✔
3408
                })
10✔
3409

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

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

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

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

4✔
3450
        // If the error encountered was severe enough, we'll now force close
4✔
3451
        // the channel to prevent reading it to the switch in the future.
4✔
3452
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureForceClose {
8✔
3453
                p.log.Warnf("Force closing link(%v)", failure.shortChanID)
4✔
3454

4✔
3455
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
4✔
3456
                        failure.chanPoint,
4✔
3457
                )
4✔
3458
                if err != nil {
8✔
3459
                        p.log.Errorf("unable to force close "+
4✔
3460
                                "link(%v): %v", failure.shortChanID, err)
4✔
3461
                } else {
8✔
3462
                        p.log.Infof("channel(%v) force "+
4✔
3463
                                "closed with txid %v",
4✔
3464
                                failure.shortChanID, closeTx.TxHash())
4✔
3465
                }
4✔
3466
        }
3467

3468
        // If this is a permanent failure, we will mark the channel borked.
3469
        if failure.linkErr.PermanentFailure && lnChan != nil {
4✔
3470
                p.log.Warnf("Marking link(%v) borked due to permanent "+
×
3471
                        "failure", failure.shortChanID)
×
3472

×
3473
                if err := lnChan.State().MarkBorked(); err != nil {
×
3474
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
3475
                                failure.shortChanID, err)
×
3476
                }
×
3477
        }
3478

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

3490
                var networkMsg lnwire.Message
4✔
3491
                if failure.linkErr.Warning {
4✔
3492
                        networkMsg = &lnwire.Warning{
×
3493
                                ChanID: failure.chanID,
×
3494
                                Data:   data,
×
3495
                        }
×
3496
                } else {
4✔
3497
                        networkMsg = &lnwire.Error{
4✔
3498
                                ChanID: failure.chanID,
4✔
3499
                                Data:   data,
4✔
3500
                        }
4✔
3501
                }
4✔
3502

3503
                err := p.SendMessage(true, networkMsg)
4✔
3504
                if err != nil {
4✔
3505
                        p.log.Errorf("unable to send msg to "+
×
3506
                                "remote peer: %v", err)
×
3507
                }
×
3508
        }
3509

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

3518
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
3519
// public key and the channel id.
3520
func (p *Brontide) fetchLinkFromKeyAndCid(
3521
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
23✔
3522

23✔
3523
        var chanLink htlcswitch.ChannelUpdateHandler
23✔
3524

23✔
3525
        // We don't need to check the error here, and can instead just loop
23✔
3526
        // over the slice and return nil.
23✔
3527
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
23✔
3528
        for _, link := range links {
45✔
3529
                if link.ChanID() == cid {
44✔
3530
                        chanLink = link
22✔
3531
                        break
22✔
3532
                }
3533
        }
3534

3535
        return chanLink
23✔
3536
}
3537

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

8✔
3546
        // First, we'll clear all indexes related to the channel in question.
8✔
3547
        chanPoint := chanCloser.Channel().ChannelPoint()
8✔
3548
        p.WipeChannel(&chanPoint)
8✔
3549

8✔
3550
        // Also clear the activeChanCloses map of this channel.
8✔
3551
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
8✔
3552
        delete(p.activeChanCloses, cid)
8✔
3553

8✔
3554
        // Next, we'll launch a goroutine which will request to be notified by
8✔
3555
        // the ChainNotifier once the closure transaction obtains a single
8✔
3556
        // confirmation.
8✔
3557
        notifier := p.cfg.ChainNotifier
8✔
3558

8✔
3559
        // If any error happens during waitForChanToClose, forward it to
8✔
3560
        // closeReq. If this channel closure is not locally initiated, closeReq
8✔
3561
        // will be nil, so just ignore the error.
8✔
3562
        errChan := make(chan error, 1)
8✔
3563
        if closeReq != nil {
14✔
3564
                errChan = closeReq.Err
6✔
3565
        }
6✔
3566

3567
        closingTx, err := chanCloser.ClosingTx()
8✔
3568
        if err != nil {
8✔
3569
                if closeReq != nil {
×
3570
                        p.log.Error(err)
×
3571
                        closeReq.Err <- err
×
3572
                }
×
3573
        }
3574

3575
        closingTxid := closingTx.TxHash()
8✔
3576

8✔
3577
        // If this is a locally requested shutdown, update the caller with a
8✔
3578
        // new event detailing the current pending state of this request.
8✔
3579
        if closeReq != nil {
14✔
3580
                closeReq.Updates <- &PendingUpdate{
6✔
3581
                        Txid: closingTxid[:],
6✔
3582
                }
6✔
3583
        }
6✔
3584

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

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

8✔
3615
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
8✔
3616
                "with txid: %v", chanPoint, closingTxID)
8✔
3617

8✔
3618
        // TODO(roasbeef): add param for num needed confs
8✔
3619
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
8✔
3620
                closingTxID, closeScript, 1, bestHeight,
8✔
3621
        )
8✔
3622
        if err != nil {
8✔
3623
                if errChan != nil {
×
3624
                        errChan <- err
×
3625
                }
×
3626
                return
×
3627
        }
3628

3629
        // In the case that the ChainNotifier is shutting down, all subscriber
3630
        // notification channels will be closed, generating a nil receive.
3631
        height, ok := <-confNtfn.Confirmed
8✔
3632
        if !ok {
12✔
3633
                return
4✔
3634
        }
4✔
3635

3636
        // The channel has been closed, remove it from any active indexes, and
3637
        // the database state.
3638
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
8✔
3639
                "height %v", chanPoint, height.BlockHeight)
8✔
3640

8✔
3641
        // Finally, execute the closure call back to mark the confirmation of
8✔
3642
        // the transaction closing the contract.
8✔
3643
        cb()
8✔
3644
}
3645

3646
// WipeChannel removes the passed channel point from all indexes associated with
3647
// the peer and the switch.
3648
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
8✔
3649
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
8✔
3650

8✔
3651
        p.activeChannels.Delete(chanID)
8✔
3652

8✔
3653
        // Instruct the HtlcSwitch to close this link as the channel is no
8✔
3654
        // longer active.
8✔
3655
        p.cfg.Switch.RemoveLink(chanID)
8✔
3656
}
8✔
3657

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

3669
        // Then, finalize the remote feature vector providing the flattened
3670
        // feature bit namespace.
3671
        p.remoteFeatures = lnwire.NewFeatureVector(
7✔
3672
                msg.Features, lnwire.Features,
7✔
3673
        )
7✔
3674

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

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

3690
        // Now that we know we understand their requirements, we'll check to
3691
        // see if they don't support anything that we deem to be mandatory.
3692
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
7✔
3693
                return fmt.Errorf("data loss protection required")
×
3694
        }
×
3695

3696
        return nil
7✔
3697
}
3698

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

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

3717
// hasNegotiatedScidAlias returns true if we've negotiated the
3718
// option-scid-alias feature bit with the peer.
3719
func (p *Brontide) hasNegotiatedScidAlias() bool {
7✔
3720
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
7✔
3721
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
7✔
3722
        return peerHas && localHas
7✔
3723
}
7✔
3724

3725
// sendInitMsg sends the Init message to the remote peer. This message contains
3726
// our currently supported local and global features.
3727
func (p *Brontide) sendInitMsg(legacyChan bool) error {
11✔
3728
        features := p.cfg.Features.Clone()
11✔
3729
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
11✔
3730

11✔
3731
        // If we have a legacy channel open with a peer, we downgrade static
11✔
3732
        // remote required to optional in case the peer does not understand the
11✔
3733
        // required feature bit. If we do not do this, the peer will reject our
11✔
3734
        // connection because it does not understand a required feature bit, and
11✔
3735
        // our channel will be unusable.
11✔
3736
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
12✔
3737
                p.log.Infof("Legacy channel open with peer, " +
1✔
3738
                        "downgrading static remote required feature bit to " +
1✔
3739
                        "optional")
1✔
3740

1✔
3741
                // Unset and set in both the local and global features to
1✔
3742
                // ensure both sets are consistent and merge able by old and
1✔
3743
                // new nodes.
1✔
3744
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3745
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3746

1✔
3747
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
3748
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
3749
        }
1✔
3750

3751
        msg := lnwire.NewInitMessage(
11✔
3752
                legacyFeatures.RawFeatureVector,
11✔
3753
                features.RawFeatureVector,
11✔
3754
        )
11✔
3755

11✔
3756
        return p.writeMessage(msg)
11✔
3757
}
3758

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

3768
        // Check if we have any channel sync messages stored for this channel.
3769
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
4✔
3770
        if err != nil {
8✔
3771
                return fmt.Errorf("unable to fetch channel sync messages for "+
4✔
3772
                        "peer %v: %v", p, err)
4✔
3773
        }
4✔
3774

3775
        if c.LastChanSyncMsg == nil {
4✔
3776
                return fmt.Errorf("no chan sync message stored for channel %v",
×
3777
                        cid)
×
3778
        }
×
3779

3780
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
4✔
3781
                return fmt.Errorf("ignoring channel reestablish from "+
×
3782
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
3783
        }
×
3784

3785
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
4✔
3786
                "peer", cid)
4✔
3787

4✔
3788
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
4✔
3789
                return fmt.Errorf("failed resending channel sync "+
×
3790
                        "message to peer %v: %v", p, err)
×
3791
        }
×
3792

3793
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
4✔
3794
                cid)
4✔
3795

4✔
3796
        // Note down that we sent the message, so we won't resend it again for
4✔
3797
        // this connection.
4✔
3798
        p.resentChanSyncMsg[cid] = struct{}{}
4✔
3799

4✔
3800
        return nil
4✔
3801
}
3802

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

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

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

3844
                if priority {
15✔
3845
                        p.queueMsg(msg, errChan)
7✔
3846
                } else {
12✔
3847
                        p.queueMsgLazy(msg, errChan)
5✔
3848
                }
5✔
3849
        }
3850

3851
        // Wait for all replies from the writeHandler. For async sends, this
3852
        // will be a NOP as the list of error chans is nil.
3853
        for _, errChan := range errChans {
13✔
3854
                select {
5✔
3855
                case err := <-errChan:
5✔
3856
                        return err
5✔
3857
                case <-p.quit:
×
3858
                        return lnpeer.ErrPeerExiting
×
3859
                case <-p.cfg.Quit:
×
3860
                        return lnpeer.ErrPeerExiting
×
3861
                }
3862
        }
3863

3864
        return nil
7✔
3865
}
3866

3867
// PubKey returns the pubkey of the peer in compressed serialized format.
3868
//
3869
// NOTE: Part of the lnpeer.Peer interface.
3870
func (p *Brontide) PubKey() [33]byte {
6✔
3871
        return p.cfg.PubKeyBytes
6✔
3872
}
6✔
3873

3874
// IdentityKey returns the public key of the remote peer.
3875
//
3876
// NOTE: Part of the lnpeer.Peer interface.
3877
func (p *Brontide) IdentityKey() *btcec.PublicKey {
19✔
3878
        return p.cfg.Addr.IdentityKey
19✔
3879
}
19✔
3880

3881
// Address returns the network address of the remote peer.
3882
//
3883
// NOTE: Part of the lnpeer.Peer interface.
3884
func (p *Brontide) Address() net.Addr {
4✔
3885
        return p.cfg.Addr.Address
4✔
3886
}
4✔
3887

3888
// AddNewChannel adds a new channel to the peer. The channel should fail to be
3889
// added if the cancel channel is closed.
3890
//
3891
// NOTE: Part of the lnpeer.Peer interface.
3892
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
3893
        cancel <-chan struct{}) error {
4✔
3894

4✔
3895
        errChan := make(chan error, 1)
4✔
3896
        newChanMsg := &newChannelMsg{
4✔
3897
                channel: newChan,
4✔
3898
                err:     errChan,
4✔
3899
        }
4✔
3900

4✔
3901
        select {
4✔
3902
        case p.newActiveChannel <- newChanMsg:
4✔
3903
        case <-cancel:
×
3904
                return errors.New("canceled adding new channel")
×
3905
        case <-p.quit:
×
3906
                return lnpeer.ErrPeerExiting
×
3907
        }
3908

3909
        // We pause here to wait for the peer to recognize the new channel
3910
        // before we close the channel barrier corresponding to the channel.
3911
        select {
4✔
3912
        case err := <-errChan:
4✔
3913
                return err
4✔
3914
        case <-p.quit:
×
3915
                return lnpeer.ErrPeerExiting
×
3916
        }
3917
}
3918

3919
// AddPendingChannel adds a pending open channel to the peer. The channel
3920
// should fail to be added if the cancel channel is closed.
3921
//
3922
// NOTE: Part of the lnpeer.Peer interface.
3923
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
3924
        cancel <-chan struct{}) error {
4✔
3925

4✔
3926
        errChan := make(chan error, 1)
4✔
3927
        newChanMsg := &newChannelMsg{
4✔
3928
                channelID: cid,
4✔
3929
                err:       errChan,
4✔
3930
        }
4✔
3931

4✔
3932
        select {
4✔
3933
        case p.newPendingChannel <- newChanMsg:
4✔
3934

3935
        case <-cancel:
×
3936
                return errors.New("canceled adding pending channel")
×
3937

3938
        case <-p.quit:
×
3939
                return lnpeer.ErrPeerExiting
×
3940
        }
3941

3942
        // We pause here to wait for the peer to recognize the new pending
3943
        // channel before we close the channel barrier corresponding to the
3944
        // channel.
3945
        select {
4✔
3946
        case err := <-errChan:
4✔
3947
                return err
4✔
3948

3949
        case <-cancel:
×
3950
                return errors.New("canceled adding pending channel")
×
3951

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

3957
// RemovePendingChannel removes a pending open channel from the peer.
3958
//
3959
// NOTE: Part of the lnpeer.Peer interface.
3960
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
4✔
3961
        errChan := make(chan error, 1)
4✔
3962
        newChanMsg := &newChannelMsg{
4✔
3963
                channelID: cid,
4✔
3964
                err:       errChan,
4✔
3965
        }
4✔
3966

4✔
3967
        select {
4✔
3968
        case p.removePendingChannel <- newChanMsg:
4✔
3969
        case <-p.quit:
×
3970
                return lnpeer.ErrPeerExiting
×
3971
        }
3972

3973
        // We pause here to wait for the peer to respond to the cancellation of
3974
        // the pending channel before we close the channel barrier
3975
        // corresponding to the channel.
3976
        select {
4✔
3977
        case err := <-errChan:
4✔
3978
                return err
4✔
3979

3980
        case <-p.quit:
×
3981
                return lnpeer.ErrPeerExiting
×
3982
        }
3983
}
3984

3985
// StartTime returns the time at which the connection was established if the
3986
// peer started successfully, and zero otherwise.
3987
func (p *Brontide) StartTime() time.Time {
4✔
3988
        return p.startTime
4✔
3989
}
4✔
3990

3991
// handleCloseMsg is called when a new cooperative channel closure related
3992
// message is received from the remote peer. We'll use this message to advance
3993
// the chan closer state machine.
3994
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
17✔
3995
        link := p.fetchLinkFromKeyAndCid(msg.cid)
17✔
3996

17✔
3997
        // We'll now fetch the matching closing state machine in order to continue,
17✔
3998
        // or finalize the channel closure process.
17✔
3999
        chanCloser, err := p.fetchActiveChanCloser(msg.cid)
17✔
4000
        if err != nil {
21✔
4001
                // If the channel is not known to us, we'll simply ignore this message.
4✔
4002
                if err == ErrChannelNotFound {
8✔
4003
                        return
4✔
4004
                }
4✔
4005

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

×
4008
                errMsg := &lnwire.Error{
×
4009
                        ChanID: msg.cid,
×
4010
                        Data:   lnwire.ErrorData(err.Error()),
×
4011
                }
×
4012
                p.queueMsg(errMsg, nil)
×
4013
                return
×
4014
        }
4015

4016
        handleErr := func(err error) {
17✔
UNCOV
4017
                err = fmt.Errorf("unable to process close msg: %w", err)
×
UNCOV
4018
                p.log.Error(err)
×
UNCOV
4019

×
UNCOV
4020
                // As the negotiations failed, we'll reset the channel state machine to
×
UNCOV
4021
                // ensure we act to on-chain events as normal.
×
UNCOV
4022
                chanCloser.Channel().ResetState()
×
UNCOV
4023

×
UNCOV
4024
                if chanCloser.CloseRequest() != nil {
×
4025
                        chanCloser.CloseRequest().Err <- err
×
4026
                }
×
UNCOV
4027
                delete(p.activeChanCloses, msg.cid)
×
UNCOV
4028

×
UNCOV
4029
                p.Disconnect(err)
×
4030
        }
4031

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

4042
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
9✔
4043
                if err != nil {
9✔
4044
                        handleErr(err)
×
4045
                        return
×
4046
                }
×
4047

4048
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
16✔
4049
                        // If the link is nil it means we can immediately queue
7✔
4050
                        // the Shutdown message since we don't have to wait for
7✔
4051
                        // commitment transaction synchronization.
7✔
4052
                        if link == nil {
8✔
4053
                                p.queueMsg(&msg, nil)
1✔
4054
                                return
1✔
4055
                        }
1✔
4056

4057
                        // Immediately disallow any new HTLC's from being added
4058
                        // in the outgoing direction.
4059
                        if !link.DisableAdds(htlcswitch.Outgoing) {
6✔
4060
                                p.log.Warnf("Outgoing link adds already "+
×
4061
                                        "disabled: %v", link.ChanID())
×
4062
                        }
×
4063

4064
                        // When we have a Shutdown to send, we defer it till the
4065
                        // next time we send a CommitSig to remain spec
4066
                        // compliant.
4067
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
12✔
4068
                                p.queueMsg(&msg, nil)
6✔
4069
                        })
6✔
4070
                })
4071

4072
                beginNegotiation := func() {
18✔
4073
                        oClosingSigned, err := chanCloser.BeginNegotiation()
9✔
4074
                        if err != nil {
9✔
UNCOV
4075
                                handleErr(err)
×
UNCOV
4076
                                return
×
UNCOV
4077
                        }
×
4078

4079
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
18✔
4080
                                p.queueMsg(&msg, nil)
9✔
4081
                        })
9✔
4082
                }
4083

4084
                if link == nil {
10✔
4085
                        beginNegotiation()
1✔
4086
                } else {
9✔
4087
                        // Now we register a flush hook to advance the
8✔
4088
                        // ChanCloser and possibly send out a ClosingSigned
8✔
4089
                        // when the link finishes draining.
8✔
4090
                        link.OnFlushedOnce(func() {
16✔
4091
                                // Remove link in goroutine to prevent deadlock.
8✔
4092
                                go p.cfg.Switch.RemoveLink(msg.cid)
8✔
4093
                                beginNegotiation()
8✔
4094
                        })
8✔
4095
                }
4096

4097
        case *lnwire.ClosingSigned:
12✔
4098
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
12✔
4099
                if err != nil {
12✔
4100
                        handleErr(err)
×
4101
                        return
×
4102
                }
×
4103

4104
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
24✔
4105
                        p.queueMsg(&msg, nil)
12✔
4106
                })
12✔
4107

4108
        default:
×
4109
                panic("impossible closeMsg type")
×
4110
        }
4111

4112
        // If we haven't finished close negotiations, then we'll continue as we
4113
        // can't yet finalize the closure.
4114
        if _, err := chanCloser.ClosingTx(); err != nil {
28✔
4115
                return
12✔
4116
        }
12✔
4117

4118
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
4119
        // the channel closure by notifying relevant sub-systems and launching a
4120
        // goroutine to wait for close tx conf.
4121
        p.finalizeChanClosure(chanCloser)
8✔
4122
}
4123

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

4138
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
4139
func (p *Brontide) NetAddress() *lnwire.NetAddress {
4✔
4140
        return p.cfg.Addr
4✔
4141
}
4✔
4142

4143
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
4144
func (p *Brontide) Inbound() bool {
4✔
4145
        return p.cfg.Inbound
4✔
4146
}
4✔
4147

4148
// ConnReq is a getter for the Brontide's connReq in cfg.
4149
func (p *Brontide) ConnReq() *connmgr.ConnReq {
4✔
4150
        return p.cfg.ConnReq
4✔
4151
}
4✔
4152

4153
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
4154
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
4✔
4155
        return p.cfg.ErrorBuffer
4✔
4156
}
4✔
4157

4158
// SetAddress sets the remote peer's address given an address.
4159
func (p *Brontide) SetAddress(address net.Addr) {
×
4160
        p.cfg.Addr.Address = address
×
4161
}
×
4162

4163
// ActiveSignal returns the peer's active signal.
4164
func (p *Brontide) ActiveSignal() chan struct{} {
4✔
4165
        return p.activeSignal
4✔
4166
}
4✔
4167

4168
// Conn returns a pointer to the peer's connection struct.
4169
func (p *Brontide) Conn() net.Conn {
4✔
4170
        return p.cfg.Conn
4✔
4171
}
4✔
4172

4173
// BytesReceived returns the number of bytes received from the peer.
4174
func (p *Brontide) BytesReceived() uint64 {
4✔
4175
        return atomic.LoadUint64(&p.bytesReceived)
4✔
4176
}
4✔
4177

4178
// BytesSent returns the number of bytes sent to the peer.
4179
func (p *Brontide) BytesSent() uint64 {
4✔
4180
        return atomic.LoadUint64(&p.bytesSent)
4✔
4181
}
4✔
4182

4183
// LastRemotePingPayload returns the last payload the remote party sent as part
4184
// of their ping.
4185
func (p *Brontide) LastRemotePingPayload() []byte {
4✔
4186
        pingPayload := p.lastPingPayload.Load()
4✔
4187
        if pingPayload == nil {
8✔
4188
                return []byte{}
4✔
4189
        }
4✔
4190

4191
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
2✔
4192
        if !ok {
2✔
4193
                return nil
×
4194
        }
×
4195

4196
        return pingBytes
2✔
4197
}
4198

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

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

4220
        p.channelEventClient = sub
7✔
4221

7✔
4222
        return nil
7✔
4223
}
4224

4225
// updateNextRevocation updates the existing channel's next revocation if it's
4226
// nil.
4227
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
7✔
4228
        chanPoint := c.FundingOutpoint
7✔
4229
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
7✔
4230

7✔
4231
        // Read the current channel.
7✔
4232
        currentChan, loaded := p.activeChannels.Load(chanID)
7✔
4233

7✔
4234
        // currentChan should exist, but we perform a check anyway to avoid nil
7✔
4235
        // pointer dereference.
7✔
4236
        if !loaded {
8✔
4237
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
4238
                        chanID)
1✔
4239
        }
1✔
4240

4241
        // currentChan should not be nil, but we perform a check anyway to
4242
        // avoid nil pointer dereference.
4243
        if currentChan == nil {
7✔
4244
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
4245
                        chanID)
1✔
4246
        }
1✔
4247

4248
        // If we're being sent a new channel, and our existing channel doesn't
4249
        // have the next revocation, then we need to update the current
4250
        // existing channel.
4251
        if currentChan.RemoteNextRevocation() != nil {
5✔
4252
                return nil
×
4253
        }
×
4254

4255
        p.log.Infof("Processing retransmitted ChannelReady for "+
5✔
4256
                "ChannelPoint(%v)", chanPoint)
5✔
4257

5✔
4258
        nextRevoke := c.RemoteNextRevocation
5✔
4259

5✔
4260
        err := currentChan.InitNextRevocation(nextRevoke)
5✔
4261
        if err != nil {
5✔
4262
                return fmt.Errorf("unable to init next revocation: %w", err)
×
4263
        }
×
4264

4265
        return nil
5✔
4266
}
4267

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

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

4✔
4282
        chanOpts := c.ChanOpts
4✔
4283
        if shouldReestablish {
8✔
4284
                // If we have to do the reestablish dance for this channel,
4✔
4285
                // ensure that we don't try to call InitRemoteMusigNonces twice
4✔
4286
                // by calling SkipNonceInit.
4✔
4287
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
4✔
4288
        }
4✔
4289

4290
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
4✔
4291
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
4292
        })
×
4293
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
4✔
4294
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
4295
        })
×
4296

4297
        // If not already active, we'll add this channel to the set of active
4298
        // channels, so we can look it up later easily according to its channel
4299
        // ID.
4300
        lnChan, err := lnwallet.NewLightningChannel(
4✔
4301
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
4✔
4302
        )
4✔
4303
        if err != nil {
4✔
4304
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
4305
        }
×
4306

4307
        // Store the channel in the activeChannels map.
4308
        p.activeChannels.Store(chanID, lnChan)
4✔
4309

4✔
4310
        p.log.Infof("New channel active ChannelPoint(%v) with peer", chanPoint)
4✔
4311

4✔
4312
        // Next, we'll assemble a ChannelLink along with the necessary items it
4✔
4313
        // needs to function.
4✔
4314
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
4✔
4315
        if err != nil {
4✔
4316
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
4317
                        err)
×
4318
        }
×
4319

4320
        // We'll query the channel DB for the new channel's initial forwarding
4321
        // policies to determine the policy we start out with.
4322
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
4✔
4323
        if err != nil {
4✔
4324
                return fmt.Errorf("unable to query for initial forwarding "+
×
4325
                        "policy: %v", err)
×
4326
        }
×
4327

4328
        // Create the link and add it to the switch.
4329
        err = p.addLink(
4✔
4330
                &chanPoint, lnChan, initialPolicy, chainEvents,
4✔
4331
                shouldReestablish, fn.None[lnwire.Shutdown](),
4✔
4332
        )
4✔
4333
        if err != nil {
4✔
4334
                return fmt.Errorf("can't register new channel link(%v) with "+
×
4335
                        "peer", chanPoint)
×
4336
        }
×
4337

4338
        return nil
4✔
4339
}
4340

4341
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
4342
// know this channel ID or not, we'll either add it to the `activeChannels` map
4343
// or init the next revocation for it.
4344
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
4✔
4345
        newChan := req.channel
4✔
4346
        chanPoint := newChan.FundingOutpoint
4✔
4347
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
4348

4✔
4349
        // Only update RemoteNextRevocation if the channel is in the
4✔
4350
        // activeChannels map and if we added the link to the switch. Only
4✔
4351
        // active channels will be added to the switch.
4✔
4352
        if p.isActiveChannel(chanID) {
8✔
4353
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
4✔
4354
                        chanPoint)
4✔
4355

4✔
4356
                // Handle it and close the err chan on the request.
4✔
4357
                close(req.err)
4✔
4358

4✔
4359
                // Update the next revocation point.
4✔
4360
                err := p.updateNextRevocation(newChan.OpenChannel)
4✔
4361
                if err != nil {
4✔
4362
                        p.log.Errorf(err.Error())
×
4363
                }
×
4364

4365
                return
4✔
4366
        }
4367

4368
        // This is a new channel, we now add it to the map.
4369
        if err := p.addActiveChannel(req.channel); err != nil {
4✔
4370
                // Log and send back the error to the request.
×
4371
                p.log.Errorf(err.Error())
×
4372
                req.err <- err
×
4373

×
4374
                return
×
4375
        }
×
4376

4377
        // Close the err chan if everything went fine.
4378
        close(req.err)
4✔
4379
}
4380

4381
// handleNewPendingChannel takes a `newChannelMsg` request and add it to
4382
// `activeChannels` map with nil value. This pending channel will be saved as
4383
// it may become active in the future. Once active, the funding manager will
4384
// send it again via `AddNewChannel`, and we'd handle the link creation there.
4385
func (p *Brontide) handleNewPendingChannel(req *newChannelMsg) {
8✔
4386
        defer close(req.err)
8✔
4387

8✔
4388
        chanID := req.channelID
8✔
4389

8✔
4390
        // If we already have this channel, something is wrong with the funding
8✔
4391
        // flow as it will only be marked as active after `ChannelReady` is
8✔
4392
        // handled. In this case, we will do nothing but log an error, just in
8✔
4393
        // case this is a legit channel.
8✔
4394
        if p.isActiveChannel(chanID) {
9✔
4395
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
4396
                        "pending channel request", chanID)
1✔
4397

1✔
4398
                return
1✔
4399
        }
1✔
4400

4401
        // The channel has already been added, we will do nothing and return.
4402
        if p.isPendingChannel(chanID) {
8✔
4403
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
4404
                        "pending channel request", chanID)
1✔
4405

1✔
4406
                return
1✔
4407
        }
1✔
4408

4409
        // This is a new channel, we now add it to the map `activeChannels`
4410
        // with nil value and mark it as a newly added channel in
4411
        // `addedChannels`.
4412
        p.activeChannels.Store(chanID, nil)
6✔
4413
        p.addedChannels.Store(chanID, struct{}{})
6✔
4414
}
4415

4416
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
4417
// from `activeChannels` map. The request will be ignored if the channel is
4418
// considered active by Brontide. Noop if the channel ID cannot be found.
4419
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
8✔
4420
        defer close(req.err)
8✔
4421

8✔
4422
        chanID := req.channelID
8✔
4423

8✔
4424
        // If we already have this channel, something is wrong with the funding
8✔
4425
        // flow as it will only be marked as active after `ChannelReady` is
8✔
4426
        // handled. In this case, we will log an error and exit.
8✔
4427
        if p.isActiveChannel(chanID) {
9✔
4428
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
4429
                        chanID)
1✔
4430
                return
1✔
4431
        }
1✔
4432

4433
        // The channel has not been added yet, we will log a warning as there
4434
        // is an unexpected call from funding manager.
4435
        if !p.isPendingChannel(chanID) {
12✔
4436
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
5✔
4437
        }
5✔
4438

4439
        // Remove the record of this pending channel.
4440
        p.activeChannels.Delete(chanID)
7✔
4441
        p.addedChannels.Delete(chanID)
7✔
4442
}
4443

4444
// sendLinkUpdateMsg sends a message that updates the channel to the
4445
// channel's message stream.
4446
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
4✔
4447
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
4✔
4448

4✔
4449
        chanStream, ok := p.activeMsgStreams[cid]
4✔
4450
        if !ok {
8✔
4451
                // If a stream hasn't yet been created, then we'll do so, add
4✔
4452
                // it to the map, and finally start it.
4✔
4453
                chanStream = newChanMsgStream(p, cid)
4✔
4454
                p.activeMsgStreams[cid] = chanStream
4✔
4455
                chanStream.Start()
4✔
4456

4✔
4457
                // Stop the stream when quit.
4✔
4458
                go func() {
8✔
4459
                        <-p.quit
4✔
4460
                        chanStream.Stop()
4✔
4461
                }()
4✔
4462
        }
4463

4464
        // With the stream obtained, add the message to the stream so we can
4465
        // continue processing message.
4466
        chanStream.AddMsg(msg)
4✔
4467
}
4468

4469
// scaleTimeout multiplies the argument duration by a constant factor depending
4470
// on variious heuristics. Currently this is only used to check whether our peer
4471
// appears to be connected over Tor and relaxes the timout deadline. However,
4472
// this is subject to change and should be treated as opaque.
4473
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
71✔
4474
        if p.isTorConnection {
75✔
4475
                return timeout * time.Duration(torTimeoutMultiplier)
4✔
4476
        }
4✔
4477

4478
        return timeout
67✔
4479
}
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