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

lightningnetwork / lnd / 12158393807

04 Dec 2024 11:03AM UTC coverage: 58.973% (+0.02%) from 58.956%
12158393807

Pull #9316

github

ziggie1984
docs: add release-notes.
Pull Request #9316: routing: fix mc blinded path behaviour.

121 of 128 new or added lines in 4 files covered. (94.53%)

77 existing lines in 22 files now uncovered.

133540 of 226443 relevant lines covered (58.97%)

19462.12 hits per line

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

78.52
/peer/brontide.go
1
package peer
2

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

15
        "github.com/btcsuite/btcd/btcec/v2"
16
        "github.com/btcsuite/btcd/chaincfg/chainhash"
17
        "github.com/btcsuite/btcd/connmgr"
18
        "github.com/btcsuite/btcd/txscript"
19
        "github.com/btcsuite/btcd/wire"
20
        "github.com/btcsuite/btclog/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
        // PongBuf is a slice we'll reuse instead of allocating memory on the
404
        // heap. Since only reads will occur and no writes, there is no need
405
        // for any synchronization primitives. As a result, it's safe to share
406
        // this across multiple Peer struct instances.
407
        PongBuf []byte
408

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

414
        // DisallowQuiescence is a flag that indicates whether the Brontide
415
        // should have the quiescence feature disabled.
416
        DisallowQuiescence bool
417

418
        // MaxFeeExposure limits the number of outstanding fees in a channel.
419
        // This value will be passed to created links.
420
        MaxFeeExposure lnwire.MilliSatoshi
421

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

427
        // AuxChanCloser is an optional instance of an abstraction that can be
428
        // used to modify the way the co-op close transaction is constructed.
429
        AuxChanCloser fn.Option[chancloser.AuxChanCloser]
430

431
        // ShouldFwdExpEndorsement is a closure that indicates whether
432
        // experimental endorsement signals should be set.
433
        ShouldFwdExpEndorsement func() bool
434

435
        // Quit is the server's quit channel. If this is closed, we halt operation.
436
        Quit chan struct{}
437
}
438

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

450
        // MUST be used atomically.
451
        bytesReceived uint64
452
        bytesSent     uint64
453

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

471
        pingManager *PingManager
472

473
        // lastPingPayload stores an unsafe pointer wrapped as an atomic
474
        // variable which points to the last payload the remote party sent us
475
        // as their ping.
476
        //
477
        // MUST be used atomically.
478
        lastPingPayload atomic.Value
479

480
        cfg Config
481

482
        // activeSignal when closed signals that the peer is now active and
483
        // ready to process messages.
484
        activeSignal chan struct{}
485

486
        // startTime is the time this peer connection was successfully established.
487
        // It will be zero for peers that did not successfully call Start().
488
        startTime time.Time
489

490
        // sendQueue is the channel which is used to queue outgoing messages to be
491
        // written onto the wire. Note that this channel is unbuffered.
492
        sendQueue chan outgoingMsg
493

494
        // outgoingQueue is a buffered channel which allows second/third party
495
        // objects to queue messages to be sent out on the wire.
496
        outgoingQueue chan outgoingMsg
497

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

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

517
        // newActiveChannel is used by the fundingManager to send fully opened
518
        // channels to the source peer which handled the funding workflow.
519
        newActiveChannel chan *newChannelMsg
520

521
        // newPendingChannel is used by the fundingManager to send pending open
522
        // channels to the source peer which handled the funding workflow.
523
        newPendingChannel chan *newChannelMsg
524

525
        // removePendingChannel is used by the fundingManager to cancel pending
526
        // open channels to the source peer when the funding flow is failed.
527
        removePendingChannel chan *newChannelMsg
528

529
        // activeMsgStreams is a map from channel id to the channel streams that
530
        // proxy messages to individual, active links.
531
        activeMsgStreams map[lnwire.ChannelID]*msgStream
532

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

539
        // localCloseChanReqs is a channel in which any local requests to close
540
        // a particular channel are sent over.
541
        localCloseChanReqs chan *htlcswitch.ChanClose
542

543
        // linkFailures receives all reported channel failures from the switch,
544
        // and instructs the channelManager to clean remaining channel state.
545
        linkFailures chan linkFailureReport
546

547
        // chanCloseMsgs is a channel that any message related to channel
548
        // closures are sent over. This includes lnwire.Shutdown message as
549
        // well as lnwire.ClosingSigned messages.
550
        chanCloseMsgs chan *closeMsg
551

552
        // remoteFeatures is the feature vector received from the peer during
553
        // the connection handshake.
554
        remoteFeatures *lnwire.FeatureVector
555

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

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

571
        // msgRouter is an instance of the msgmux.Router which is used to send
572
        // off new wire messages for handing.
573
        msgRouter fn.Option[msgmux.Router]
574

575
        // globalMsgRouter is a flag that indicates whether we have a global
576
        // msg router. If so, then we don't worry about stopping the msg router
577
        // when a peer disconnects.
578
        globalMsgRouter bool
579

580
        startReady chan struct{}
581
        quit       chan struct{}
582
        wg         sync.WaitGroup
583

584
        // log is a peer-specific logging instance.
585
        log btclog.Logger
586
}
587

588
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer interface.
589
var _ lnpeer.Peer = (*Brontide)(nil)
590

591
// NewBrontide creates a new Brontide from a peer.Config struct.
592
func NewBrontide(cfg Config) *Brontide {
29✔
593
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
29✔
594

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

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

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

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

29✔
632
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
33✔
633
                remoteAddr := cfg.Conn.RemoteAddr().String()
4✔
634
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
4✔
635
                        strings.Contains(remoteAddr, "127.0.0.1")
4✔
636
        }
4✔
637

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

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

665
                return lastSerializedBlockHeader[:]
2✔
666
        }
667

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

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

697
        return p
29✔
698
}
699

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

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

7✔
712
        p.log.Tracef("starting with conn[%v->%v]",
7✔
713
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
7✔
714

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

726
        if len(activeChans) == 0 {
12✔
727
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
5✔
728
        }
5✔
729

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

738
                haveLegacyChan = true
4✔
739
                break
4✔
740
        }
741

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

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

7✔
757
                msg, err := p.readNextMessage()
7✔
758
                if err != nil {
8✔
759
                        readErr <- err
1✔
760
                        msgChan <- nil
1✔
761
                        return
1✔
762
                }
1✔
763
                readErr <- nil
7✔
764
                msgChan <- msg
7✔
765
        }()
766

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

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

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

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

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

815
        msgs, err := p.loadActiveChannels(activeChans)
7✔
816
        if err != nil {
7✔
817
                return fmt.Errorf("unable to load channels: %w", err)
×
818
        }
×
819

820
        p.startTime = time.Now()
7✔
821

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

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

839
        err = p.pingManager.Start()
7✔
840
        if err != nil {
7✔
841
                return fmt.Errorf("could not start ping manager %w", err)
×
842
        }
×
843

844
        p.wg.Add(4)
7✔
845
        go p.queueHandler()
7✔
846
        go p.writeHandler()
7✔
847
        go p.channelManager()
7✔
848
        go p.readHandler()
7✔
849

7✔
850
        // Signal to any external processes that the peer is now active.
7✔
851
        close(p.activeSignal)
7✔
852

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

7✔
868
        return nil
7✔
869
}
870

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

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

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

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

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

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

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

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

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

7✔
950
        // Return a slice of messages to send to the peers in case the channel
7✔
951
        // cannot be loaded normally.
7✔
952
        var msgs []lnwire.Message
7✔
953

7✔
954
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
7✔
955

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

976
                                err = p.cfg.AddLocalAlias(
4✔
977
                                        aliasScid, dbChan.ShortChanID(), false,
4✔
978
                                        false,
4✔
979
                                )
4✔
980
                                if err != nil {
4✔
981
                                        return nil, err
×
982
                                }
×
983

