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

lightningnetwork / lnd / 12231552240

09 Dec 2024 08:17AM UTC coverage: 58.955% (+0.02%) from 58.933%
12231552240

Pull #9242

github

aakselrod
go.mod: update btcwallet to latest to eliminate waddrmgr deadlock
Pull Request #9242: Reapply #8644

24 of 40 new or added lines in 3 files covered. (60.0%)

89 existing lines in 18 files now uncovered.

133525 of 226485 relevant lines covered (58.96%)

19398.62 hits per line

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

78.03
/peer/brontide.go
1
package peer
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

121
        err chan error
122
}
123

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

418
        // DisallowQuiescence is a flag that indicates whether the Brontide
419
        // should have the quiescence feature disabled.
420
        DisallowQuiescence bool
421

422
        // MaxFeeExposure limits the number of outstanding fees in a channel.
423
        // This value will be passed to created links.
424
        MaxFeeExposure lnwire.MilliSatoshi
425

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

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

435
        // ShouldFwdExpEndorsement is a closure that indicates whether
436
        // experimental endorsement signals should be set.
437
        ShouldFwdExpEndorsement func() bool
438

439
        // Quit is the server's quit channel. If this is closed, we halt operation.
440
        Quit chan struct{}
441
}
442

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

454
        // MUST be used atomically.
455
        bytesReceived uint64
456
        bytesSent     uint64
457

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

475
        pingManager *PingManager
476

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

484
        cfg Config
485

486
        // activeSignal when closed signals that the peer is now active and
487
        // ready to process messages.
488
        activeSignal chan struct{}
489

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

494
        // sendQueue is the channel which is used to queue outgoing messages to be
495
        // written onto the wire. Note that this channel is unbuffered.
496
        sendQueue chan outgoingMsg
497

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

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

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

521
        // newActiveChannel is used by the fundingManager to send fully opened
522
        // channels to the source peer which handled the funding workflow.
523
        newActiveChannel chan *newChannelMsg
524

525
        // newPendingChannel is used by the fundingManager to send pending open
526
        // channels to the source peer which handled the funding workflow.
527
        newPendingChannel chan *newChannelMsg
528

529
        // removePendingChannel is used by the fundingManager to cancel pending
530
        // open channels to the source peer when the funding flow is failed.
531
        removePendingChannel chan *newChannelMsg
532

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

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

543
        // localCloseChanReqs is a channel in which any local requests to close
544
        // a particular channel are sent over.
545
        localCloseChanReqs chan *htlcswitch.ChanClose
546

547
        // linkFailures receives all reported channel failures from the switch,
548
        // and instructs the channelManager to clean remaining channel state.
549
        linkFailures chan linkFailureReport
550

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

556
        // remoteFeatures is the feature vector received from the peer during
557
        // the connection handshake.
558
        remoteFeatures *lnwire.FeatureVector
559

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

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

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

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

584
        startReady chan struct{}
585
        quit       chan struct{}
586
        wg         sync.WaitGroup
587

588
        // log is a peer-specific logging instance.
589
        log btclog.Logger
590
}
591

592
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer interface.
593
var _ lnpeer.Peer = (*Brontide)(nil)
594

595
// NewBrontide creates a new Brontide from a peer.Config struct.
596
func NewBrontide(cfg Config) *Brontide {
29✔
597
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
29✔
598

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

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

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

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

29✔
636
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
33✔
637
                remoteAddr := cfg.Conn.RemoteAddr().String()
4✔
638
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
4✔
639
                        strings.Contains(remoteAddr, "127.0.0.1")
4✔
640
        }
4✔
641

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

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

669
                return lastSerializedBlockHeader[:]
1✔
670
        }
671

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

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

701
        return p
29✔
702
}
703

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

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

7✔
716
        p.log.Tracef("starting with conn[%v->%v]",
7✔
717
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
7✔
718

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

730
        if len(activeChans) == 0 {
12✔
731
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
5✔
732
        }
5✔
733

734
        // Quickly check if we have any existing legacy channels with this
735
        // peer.
736
        haveLegacyChan := false
7✔
737
        for _, c := range activeChans {
13✔
738
                if c.ChanType.IsTweakless() {
12✔
739
                        continue
6✔
740
                }
741

742
                haveLegacyChan = true
4✔
743
                break
4✔
744
        }
745

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

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

7✔
761
                msg, err := p.readNextMessage()
7✔
762
                if err != nil {
7✔
UNCOV
763
                        readErr <- err
×
UNCOV
764
                        msgChan <- nil
×
UNCOV
765
                        return
×
UNCOV
766
                }
×
767
                readErr <- nil
7✔
768
                msgChan <- msg
7✔
769
        }()
770

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

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

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

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

813
        // Register the message router now as we may need to register some
814
        // endpoints while loading the channels below.
815
        p.msgRouter.WhenSome(func(router msgmux.Router) {
14✔
816
                router.Start()
7✔
817
        })
7✔
818

819
        msgs, err := p.loadActiveChannels(activeChans)
7✔
820
        if err != nil {
7✔
821
                return fmt.Errorf("unable to load channels: %w", err)
×
822
        }
×
823

824
        p.startTime = time.Now()
7✔
825

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

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

843
        err = p.pingManager.Start()
7✔
844
        if err != nil {
7✔
845
                return fmt.Errorf("could not start ping manager %w", err)
×
846
        }
×
847

848
        p.wg.Add(4)
7✔
849
        go p.queueHandler()
7✔
850
        go p.writeHandler()
7✔
851
        go p.channelManager()
7✔
852
        go p.readHandler()
7✔
853

7✔
854
        // Signal to any external processes that the peer is now active.
7✔
855
        close(p.activeSignal)
7✔
856

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

7✔
872
        return nil
7✔
873
}
874

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

7✔
883
                if p.cfg.AuthGossiper == nil {
10✔
884
                        // This should only ever be hit in the unit tests.
3✔
885
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
3✔
886
                                "gossip sync.")
3✔
887
                        return
3✔
888
                }
3✔
889

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

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

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

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

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

937
        return &chancloser.DeliveryAddrWithKey{
13✔
938
                DeliveryAddress: deliveryScript,
13✔
939
                InternalKey: fn.MapOption(
13✔
940
                        func(desc keychain.KeyDescriptor) btcec.PublicKey {
17✔
941
                                return *desc.PubKey
4✔
942
                        },
4✔
943
                )(internalKeyDesc),
944
        }, nil
945
}
946

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

7✔
954
        // Return a slice of messages to send to the peers in case the channel
7✔
955
        // cannot be loaded normally.
7✔
956
        var msgs []lnwire.Message
7✔
957

7✔
958
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
7✔
959

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

980
                                err = p.cfg.AddLocalAlias(
4✔
981
                                        aliasScid, dbChan.ShortChanID(), false,
4✔
982
                                        false,
4✔
983
                                )
4✔
984
                                if err != nil {
4✔
985
                                        return nil, err
×
986
                                }
×
987

988
                                chanID := lnwire.NewChanIDFromOutPoint(
4✔
989
                                        dbChan.FundingOutpoint,
4✔
990
                                )
4✔
991

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