984
                                chanID := lnwire.NewChanIDFromOutPoint(
4✔
985
                                        dbChan.FundingOutpoint,
4✔
986
                                )
4✔
987

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

995
                                channelReadyMsg := lnwire.NewChannelReady(
4✔
996
                                        chanID, second,
4✔
997
                                )
4✔
998
                                channelReadyMsg.AliasScid = &aliasScid
4✔
999

4✔
1000
                                msgs = append(msgs, channelReadyMsg)
4✔
1001
                        }
1002

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

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

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

1037
                chanPoint := dbChan.FundingOutpoint
6✔
1038

6✔
1039
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
6✔
1040

6✔
1041
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
6✔
1042
                        chanPoint, lnChan.IsPending())
6✔
1043

6✔
1044
                // Skip adding any permanently irreconcilable channels to the
6✔
1045
                // htlcswitch.
6✔
1046
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
6✔
1047
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
12✔
1048

6✔
1049
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
6✔
1050
                                "start.", chanPoint, dbChan.ChanStatus())
6✔
1051

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

1066
                        msgs = append(msgs, chanSync)
6✔
1067

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

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

1083
                                if shutdownMsg == nil {
×
1084
                                        continue
×
1085
                                }
1086

1087
                                // Append the message to the set of messages to
1088
                                // send.
1089
                                msgs = append(msgs, shutdownMsg)
×
1090
                        }
1091

1092
                        continue
6✔
1093
                }
1094

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

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

4✔
1117
                        selfPolicy = p1
4✔
1118
                } else {
8✔
1119
                        selfPolicy = p2
4✔
1120
                }
4✔
1121

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

1135
                        inboundFee := models.NewInboundFeeFromWire(
4✔
1136
                                inboundWireFee,
4✔
1137
                        )
4✔
1138

4✔
1139
                        forwardingPolicy = &models.ForwardingPolicy{
4✔
1140
                                MinHTLCOut:    selfPolicy.MinHTLC,
4✔
1141
                                MaxHTLC:       selfPolicy.MaxHTLC,
4✔
1142
                                BaseFee:       selfPolicy.FeeBaseMSat,
4✔
1143
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
4✔
1144
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
4✔
1145

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

1155
                p.log.Tracef("Using link policy of: %v",
4✔
1156
                        spew.Sdump(forwardingPolicy))
4✔
1157

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

4✔
1167
                        continue
4✔
1168
                }
1169

1170
                shutdownInfo, err := lnChan.State().ShutdownInfo()
4✔
1171
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
4✔
1172
                        return nil, err
×
1173
                }
×
1174

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

×
1188
                                return
×
1189
                        }
×
1190

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

×
1206
                                return
×
1207
                        }
×
1208

1209
                        chanID := lnwire.NewChanIDFromOutPoint(
4✔
1210
                                lnChan.State().FundingOutpoint,
4✔
1211
                        )
4✔
1212

4✔
1213
                        p.activeChanCloses[chanID] = chanCloser
4✔
1214

4✔
1215
                        // Create the Shutdown message.
4✔
1216
                        shutdown, err := chanCloser.ShutdownChan()
4✔
1217
                        if err != nil {
4✔
1218
                                delete(p.activeChanCloses, chanID)
×
1219
                                shutdownInfoErr = err
×
1220

×
1221
                                return
×
1222
                        }
×
1223

1224
                        shutdownMsg = fn.Some(*shutdown)
4✔
1225
                })
1226
                if shutdownInfoErr != nil {
4✔
1227
                        return nil, shutdownInfoErr
×
1228
                }
×
1229

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

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

1247
                p.activeChannels.Store(chanID, lnChan)
4✔
1248
        }
1249

1250
        return msgs, nil
7✔
1251
}
1252

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

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

4✔
1266
                failure := linkFailureReport{
4✔
1267
                        chanPoint:   *chanPoint,
4✔
1268
                        chanID:      chanID,
4✔
1269
                        shortChanID: shortChanID,
4✔
1270
                        linkErr:     linkErr,
4✔
1271
                }
4✔
1272

4✔
1273
                select {
4✔
1274
                case p.linkFailures <- failure:
4✔
1275
                case <-p.quit:
×
1276
                case <-p.cfg.Quit:
1✔
1277
                }
1278
        }
1279

1280
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
8✔
1281
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
4✔
1282
        }
4✔
1283

1284
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
8✔
1285
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
4✔
1286
        }
4✔
1287

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

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

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

1348
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1349
// one confirmed public channel exists with them.
1350
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
7✔
1351
        defer p.wg.Done()
7✔
1352

7✔
1353
        hasConfirmedPublicChan := false
7✔
1354
        for _, channel := range channels {
13✔
1355
                if channel.IsPending {
10✔
1356
                        continue
4✔
1357
                }
1358
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
12✔
1359
                        continue
6✔
1360
                }
1361

1362
                hasConfirmedPublicChan = true
4✔
1363
                break
4✔
1364
        }
1365
        if !hasConfirmedPublicChan {
14✔
1366
                return
7✔
1367
        }
7✔
1368

1369
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
4✔
1370
        if err != nil {
4✔
1371
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1372
                return
×
1373
        }
×
1374

1375
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
4✔
1376
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1377
        }
×
1378
}
1379

1380
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1381
// have any active channels with them.
1382
func (p *Brontide) maybeSendChannelUpdates() {
7✔
1383
        defer p.wg.Done()
7✔
1384

7✔
1385
        // If we don't have any active channels, then we can exit early.
7✔
1386
        if p.activeChannels.Len() == 0 {
12✔
1387
                return
5✔
1388
        }
5✔
1389

1390
        maybeSendUpd := func(cid lnwire.ChannelID,
6✔
1391
                lnChan *lnwallet.LightningChannel) error {
12✔
1392

6✔
1393
                // Nil channels are pending, so we'll skip them.
6✔
1394
                if lnChan == nil {
10✔
1395
                        return nil
4✔
1396
                }
4✔
1397

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

1406
                        // Otherwise, we can use the normal scid.
1407
                        default:
6✔
1408
                                return dbChan.ShortChanID()
6✔
1409
                        }
1410
                }()
1411

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

4✔
1422
                        return nil
4✔
1423
                }
4✔
1424

1425
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
6✔
1426
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
6✔
1427

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

×
1437
                        return err
×
1438
                }
×
1439

1440
                return nil
6✔
1441
        }
1442

1443
        p.activeChannels.ForEach(maybeSendUpd)
6✔
1444
}
1445

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

1463
        select {
4✔
1464
        case <-ready:
4✔
1465
        case <-p.quit:
1✔
1466
        }
1467

1468
        p.wg.Wait()
4✔
1469
}
1470

1471
// Disconnect terminates the connection with the remote peer. Additionally, a
1472
// signal is sent to the server and htlcSwitch indicating the resources
1473
// allocated to the peer can now be cleaned up.
1474
func (p *Brontide) Disconnect(reason error) {
5✔
1475
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
9✔
1476
                return
4✔
1477
        }
4✔
1478

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

4✔
1488
                select {
4✔
1489
                case <-p.startReady:
4✔
1490
                case <-p.quit:
×
1491
                        return
×
1492
                }
1493
        }
1494

1495
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
5✔
1496
        p.storeError(err)
5✔
1497

5✔
1498
        p.log.Infof(err.Error())
5✔
1499

5✔
1500
        // Stop PingManager before closing TCP connection.
5✔
1501
        p.pingManager.Stop()
5✔
1502

5✔
1503
        // Ensure that the TCP connection is properly closed before continuing.
5✔
1504
        p.cfg.Conn.Close()
5✔
1505

5✔
1506
        close(p.quit)
5✔
1507

5✔
1508
        // If our msg router isn't global (local to this instance), then we'll
5✔
1509
        // stop it. Otherwise, we'll leave it running.
5✔
1510
        if !p.globalMsgRouter {
10✔
1511
                p.msgRouter.WhenSome(func(router msgmux.Router) {
10✔
1512
                        router.Stop()
5✔
1513
                })
5✔
1514
        }