999
                                channelReadyMsg := lnwire.NewChannelReady(
4✔
1000
                                        chanID, second,
4✔
1001
                                )
4✔
1002
                                channelReadyMsg.AliasScid = &aliasScid
4✔
1003

4✔
1004
                                msgs = append(msgs, channelReadyMsg)
4✔
1005
                        }
1006

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

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

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

1041
                chanPoint := dbChan.FundingOutpoint
6✔
1042

6✔
1043
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
6✔
1044

6✔
1045
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
6✔
1046
                        chanPoint, lnChan.IsPending())
6✔
1047

6✔
1048
                // Skip adding any permanently irreconcilable channels to the
6✔
1049
                // htlcswitch.
6✔
1050
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
6✔
1051
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
12✔
1052

6✔
1053
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
6✔
1054
                                "start.", chanPoint, dbChan.ChanStatus())
6✔
1055

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

1070
                        msgs = append(msgs, chanSync)
6✔
1071

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

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

1087
                                if shutdownMsg == nil {
×
1088
                                        continue
×
1089
                                }
1090

1091
                                // Append the message to the set of messages to
1092
                                // send.
1093
                                msgs = append(msgs, shutdownMsg)
×
1094
                        }
1095

1096
                        continue
6✔
1097
                }
1098

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

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

4✔
1121
                        selfPolicy = p1
4✔
1122
                } else {
8✔
1123
                        selfPolicy = p2
4✔
1124
                }
4✔
1125

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

1139
                        inboundFee := models.NewInboundFeeFromWire(
4✔
1140
                                inboundWireFee,
4✔
1141
                        )
4✔
1142

4✔
1143
                        forwardingPolicy = &models.ForwardingPolicy{
4✔
1144
                                MinHTLCOut:    selfPolicy.MinHTLC,
4✔
1145
                                MaxHTLC:       selfPolicy.MaxHTLC,
4✔
1146
                                BaseFee:       selfPolicy.FeeBaseMSat,
4✔
1147
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
4✔
1148
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
4✔
1149

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

1159
                p.log.Tracef("Using link policy of: %v",
4✔
1160
                        spew.Sdump(forwardingPolicy))
4✔
1161

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

4✔
1171
                        continue
4✔
1172
                }
1173

1174
                shutdownInfo, err := lnChan.State().ShutdownInfo()
4✔
1175
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
4✔
1176
                        return nil, err
×
1177
                }
×
1178

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

×
1192
                                return
×
1193
                        }
×
1194

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

×
1210
                                return
×
1211
                        }
×
1212

1213
                        chanID := lnwire.NewChanIDFromOutPoint(
4✔
1214
                                lnChan.State().FundingOutpoint,
4✔
1215
                        )
4✔
1216

4✔
1217
                        p.activeChanCloses[chanID] = chanCloser
4✔
1218

4✔
1219
                        // Create the Shutdown message.
4✔
1220
                        shutdown, err := chanCloser.ShutdownChan()
4✔
1221
                        if err != nil {
4✔
1222
                                delete(p.activeChanCloses, chanID)
×
1223
                                shutdownInfoErr = err
×
1224

×
1225
                                return
×
1226
                        }
×
1227

1228
                        shutdownMsg = fn.Some(*shutdown)
4✔
1229
                })
1230
                if shutdownInfoErr != nil {
4✔
1231
                        return nil, shutdownInfoErr
×
1232
                }
×
1233

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

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

1251
                p.activeChannels.Store(chanID, lnChan)
4✔
1252
        }
1253

1254
        return msgs, nil
7✔
1255
}
1256

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

4✔
1264
        // onChannelFailure will be called by the link in case the channel
4✔
1265
        // fails for some reason.
4✔
1266
        onChannelFailure := func(chanID lnwire.ChannelID,
4✔
1267
                shortChanID lnwire.ShortChannelID,
4✔
1268
                linkErr htlcswitch.LinkFailureError) {
8✔
1269

4✔
1270
                failure := linkFailureReport{
4✔
1271
                        chanPoint:   *chanPoint,
4✔
1272
                        chanID:      chanID,
4✔
1273
                        shortChanID: shortChanID,
4✔
1274
                        linkErr:     linkErr,
4✔
1275
                }
4✔
1276

4✔
1277
                select {
4✔
1278
                case p.linkFailures <- failure:
4✔
1279
                case <-p.quit:
×
1280
                case <-p.cfg.Quit:
×
1281
                }
1282
        }
1283

1284
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
8✔
1285
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
4✔
1286
        }
4✔
1287

1288
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
8✔
1289
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
4✔
1290
        }
4✔
1291

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

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

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

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

7✔
1358
        hasConfirmedPublicChan := false
7✔
1359
        for _, channel := range channels {
13✔
1360
                if channel.IsPending {
10✔
1361
                        continue
4✔
1362
                }
1363
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
12✔
1364
                        continue
6✔
1365
                }
1366

1367
                hasConfirmedPublicChan = true
4✔
1368
                break
4✔
1369
        }
1370
        if !hasConfirmedPublicChan {
14✔
1371
                return
7✔
1372
        }
7✔
1373

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

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

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

7✔
1390
        // If we don't have any active channels, then we can exit early.
7✔
1391
        if p.activeChannels.Len() == 0 {
12✔
1392
                return
5✔
1393
        }
5✔
1394

1395
        maybeSendUpd := func(cid lnwire.ChannelID,
6✔
1396
                lnChan *lnwallet.LightningChannel) error {
12✔
1397

6✔
1398
                // Nil channels are pending, so we'll skip them.
6✔
1399
                if lnChan == nil {
10✔
1400
                        return nil
4✔
1401
                }
4✔
1402

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

1411
                        // Otherwise, we can use the normal scid.
1412
                        default:
6✔
1413
                                return dbChan.ShortChanID()
6✔
1414
                        }
1415
                }()
1416

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

4✔
1427
                        return nil
4✔
1428
                }
4✔
1429

1430
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
6✔
1431
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
6✔
1432

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

×
1442
                        return err
×
1443
                }
×
1444

1445
                return nil
6✔
1446
        }
1447

1448
        p.activeChannels.ForEach(maybeSendUpd)
6✔
1449
}
1450

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

1468
        select {
4✔
1469
        case <-ready:
4✔
UNCOV
1470
        case <-p.quit:
×
1471
        }
1472

1473
        p.wg.Wait()
4✔
1474
}
1475

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

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

4✔
1493
                select {
4✔
1494
                case <-p.startReady:
4✔
1495
                case <-p.quit:
×
1496
                        return
×
1497
                }
1498
        }
1499

1500
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
4✔
1501
        p.storeError(err)
4✔
1502

4✔
1503
        p.log.Infof(err.Error())
4✔
1504

4✔
1505
        // Stop PingManager before closing TCP connection.
4✔
1506
        p.pingManager.Stop()
4✔
1507

4✔
1508
        // Ensure that the TCP connection is properly closed before continuing.
4✔
1509
        p.cfg.Conn.Close()
4✔
1510

4✔
1511
        close(p.quit)
4✔
1512

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

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

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

1536
        pktLen, err := noiseConn.ReadNextHeader()