1515
}
1516

1517
// String returns the string representation of this peer.
1518
func (p *Brontide) String() string {
5✔
1519
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
5✔
1520
}
5✔
1521

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

1531
        pktLen, err := noiseConn.ReadNextHeader()
11✔
1532
        if err != nil {
15✔
1533
                return nil, fmt.Errorf("read next header: %w", err)
4✔
1534
        }
4✔
1535

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

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

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

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

1585
        p.logWireMessage(nextMsg, true)
8✔
1586

8✔
1587
        return nextMsg, nil
8✔
1588
}
1589

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

1598
        peer *Brontide
1599

1600
        apply func(lnwire.Message)
1601

1602
        startMsg string
1603
        stopMsg  string
1604

1605
        msgCond *sync.Cond
1606
        msgs    []lnwire.Message
1607

1608
        mtx sync.Mutex
1609

1610
        producerSema chan struct{}
1611

1612
        wg   sync.WaitGroup
1613
        quit chan struct{}
1614
}
1615

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

7✔
1624
        stream := &msgStream{
7✔
1625
                peer:         p,
7✔
1626
                apply:        apply,
7✔
1627
                startMsg:     startMsg,
7✔
1628
                stopMsg:      stopMsg,
7✔
1629
                producerSema: make(chan struct{}, bufSize),
7✔
1630
                quit:         make(chan struct{}),
7✔
1631
        }
7✔
1632
        stream.msgCond = sync.NewCond(&stream.mtx)
7✔
1633

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

1642
        return stream
7✔
1643
}
1644

1645
// Start starts the chanMsgStream.
1646
func (ms *msgStream) Start() {
7✔
1647
        ms.wg.Add(1)
7✔
1648
        go ms.msgConsumer()
7✔
1649
}
7✔
1650

1651
// Stop stops the chanMsgStream.
1652
func (ms *msgStream) Stop() {
4✔
1653
        // TODO(roasbeef): signal too?
4✔
1654

4✔
1655
        close(ms.quit)
4✔
1656

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

1664
        ms.wg.Wait()
4✔
1665
}
1666

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

7✔
1674
        peerLog.Tracef(ms.startMsg)
7✔
1675

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

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

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

4✔
1704
                ms.msgCond.L.Unlock()
4✔
1705

4✔
1706
                ms.apply(msg)
4✔
1707

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

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

1738
        // Next, we'll lock the condition, and add the message to the end of
1739
        // the message queue.
1740
        ms.msgCond.L.Lock()
4✔
1741
        ms.msgs = append(ms.msgs, msg)
4✔
1742
        ms.msgCond.L.Unlock()
4✔
1743

4✔
1744
        // With the message added, we signal to the msgConsumer that there are
4✔
1745
        // additional messages to consume.
4✔
1746
        ms.msgCond.Signal()
4✔
1747
}
1748

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

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

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

4✔
1775
        // The link may already be active by this point, and we may have missed the
4✔
1776
        // ActiveLinkEvent. Check if the link exists.
4✔
1777
        link := p.fetchLinkFromKeyAndCid(cid)
4✔
1778
        if link != nil {
8✔
1779
                return link
4✔
1780
        }
4✔
1781

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

1796
                        chanPoint := event.ChannelPoint
4✔
1797

4✔
1798
                        // Check whether the retrieved chanPoint matches the target
4✔
1799
                        // channel id.
4✔
1800
                        if !cid.IsChanPoint(chanPoint) {
4✔
1801
                                continue
×
1802
                        }
1803

1804
                        // The link shouldn't be nil as we received an
1805
                        // ActiveLinkEvent. If it is nil, we return nil and the
1806
                        // calling function should catch it.
1807
                        return p.fetchLinkFromKeyAndCid(cid)
4✔
1808

1809
                case <-p.quit:
4✔
1810
                        return nil
4✔
1811
                }
1812
        }
1813
}
1814

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

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

4✔
1831
                        // If the link is still not active and the calling function
4✔
1832
                        // errored out, just return.
4✔
1833
                        if chanLink == nil {
8✔
1834
                                p.log.Warnf("Link=%v is not active", cid)
4✔
1835
                                return
4✔
1836
                        }
4✔
1837
                }
1838

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

1848
                chanLink.HandleChannelUpdate(msg)
4✔
1849
        }
1850

1851
        return newMsgStream(p,
4✔
1852
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
4✔
1853
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
4✔
1854
                1000,
4✔
1855
                apply,
4✔
1856
        )
4✔
1857
}
1858

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

1869
        return newMsgStream(
7✔
1870
                p,
7✔
1871
                "Update stream for gossiper created",
7✔
1872
                "Update stream for gossiper exited",
7✔
1873
                1000,
7✔
1874
                apply,
7✔
1875
        )
7✔
1876
}
1877

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

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

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

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

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

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

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

1948
                        // If the error we encountered wasn't just a message we
1949
                        // didn't recognize, then we'll stop all processing as
1950
                        // this is a fatal error.
1951
                        default:
4✔
1952
                                break out
4✔
1953
                        }
1954
                }
1955

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

1966
                // No error occurred, and the message was handled by the
1967
                // router.
1968
                if err == nil {
5✔
1969
                        continue
×
1970
                }
1971

1972
                var (
5✔
1973
                        targetChan   lnwire.ChannelID
5✔
1974
                        isLinkUpdate bool
5✔
1975
                )
5✔
1976

5✔
1977
                switch msg := nextMsg.(type) {
5✔
1978
                case *lnwire.Pong:
2✔
1979
                        // When we receive a Pong message in response to our
2✔
1980
                        // last ping message, we send it to the pingManager
2✔
1981
                        p.pingManager.ReceivedPong(msg)
2✔
1982

1983
                case *lnwire.Ping:
2✔
1984
                        // First, we'll store their latest ping payload within
2✔
1985
                        // the relevant atomic variable.
2✔
1986
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
2✔
1987

2✔
1988
                        // Next, we'll send over the amount of specified pong
2✔
1989
                        // bytes.
2✔
1990
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
2✔
1991
                        p.queueMsg(pong, nil)
2✔
1992

1993
                case *lnwire.OpenChannel,
1994
                        *lnwire.AcceptChannel,
1995
                        *lnwire.FundingCreated,
1996
                        *lnwire.FundingSigned,
1997
                        *lnwire.ChannelReady:
4✔
1998

4✔
1999
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
4✔
2000

2001
                case *lnwire.Shutdown:
4✔
2002
                        select {
4✔
2003
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
4✔
2004
                        case <-p.quit:
×
2005
                                break out
×
2006
                        }
2007
                case *lnwire.ClosingSigned:
4✔
2008
                        select {
4✔
2009
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
4✔
2010
                        case <-p.quit:
×
2011
                                break out
×
2012
                        }
2013

2014
                case *lnwire.Warning:
×
2015
                        targetChan = msg.ChanID
×
2016
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2017

2018
                case *lnwire.Error:
4✔
2019
                        targetChan = msg.ChanID
4✔
2020
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
4✔
2021

2022
                case *lnwire.ChannelReestablish:
4✔
2023
                        targetChan = msg.ChanID
4✔
2024
                        isLinkUpdate = p.hasChannel(targetChan)
4✔
2025

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

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

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

2058
                case *lnwire.ChannelUpdate1,
2059
                        *lnwire.ChannelAnnouncement1,
2060
                        *lnwire.NodeAnnouncement,
2061
                        *lnwire.AnnounceSignatures1,
2062
                        *lnwire.GossipTimestampRange,
2063
                        *lnwire.QueryShortChanIDs,
2064
                        *lnwire.QueryChannelRange,
2065
                        *lnwire.ReplyChannelRange,
2066
                        *lnwire.ReplyShortChanIDsEnd:
4✔
2067

4✔
2068
                        discStream.AddMsg(msg)
4✔
2069

2070
                case *lnwire.Custom:
5✔
2071
                        err := p.handleCustomMessage(msg)
5✔
2072
                        if err != nil {
5✔
2073
                                p.storeError(err)
×
2074
                                p.log.Errorf("%v", err)
×
2075
                        }
×
2076

2077
                default:
×
2078
                        // If the message we received is unknown to us, store
×
2079
                        // the type to track the failure.
×
2080
                        err := fmt.Errorf("unknown message type %v received",
×
2081
                                uint16(msg.MsgType()))
×
2082
                        p.storeError(err)
×
2083

×
2084
                        p.log.Errorf("%v", err)
×
2085
                }