11✔
1537
        if err != nil {
15✔
1538
                return nil, fmt.Errorf("read next header: %w", err)
4✔
1539
        }
4✔
1540

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

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

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

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

1590
        p.logWireMessage(nextMsg, true)
8✔
1591

8✔
1592
        return nextMsg, nil
8✔
1593
}
1594

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

1603
        peer *Brontide
1604

1605
        apply func(lnwire.Message)
1606

1607
        startMsg string
1608
        stopMsg  string
1609

1610
        msgCond *sync.Cond
1611
        msgs    []lnwire.Message
1612

1613
        mtx sync.Mutex
1614

1615
        producerSema chan struct{}
1616

1617
        wg   sync.WaitGroup
1618
        quit chan struct{}
1619
}
1620

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

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

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

1647
        return stream
7✔
1648
}
1649

1650
// Start starts the chanMsgStream.
1651
func (ms *msgStream) Start() {
7✔
1652
        ms.wg.Add(1)
7✔
1653
        go ms.msgConsumer()
7✔
1654
}
7✔
1655

1656
// Stop stops the chanMsgStream.
1657
func (ms *msgStream) Stop() {
4✔
1658
        // TODO(roasbeef): signal too?
4✔
1659

4✔
1660
        close(ms.quit)
4✔
1661

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

1669
        ms.wg.Wait()
4✔
1670
}
1671

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

7✔
1679
        peerLog.Tracef(ms.startMsg)
7✔
1680

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

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

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

4✔
1709
                ms.msgCond.L.Unlock()
4✔
1710

4✔
1711
                ms.apply(msg)
4✔
1712

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

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

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

4✔
1749
        // With the message added, we signal to the msgConsumer that there are
4✔
1750
        // additional messages to consume.
4✔
1751
        ms.msgCond.Signal()
4✔
1752
}
1753

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

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

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

4✔
1780
        // The link may already be active by this point, and we may have missed the
4✔
1781
        // ActiveLinkEvent. Check if the link exists.
4✔
1782
        link := p.fetchLinkFromKeyAndCid(cid)
4✔
1783
        if link != nil {
8✔
1784
                return link
4✔
1785
        }
4✔
1786

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

1801
                        chanPoint := event.ChannelPoint
4✔
1802

4✔
1803
                        // Check whether the retrieved chanPoint matches the target
4✔
1804
                        // channel id.
4✔
1805
                        if !cid.IsChanPoint(chanPoint) {
4✔
1806
                                continue
×
1807
                        }
1808

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

1814
                case <-p.quit:
4✔
1815
                        return nil
4✔
1816
                }
1817
        }
1818
}
1819

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

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

4✔
1836
                        // If the link is still not active and the calling function
4✔
1837
                        // errored out, just return.
4✔
1838
                        if chanLink == nil {
8✔
1839
                                p.log.Warnf("Link=%v is not active", cid)
4✔
1840
                                return
4✔
1841
                        }
4✔
1842
                }
1843

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

1853
                chanLink.HandleChannelUpdate(msg)
4✔
1854
        }
1855

1856
        return newMsgStream(p,
4✔
1857
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
4✔
1858
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
4✔
1859
                1000,
4✔
1860
                apply,
4✔
1861
        )
4✔
1862
}
1863

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

1874
        return newMsgStream(
7✔
1875
                p,
7✔
1876
                "Update stream for gossiper created",
7✔
1877
                "Update stream for gossiper exited",
7✔
1878
                1000,
7✔
1879
                apply,
7✔
1880
        )
7✔
1881
}
1882

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

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

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

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

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

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

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

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

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

1971
                // No error occurred, and the message was handled by the
1972
                // router.
1973
                if err == nil {
5✔
1974
                        continue
×
1975
                }
1976

1977
                var (
5✔
1978
                        targetChan   lnwire.ChannelID
5✔
1979
                        isLinkUpdate bool
5✔
1980
                )
5✔
1981

5✔
1982
                switch msg := nextMsg.(type) {
5✔
1983
                case *lnwire.Pong:
1✔
1984
                        // When we receive a Pong message in response to our
1✔
1985
                        // last ping message, we send it to the pingManager
1✔
1986
                        p.pingManager.ReceivedPong(msg)
1✔
1987

1988
                case *lnwire.Ping:
1✔
1989
                        // First, we'll store their latest ping payload within
1✔
1990
                        // the relevant atomic variable.
1✔
1991
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
1✔
1992

1✔
1993
                        // Next, we'll send over the amount of specified pong
1✔
1994
                        // bytes.
1✔
1995
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
1✔
1996
                        p.queueMsg(pong, nil)
1✔
1997

1998
                case *lnwire.OpenChannel,
1999
                        *lnwire.AcceptChannel,
2000
                        *lnwire.FundingCreated,
2001
                        *lnwire.FundingSigned,
2002
                        *lnwire.ChannelReady:
4✔
2003

4✔
2004
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
4✔
2005

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

2019
                case *lnwire.Warning:
×
2020
                        targetChan = msg.ChanID
×
2021
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2022

2023
                case *lnwire.Error:
4✔
2024
                        targetChan = msg.ChanID
4✔
2025
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
4✔
2026

2027
                case *lnwire.ChannelReestablish:
4✔
2028
                        targetChan = msg.ChanID
4✔
2029
                        isLinkUpdate = p.hasChannel(targetChan)
4✔
2030

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

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

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

2063
                case *lnwire.ChannelUpdate1,
2064
                        *lnwire.ChannelAnnouncement1,
2065
                        *lnwire.NodeAnnouncement,
2066
                        *lnwire.AnnounceSignatures1,
2067
                        *lnwire.GossipTimestampRange,
2068
                        *lnwire.QueryShortChanIDs,
2069
                        *lnwire.QueryChannelRange,
2070
                        *lnwire.ReplyChannelRange,
2071
                        *lnwire.ReplyShortChanIDsEnd:
4✔
2072

4✔
2073
                        discStream.AddMsg(msg)
4✔
2074

2075
                case *lnwire.Custom:
5✔
2076
                        err := p.handleCustomMessage(msg)
5✔
2077
                        if err != nil {
5✔
2078
                                p.storeError(err)
×
2079
                                p.log.Errorf("%v", err)
×
2080
                        }
×
2081

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

×
2089
                        p.log.Errorf("%v", err)
×
2090
                }
2091

2092
                if isLinkUpdate {
9✔
2093
                        // If this is a channel update, then we need to feed it
4✔
2094
                        // into the channel's in-order message stream.
4✔
2095
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
4✔
2096
                }
4✔
2097

2098
                idleTimer.Reset(idleTimeout)
5✔
2099
        }
2100

2101
        p.Disconnect(errors.New("read handler closed"))
4✔
2102

4✔
2103
        p.log.Trace("readHandler for peer done")
4✔
2104
}
2105

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

2114
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
5✔
2115
}
2116

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

2128
        // Return false if the channel is unknown.
2129
        channel, ok := p.activeChannels.Load(chanID)
4✔
2130
        if !ok {
4✔
2131
                return false
×
2132
        }
×
2133

2134
        // During startup, we will use a nil value to mark a pending channel
2135
        // that's loaded from disk.
2136
        return channel == nil
4✔
2137
}
2138

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

12✔
2148
        return channel != nil
12✔
2149
}
12✔
2150

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

2160
        return channel == nil
3✔
2161
}
2162

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

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

4✔
2177
        p.activeChannels.Range(func(_ lnwire.ChannelID,
4✔
2178
                channel *lnwallet.LightningChannel) bool {
8✔
2179

4✔
2180
                // Pending channels will be nil in the activeChannels map.
4✔
2181
                if channel == nil {
8✔
2182
                        // Return true to continue the iteration.
4✔
2183
                        return true
4✔
2184
                }
4✔
2185

2186
                haveChannels = true
4✔
2187

4✔
2188
                // Return false to break the iteration.
4✔
2189
                return false
4✔
2190
        })
2191

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

2199
        p.cfg.ErrorBuffer.Add(
4✔
2200
                &TimestampedError{Timestamp: time.Now(), Error: err},
4✔
2201
        )
4✔
2202
}
2203

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

4✔
2213
        if errMsg, ok := msg.(*lnwire.Error); ok {
8✔
2214
                p.storeError(errMsg)
4✔
2215
        }
4✔
2216

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

2225
                return false
×
2226

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

2233
        // If not we hand the message to the channel link for this channel.
2234
        case p.isActiveChannel(chanID):
4✔
2235
                return true
4✔
2236

2237
        default:
4✔
2238
                return false
4✔
2239
        }
2240
}
2241

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

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

2258
        case *lnwire.AcceptChannel:
4✔
2259
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
4✔
2260
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
4✔
2261
                        msg.MinAcceptDepth)
4✔
2262

2263
        case *lnwire.FundingCreated:
4✔
2264
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
4✔
2265
                        msg.PendingChannelID[:], msg.FundingPoint)
4✔
2266

2267
        case *lnwire.FundingSigned:
4✔
2268
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
4✔
2269

2270
        case *lnwire.ChannelReady:
4✔
2271
                return fmt.Sprintf("chan_id=%v, next_point=%x",
4✔
2272
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
4✔
2273

2274
        case *lnwire.Shutdown:
4✔
2275
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
4✔
2276
                        msg.Address[:])
4✔
2277

2278
        case *lnwire.ClosingSigned:
4✔
2279
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
4✔
2280
                        msg.FeeSatoshis)
4✔
2281

2282
        case *lnwire.UpdateAddHTLC:
4✔
2283
                var blindingPoint []byte
4✔
2284
                msg.BlindingPoint.WhenSome(
4✔
2285
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
4✔
2286
                                *btcec.PublicKey]) {
8✔
2287

4✔
2288
                                blindingPoint = b.Val.SerializeCompressed()
4✔
2289
                        },
4✔
2290
                )
2291

2292
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
4✔
2293
                        "hash=%x, blinding_point=%x, custom_records=%v",
4✔
2294
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
4✔
2295
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
4✔
2296

2297
        case *lnwire.UpdateFailHTLC:
4✔
2298
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
4✔
2299
                        msg.ID, msg.Reason)
4✔
2300

2301
        case *lnwire.UpdateFulfillHTLC:
4✔
2302
                return fmt.Sprintf("chan_id=%v, id=%v, pre_image=%x, "+
4✔
2303
                        "custom_records=%v", msg.ChanID, msg.ID,
4✔
2304
                        msg.PaymentPreimage[:], msg.CustomRecords)
4✔
2305

2306
        case *lnwire.CommitSig:
4✔
2307
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
4✔
2308
                        len(msg.HtlcSigs))
4✔
2309

2310
        case *lnwire.RevokeAndAck:
4✔
2311
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
4✔
2312
                        msg.ChanID, msg.Revocation[:],
4✔
2313
                        msg.NextRevocationKey.SerializeCompressed())
4✔
2314

2315
        case *lnwire.UpdateFailMalformedHTLC:
4✔
2316
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
4✔
2317
                        msg.ChanID, msg.ID, msg.FailureCode)
4✔
2318

2319
        case *lnwire.Warning:
×
2320
                return fmt.Sprintf("%v", msg.Warning())
×
2321

2322
        case *lnwire.Error:
4✔
2323
                return fmt.Sprintf("%v", msg.Error())
4✔
2324

2325
        case *lnwire.AnnounceSignatures1:
4✔
2326
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
4✔
2327
                        msg.ShortChannelID.ToUint64())
4✔
2328

2329
        case *lnwire.ChannelAnnouncement1:
4✔
2330
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
4✔
2331
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
4✔
2332

2333
        case *lnwire.ChannelUpdate1:
4✔
2334
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
4✔
2335
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
4✔
2336
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
4✔
2337
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
4✔
2338

2339
        case *lnwire.NodeAnnouncement:
4✔
2340
                return fmt.Sprintf("node=%x, update_time=%v",
4✔
2341
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
4✔
2342

2343
        case *lnwire.Ping:
1✔
2344
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
1✔
2345

2346
        case *lnwire.Pong:
1✔
2347
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
1✔
2348

2349
        case *lnwire.UpdateFee:
×
2350
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2351
                        msg.ChanID, int64(msg.FeePerKw))
×
2352

2353
        case *lnwire.ChannelReestablish:
4✔
2354
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
4✔
2355
                        "remote_tail_height=%v", msg.ChanID,
4✔
2356
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
4✔
2357

2358
        case *lnwire.ReplyShortChanIDsEnd:
4✔
2359
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
4✔
2360
                        msg.Complete)
4✔
2361

2362
        case *lnwire.ReplyChannelRange:
4✔
2363
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
4✔
2364
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
4✔
2365
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
4✔
2366
                        msg.EncodingType)
4✔
2367

2368
        case *lnwire.QueryShortChanIDs:
4✔
2369
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
4✔
2370
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
4✔
2371

2372
        case *lnwire.QueryChannelRange:
4✔
2373
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
4✔
2374
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
4✔
2375
                        msg.LastBlockHeight())
4✔
2376

2377
        case *lnwire.GossipTimestampRange:
4✔
2378
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
4✔
2379
                        "stamp_range=%v", msg.ChainHash,
4✔
2380
                        time.Unix(int64(msg.FirstTimestamp), 0),
4✔
2381
                        msg.TimestampRange)
4✔
2382

2383
        case *lnwire.Stfu:
4✔
2384
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
4✔
2385
                        msg.Initiator)
4✔
2386

2387
        case *lnwire.Custom:
4✔
2388
                return fmt.Sprintf("type=%d", msg.Type)
4✔
2389
        }
2390

2391
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2392
}
2393

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

2405
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
25✔
2406
                // Debug summary of message.
4✔
2407
                summary := messageSummary(msg)
4✔
2408
                if len(summary) > 0 {
8✔
2409
                        summary = "(" + summary + ")"
4✔
2410
                }
4✔
2411

2412
                preposition := "to"
4✔
2413
                if read {
8✔
2414
                        preposition = "from"
4✔
2415
                }
4✔
2416

2417
                var msgType string
4✔
2418
                if msg.MsgType() < lnwire.CustomTypeStart {
8✔
2419
                        msgType = msg.MsgType().String()
4✔
2420
                } else {
8✔
2421
                        msgType = "custom"
4✔
2422
                }