2086

2087
                if isLinkUpdate {
9✔
2088
                        // If this is a channel update, then we need to feed it
4✔
2089
                        // into the channel's in-order message stream.
4✔
2090
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
4✔
2091
                }
4✔
2092

2093
                idleTimer.Reset(idleTimeout)
5✔
2094
        }
2095

2096
        p.Disconnect(errors.New("read handler closed"))
4✔
2097

4✔
2098
        p.log.Trace("readHandler for peer done")
4✔
2099
}
2100

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

2109
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
5✔
2110
}
2111

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

2123
        // Return false if the channel is unknown.
2124
        channel, ok := p.activeChannels.Load(chanID)
4✔
2125
        if !ok {
4✔
2126
                return false
×
2127
        }
×
2128

2129
        // During startup, we will use a nil value to mark a pending channel
2130
        // that's loaded from disk.
2131
        return channel == nil
4✔
2132
}
2133

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

12✔
2143
        return channel != nil
12✔
2144
}
12✔
2145

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

2155
        return channel == nil
3✔
2156
}
2157

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

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

5✔
2172
        p.activeChannels.Range(func(_ lnwire.ChannelID,
5✔
2173
                channel *lnwallet.LightningChannel) bool {
10✔
2174

5✔
2175
                // Pending channels will be nil in the activeChannels map.
5✔
2176
                if channel == nil {
9✔
2177
                        // Return true to continue the iteration.
4✔
2178
                        return true
4✔
2179
                }
4✔
2180

2181
                haveChannels = true
5✔
2182

5✔
2183
                // Return false to break the iteration.
5✔
2184
                return false
5✔
2185
        })
2186

2187
        // If we do not have any active channels with the peer, we do not store
2188
        // errors as a dos mitigation.
2189
        if !haveChannels {
9✔
2190
                p.log.Trace("no channels with peer, not storing err")
4✔
2191
                return
4✔
2192
        }
4✔
2193

2194
        p.cfg.ErrorBuffer.Add(
5✔
2195
                &TimestampedError{Timestamp: time.Now(), Error: err},
5✔
2196
        )
5✔
2197
}
2198

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

4✔
2208
        if errMsg, ok := msg.(*lnwire.Error); ok {
8✔
2209
                p.storeError(errMsg)
4✔
2210
        }
4✔
2211

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

2220
                return false
×
2221

2222
        // If the channel ID for the message corresponds to a pending channel,
2223
        // then the funding manager will handle it.
2224
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
4✔
2225
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
4✔
2226
                return false
4✔
2227

2228
        // If not we hand the message to the channel link for this channel.
2229
        case p.isActiveChannel(chanID):
4✔
2230
                return true
4✔
2231

2232
        default:
4✔
2233
                return false
4✔
2234
        }
2235
}
2236

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

2246
        case *lnwire.OpenChannel:
4✔
2247
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
4✔
2248
                        "push_amt=%v, reserve=%v, flags=%v",
4✔
2249
                        msg.PendingChannelID[:], msg.ChainHash,
4✔
2250
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
4✔
2251
                        msg.ChannelReserve, msg.ChannelFlags)
4✔
2252

2253
        case *lnwire.AcceptChannel:
4✔
2254
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
4✔
2255
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
4✔
2256
                        msg.MinAcceptDepth)
4✔
2257

2258
        case *lnwire.FundingCreated:
4✔
2259
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
4✔
2260
                        msg.PendingChannelID[:], msg.FundingPoint)
4✔
2261

2262
        case *lnwire.FundingSigned:
4✔
2263
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
4✔
2264

2265
        case *lnwire.ChannelReady:
4✔
2266
                return fmt.Sprintf("chan_id=%v, next_point=%x",
4✔
2267
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
4✔
2268

2269
        case *lnwire.Shutdown:
4✔
2270
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
4✔
2271
                        msg.Address[:])
4✔
2272

2273
        case *lnwire.ClosingSigned:
4✔
2274
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
4✔
2275
                        msg.FeeSatoshis)
4✔
2276

2277
        case *lnwire.UpdateAddHTLC:
4✔
2278
                var blindingPoint []byte
4✔
2279
                msg.BlindingPoint.WhenSome(
4✔
2280
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
4✔
2281
                                *btcec.PublicKey]) {
8✔
2282

4✔
2283
                                blindingPoint = b.Val.SerializeCompressed()
4✔
2284
                        },
4✔
2285
                )
2286

2287
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
4✔
2288
                        "hash=%x, blinding_point=%x, custom_records=%v",
4✔
2289
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
4✔
2290
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
4✔
2291

2292
        case *lnwire.UpdateFailHTLC:
4✔
2293
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
4✔
2294
                        msg.ID, msg.Reason)
4✔
2295

2296
        case *lnwire.UpdateFulfillHTLC:
4✔
2297
                return fmt.Sprintf("chan_id=%v, id=%v, pre_image=%x, "+
4✔
2298
                        "custom_records=%v", msg.ChanID, msg.ID,
4✔
2299
                        msg.PaymentPreimage[:], msg.CustomRecords)
4✔
2300

2301
        case *lnwire.CommitSig:
4✔
2302
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
4✔
2303
                        len(msg.HtlcSigs))
4✔
2304

2305
        case *lnwire.RevokeAndAck:
4✔
2306
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
4✔
2307
                        msg.ChanID, msg.Revocation[:],
4✔
2308
                        msg.NextRevocationKey.SerializeCompressed())
4✔
2309

2310
        case *lnwire.UpdateFailMalformedHTLC:
4✔
2311
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
4✔
2312
                        msg.ChanID, msg.ID, msg.FailureCode)
4✔
2313

2314
        case *lnwire.Warning:
×
2315
                return fmt.Sprintf("%v", msg.Warning())
×
2316

2317
        case *lnwire.Error:
4✔
2318
                return fmt.Sprintf("%v", msg.Error())
4✔
2319

2320
        case *lnwire.AnnounceSignatures1:
4✔
2321
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
4✔
2322
                        msg.ShortChannelID.ToUint64())
4✔
2323

2324
        case *lnwire.ChannelAnnouncement1:
4✔
2325
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
4✔
2326
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
4✔
2327

2328
        case *lnwire.ChannelUpdate1:
4✔
2329
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
4✔
2330
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
4✔
2331
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
4✔
2332
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
4✔
2333

2334
        case *lnwire.NodeAnnouncement:
4✔
2335
                return fmt.Sprintf("node=%x, update_time=%v",
4✔
2336
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
4✔
2337

2338
        case *lnwire.Ping:
2✔
2339
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
2✔
2340

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

2344
        case *lnwire.UpdateFee:
×
2345
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2346
                        msg.ChanID, int64(msg.FeePerKw))
×
2347

2348
        case *lnwire.ChannelReestablish:
4✔
2349
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
4✔
2350
                        "remote_tail_height=%v", msg.ChanID,
4✔
2351
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
4✔
2352

2353
        case *lnwire.ReplyShortChanIDsEnd:
4✔
2354
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
4✔
2355
                        msg.Complete)
4✔
2356

2357
        case *lnwire.ReplyChannelRange:
4✔
2358
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
4✔
2359
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
4✔
2360
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
4✔
2361
                        msg.EncodingType)
4✔
2362

2363
        case *lnwire.QueryShortChanIDs:
4✔
2364
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
4✔
2365
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
4✔
2366

2367
        case *lnwire.QueryChannelRange:
4✔
2368
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
4✔
2369
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
4✔
2370
                        msg.LastBlockHeight())
4✔
2371

2372
        case *lnwire.GossipTimestampRange:
4✔
2373
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
4✔
2374
                        "stamp_range=%v", msg.ChainHash,
4✔
2375
                        time.Unix(int64(msg.FirstTimestamp), 0),
4✔
2376
                        msg.TimestampRange)
4✔
2377

2378
        case *lnwire.Stfu:
4✔
2379
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
4✔
2380
                        msg.Initiator)
4✔
2381

2382
        case *lnwire.Custom:
4✔
2383
                return fmt.Sprintf("type=%d", msg.Type)
4✔
2384
        }
2385

2386
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2387
}
2388

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

2400
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
25✔
2401
                // Debug summary of message.
4✔
2402
                summary := messageSummary(msg)
4✔
2403
                if len(summary) > 0 {
8✔
2404
                        summary = "(" + summary + ")"
4✔
2405
                }
4✔
2406

2407
                preposition := "to"
4✔
2408
                if read {
8✔
2409
                        preposition = "from"
4✔
2410
                }
4✔
2411

2412
                var msgType string
4✔
2413
                if msg.MsgType() < lnwire.CustomTypeStart {
8✔
2414
                        msgType = msg.MsgType().String()
4✔
2415
                } else {
8✔
2416
                        msgType = "custom"
4✔
2417
                }
4✔
2418

2419
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
4✔
2420
                        msgType, summary, preposition, p)
4✔
2421
        }))
2422

2423
        prefix := "readMessage from peer"
21✔
2424
        if !read {
38✔
2425
                prefix = "writeMessage to peer"
17✔
2426
        }
17✔
2427

2428
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
21✔
2429
}
2430

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

2448
        noiseConn := p.cfg.Conn
17✔
2449

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

2461
                // Flush the pending message to the wire. If an error is
2462
                // encountered, e.g. write timeout, the number of bytes written
2463
                // so far will be returned.
2464
                n, err := noiseConn.Flush()
17✔
2465

17✔
2466
                // Record the number of bytes written on the wire, if any.
17✔
2467
                if n > 0 {
21✔
2468
                        atomic.AddUint64(&p.bytesSent, uint64(n))
4✔
2469
                }
4✔
2470

2471
                return err
17✔
2472
        }
2473

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

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

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

2501
        return flushMsg()
17✔
2502
}
2503

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

2519
        var exitErr error
7✔
2520

7✔
2521
out:
7✔
2522
        for {
18✔
2523
                select {
11✔
2524
                case outMsg := <-p.sendQueue:
8✔
2525
                        // Record the time at which we first attempt to send the
8✔
2526
                        // message.
8✔
2527
                        startTime := time.Now()
8✔
2528

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

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

×
2550
                                goto retry
×
2551
                        }
2552

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

8✔
2563
                        // If the peer requested a synchronous write, respond
8✔
2564
                        // with the error.
8✔
2565
                        if outMsg.errChan != nil {
13✔
2566
                                outMsg.errChan <- err
5✔
2567
                        }
5✔
2568

2569
                        if err != nil {
8✔
2570
                                exitErr = fmt.Errorf("unable to write "+
×
2571
                                        "message: %v", err)
×
2572
                                break out
×
2573
                        }
2574

2575
                case <-p.quit:
4✔
2576
                        exitErr = lnpeer.ErrPeerExiting
4✔
2577
                        break out
4✔
2578
                }
2579
        }
2580

2581
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2582
        // disconnect.
2583
        p.wg.Done()
4✔
2584

4✔
2585
        p.Disconnect(exitErr)
4✔
2586

4✔
2587
        p.log.Trace("writeHandler for peer done")
4✔
2588
}
2589

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

7✔
2597
        // priorityMsgs holds an in order list of messages deemed high-priority
7✔
2598
        // to be added to the sendQueue. This predominately includes messages
7✔
2599
        // from the funding manager and htlcswitch.
7✔
2600
        priorityMsgs := list.New()
7✔
2601

7✔
2602
        // lazyMsgs holds an in order list of messages deemed low-priority to be
7✔
2603
        // added to the sendQueue only after all high-priority messages have
7✔
2604
        // been queued. This predominately includes messages from the gossiper.
7✔
2605
        lazyMsgs := list.New()
7✔
2606

7✔
2607
        for {
22✔
2608
                // Examine the front of the priority queue, if it is empty check
15✔
2609
                // the low priority queue.
15✔
2610
                elem := priorityMsgs.Front()
15✔
2611
                if elem == nil {
27✔
2612
                        elem = lazyMsgs.Front()
12✔
2613
                }
12✔
2614

2615
                if elem != nil {
23✔
2616
                        front := elem.Value.(outgoingMsg)
8✔
2617

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

2657
// PingTime returns the estimated ping time to the peer in microseconds.
2658
func (p *Brontide) PingTime() int64 {
4✔
2659
        return p.pingManager.GetPingTimeMicroSeconds()
4✔
2660
}
4✔
2661

2662
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2663
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2664
// or failed to write, and nil otherwise.
2665
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
28✔
2666
        p.queue(true, msg, errChan)
28✔
2667
}
28✔
2668

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

2676
// queue sends a given message to the queueHandler using the passed priority. If
2677
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2678
// failed to write, and nil otherwise.
2679
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2680
        errChan chan error) {
29✔
2681

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

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

4✔
2700
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
4✔
2701
                activeChan *lnwallet.LightningChannel) error {
8✔
2702

4✔
2703
                // If the activeChan is nil, then we skip it as the channel is
4✔
2704
                // pending.
4✔
2705
                if activeChan == nil {
8✔
2706
                        return nil
4✔
2707
                }
4✔
2708

2709
                // We'll only return a snapshot for channels that are
2710
                // *immediately* available for routing payments over.
2711
                if activeChan.RemoteNextRevocation() == nil {
8✔
2712
                        return nil
4✔
2713
                }
4✔
2714

2715
                snapshot := activeChan.StateSnapshot()
4✔
2716
                snapshots = append(snapshots, snapshot)
4✔
2717

4✔
2718
                return nil
4✔
2719
        })
2720

2721
        return snapshots
4✔
2722
}
2723

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

2734
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
10✔
2735
                addrType, false, lnwallet.DefaultAccountName,
10✔
2736
        )
10✔
2737
        if err != nil {
10✔
2738
                return nil, err
×
2739
        }
×
2740
        p.log.Infof("Delivery addr for channel close: %v",
10✔
2741
                deliveryAddr)
10✔
2742

10✔
2743
        return txscript.PayToAddrScript(deliveryAddr)
10✔
2744
}
2745

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

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

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

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

2776
                // The funding flow for a pending channel is failed, we will
2777
                // remove it from Brontide.
2778
                case req := <-p.removePendingChannel:
5✔
2779
                        p.handleRemovePendingChannel(req)
5✔
2780

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

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

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

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

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

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

2828
                case <-p.quit:
5✔
2829
                        // As, we've been signalled to exit, we'll reset all
5✔
2830
                        // our active channel back to their default state.
5✔
2831
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
5✔
2832
                                lc *lnwallet.LightningChannel) error {
10✔
2833

5✔
2834
                                // Exit if the channel is nil as it's a pending
5✔
2835
                                // channel.
5✔
2836
                                if lc == nil {
9✔
2837
                                        return nil
4✔
2838
                                }
4✔
2839

2840
                                lc.ResetState()
5✔
2841

5✔
2842
                                return nil
5✔
2843
                        })
2844

2845
                        break out
5✔
2846
                }
2847
        }
2848
}
2849

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

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

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

4✔
2868
                switch {
4✔
2869
                // No error occurred, continue to request the next channel.
2870
                case err == nil:
4✔
2871
                        continue
4✔
2872

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

4✔
2879
                        continue
4✔
2880

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

×
2898
                                continue
×
2899
                        }