4✔
2423

2424
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
4✔
2425
                        msgType, summary, preposition, p)
4✔
2426
        }))
2427

2428
        prefix := "readMessage from peer"
21✔
2429
        if !read {
38✔
2430
                prefix = "writeMessage to peer"
17✔
2431
        }
17✔
2432

2433
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
21✔
2434
}
2435

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

2453
        noiseConn := p.cfg.Conn
17✔
2454

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

2466
                // Flush the pending message to the wire. If an error is
2467
                // encountered, e.g. write timeout, the number of bytes written
2468
                // so far will be returned.
2469
                n, err := noiseConn.Flush()
17✔
2470

17✔
2471
                // Record the number of bytes written on the wire, if any.
17✔
2472
                if n > 0 {
21✔
2473
                        atomic.AddUint64(&p.bytesSent, uint64(n))
4✔
2474
                }
4✔
2475

2476
                return err
17✔
2477
        }
2478

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

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

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

2506
        return flushMsg()
17✔
2507
}
2508

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

2524
        var exitErr error
7✔
2525

7✔
2526
out:
7✔
2527
        for {
18✔
2528
                select {
11✔
2529
                case outMsg := <-p.sendQueue:
8✔
2530
                        // Record the time at which we first attempt to send the
8✔
2531
                        // message.
8✔
2532
                        startTime := time.Now()
8✔
2533

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

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

×
2555
                                goto retry
×
2556
                        }
2557

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

8✔
2568
                        // If the peer requested a synchronous write, respond
8✔
2569
                        // with the error.
8✔
2570
                        if outMsg.errChan != nil {
13✔
2571
                                outMsg.errChan <- err
5✔
2572
                        }
5✔
2573

2574
                        if err != nil {
8✔
2575
                                exitErr = fmt.Errorf("unable to write "+
×
2576
                                        "message: %v", err)
×
2577
                                break out
×
2578
                        }
2579

2580
                case <-p.quit:
4✔
2581
                        exitErr = lnpeer.ErrPeerExiting
4✔
2582
                        break out
4✔
2583
                }
2584
        }
2585

2586
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2587
        // disconnect.
2588
        p.wg.Done()
4✔
2589

4✔
2590
        p.Disconnect(exitErr)
4✔
2591

4✔
2592
        p.log.Trace("writeHandler for peer done")
4✔
2593
}
2594

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

7✔
2602
        // priorityMsgs holds an in order list of messages deemed high-priority
7✔
2603
        // to be added to the sendQueue. This predominately includes messages
7✔
2604
        // from the funding manager and htlcswitch.
7✔
2605
        priorityMsgs := list.New()
7✔
2606

7✔
2607
        // lazyMsgs holds an in order list of messages deemed low-priority to be
7✔
2608
        // added to the sendQueue only after all high-priority messages have
7✔
2609
        // been queued. This predominately includes messages from the gossiper.
7✔
2610
        lazyMsgs := list.New()
7✔
2611

7✔
2612
        for {
22✔
2613
                // Examine the front of the priority queue, if it is empty check
15✔
2614
                // the low priority queue.
15✔
2615
                elem := priorityMsgs.Front()
15✔
2616
                if elem == nil {
27✔
2617
                        elem = lazyMsgs.Front()
12✔
2618
                }
12✔
2619

2620
                if elem != nil {
23✔
2621
                        front := elem.Value.(outgoingMsg)
8✔
2622

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

2662
// PingTime returns the estimated ping time to the peer in microseconds.
2663
func (p *Brontide) PingTime() int64 {
4✔
2664
        return p.pingManager.GetPingTimeMicroSeconds()
4✔
2665
}
4✔
2666

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

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

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

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

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

4✔
2705
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
4✔
2706
                activeChan *lnwallet.LightningChannel) error {
8✔
2707

4✔
2708
                // If the activeChan is nil, then we skip it as the channel is
4✔
2709
                // pending.
4✔
2710
                if activeChan == nil {
8✔
2711
                        return nil
4✔
2712
                }
4✔
2713

2714
                // We'll only return a snapshot for channels that are
2715
                // *immediately* available for routing payments over.
2716
                if activeChan.RemoteNextRevocation() == nil {
8✔
2717
                        return nil
4✔
2718
                }
4✔
2719

2720
                snapshot := activeChan.StateSnapshot()
4✔
2721
                snapshots = append(snapshots, snapshot)
4✔
2722

4✔
2723
                return nil
4✔
2724
        })
2725

2726
        return snapshots
4✔
2727
}
2728

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

2739
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
10✔
2740
                addrType, false, lnwallet.DefaultAccountName,
10✔
2741
        )
10✔
2742
        if err != nil {
10✔
2743
                return nil, err
×
2744
        }
×
2745
        p.log.Infof("Delivery addr for channel close: %v",
10✔
2746
                deliveryAddr)
10✔
2747

10✔
2748
        return txscript.PayToAddrScript(deliveryAddr)
10✔
2749
}
2750

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

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

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

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

2781
                // The funding flow for a pending channel is failed, we will
2782
                // remove it from Brontide.
2783
                case req := <-p.removePendingChannel:
5✔
2784
                        p.handleRemovePendingChannel(req)
5✔
2785

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

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

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

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

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

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

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

4✔
2839
                                // Exit if the channel is nil as it's a pending
4✔
2840
                                // channel.
4✔
2841
                                if lc == nil {
8✔
2842
                                        return nil
4✔
2843
                                }
4✔
2844

2845
                                lc.ResetState()
4✔
2846

4✔
2847
                                return nil
4✔
2848
                        })
2849

2850
                        break out
4✔
2851
                }
2852
        }
2853
}
2854

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

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

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

4✔
2873
                switch {
4✔
2874
                // No error occurred, continue to request the next channel.
2875
                case err == nil:
4✔
2876
                        continue
4✔
2877

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

4✔
2884
                        continue
4✔
2885

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

×
2903
                                continue
×
2904
                        }
2905

2906
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
2907
                                "ChanStatusManager reported inactive, retrying")
×
2908

×
2909
                        // Add the channel to the retry map.
×
2910
                        retryChans[chanPoint] = struct{}{}
×
2911
                }
2912
        }
2913

2914
        // Retry the channels if we have any.
2915
        if len(retryChans) != 0 {
4✔
2916
                p.retryRequestEnable(retryChans)
×
2917
        }
×
2918
}
2919

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

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

2936
        // First, we'll ensure that we actually know of the target channel. If
2937
        // not, we'll ignore this message.
2938
        channel, ok := p.activeChannels.Load(chanID)
7✔
2939

7✔
2940
        // If the channel isn't in the map or the channel is nil, return
7✔
2941
        // ErrChannelNotFound as the channel is pending.
7✔
2942
        if !ok || channel == nil {
11✔
2943
                return nil, ErrChannelNotFound
4✔
2944
        }
4✔
2945

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

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

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

2987
        p.activeChanCloses[chanID] = chanCloser
7✔
2988

7✔
2989
        return chanCloser, nil
7✔
2990
}
2991

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

4✔
2998
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
4✔
2999
                lnChan *lnwallet.LightningChannel) bool {
8✔
3000

4✔
3001
                // If the lnChan is nil, continue as this is a pending channel.
4✔
3002
                if lnChan == nil {
6✔
3003
                        return true
2✔
3004
                }
2✔
3005

3006
                dbChan := lnChan.State()
4✔
3007
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
4✔
3008
                if !isPublic || dbChan.IsPending {
4✔
3009
                        return true
×
3010
                }
×
3011

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

3021
                activePublicChans = append(
4✔
3022
                        activePublicChans, dbChan.FundingOutpoint,
4✔
3023
                )
4✔
3024

4✔
3025
                return true
4✔
3026
        })
3027

3028
        return activePublicChans
4✔
3029
}
3030

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

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

×
3045
                // If this channel is irrelevant, return nil so the loop can
×
3046
                // jump to next iteration.
×
3047
                if !found {
×
3048
                        return nil
×
3049
                }
×
3050

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

×
3059
                // Send the request.
×
3060
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3061
                if err != nil {
×
3062
                        return fmt.Errorf("request enabling channel %v "+
×
3063
                                "failed: %w", chanPoint, err)
×
3064
                }
×
3065

3066
                return nil
×
3067
        }
3068

3069
        for {
×
3070
                // If activeChans is empty, we've done processing all the
×
3071
                // channels.
×
3072
                if len(activeChans) == 0 {
×
3073
                        p.log.Debug("Finished retry enabling channels")
×
3074
                        return
×
3075
                }
×
3076

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

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

3094
                                continue
×
3095
                        }
3096

3097
                        // Otherwise check for inactive link event, and jump to
3098
                        // next iteration if it's not.
3099
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3100
                        if !ok {
×
3101
                                continue
×
3102
                        }
3103

3104
                        // Found an inactive link event, if this is our
3105
                        // targeted channel, remove it from our map.
3106
                        chanPoint := *inactive.ChannelPoint
×
3107
                        _, found := activeChans[chanPoint]
×
3108
                        if !found {
×
3109
                                continue
×
3110
                        }
3111

3112
                        delete(activeChans, chanPoint)
×
3113
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3114
                                "inactive link event", chanPoint)
×
3115

3116
                case <-p.quit:
×
3117
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3118
                        return
×
3119
                }
3120
        }
3121
}
3122

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

16✔
3129
        // If no upfront shutdown script was provided, return the user
16✔
3130
        // requested address (which may be nil).
16✔
3131
        if len(upfront) == 0 {
26✔
3132
                return requested, nil
10✔
3133
        }
10✔
3134

3135
        // If an upfront shutdown script was provided, and the user did not
3136
        // request a custom shutdown script, return the upfront address.
3137
        if len(requested) == 0 {
16✔
3138
                return upfront, nil
6✔
3139
        }
6✔
3140

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

3149
        // The user requested script matches the upfront shutdown script, so we
3150
        // can return it without error.
3151
        return upfront, nil
2✔
3152
}
3153

3154
// restartCoopClose checks whether we need to restart the cooperative close
3155
// process for a given channel.
3156
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3157
        *lnwire.Shutdown, error) {
×
3158

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

3177
        var deliveryScript []byte
×
3178

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

3188
        // An error other than ErrNoShutdownInfo was returned
3189
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3190
                return nil, err
×
3191

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

×
3201
                                return nil, fmt.Errorf("close addr unavailable")
×
3202
                        }
×
3203
                }
3204
        }
3205

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

3215
        // Determine whether we or the peer are the initiator of the coop
3216
        // close attempt by looking at the channel's status.
3217
        closingParty := lntypes.Remote
×
3218
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3219
                closingParty = lntypes.Local
×
3220
        }
×
3221

3222
        addr, err := p.addrWithInternalKey(deliveryScript)
×
3223
        if err != nil {
×
3224
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3225
        }
×
3226
        chanCloser, err := p.createChanCloser(
×
3227
                lnChan, addr, feePerKw, nil, closingParty,
×
3228
        )
×
3229
        if err != nil {
×
3230
                p.log.Errorf("unable to create chan closer: %v", err)
×
3231
                return nil, fmt.Errorf("unable to create chan closer")
×
3232
        }
×
3233

3234
        // This does not need a mutex even though it is in a different
3235
        // goroutine since this is done before the channelManager goroutine is
3236
        // created.
3237
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
×
3238
        p.activeChanCloses[chanID] = chanCloser
×
3239

×
3240
        // Create the Shutdown message.
×
3241
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3242
        if err != nil {
×
3243
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3244
                delete(p.activeChanCloses, chanID)
×
3245
                return nil, err
×
3246
        }
×
3247

3248
        return shutdownMsg, nil
×
3249
}
3250

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

13✔
3258
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
13✔
3259
        if err != nil {
13✔
3260
                p.log.Errorf("unable to obtain best block: %v", err)
×
3261
                return nil, fmt.Errorf("cannot obtain best block")
×
3262
        }
×
3263

3264
        // The req will only be set if we initiated the co-op closing flow.
3265
        var maxFee chainfee.SatPerKWeight
13✔
3266
        if req != nil {
23✔
3267
                maxFee = req.MaxFee
10✔
3268
        }
10✔
3269

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

3296
        return chanCloser, nil
13✔
3297
}
3298

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

11✔
3304
        channel, ok := p.activeChannels.Load(chanID)
11✔
3305

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

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

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

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

×
3355
                        return
×
3356
                }
×
3357
                chanCloser, err := p.createChanCloser(
10✔
3358
                        channel, addr, req.TargetFeePerKw, req, lntypes.Local,
10✔
3359
                )
10✔
3360
                if err != nil {
10✔
3361
                        p.log.Errorf(err.Error())
×
3362
                        req.Err <- err
×
3363
                        return
×
3364
                }
×
3365

3366
                p.activeChanCloses[chanID] = chanCloser
10✔
3367

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

×
3377
                        // As we were unable to shutdown the channel, we'll
×
3378
                        // return it back to its normal state.
×
3379
                        channel.ResetState()
×
3380
                        return
×
3381
                }
×
3382

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

3396
                if !link.DisableAdds(htlcswitch.Outgoing) {
10✔
3397
                        p.log.Warnf("Outgoing link adds already "+
×
3398
                                "disabled: %v", link.ChanID())
×
3399
                }
×
3400

3401
                link.OnCommitOnce(htlcswitch.Outgoing, func() {
20✔
3402
                        p.queueMsg(shutdownMsg, nil)
10✔
3403
                })
10✔
3404

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

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

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

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

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

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

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

×
3468
                if err := lnChan.State().MarkBorked(); err != nil {
×
3469
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
3470
                                failure.shortChanID, err)
×
3471
                }
×
3472
        }
3473

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

3485
                var networkMsg lnwire.Message
4✔
3486
                if failure.linkErr.Warning {
4✔
3487
                        networkMsg = &lnwire.Warning{
×
3488
                                ChanID: failure.chanID,
×
3489
                                Data:   data,
×
3490
                        }
×
3491
                } else {
4✔
3492
                        networkMsg = &lnwire.Error{
4✔
3493
                                ChanID: failure.chanID,
4✔
3494
                                Data:   data,
4✔
3495
                        }
4✔
3496
                }