2900

2901
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
2902
                                "ChanStatusManager reported inactive, retrying")
×
2903

×
2904
                        // Add the channel to the retry map.
×
2905
                        retryChans[chanPoint] = struct{}{}
×
2906
                }
2907
        }
2908

2909
        // Retry the channels if we have any.
2910
        if len(retryChans) != 0 {
4✔
2911
                p.retryRequestEnable(retryChans)
×
2912
        }
×
2913
}
2914

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

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

2931
        // First, we'll ensure that we actually know of the target channel. If
2932
        // not, we'll ignore this message.
2933
        channel, ok := p.activeChannels.Load(chanID)
7✔
2934

7✔
2935
        // If the channel isn't in the map or the channel is nil, return
7✔
2936
        // ErrChannelNotFound as the channel is pending.
7✔
2937
        if !ok || channel == nil {
11✔
2938
                return nil, ErrChannelNotFound
4✔
2939
        }
4✔
2940

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

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

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

2982
        p.activeChanCloses[chanID] = chanCloser
7✔
2983

7✔
2984
        return chanCloser, nil
7✔
2985
}
2986

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

4✔
2993
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
4✔
2994
                lnChan *lnwallet.LightningChannel) bool {
8✔
2995

4✔
2996
                // If the lnChan is nil, continue as this is a pending channel.
4✔
2997
                if lnChan == nil {
6✔
2998
                        return true
2✔
2999
                }
2✔
3000

3001
                dbChan := lnChan.State()
4✔
3002
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
4✔
3003
                if !isPublic || dbChan.IsPending {
4✔
3004
                        return true
×
3005
                }
×
3006

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

3016
                activePublicChans = append(
4✔
3017
                        activePublicChans, dbChan.FundingOutpoint,
4✔
3018
                )
4✔
3019

4✔
3020
                return true
4✔
3021
        })
3022

3023
        return activePublicChans
4✔
3024
}
3025

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

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

×
3040
                // If this channel is irrelevant, return nil so the loop can
×
3041
                // jump to next iteration.
×
3042
                if !found {
×
3043
                        return nil
×
3044
                }
×
3045

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

×
3054
                // Send the request.
×
3055
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3056
                if err != nil {
×
3057
                        return fmt.Errorf("request enabling channel %v "+
×
3058
                                "failed: %w", chanPoint, err)
×
3059
                }
×
3060

3061
                return nil
×
3062
        }
3063

3064
        for {
×
3065
                // If activeChans is empty, we've done processing all the
×
3066
                // channels.
×
3067
                if len(activeChans) == 0 {
×
3068
                        p.log.Debug("Finished retry enabling channels")
×
3069
                        return
×
3070
                }
×
3071

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

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

3089
                                continue
×
3090
                        }
3091

3092
                        // Otherwise check for inactive link event, and jump to
3093
                        // next iteration if it's not.
3094
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3095
                        if !ok {
×
3096
                                continue
×
3097
                        }
3098

3099
                        // Found an inactive link event, if this is our
3100
                        // targeted channel, remove it from our map.
3101
                        chanPoint := *inactive.ChannelPoint
×
3102
                        _, found := activeChans[chanPoint]
×
3103
                        if !found {
×
3104
                                continue
×
3105
                        }
3106

3107
                        delete(activeChans, chanPoint)
×
3108
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3109
                                "inactive link event", chanPoint)
×
3110

3111
                case <-p.quit:
×
3112
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3113
                        return
×
3114
                }
3115
        }
3116
}
3117

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

16✔
3124
        // If no upfront shutdown script was provided, return the user
16✔
3125
        // requested address (which may be nil).
16✔
3126
        if len(upfront) == 0 {
26✔
3127
                return requested, nil
10✔
3128
        }
10✔
3129

3130
        // If an upfront shutdown script was provided, and the user did not
3131
        // request a custom shutdown script, return the upfront address.
3132
        if len(requested) == 0 {
16✔
3133
                return upfront, nil
6✔
3134
        }
6✔
3135

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

3144
        // The user requested script matches the upfront shutdown script, so we
3145
        // can return it without error.
3146
        return upfront, nil
2✔
3147
}
3148

3149
// restartCoopClose checks whether we need to restart the cooperative close
3150
// process for a given channel.
3151
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3152
        *lnwire.Shutdown, error) {
×
3153

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

3172
        var deliveryScript []byte
×
3173

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

3183
        // An error other than ErrNoShutdownInfo was returned
3184
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3185
                return nil, err
×
3186

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

×
3196
                                return nil, fmt.Errorf("close addr unavailable")
×
3197
                        }
×
3198
                }
3199
        }
3200

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

3210
        // Determine whether we or the peer are the initiator of the coop
3211
        // close attempt by looking at the channel's status.
3212
        closingParty := lntypes.Remote
×
3213
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3214
                closingParty = lntypes.Local
×
3215
        }
×
3216

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

3229
        // This does not need a mutex even though it is in a different
3230
        // goroutine since this is done before the channelManager goroutine is
3231
        // created.
3232
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
×
3233
        p.activeChanCloses[chanID] = chanCloser
×
3234

×
3235
        // Create the Shutdown message.
×
3236
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3237
        if err != nil {
×
3238
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3239
                delete(p.activeChanCloses, chanID)
×
3240
                return nil, err
×
3241
        }
×
3242

3243
        return shutdownMsg, nil
×
3244
}
3245

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

13✔
3253
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
13✔
3254
        if err != nil {
13✔
3255
                p.log.Errorf("unable to obtain best block: %v", err)
×
3256
                return nil, fmt.Errorf("cannot obtain best block")
×
3257
        }
×
3258

3259
        // The req will only be set if we initiated the co-op closing flow.
3260
        var maxFee chainfee.SatPerKWeight
13✔
3261
        if req != nil {
23✔
3262
                maxFee = req.MaxFee
10✔
3263
        }
10✔
3264

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

3291
        return chanCloser, nil
13✔
3292
}
3293

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

11✔
3299
        channel, ok := p.activeChannels.Load(chanID)
11✔
3300

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

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

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

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

×
3350
                        return
×
3351
                }
×
3352
                chanCloser, err := p.createChanCloser(
10✔
3353
                        channel, addr, req.TargetFeePerKw, req, lntypes.Local,
10✔
3354
                )
10✔
3355
                if err != nil {
10✔
3356
                        p.log.Errorf(err.Error())
×
3357
                        req.Err <- err
×
3358
                        return
×
3359
                }
×
3360

3361
                p.activeChanCloses[chanID] = chanCloser
10✔
3362

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

×
3372
                        // As we were unable to shutdown the channel, we'll
×
3373
                        // return it back to its normal state.
×
3374
                        channel.ResetState()
×
3375
                        return
×
3376
                }
×
3377

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

3391
                if !link.DisableAdds(htlcswitch.Outgoing) {
10✔
3392
                        p.log.Warnf("Outgoing link adds already "+
×
3393
                                "disabled: %v", link.ChanID())
×
3394
                }
×
3395

3396
                link.OnCommitOnce(htlcswitch.Outgoing, func() {
20✔
3397
                        p.queueMsg(shutdownMsg, nil)
10✔
3398
                })
10✔
3399

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

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

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

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

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

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

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

×
3463
                if err := lnChan.State().MarkBorked(); err != nil {
×
3464
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
3465
                                failure.shortChanID, err)
×
3466
                }
×
3467
        }
3468

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

3480
                var networkMsg lnwire.Message
4✔
3481
                if failure.linkErr.Warning {
4✔
3482
                        networkMsg = &lnwire.Warning{
×
3483
                                ChanID: failure.chanID,
×
3484
                                Data:   data,
×
3485
                        }
×
3486
                } else {
4✔
3487
                        networkMsg = &lnwire.Error{
4✔
3488
                                ChanID: failure.chanID,
4✔
3489
                                Data:   data,
4✔
3490
                        }
4✔
3491
                }