4✔
3497

3498
                err := p.SendMessage(true, networkMsg)
4✔
3499
                if err != nil {
4✔
3500
                        p.log.Errorf("unable to send msg to "+
×
3501
                                "remote peer: %v", err)
×
3502
                }
×
3503
        }
3504

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

3513
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
3514
// public key and the channel id.
3515
func (p *Brontide) fetchLinkFromKeyAndCid(
3516
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
23✔
3517

23✔
3518
        var chanLink htlcswitch.ChannelUpdateHandler
23✔
3519

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

3530
        return chanLink
23✔
3531
}
3532

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

8✔
3541
        // First, we'll clear all indexes related to the channel in question.
8✔
3542
        chanPoint := chanCloser.Channel().ChannelPoint()
8✔
3543
        p.WipeChannel(&chanPoint)
8✔
3544

8✔
3545
        // Also clear the activeChanCloses map of this channel.
8✔
3546
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
8✔
3547
        delete(p.activeChanCloses, cid)
8✔
3548

8✔
3549
        // Next, we'll launch a goroutine which will request to be notified by
8✔
3550
        // the ChainNotifier once the closure transaction obtains a single
8✔
3551
        // confirmation.
8✔
3552
        notifier := p.cfg.ChainNotifier
8✔
3553

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

3562
        closingTx, err := chanCloser.ClosingTx()
8✔
3563
        if err != nil {
8✔
3564
                if closeReq != nil {
×
3565
                        p.log.Error(err)
×
3566
                        closeReq.Err <- err
×
3567
                }
×
3568
        }
3569

3570
        closingTxid := closingTx.TxHash()
8✔
3571

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

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

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

8✔
3610
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
8✔
3611
                "with txid: %v", chanPoint, closingTxID)
8✔
3612

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

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

3631
        // The channel has been closed, remove it from any active indexes, and
3632
        // the database state.
3633
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
8✔
3634
                "height %v", chanPoint, height.BlockHeight)
8✔
3635

8✔
3636
        // Finally, execute the closure call back to mark the confirmation of
8✔
3637
        // the transaction closing the contract.
8✔
3638
        cb()
8✔
3639
}
3640

3641
// WipeChannel removes the passed channel point from all indexes associated with
3642
// the peer and the switch.
3643
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
8✔
3644
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
8✔
3645

8✔
3646
        p.activeChannels.Delete(chanID)
8✔
3647

8✔
3648
        // Instruct the HtlcSwitch to close this link as the channel is no
8✔
3649
        // longer active.
8✔
3650
        p.cfg.Switch.RemoveLink(chanID)
8✔
3651
}
8✔
3652

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

3664
        // Then, finalize the remote feature vector providing the flattened
3665
        // feature bit namespace.
3666
        p.remoteFeatures = lnwire.NewFeatureVector(
7✔
3667
                msg.Features, lnwire.Features,
7✔
3668
        )
7✔
3669

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

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

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

3691
        return nil
7✔
3692
}
3693

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

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

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

3720
// sendInitMsg sends the Init message to the remote peer. This message contains
3721
// our currently supported local and global features.
3722
func (p *Brontide) sendInitMsg(legacyChan bool) error {
11✔
3723
        features := p.cfg.Features.Clone()
11✔
3724
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
11✔
3725

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

1✔
3736
                // Unset and set in both the local and global features to
1✔
3737
                // ensure both sets are consistent and merge able by old and
1✔
3738
                // new nodes.
1✔
3739
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3740
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3741

1✔
3742
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
3743
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
3744
        }
1✔
3745

3746
        msg := lnwire.NewInitMessage(
11✔
3747
                legacyFeatures.RawFeatureVector,
11✔
3748
                features.RawFeatureVector,
11✔
3749
        )
11✔
3750

11✔
3751
        return p.writeMessage(msg)
11✔
3752
}
3753

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

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

3770
        if c.LastChanSyncMsg == nil {
4✔
3771
                return fmt.Errorf("no chan sync message stored for channel %v",
×
3772
                        cid)
×
3773
        }
×
3774

3775
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
4✔
3776
                return fmt.Errorf("ignoring channel reestablish from "+
×
3777
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
3778
        }
×
3779

3780
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
4✔
3781
                "peer", cid)
4✔
3782

4✔
3783
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
4✔
3784
                return fmt.Errorf("failed resending channel sync "+
×
3785
                        "message to peer %v: %v", p, err)
×
3786
        }
×
3787

3788
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
4✔
3789
                cid)
4✔
3790

4✔
3791
        // Note down that we sent the message, so we won't resend it again for
4✔
3792
        // this connection.
4✔
3793
        p.resentChanSyncMsg[cid] = struct{}{}
4✔
3794

4✔
3795
        return nil
4✔
3796
}
3797

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

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

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

3839
                if priority {
15✔
3840
                        p.queueMsg(msg, errChan)
7✔
3841
                } else {
12✔
3842
                        p.queueMsgLazy(msg, errChan)
5✔
3843
                }
5✔
3844
        }
3845

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

3859
        return nil
7✔
3860
}
3861

3862
// PubKey returns the pubkey of the peer in compressed serialized format.
3863
//
3864
// NOTE: Part of the lnpeer.Peer interface.
3865
func (p *Brontide) PubKey() [33]byte {
6✔
3866
        return p.cfg.PubKeyBytes
6✔
3867
}
6✔
3868

3869
// IdentityKey returns the public key of the remote peer.
3870
//
3871
// NOTE: Part of the lnpeer.Peer interface.
3872
func (p *Brontide) IdentityKey() *btcec.PublicKey {
19✔
3873
        return p.cfg.Addr.IdentityKey
19✔
3874
}
19✔
3875

3876
// Address returns the network address of the remote peer.
3877
//
3878
// NOTE: Part of the lnpeer.Peer interface.
3879
func (p *Brontide) Address() net.Addr {
4✔
3880
        return p.cfg.Addr.Address
4✔
3881
}
4✔
3882

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

4✔
3890
        errChan := make(chan error, 1)
4✔
3891
        newChanMsg := &newChannelMsg{
4✔
3892
                channel: newChan,
4✔
3893
                err:     errChan,
4✔
3894
        }
4✔
3895

4✔
3896
        select {
4✔
3897
        case p.newActiveChannel <- newChanMsg:
4✔
3898
        case <-cancel:
×
3899
                return errors.New("canceled adding new channel")
×
3900
        case <-p.quit:
×
3901
                return lnpeer.ErrPeerExiting
×
3902
        }
3903

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

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

4✔
3921
        errChan := make(chan error, 1)
4✔
3922
        newChanMsg := &newChannelMsg{
4✔
3923
                channelID: cid,
4✔
3924
                err:       errChan,
4✔
3925
        }
4✔
3926

4✔
3927
        select {
4✔
3928
        case p.newPendingChannel <- newChanMsg:
4✔
3929

3930
        case <-cancel:
×
3931
                return errors.New("canceled adding pending channel")
×
3932

3933
        case <-p.quit:
×
3934
                return lnpeer.ErrPeerExiting
×
3935
        }