4✔
3492

3493
                err := p.SendMessage(true, networkMsg)
4✔
3494
                if err != nil {
4✔
3495
                        p.log.Errorf("unable to send msg to "+
×
3496
                                "remote peer: %v", err)
×
3497
                }
×
3498
        }
3499

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

3508
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
3509
// public key and the channel id.
3510
func (p *Brontide) fetchLinkFromKeyAndCid(
3511
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
23✔
3512

23✔
3513
        var chanLink htlcswitch.ChannelUpdateHandler
23✔
3514

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

3525
        return chanLink
23✔
3526
}
3527

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

8✔
3536
        // First, we'll clear all indexes related to the channel in question.
8✔
3537
        chanPoint := chanCloser.Channel().ChannelPoint()
8✔
3538
        p.WipeChannel(&chanPoint)
8✔
3539

8✔
3540
        // Also clear the activeChanCloses map of this channel.
8✔
3541
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
8✔
3542
        delete(p.activeChanCloses, cid)
8✔
3543

8✔
3544
        // Next, we'll launch a goroutine which will request to be notified by
8✔
3545
        // the ChainNotifier once the closure transaction obtains a single
8✔
3546
        // confirmation.
8✔
3547
        notifier := p.cfg.ChainNotifier
8✔
3548

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

3557
        closingTx, err := chanCloser.ClosingTx()
8✔
3558
        if err != nil {
8✔
3559
                if closeReq != nil {
×
3560
                        p.log.Error(err)
×
3561
                        closeReq.Err <- err
×
3562
                }
×
3563
        }
3564

3565
        closingTxid := closingTx.TxHash()
8✔
3566

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

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

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

8✔
3605
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
8✔
3606
                "with txid: %v", chanPoint, closingTxID)
8✔
3607

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

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

3626
        // The channel has been closed, remove it from any active indexes, and
3627
        // the database state.
3628
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
8✔
3629
                "height %v", chanPoint, height.BlockHeight)
8✔
3630

8✔
3631
        // Finally, execute the closure call back to mark the confirmation of
8✔
3632
        // the transaction closing the contract.
8✔
3633
        cb()
8✔
3634
}
3635

3636
// WipeChannel removes the passed channel point from all indexes associated with
3637
// the peer and the switch.
3638
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
8✔
3639
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
8✔
3640

8✔
3641
        p.activeChannels.Delete(chanID)
8✔
3642

8✔
3643
        // Instruct the HtlcSwitch to close this link as the channel is no
8✔
3644
        // longer active.
8✔
3645
        p.cfg.Switch.RemoveLink(chanID)
8✔
3646
}
8✔
3647

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

3659
        // Then, finalize the remote feature vector providing the flattened
3660
        // feature bit namespace.
3661
        p.remoteFeatures = lnwire.NewFeatureVector(
7✔
3662
                msg.Features, lnwire.Features,
7✔
3663
        )
7✔
3664

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

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

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

3686
        return nil
7✔
3687
}
3688

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

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

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

3715
// sendInitMsg sends the Init message to the remote peer. This message contains
3716
// our currently supported local and global features.
3717
func (p *Brontide) sendInitMsg(legacyChan bool) error {
11✔
3718
        features := p.cfg.Features.Clone()
11✔
3719
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
11✔
3720

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

1✔
3731
                // Unset and set in both the local and global features to
1✔
3732
                // ensure both sets are consistent and merge able by old and
1✔
3733
                // new nodes.
1✔
3734
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3735
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3736

1✔
3737
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
3738
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
3739
        }
1✔
3740

3741
        msg := lnwire.NewInitMessage(
11✔
3742
                legacyFeatures.RawFeatureVector,
11✔
3743
                features.RawFeatureVector,
11✔
3744
        )
11✔
3745

11✔
3746
        return p.writeMessage(msg)
11✔
3747
}
3748

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

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

3765
        if c.LastChanSyncMsg == nil {
4✔
3766
                return fmt.Errorf("no chan sync message stored for channel %v",
×
3767
                        cid)
×
3768
        }
×
3769

3770
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
4✔
3771
                return fmt.Errorf("ignoring channel reestablish from "+
×
3772
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
3773
        }
×
3774

3775
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
4✔
3776
                "peer", cid)
4✔
3777

4✔
3778
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
4✔
3779
                return fmt.Errorf("failed resending channel sync "+
×
3780
                        "message to peer %v: %v", p, err)
×
3781
        }
×
3782

3783
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
4✔
3784
                cid)
4✔
3785

4✔
3786
        // Note down that we sent the message, so we won't resend it again for
4✔
3787
        // this connection.
4✔
3788
        p.resentChanSyncMsg[cid] = struct{}{}
4✔
3789

4✔
3790
        return nil
4✔
3791
}
3792

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

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

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

3834
                if priority {
15✔
3835
                        p.queueMsg(msg, errChan)
7✔
3836
                } else {
12✔
3837
                        p.queueMsgLazy(msg, errChan)
5✔
3838
                }
5✔
3839
        }
3840

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

3854
        return nil
7✔
3855
}
3856

3857
// PubKey returns the pubkey of the peer in compressed serialized format.
3858
//
3859
// NOTE: Part of the lnpeer.Peer interface.
3860
func (p *Brontide) PubKey() [33]byte {
6✔
3861
        return p.cfg.PubKeyBytes
6✔
3862
}
6✔
3863

3864
// IdentityKey returns the public key of the remote peer.
3865
//
3866
// NOTE: Part of the lnpeer.Peer interface.
3867
func (p *Brontide) IdentityKey() *btcec.PublicKey {
19✔
3868
        return p.cfg.Addr.IdentityKey
19✔
3869
}
19✔
3870

3871
// Address returns the network address of the remote peer.
3872
//
3873
// NOTE: Part of the lnpeer.Peer interface.
3874
func (p *Brontide) Address() net.Addr {
4✔
3875
        return p.cfg.Addr.Address
4✔
3876
}
4✔
3877

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

4✔
3885
        errChan := make(chan error, 1)
4✔
3886
        newChanMsg := &newChannelMsg{
4✔
3887
                channel: newChan,
4✔
3888
                err:     errChan,
4✔
3889
        }
4✔
3890

4✔
3891
        select {
4✔
3892
        case p.newActiveChannel <- newChanMsg:
4✔
3893
        case <-cancel:
×
3894
                return errors.New("canceled adding new channel")
×
3895
        case <-p.quit:
×
3896
                return lnpeer.ErrPeerExiting
×
3897
        }
3898

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

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

4✔
3916
        errChan := make(chan error, 1)
4✔
3917
        newChanMsg := &newChannelMsg{
4✔
3918
                channelID: cid,
4✔
3919
                err:       errChan,
4✔
3920
        }
4✔
3921

4✔
3922
        select {
4✔
3923
        case p.newPendingChannel <- newChanMsg:
4✔
3924

3925
        case <-cancel:
×
3926
                return errors.New("canceled adding pending channel")
×
3927

3928
        case <-p.quit:
×
3929
                return lnpeer.ErrPeerExiting
×
3930
        }
3931

3932
        // We pause here to wait for the peer to recognize the new pending
3933
        // channel before we close the channel barrier corresponding to the
3934
        // channel.
3935
        select {
4✔
3936
        case err := <-errChan:
4✔
3937
                return err
4✔
3938

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

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

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

4✔
3957
        select {
4✔
3958
        case p.removePendingChannel <- newChanMsg:
4✔
3959
        case <-p.quit:
×
3960
                return lnpeer.ErrPeerExiting
×
3961
        }
3962

3963
        // We pause here to wait for the peer to respond to the cancellation of
3964
        // the pending channel before we close the channel barrier
3965
        // corresponding to the channel.
3966
        select {
4✔
3967
        case err := <-errChan:
4✔
3968
                return err
4✔
3969

3970
        case <-p.quit:
×
3971
                return lnpeer.ErrPeerExiting
×
3972
        }
3973
}
3974

3975
// StartTime returns the time at which the connection was established if the
3976
// peer started successfully, and zero otherwise.
3977
func (p *Brontide) StartTime() time.Time {
4✔
3978
        return p.startTime
4✔
3979
}
4✔
3980

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

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

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

×
3998
                errMsg := &lnwire.Error{
×
3999
                        ChanID: msg.cid,
×
4000
                        Data:   lnwire.ErrorData(err.Error()),
×
4001
                }
×
4002
                p.queueMsg(errMsg, nil)
×
4003
                return
×
4004
        }
4005

4006
        handleErr := func(err error) {
18✔
4007
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
4008
                p.log.Error(err)
1✔
4009

1✔
4010
                // As the negotiations failed, we'll reset the channel state machine to
1✔
4011
                // ensure we act to on-chain events as normal.
1✔
4012
                chanCloser.Channel().ResetState()
1✔
4013

1✔
4014
                if chanCloser.CloseRequest() != nil {
1✔
4015
                        chanCloser.CloseRequest().Err <- err
×
4016
                }
×
4017
                delete(p.activeChanCloses, msg.cid)
1✔
4018

1✔
4019
                p.Disconnect(err)
1✔
4020
        }
4021

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

4032
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
9✔
4033
                if err != nil {
9✔
4034
                        handleErr(err)
×
4035
                        return
×
4036
                }
×
4037

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

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

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

4062
                beginNegotiation := func() {
18✔
4063
                        oClosingSigned, err := chanCloser.BeginNegotiation()
9✔
4064
                        if err != nil {
10✔
4065
                                handleErr(err)
1✔
4066
                                return
1✔
4067
                        }
1✔
4068

4069
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
16✔
4070
                                p.queueMsg(&msg, nil)
8✔
4071
                        })
8✔
4072
                }
4073

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

4087
        case *lnwire.ClosingSigned:
12✔
4088
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
12✔
4089
                if err != nil {
12✔
UNCOV
4090
                        handleErr(err)
×
UNCOV
4091
                        return
×
UNCOV
4092
                }
×
4093

4094
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
24✔
4095
                        p.queueMsg(&msg, nil)
12✔
4096
                })
12✔
4097

4098
        default:
×
4099
                panic("impossible closeMsg type")
×
4100
        }
4101

4102
        // If we haven't finished close negotiations, then we'll continue as we
4103
        // can't yet finalize the closure.
4104
        if _, err := chanCloser.ClosingTx(); err != nil {
30✔
4105
                return
13✔
4106
        }
13✔
4107

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

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

4128
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
4129
func (p *Brontide) NetAddress() *lnwire.NetAddress {
4✔
4130
        return p.cfg.Addr
4✔
4131
}
4✔
4132

4133
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
4134
func (p *Brontide) Inbound() bool {
4✔
4135
        return p.cfg.Inbound
4✔
4136
}
4✔
4137

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

4143
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
4144
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
4✔
4145
        return p.cfg.ErrorBuffer
4✔
4146
}
4✔
4147

4148
// SetAddress sets the remote peer's address given an address.
4149
func (p *Brontide) SetAddress(address net.Addr) {
×
4150
        p.cfg.Addr.Address = address
×
4151
}
×
4152

4153
// ActiveSignal returns the peer's active signal.
4154
func (p *Brontide) ActiveSignal() chan struct{} {
4✔
4155
        return p.activeSignal
4✔
4156
}
4✔
4157

4158
// Conn returns a pointer to the peer's connection struct.
4159
func (p *Brontide) Conn() net.Conn {
4✔
4160
        return p.cfg.Conn
4✔
4161
}
4✔
4162

4163
// BytesReceived returns the number of bytes received from the peer.
4164
func (p *Brontide) BytesReceived() uint64 {
4✔
4165
        return atomic.LoadUint64(&p.bytesReceived)
4✔
4166
}
4✔
4167

4168
// BytesSent returns the number of bytes sent to the peer.
4169
func (p *Brontide) BytesSent() uint64 {
4✔
4170
        return atomic.LoadUint64(&p.bytesSent)
4✔
4171
}
4✔
4172

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

4181
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
2✔
4182
        if !ok {
2✔
4183
                return nil
×
4184
        }
×
4185

4186
        return pingBytes
2✔
4187
}
4188

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

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

4210
        p.channelEventClient = sub
7✔
4211

7✔
4212
        return nil
7✔
4213
}
4214

4215
// updateNextRevocation updates the existing channel's next revocation if it's
4216
// nil.
4217
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
7✔
4218
        chanPoint := c.FundingOutpoint
7✔
4219
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
7✔
4220

7✔
4221
        // Read the current channel.
7✔
4222
        currentChan, loaded := p.activeChannels.Load(chanID)
7✔
4223

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

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

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

4245
        p.log.Infof("Processing retransmitted ChannelReady for "+
5✔
4246
                "ChannelPoint(%v)", chanPoint)
5✔
4247

5✔
4248
        nextRevoke := c.RemoteNextRevocation
5✔
4249

5✔
4250
        err := currentChan.InitNextRevocation(nextRevoke)
5✔
4251
        if err != nil {
5✔
4252
                return fmt.Errorf("unable to init next revocation: %w", err)
×
4253
        }
×
4254

4255
        return nil
5✔
4256
}
4257

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

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

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

4280
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
4✔
4281
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
4282
        })
×
4283
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
4✔
4284
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
4285
        })
×
4286
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
4✔
4287
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
4288
        })
×
4289

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

4300
        // Store the channel in the activeChannels map.
4301
        p.activeChannels.Store(chanID, lnChan)
4✔
4302

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

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

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

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

4331
        return nil
4✔
4332
}
4333

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

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

4✔
4349
                // Handle it and close the err chan on the request.
4✔
4350
                close(req.err)
4✔
4351

4✔
4352
                // Update the next revocation point.
4✔
4353
                err := p.updateNextRevocation(newChan.OpenChannel)
4✔
4354
                if err != nil {
4✔
4355
                        p.log.Errorf(err.Error())
×
4356
                }
×
4357

4358
                return
4✔
4359
        }
4360

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

×
4367
                return
×
4368
        }
×
4369

4370
        // Close the err chan if everything went fine.
4371
        close(req.err)
4✔
4372
}
4373

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

8✔
4381
        chanID := req.channelID
8✔
4382

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

1✔
4391
                return
1✔
4392
        }
1✔
4393

4394
        // The channel has already been added, we will do nothing and return.
4395
        if p.isPendingChannel(chanID) {
8✔
4396
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
4397
                        "pending channel request", chanID)
1✔
4398

1✔
4399
                return
1✔
4400
        }
1✔
4401

4402
        // This is a new channel, we now add it to the map `activeChannels`
4403
        // with nil value and mark it as a newly added channel in
4404
        // `addedChannels`.
4405
        p.activeChannels.Store(chanID, nil)
6✔
4406
        p.addedChannels.Store(chanID, struct{}{})
6✔
4407
}
4408

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

8✔
4415
        chanID := req.channelID
8✔
4416

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

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

4432
        // Remove the record of this pending channel.
4433
        p.activeChannels.Delete(chanID)
7✔
4434
        p.addedChannels.Delete(chanID)
7✔
4435
}
4436

4437
// sendLinkUpdateMsg sends a message that updates the channel to the
4438
// channel's message stream.
4439
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
4✔
4440
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
4✔
4441

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

4✔
4450
                // Stop the stream when quit.
4✔
4451
                go func() {
8✔
4452
                        <-p.quit
4✔
4453
                        chanStream.Stop()
4✔
4454
                }()
4✔
4455
        }
4456

4457
        // With the stream obtained, add the message to the stream so we can
4458
        // continue processing message.
4459
        chanStream.AddMsg(msg)
4✔
4460
}
4461

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

4471
        return timeout
67✔
4472
}
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