3936

3937
        // We pause here to wait for the peer to recognize the new pending
3938
        // channel before we close the channel barrier corresponding to the
3939
        // channel.
3940
        select {
4✔
3941
        case err := <-errChan:
4✔
3942
                return err
4✔
3943

3944
        case <-cancel:
×
3945
                return errors.New("canceled adding pending channel")
×
3946

3947
        case <-p.quit:
×
3948
                return lnpeer.ErrPeerExiting
×
3949
        }
3950
}
3951

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

4✔
3962
        select {
4✔
3963
        case p.removePendingChannel <- newChanMsg:
4✔
3964
        case <-p.quit:
×
3965
                return lnpeer.ErrPeerExiting
×
3966
        }
3967

3968
        // We pause here to wait for the peer to respond to the cancellation of
3969
        // the pending channel before we close the channel barrier
3970
        // corresponding to the channel.
3971
        select {
4✔
3972
        case err := <-errChan:
4✔
3973
                return err
4✔
3974

3975
        case <-p.quit:
×
3976
                return lnpeer.ErrPeerExiting
×
3977
        }
3978
}
3979

3980
// StartTime returns the time at which the connection was established if the
3981
// peer started successfully, and zero otherwise.
3982
func (p *Brontide) StartTime() time.Time {
4✔
3983
        return p.startTime
4✔
3984
}
4✔
3985

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

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

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

×
4003
                errMsg := &lnwire.Error{
×
4004
                        ChanID: msg.cid,
×
4005
                        Data:   lnwire.ErrorData(err.Error()),
×
4006
                }
×
4007
                p.queueMsg(errMsg, nil)
×
4008
                return
×
4009
        }
4010

4011
        handleErr := func(err error) {
18✔
4012
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
4013
                p.log.Error(err)
1✔
4014

1✔
4015
                // As the negotiations failed, we'll reset the channel state machine to
1✔
4016
                // ensure we act to on-chain events as normal.
1✔
4017
                chanCloser.Channel().ResetState()
1✔
4018

1✔
4019
                if chanCloser.CloseRequest() != nil {
1✔
4020
                        chanCloser.CloseRequest().Err <- err
×
4021
                }
×
4022
                delete(p.activeChanCloses, msg.cid)
1✔
4023

1✔
4024
                p.Disconnect(err)
1✔
4025
        }
4026

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

4037
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
9✔
4038
                if err != nil {
9✔
4039
                        handleErr(err)
×
4040
                        return
×
4041
                }
×
4042

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

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

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

4067
                beginNegotiation := func() {
18✔
4068
                        oClosingSigned, err := chanCloser.BeginNegotiation()
9✔
4069
                        if err != nil {
9✔
UNCOV
4070
                                handleErr(err)
×
UNCOV
4071
                                return
×
UNCOV
4072
                        }
×
4073

4074
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
18✔
4075
                                p.queueMsg(&msg, nil)
9✔
4076
                        })
9✔
4077
                }
4078

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

4092
        case *lnwire.ClosingSigned:
12✔
4093
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
12✔
4094
                if err != nil {
13✔
4095
                        handleErr(err)
1✔
4096
                        return
1✔
4097
                }
1✔
4098

4099
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
24✔
4100
                        p.queueMsg(&msg, nil)
12✔
4101
                })
12✔
4102

4103
        default:
×
4104
                panic("impossible closeMsg type")
×
4105
        }
4106

4107
        // If we haven't finished close negotiations, then we'll continue as we
4108
        // can't yet finalize the closure.
4109
        if _, err := chanCloser.ClosingTx(); err != nil {
28✔
4110
                return
12✔
4111
        }
12✔
4112

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

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

4133
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
4134
func (p *Brontide) NetAddress() *lnwire.NetAddress {
4✔
4135
        return p.cfg.Addr
4✔
4136
}
4✔
4137

4138
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
4139
func (p *Brontide) Inbound() bool {
4✔
4140
        return p.cfg.Inbound
4✔
4141
}
4✔
4142

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

4148
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
4149
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
4✔
4150
        return p.cfg.ErrorBuffer
4✔
4151
}
4✔
4152

4153
// SetAddress sets the remote peer's address given an address.
4154
func (p *Brontide) SetAddress(address net.Addr) {
×
4155
        p.cfg.Addr.Address = address
×
4156
}
×
4157

4158
// ActiveSignal returns the peer's active signal.
4159
func (p *Brontide) ActiveSignal() chan struct{} {
4✔
4160
        return p.activeSignal
4✔
4161
}
4✔
4162

4163
// Conn returns a pointer to the peer's connection struct.
4164
func (p *Brontide) Conn() net.Conn {
4✔
4165
        return p.cfg.Conn
4✔
4166
}
4✔
4167

4168
// BytesReceived returns the number of bytes received from the peer.
4169
func (p *Brontide) BytesReceived() uint64 {
4✔
4170
        return atomic.LoadUint64(&p.bytesReceived)
4✔
4171
}
4✔
4172

4173
// BytesSent returns the number of bytes sent to the peer.
4174
func (p *Brontide) BytesSent() uint64 {
4✔
4175
        return atomic.LoadUint64(&p.bytesSent)
4✔
4176
}
4✔
4177

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

4186
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
1✔
4187
        if !ok {
1✔
4188
                return nil
×
4189
        }
×
4190

4191
        return pingBytes
1✔
4192
}
4193

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

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

4215
        p.channelEventClient = sub
7✔
4216

7✔
4217
        return nil
7✔
4218
}
4219

4220
// updateNextRevocation updates the existing channel's next revocation if it's
4221
// nil.
4222
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
7✔
4223
        chanPoint := c.FundingOutpoint
7✔
4224
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
7✔
4225

7✔
4226
        // Read the current channel.
7✔
4227
        currentChan, loaded := p.activeChannels.Load(chanID)
7✔
4228

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

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

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

4250
        p.log.Infof("Processing retransmitted ChannelReady for "+
5✔
4251
                "ChannelPoint(%v)", chanPoint)
5✔
4252

5✔
4253
        nextRevoke := c.RemoteNextRevocation
5✔
4254

5✔
4255
        err := currentChan.InitNextRevocation(nextRevoke)
5✔
4256
        if err != nil {
5✔
4257
                return fmt.Errorf("unable to init next revocation: %w", err)
×
4258
        }
×
4259

4260
        return nil
5✔
4261
}
4262

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

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

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

4285
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
4✔
4286
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
4287
        })
×
4288
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
4✔
4289
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
4290
        })
×
4291
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
4✔
4292
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
4293
        })
×
4294

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

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

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

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

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

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

4336
        return nil
4✔
4337
}
4338

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

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

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

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

4363
                return
4✔
4364
        }
4365

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

×
4372
                return
×
4373
        }
×
4374

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

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

8✔
4386
        chanID := req.channelID
8✔
4387

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

1✔
4396
                return
1✔
4397
        }
1✔
4398

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

1✔
4404
                return
1✔
4405
        }
1✔
4406

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

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

8✔
4420
        chanID := req.channelID
8✔
4421

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

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

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

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

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

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

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

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

4476
        return timeout
67✔
4477
}
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