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

lightningnetwork / lnd / 11930700938

20 Nov 2024 09:41AM UTC coverage: 58.951% (-0.02%) from 58.968%
11930700938

push

github

web-flow
Merge pull request #9253 from ziggie1984/fix-chanArb-deadlock

fix chanArb deadlock

62 of 80 new or added lines in 5 files covered. (77.5%)

116 existing lines in 20 files now uncovered.

132753 of 225191 relevant lines covered (58.95%)

19545.39 hits per line

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

77.36
/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/build"
24
        "github.com/lightningnetwork/lnd/chainntnfs"
25
        "github.com/lightningnetwork/lnd/channeldb"
26
        "github.com/lightningnetwork/lnd/channeldb/models"
27
        "github.com/lightningnetwork/lnd/channelnotifier"
28
        "github.com/lightningnetwork/lnd/contractcourt"
29
        "github.com/lightningnetwork/lnd/discovery"
30
        "github.com/lightningnetwork/lnd/feature"
31
        "github.com/lightningnetwork/lnd/fn"
32
        "github.com/lightningnetwork/lnd/funding"
33
        "github.com/lightningnetwork/lnd/htlcswitch"
34
        "github.com/lightningnetwork/lnd/htlcswitch/hodl"
35
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
36
        "github.com/lightningnetwork/lnd/input"
37
        "github.com/lightningnetwork/lnd/invoices"
38
        "github.com/lightningnetwork/lnd/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 *channeldb.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
        // MaxFeeExposure limits the number of outstanding fees in a channel.
415
        // This value will be passed to created links.
416
        MaxFeeExposure lnwire.MilliSatoshi
417

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

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

427
        // Quit is the server's quit channel. If this is closed, we halt operation.
428
        Quit chan struct{}
429
}
430

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

442
        // MUST be used atomically.
443
        bytesReceived uint64
444
        bytesSent     uint64
445

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

463
        pingManager *PingManager
464

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

472
        cfg Config
473

474
        // activeSignal when closed signals that the peer is now active and
475
        // ready to process messages.
476
        activeSignal chan struct{}
477

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

482
        // sendQueue is the channel which is used to queue outgoing messages to be
483
        // written onto the wire. Note that this channel is unbuffered.
484
        sendQueue chan outgoingMsg
485

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

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

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

509
        // newActiveChannel is used by the fundingManager to send fully opened
510
        // channels to the source peer which handled the funding workflow.
511
        newActiveChannel chan *newChannelMsg
512

513
        // newPendingChannel is used by the fundingManager to send pending open
514
        // channels to the source peer which handled the funding workflow.
515
        newPendingChannel chan *newChannelMsg
516

517
        // removePendingChannel is used by the fundingManager to cancel pending
518
        // open channels to the source peer when the funding flow is failed.
519
        removePendingChannel chan *newChannelMsg
520

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

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

531
        // localCloseChanReqs is a channel in which any local requests to close
532
        // a particular channel are sent over.
533
        localCloseChanReqs chan *htlcswitch.ChanClose
534

535
        // linkFailures receives all reported channel failures from the switch,
536
        // and instructs the channelManager to clean remaining channel state.
537
        linkFailures chan linkFailureReport
538

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

544
        // remoteFeatures is the feature vector received from the peer during
545
        // the connection handshake.
546
        remoteFeatures *lnwire.FeatureVector
547

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

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

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

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

572
        startReady chan struct{}
573
        quit       chan struct{}
574
        wg         sync.WaitGroup
575

576
        // log is a peer-specific logging instance.
577
        log btclog.Logger
578
}
579

580
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer interface.
581
var _ lnpeer.Peer = (*Brontide)(nil)
582

583
// NewBrontide creates a new Brontide from a peer.Config struct.
584
func NewBrontide(cfg Config) *Brontide {
28✔
585
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
28✔
586

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

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

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

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

28✔
624
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
31✔
625
                remoteAddr := cfg.Conn.RemoteAddr().String()
3✔
626
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
3✔
627
                        strings.Contains(remoteAddr, "127.0.0.1")
3✔
628
        }
3✔
629

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

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

657
                return lastSerializedBlockHeader[:]
1✔
658
        }
659

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

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

689
        return p
28✔
690
}
691

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

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

6✔
704
        p.log.Tracef("starting with conn[%v->%v]",
6✔
705
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
6✔
706

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

718
        if len(activeChans) == 0 {
10✔
719
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
4✔
720
        }
4✔
721

722
        // Quickly check if we have any existing legacy channels with this
723
        // peer.
724
        haveLegacyChan := false
6✔
725
        for _, c := range activeChans {
11✔
726
                if c.ChanType.IsTweakless() {
10✔
727
                        continue
5✔
728
                }
729

730
                haveLegacyChan = true
3✔
731
                break
3✔
732
        }
733

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

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

6✔
749
                msg, err := p.readNextMessage()
6✔
750
                if err != nil {
6✔
UNCOV
751
                        readErr <- err
×
UNCOV
752
                        msgChan <- nil
×
UNCOV
753
                        return
×
UNCOV
754
                }
×
755
                readErr <- nil
6✔
756
                msgChan <- msg
6✔
757
        }()
758

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

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

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

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

801
        // Register the message router now as we may need to register some
802
        // endpoints while loading the channels below.
803
        p.msgRouter.WhenSome(func(router msgmux.Router) {
12✔
804
                router.Start()
6✔
805
        })
6✔
806

807
        msgs, err := p.loadActiveChannels(activeChans)
6✔
808
        if err != nil {
6✔
809
                return fmt.Errorf("unable to load channels: %w", err)
×
810
        }
×
811

812
        p.startTime = time.Now()
6✔
813

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

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

831
        err = p.pingManager.Start()
6✔
832
        if err != nil {
6✔
833
                return fmt.Errorf("could not start ping manager %w", err)
×
834
        }
×
835

836
        p.wg.Add(4)
6✔
837
        go p.queueHandler()
6✔
838
        go p.writeHandler()
6✔
839
        go p.channelManager()
6✔
840
        go p.readHandler()
6✔
841

6✔
842
        // Signal to any external processes that the peer is now active.
6✔
843
        close(p.activeSignal)
6✔
844

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

6✔
860
        return nil
6✔
861
}
862

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

6✔
871
                if p.cfg.AuthGossiper == nil {
9✔
872
                        // This should only ever be hit in the unit tests.
3✔
873
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
3✔
874
                                "gossip sync.")
3✔
875
                        return
3✔
876
                }
3✔
877

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

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

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

908
// addrWithInternalKey takes a delivery script, then attempts to supplement it
909
// with information related to the internal key for the addr, but only if it's
910
// a taproot addr.
911
func (p *Brontide) addrWithInternalKey(
912
        deliveryScript []byte) (*chancloser.DeliveryAddrWithKey, error) {
12✔
913

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

925
        return &chancloser.DeliveryAddrWithKey{
12✔
926
                DeliveryAddress: deliveryScript,
12✔
927
                InternalKey: fn.MapOption(
12✔
928
                        func(desc keychain.KeyDescriptor) btcec.PublicKey {
15✔
929
                                return *desc.PubKey
3✔
930
                        },
3✔
931
                )(internalKeyDesc),
932
        }, nil
933
}
934

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

6✔
942
        // Return a slice of messages to send to the peers in case the channel
6✔
943
        // cannot be loaded normally.
6✔
944
        var msgs []lnwire.Message
6✔
945

6✔
946
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
6✔
947

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

968
                                err = p.cfg.AddLocalAlias(
3✔
969
                                        aliasScid, dbChan.ShortChanID(), false,
3✔
970
                                        false,
3✔
971
                                )
3✔
972
                                if err != nil {
3✔
973
                                        return nil, err
×
974
                                }
×
975

976
                                chanID := lnwire.NewChanIDFromOutPoint(
3✔
977
                                        dbChan.FundingOutpoint,
3✔
978
                                )
3✔
979

3✔
980
                                // Fetch the second commitment point to send in
3✔
981
                                // the channel_ready message.
3✔
982
                                second, err := dbChan.SecondCommitmentPoint()
3✔
983
                                if err != nil {
3✔
984
                                        return nil, err
×
985
                                }
×
986

987
                                channelReadyMsg := lnwire.NewChannelReady(
3✔
988
                                        chanID, second,
3✔
989
                                )
3✔
990
                                channelReadyMsg.AliasScid = &aliasScid
3✔
991

3✔
992
                                msgs = append(msgs, channelReadyMsg)
3✔
993
                        }
994

995
                        // If we've negotiated the option-scid-alias feature
996
                        // and this channel does not have ScidAliasFeature set
997
                        // to true due to an upgrade where the feature bit was
998
                        // turned on, we'll update the channel's database
999
                        // state.
1000
                        err := dbChan.MarkScidAliasNegotiated()
3✔
1001
                        if err != nil {
3✔
1002
                                return nil, err
×
1003
                        }
×
1004
                }
1005

1006
                var chanOpts []lnwallet.ChannelOpt
5✔
1007
                p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
5✔
1008
                        chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
1009
                })
×
1010
                p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
5✔
1011
                        chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
1012
                })
×
1013
                p.cfg.AuxResolver.WhenSome(
5✔
1014
                        func(s lnwallet.AuxContractResolver) {
5✔
1015
                                chanOpts = append(
×
1016
                                        chanOpts, lnwallet.WithAuxResolver(s),
×
1017
                                )
×
1018
                        },
×
1019
                )
1020

1021
                lnChan, err := lnwallet.NewLightningChannel(
5✔
1022
                        p.cfg.Signer, dbChan, p.cfg.SigPool, chanOpts...,
5✔
1023
                )
5✔
1024
                if err != nil {
5✔
1025
                        return nil, fmt.Errorf("unable to create channel "+
×
1026
                                "state machine: %w", err)
×
1027
                }
×
1028

1029
                chanPoint := dbChan.FundingOutpoint
5✔
1030

5✔
1031
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
5✔
1032

5✔
1033
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
5✔
1034
                        chanPoint, lnChan.IsPending())
5✔
1035

5✔
1036
                // Skip adding any permanently irreconcilable channels to the
5✔
1037
                // htlcswitch.
5✔
1038
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
5✔
1039
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
10✔
1040

5✔
1041
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
5✔
1042
                                "start.", chanPoint, dbChan.ChanStatus())
5✔
1043

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

1058
                        msgs = append(msgs, chanSync)
5✔
1059

5✔
1060
                        // Check if this channel needs to have the cooperative
5✔
1061
                        // close process restarted. If so, we'll need to send
5✔
1062
                        // the Shutdown message that is returned.
5✔
1063
                        if dbChan.HasChanStatus(
5✔
1064
                                channeldb.ChanStatusCoopBroadcasted,
5✔
1065
                        ) {
5✔
1066

×
1067
                                shutdownMsg, err := p.restartCoopClose(lnChan)
×
1068
                                if err != nil {
×
1069
                                        p.log.Errorf("Unable to restart "+
×
1070
                                                "coop close for channel: %v",
×
1071
                                                err)
×
1072
                                        continue
×
1073
                                }
1074

1075
                                if shutdownMsg == nil {
×
1076
                                        continue
×
1077
                                }
1078

1079
                                // Append the message to the set of messages to
1080
                                // send.
1081
                                msgs = append(msgs, shutdownMsg)
×
1082
                        }
1083

1084
                        continue
5✔
1085
                }
1086

1087
                // Before we register this new link with the HTLC Switch, we'll
1088
                // need to fetch its current link-layer forwarding policy from
1089
                // the database.
1090
                graph := p.cfg.ChannelGraph
3✔
1091
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
3✔
1092
                        &chanPoint,
3✔
1093
                )
3✔
1094
                if err != nil && !errors.Is(err, channeldb.ErrEdgeNotFound) {
3✔
1095
                        return nil, err
×
1096
                }
×
1097

1098
                // We'll filter out our policy from the directional channel
1099
                // edges based whom the edge connects to. If it doesn't connect
1100
                // to us, then we know that we were the one that advertised the
1101
                // policy.
1102
                //
1103
                // TODO(roasbeef): can add helper method to get policy for
1104
                // particular channel.
1105
                var selfPolicy *models.ChannelEdgePolicy
3✔
1106
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
3✔
1107
                        p.cfg.ServerPubKey[:]) {
6✔
1108

3✔
1109
                        selfPolicy = p1
3✔
1110
                } else {
6✔
1111
                        selfPolicy = p2
3✔
1112
                }
3✔
1113

1114
                // If we don't yet have an advertised routing policy, then
1115
                // we'll use the current default, otherwise we'll translate the
1116
                // routing policy into a forwarding policy.
1117
                var forwardingPolicy *models.ForwardingPolicy
3✔
1118
                if selfPolicy != nil {
6✔
1119
                        var inboundWireFee lnwire.Fee
3✔
1120
                        _, err := selfPolicy.ExtraOpaqueData.ExtractRecords(
3✔
1121
                                &inboundWireFee,
3✔
1122
                        )
3✔
1123
                        if err != nil {
3✔
1124
                                return nil, err
×
1125
                        }
×
1126

1127
                        inboundFee := models.NewInboundFeeFromWire(
3✔
1128
                                inboundWireFee,
3✔
1129
                        )
3✔
1130

3✔
1131
                        forwardingPolicy = &models.ForwardingPolicy{
3✔
1132
                                MinHTLCOut:    selfPolicy.MinHTLC,
3✔
1133
                                MaxHTLC:       selfPolicy.MaxHTLC,
3✔
1134
                                BaseFee:       selfPolicy.FeeBaseMSat,
3✔
1135
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
3✔
1136
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
3✔
1137

3✔
1138
                                InboundFee: inboundFee,
3✔
1139
                        }
3✔
1140
                } else {
3✔
1141
                        p.log.Warnf("Unable to find our forwarding policy "+
3✔
1142
                                "for channel %v, using default values",
3✔
1143
                                chanPoint)
3✔
1144
                        forwardingPolicy = &p.cfg.RoutingPolicy
3✔
1145
                }
3✔
1146

1147
                p.log.Tracef("Using link policy of: %v",
3✔
1148
                        spew.Sdump(forwardingPolicy))
3✔
1149

3✔
1150
                // If the channel is pending, set the value to nil in the
3✔
1151
                // activeChannels map. This is done to signify that the channel
3✔
1152
                // is pending. We don't add the link to the switch here - it's
3✔
1153
                // the funding manager's responsibility to spin up pending
3✔
1154
                // channels. Adding them here would just be extra work as we'll
3✔
1155
                // tear them down when creating + adding the final link.
3✔
1156
                if lnChan.IsPending() {
6✔
1157
                        p.activeChannels.Store(chanID, nil)
3✔
1158

3✔
1159
                        continue
3✔
1160
                }
1161

1162
                shutdownInfo, err := lnChan.State().ShutdownInfo()
3✔
1163
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
3✔
1164
                        return nil, err
×
1165
                }
×
1166

1167
                var (
3✔
1168
                        shutdownMsg     fn.Option[lnwire.Shutdown]
3✔
1169
                        shutdownInfoErr error
3✔
1170
                )
3✔
1171
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
6✔
1172
                        // Compute an ideal fee.
3✔
1173
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3✔
1174
                                p.cfg.CoopCloseTargetConfs,
3✔
1175
                        )
3✔
1176
                        if err != nil {
3✔
1177
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1178
                                        "estimate fee: %w", err)
×
1179

×
1180
                                return
×
1181
                        }
×
1182

1183
                        addr, err := p.addrWithInternalKey(
3✔
1184
                                info.DeliveryScript.Val,
3✔
1185
                        )
3✔
1186
                        if err != nil {
3✔
1187
                                shutdownInfoErr = fmt.Errorf("unable to make "+
×
1188
                                        "delivery addr: %w", err)
×
1189
                                return
×
1190
                        }
×
1191
                        chanCloser, err := p.createChanCloser(
3✔
1192
                                lnChan, addr, feePerKw, nil, info.Closer(),
3✔
1193
                        )
3✔
1194
                        if err != nil {
3✔
1195
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1196
                                        "create chan closer: %w", err)
×
1197

×
1198
                                return
×
1199
                        }
×
1200

1201
                        chanID := lnwire.NewChanIDFromOutPoint(
3✔
1202
                                lnChan.State().FundingOutpoint,
3✔
1203
                        )
3✔
1204

3✔
1205
                        p.activeChanCloses[chanID] = chanCloser
3✔
1206

3✔
1207
                        // Create the Shutdown message.
3✔
1208
                        shutdown, err := chanCloser.ShutdownChan()
3✔
1209
                        if err != nil {
3✔
1210
                                delete(p.activeChanCloses, chanID)
×
1211
                                shutdownInfoErr = err
×
1212

×
1213
                                return
×
1214
                        }
×
1215

1216
                        shutdownMsg = fn.Some(*shutdown)
3✔
1217
                })
1218
                if shutdownInfoErr != nil {
3✔
1219
                        return nil, shutdownInfoErr
×
1220
                }
×
1221

1222
                // Subscribe to the set of on-chain events for this channel.
1223
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
3✔
1224
                        chanPoint,
3✔
1225
                )
3✔
1226
                if err != nil {
3✔
1227
                        return nil, err
×
1228
                }
×
1229

1230
                err = p.addLink(
3✔
1231
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
3✔
1232
                        true, shutdownMsg,
3✔
1233
                )
3✔
1234
                if err != nil {
3✔
1235
                        return nil, fmt.Errorf("unable to add link %v to "+
×
1236
                                "switch: %v", chanPoint, err)
×
1237
                }
×
1238

1239
                p.activeChannels.Store(chanID, lnChan)
3✔
1240
        }
1241

1242
        return msgs, nil
6✔
1243
}
1244

1245
// addLink creates and adds a new ChannelLink from the specified channel.
1246
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1247
        lnChan *lnwallet.LightningChannel,
1248
        forwardingPolicy *models.ForwardingPolicy,
1249
        chainEvents *contractcourt.ChainEventSubscription,
1250
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
3✔
1251

3✔
1252
        // onChannelFailure will be called by the link in case the channel
3✔
1253
        // fails for some reason.
3✔
1254
        onChannelFailure := func(chanID lnwire.ChannelID,
3✔
1255
                shortChanID lnwire.ShortChannelID,
3✔
1256
                linkErr htlcswitch.LinkFailureError) {
6✔
1257

3✔
1258
                failure := linkFailureReport{
3✔
1259
                        chanPoint:   *chanPoint,
3✔
1260
                        chanID:      chanID,
3✔
1261
                        shortChanID: shortChanID,
3✔
1262
                        linkErr:     linkErr,
3✔
1263
                }
3✔
1264

3✔
1265
                select {
3✔
1266
                case p.linkFailures <- failure:
3✔
1267
                case <-p.quit:
×
1268
                case <-p.cfg.Quit:
×
1269
                }
1270
        }
1271

1272
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
6✔
1273
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
3✔
1274
        }
3✔
1275

1276
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
6✔
1277
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
3✔
1278
        }
3✔
1279

1280
        //nolint:lll
1281
        linkCfg := htlcswitch.ChannelLinkConfig{
3✔
1282
                Peer:                   p,
3✔
1283
                DecodeHopIterators:     p.cfg.Sphinx.DecodeHopIterators,
3✔
1284
                ExtractErrorEncrypter:  p.cfg.Sphinx.ExtractErrorEncrypter,
3✔
1285
                FetchLastChannelUpdate: p.cfg.FetchLastChanUpdate,
3✔
1286
                HodlMask:               p.cfg.Hodl.Mask(),
3✔
1287
                Registry:               p.cfg.Invoices,
3✔
1288
                BestHeight:             p.cfg.Switch.BestHeight,
3✔
1289
                Circuits:               p.cfg.Switch.CircuitModifier(),
3✔
1290
                ForwardPackets:         p.cfg.InterceptSwitch.ForwardPackets,
3✔
1291
                FwrdingPolicy:          *forwardingPolicy,
3✔
1292
                FeeEstimator:           p.cfg.FeeEstimator,
3✔
1293
                PreimageCache:          p.cfg.WitnessBeacon,
3✔
1294
                ChainEvents:            chainEvents,
3✔
1295
                UpdateContractSignals:  updateContractSignals,
3✔
1296
                NotifyContractUpdate:   notifyContractUpdate,
3✔
1297
                OnChannelFailure:       onChannelFailure,
3✔
1298
                SyncStates:             syncStates,
3✔
1299
                BatchTicker:            ticker.New(p.cfg.ChannelCommitInterval),
3✔
1300
                FwdPkgGCTicker:         ticker.New(time.Hour),
3✔
1301
                PendingCommitTicker: ticker.New(
3✔
1302
                        p.cfg.PendingCommitInterval,
3✔
1303
                ),
3✔
1304
                BatchSize:               p.cfg.ChannelCommitBatchSize,
3✔
1305
                UnsafeReplay:            p.cfg.UnsafeReplay,
3✔
1306
                MinUpdateTimeout:        htlcswitch.DefaultMinLinkFeeUpdateTimeout,
3✔
1307
                MaxUpdateTimeout:        htlcswitch.DefaultMaxLinkFeeUpdateTimeout,
3✔
1308
                OutgoingCltvRejectDelta: p.cfg.OutgoingCltvRejectDelta,
3✔
1309
                TowerClient:             p.cfg.TowerClient,
3✔
1310
                MaxOutgoingCltvExpiry:   p.cfg.MaxOutgoingCltvExpiry,
3✔
1311
                MaxFeeAllocation:        p.cfg.MaxChannelFeeAllocation,
3✔
1312
                MaxAnchorsCommitFeeRate: p.cfg.MaxAnchorsCommitFeeRate,
3✔
1313
                NotifyActiveLink:        p.cfg.ChannelNotifier.NotifyActiveLinkEvent,
3✔
1314
                NotifyActiveChannel:     p.cfg.ChannelNotifier.NotifyActiveChannelEvent,
3✔
1315
                NotifyInactiveChannel:   p.cfg.ChannelNotifier.NotifyInactiveChannelEvent,
3✔
1316
                NotifyInactiveLinkEvent: p.cfg.ChannelNotifier.NotifyInactiveLinkEvent,
3✔
1317
                HtlcNotifier:            p.cfg.HtlcNotifier,
3✔
1318
                GetAliases:              p.cfg.GetAliases,
3✔
1319
                PreviouslySentShutdown:  shutdownMsg,
3✔
1320
                DisallowRouteBlinding:   p.cfg.DisallowRouteBlinding,
3✔
1321
                MaxFeeExposure:          p.cfg.MaxFeeExposure,
3✔
1322
        }
3✔
1323

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

3✔
1331
        // With the channel link created, we'll now notify the htlc switch so
3✔
1332
        // this channel can be used to dispatch local payments and also
3✔
1333
        // passively forward payments.
3✔
1334
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
3✔
1335
}
1336

1337
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1338
// one confirmed public channel exists with them.
1339
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
6✔
1340
        defer p.wg.Done()
6✔
1341

6✔
1342
        hasConfirmedPublicChan := false
6✔
1343
        for _, channel := range channels {
11✔
1344
                if channel.IsPending {
8✔
1345
                        continue
3✔
1346
                }
1347
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
10✔
1348
                        continue
5✔
1349
                }
1350

1351
                hasConfirmedPublicChan = true
3✔
1352
                break
3✔
1353
        }
1354
        if !hasConfirmedPublicChan {
12✔
1355
                return
6✔
1356
        }
6✔
1357

1358
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
3✔
1359
        if err != nil {
3✔
1360
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1361
                return
×
1362
        }
×
1363

1364
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
3✔
1365
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1366
        }
×
1367
}
1368

1369
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1370
// have any active channels with them.
1371
func (p *Brontide) maybeSendChannelUpdates() {
6✔
1372
        defer p.wg.Done()
6✔
1373

6✔
1374
        // If we don't have any active channels, then we can exit early.
6✔
1375
        if p.activeChannels.Len() == 0 {
10✔
1376
                return
4✔
1377
        }
4✔
1378

1379
        maybeSendUpd := func(cid lnwire.ChannelID,
5✔
1380
                lnChan *lnwallet.LightningChannel) error {
10✔
1381

5✔
1382
                // Nil channels are pending, so we'll skip them.
5✔
1383
                if lnChan == nil {
8✔
1384
                        return nil
3✔
1385
                }
3✔
1386

1387
                dbChan := lnChan.State()
5✔
1388
                scid := func() lnwire.ShortChannelID {
10✔
1389
                        switch {
5✔
1390
                        // Otherwise if it's a zero conf channel and confirmed,
1391
                        // then we need to use the "real" scid.
1392
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
3✔
1393
                                return dbChan.ZeroConfRealScid()
3✔
1394

1395
                        // Otherwise, we can use the normal scid.
1396
                        default:
5✔
1397
                                return dbChan.ShortChanID()
5✔
1398
                        }
1399
                }()
1400

1401
                // Now that we know the channel is in a good state, we'll try
1402
                // to fetch the update to send to the remote peer. If the
1403
                // channel is pending, and not a zero conf channel, we'll get
1404
                // an error here which we'll ignore.
1405
                chanUpd, err := p.cfg.FetchLastChanUpdate(scid)
5✔
1406
                if err != nil {
8✔
1407
                        p.log.Debugf("Unable to fetch channel update for "+
3✔
1408
                                "ChannelPoint(%v), scid=%v: %v",
3✔
1409
                                dbChan.FundingOutpoint, dbChan.ShortChanID, err)
3✔
1410

3✔
1411
                        return nil
3✔
1412
                }
3✔
1413

1414
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
5✔
1415
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
5✔
1416

5✔
1417
                // We'll send it as a normal message instead of using the lazy
5✔
1418
                // queue to prioritize transmission of the fresh update.
5✔
1419
                if err := p.SendMessage(false, chanUpd); err != nil {
5✔
1420
                        err := fmt.Errorf("unable to send channel update for "+
×
1421
                                "ChannelPoint(%v), scid=%v: %w",
×
1422
                                dbChan.FundingOutpoint, dbChan.ShortChanID(),
×
1423
                                err)
×
1424
                        p.log.Errorf(err.Error())
×
1425

×
1426
                        return err
×
1427
                }
×
1428

1429
                return nil
5✔
1430
        }
1431

1432
        p.activeChannels.ForEach(maybeSendUpd)
5✔
1433
}
1434

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

1452
        select {
3✔
1453
        case <-ready:
3✔
UNCOV
1454
        case <-p.quit:
×
1455
        }
1456

1457
        p.wg.Wait()
3✔
1458
}
1459

1460
// Disconnect terminates the connection with the remote peer. Additionally, a
1461
// signal is sent to the server and htlcSwitch indicating the resources
1462
// allocated to the peer can now be cleaned up.
1463
func (p *Brontide) Disconnect(reason error) {
3✔
1464
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
6✔
1465
                return
3✔
1466
        }
3✔
1467

1468
        // Make sure initialization has completed before we try to tear things
1469
        // down.
1470
        //
1471
        // NOTE: We only read the `startReady` chan if the peer has been
1472
        // started, otherwise we will skip reading it as this chan won't be
1473
        // closed, hence blocks forever.
1474
        if atomic.LoadInt32(&p.started) == 1 {
6✔
1475
                p.log.Debugf("Started, waiting on startReady signal")
3✔
1476

3✔
1477
                select {
3✔
1478
                case <-p.startReady:
3✔
1479
                case <-p.quit:
×
1480
                        return
×
1481
                }
1482
        }
1483

1484
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
3✔
1485
        p.storeError(err)
3✔
1486

3✔
1487
        p.log.Infof(err.Error())
3✔
1488

3✔
1489
        // Stop PingManager before closing TCP connection.
3✔
1490
        p.pingManager.Stop()
3✔
1491

3✔
1492
        // Ensure that the TCP connection is properly closed before continuing.
3✔
1493
        p.cfg.Conn.Close()
3✔
1494

3✔
1495
        close(p.quit)
3✔
1496

3✔
1497
        // If our msg router isn't global (local to this instance), then we'll
3✔
1498
        // stop it. Otherwise, we'll leave it running.
3✔
1499
        if !p.globalMsgRouter {
6✔
1500
                p.msgRouter.WhenSome(func(router msgmux.Router) {
6✔
1501
                        router.Stop()
3✔
1502
                })
3✔
1503
        }
1504
}
1505

1506
// String returns the string representation of this peer.
1507
func (p *Brontide) String() string {
20✔
1508
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
20✔
1509
}
20✔
1510

1511
// readNextMessage reads, and returns the next message on the wire along with
1512
// any additional raw payload.
1513
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
10✔
1514
        noiseConn := p.cfg.Conn
10✔
1515
        err := noiseConn.SetReadDeadline(time.Time{})
10✔
1516
        if err != nil {
10✔
1517
                return nil, err
×
1518
        }
×
1519

1520
        pktLen, err := noiseConn.ReadNextHeader()
10✔
1521
        if err != nil {
13✔
1522
                return nil, fmt.Errorf("read next header: %w", err)
3✔
1523
        }
3✔
1524

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

1547
                // The ReadNextBody method will actually end up re-using the
1548
                // buffer, so within this closure, we can continue to use
1549
                // rawMsg as it's just a slice into the buf from the buffer
1550
                // pool.
1551
                rawMsg, readErr := noiseConn.ReadNextBody(buf[:pktLen])
7✔
1552
                if readErr != nil {
7✔
1553
                        return fmt.Errorf("read next body: %w", readErr)
×
1554
                }
×
1555
                msgLen = uint64(len(rawMsg))
7✔
1556

7✔
1557
                // Next, create a new io.Reader implementation from the raw
7✔
1558
                // message, and use this to decode the message directly from.
7✔
1559
                msgReader := bytes.NewReader(rawMsg)
7✔
1560
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
7✔
1561
                if err != nil {
10✔
1562
                        return err
3✔
1563
                }
3✔
1564

1565
                // At this point, rawMsg and buf will be returned back to the
1566
                // buffer pool for re-use.
1567
                return nil
7✔
1568
        })
1569
        atomic.AddUint64(&p.bytesReceived, msgLen)
7✔
1570
        if err != nil {
10✔
1571
                return nil, err
3✔
1572
        }
3✔
1573

1574
        p.logWireMessage(nextMsg, true)
7✔
1575

7✔
1576
        return nextMsg, nil
7✔
1577
}
1578

1579
// msgStream implements a goroutine-safe, in-order stream of messages to be
1580
// delivered via closure to a receiver. These messages MUST be in order due to
1581
// the nature of the lightning channel commitment and gossiper state machines.
1582
// TODO(conner): use stream handler interface to abstract out stream
1583
// state/logging.
1584
type msgStream struct {
1585
        streamShutdown int32 // To be used atomically.
1586

1587
        peer *Brontide
1588

1589
        apply func(lnwire.Message)
1590

1591
        startMsg string
1592
        stopMsg  string
1593

1594
        msgCond *sync.Cond
1595
        msgs    []lnwire.Message
1596

1597
        mtx sync.Mutex
1598

1599
        producerSema chan struct{}
1600

1601
        wg   sync.WaitGroup
1602
        quit chan struct{}
1603
}
1604

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

6✔
1613
        stream := &msgStream{
6✔
1614
                peer:         p,
6✔
1615
                apply:        apply,
6✔
1616
                startMsg:     startMsg,
6✔
1617
                stopMsg:      stopMsg,
6✔
1618
                producerSema: make(chan struct{}, bufSize),
6✔
1619
                quit:         make(chan struct{}),
6✔
1620
        }
6✔
1621
        stream.msgCond = sync.NewCond(&stream.mtx)
6✔
1622

6✔
1623
        // Before we return the active stream, we'll populate the producer's
6✔
1624
        // semaphore channel. We'll use this to ensure that the producer won't
6✔
1625
        // attempt to allocate memory in the queue for an item until it has
6✔
1626
        // sufficient extra space.
6✔
1627
        for i := uint32(0); i < bufSize; i++ {
3,009✔
1628
                stream.producerSema <- struct{}{}
3,003✔
1629
        }
3,003✔
1630

1631
        return stream
6✔
1632
}
1633

1634
// Start starts the chanMsgStream.
1635
func (ms *msgStream) Start() {
6✔
1636
        ms.wg.Add(1)
6✔
1637
        go ms.msgConsumer()
6✔
1638
}
6✔
1639

1640
// Stop stops the chanMsgStream.
1641
func (ms *msgStream) Stop() {
3✔
1642
        // TODO(roasbeef): signal too?
3✔
1643

3✔
1644
        close(ms.quit)
3✔
1645

3✔
1646
        // Now that we've closed the channel, we'll repeatedly signal the msg
3✔
1647
        // consumer until we've detected that it has exited.
3✔
1648
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
6✔
1649
                ms.msgCond.Signal()
3✔
1650
                time.Sleep(time.Millisecond * 100)
3✔
1651
        }
3✔
1652

1653
        ms.wg.Wait()
3✔
1654
}
1655

1656
// msgConsumer is the main goroutine that streams messages from the peer's
1657
// readHandler directly to the target channel.
1658
func (ms *msgStream) msgConsumer() {
6✔
1659
        defer ms.wg.Done()
6✔
1660
        defer peerLog.Tracef(ms.stopMsg)
6✔
1661
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
6✔
1662

6✔
1663
        peerLog.Tracef(ms.startMsg)
6✔
1664

6✔
1665
        for {
12✔
1666
                // First, we'll check our condition. If the queue of messages
6✔
1667
                // is empty, then we'll wait until a new item is added.
6✔
1668
                ms.msgCond.L.Lock()
6✔
1669
                for len(ms.msgs) == 0 {
12✔
1670
                        ms.msgCond.Wait()
6✔
1671

6✔
1672
                        // If we woke up in order to exit, then we'll do so.
6✔
1673
                        // Otherwise, we'll check the message queue for any new
6✔
1674
                        // items.
6✔
1675
                        select {
6✔
1676
                        case <-ms.peer.quit:
3✔
1677
                                ms.msgCond.L.Unlock()
3✔
1678
                                return
3✔
1679
                        case <-ms.quit:
3✔
1680
                                ms.msgCond.L.Unlock()
3✔
1681
                                return
3✔
1682
                        default:
3✔
1683
                        }
1684
                }
1685

1686
                // Grab the message off the front of the queue, shifting the
1687
                // slice's reference down one in order to remove the message
1688
                // from the queue.
1689
                msg := ms.msgs[0]
3✔
1690
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
3✔
1691
                ms.msgs = ms.msgs[1:]
3✔
1692

3✔
1693
                ms.msgCond.L.Unlock()
3✔
1694

3✔
1695
                ms.apply(msg)
3✔
1696

3✔
1697
                // We've just successfully processed an item, so we'll signal
3✔
1698
                // to the producer that a new slot in the buffer. We'll use
3✔
1699
                // this to bound the size of the buffer to avoid allowing it to
3✔
1700
                // grow indefinitely.
3✔
1701
                select {
3✔
1702
                case ms.producerSema <- struct{}{}:
3✔
1703
                case <-ms.peer.quit:
3✔
1704
                        return
3✔
1705
                case <-ms.quit:
3✔
1706
                        return
3✔
1707
                }
1708
        }
1709
}
1710

1711
// AddMsg adds a new message to the msgStream. This function is safe for
1712
// concurrent access.
1713
func (ms *msgStream) AddMsg(msg lnwire.Message) {
3✔
1714
        // First, we'll attempt to receive from the producerSema struct. This
3✔
1715
        // acts as a semaphore to prevent us from indefinitely buffering
3✔
1716
        // incoming items from the wire. Either the msg queue isn't full, and
3✔
1717
        // we'll not block, or the queue is full, and we'll block until either
3✔
1718
        // we're signalled to quit, or a slot is freed up.
3✔
1719
        select {
3✔
1720
        case <-ms.producerSema:
3✔
1721
        case <-ms.peer.quit:
×
1722
                return
×
1723
        case <-ms.quit:
×
1724
                return
×
1725
        }
1726

1727
        // Next, we'll lock the condition, and add the message to the end of
1728
        // the message queue.
1729
        ms.msgCond.L.Lock()
3✔
1730
        ms.msgs = append(ms.msgs, msg)
3✔
1731
        ms.msgCond.L.Unlock()
3✔
1732

3✔
1733
        // With the message added, we signal to the msgConsumer that there are
3✔
1734
        // additional messages to consume.
3✔
1735
        ms.msgCond.Signal()
3✔
1736
}
1737

1738
// waitUntilLinkActive waits until the target link is active and returns a
1739
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1740
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1741
func waitUntilLinkActive(p *Brontide,
1742
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
3✔
1743

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

3✔
1746
        // Subscribe to receive channel events.
3✔
1747
        //
3✔
1748
        // NOTE: If the link is already active by SubscribeChannelEvents, then
3✔
1749
        // GetLink will retrieve the link and we can send messages. If the link
3✔
1750
        // becomes active between SubscribeChannelEvents and GetLink, then GetLink
3✔
1751
        // will retrieve the link. If the link becomes active after GetLink, then
3✔
1752
        // we will get an ActiveLinkEvent notification and retrieve the link. If
3✔
1753
        // the call to GetLink is before SubscribeChannelEvents, however, there
3✔
1754
        // will be a race condition.
3✔
1755
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
3✔
1756
        if err != nil {
6✔
1757
                // If we have a non-nil error, then the server is shutting down and we
3✔
1758
                // can exit here and return nil. This means no message will be delivered
3✔
1759
                // to the link.
3✔
1760
                return nil
3✔
1761
        }
3✔
1762
        defer sub.Cancel()
3✔
1763

3✔
1764
        // The link may already be active by this point, and we may have missed the
3✔
1765
        // ActiveLinkEvent. Check if the link exists.
3✔
1766
        link := p.fetchLinkFromKeyAndCid(cid)
3✔
1767
        if link != nil {
6✔
1768
                return link
3✔
1769
        }
3✔
1770

1771
        // If the link is nil, we must wait for it to be active.
1772
        for {
6✔
1773
                select {
3✔
1774
                // A new event has been sent by the ChannelNotifier. We first check
1775
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1776
                // that the event is for this channel. Otherwise, we discard the
1777
                // message.
1778
                case e := <-sub.Updates():
3✔
1779
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
3✔
1780
                        if !ok {
6✔
1781
                                // Ignore this notification.
3✔
1782
                                continue
3✔
1783
                        }
1784

1785
                        chanPoint := event.ChannelPoint
3✔
1786

3✔
1787
                        // Check whether the retrieved chanPoint matches the target
3✔
1788
                        // channel id.
3✔
1789
                        if !cid.IsChanPoint(chanPoint) {
3✔
1790
                                continue
×
1791
                        }
1792

1793
                        // The link shouldn't be nil as we received an
1794
                        // ActiveLinkEvent. If it is nil, we return nil and the
1795
                        // calling function should catch it.
1796
                        return p.fetchLinkFromKeyAndCid(cid)
3✔
1797

1798
                case <-p.quit:
3✔
1799
                        return nil
3✔
1800
                }
1801
        }
1802
}
1803

1804
// newChanMsgStream is used to create a msgStream between the peer and
1805
// particular channel link in the htlcswitch. We utilize additional
1806
// synchronization with the fundingManager to ensure we don't attempt to
1807
// dispatch a message to a channel before it is fully active. A reference to the
1808
// channel this stream forwards to is held in scope to prevent unnecessary
1809
// lookups.
1810
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
3✔
1811
        var chanLink htlcswitch.ChannelUpdateHandler
3✔
1812

3✔
1813
        apply := func(msg lnwire.Message) {
6✔
1814
                // This check is fine because if the link no longer exists, it will
3✔
1815
                // be removed from the activeChannels map and subsequent messages
3✔
1816
                // shouldn't reach the chan msg stream.
3✔
1817
                if chanLink == nil {
6✔
1818
                        chanLink = waitUntilLinkActive(p, cid)
3✔
1819

3✔
1820
                        // If the link is still not active and the calling function
3✔
1821
                        // errored out, just return.
3✔
1822
                        if chanLink == nil {
6✔
1823
                                p.log.Warnf("Link=%v is not active", cid)
3✔
1824
                                return
3✔
1825
                        }
3✔
1826
                }
1827

1828
                // In order to avoid unnecessarily delivering message
1829
                // as the peer is exiting, we'll check quickly to see
1830
                // if we need to exit.
1831
                select {
3✔
1832
                case <-p.quit:
×
1833
                        return
×
1834
                default:
3✔
1835
                }
1836

1837
                chanLink.HandleChannelUpdate(msg)
3✔
1838
        }
1839

1840
        return newMsgStream(p,
3✔
1841
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
3✔
1842
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
3✔
1843
                1000,
3✔
1844
                apply,
3✔
1845
        )
3✔
1846
}
1847

1848
// newDiscMsgStream is used to setup a msgStream between the peer and the
1849
// authenticated gossiper. This stream should be used to forward all remote
1850
// channel announcements.
1851
func newDiscMsgStream(p *Brontide) *msgStream {
6✔
1852
        apply := func(msg lnwire.Message) {
9✔
1853
                // TODO(yy): `ProcessRemoteAnnouncement` returns an error chan
3✔
1854
                // and we need to process it.
3✔
1855
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(msg, p)
3✔
1856
        }
3✔
1857

1858
        return newMsgStream(
6✔
1859
                p,
6✔
1860
                "Update stream for gossiper created",
6✔
1861
                "Update stream for gossiper exited",
6✔
1862
                1000,
6✔
1863
                apply,
6✔
1864
        )
6✔
1865
}
1866

1867
// readHandler is responsible for reading messages off the wire in series, then
1868
// properly dispatching the handling of the message to the proper subsystem.
1869
//
1870
// NOTE: This method MUST be run as a goroutine.
1871
func (p *Brontide) readHandler() {
6✔
1872
        defer p.wg.Done()
6✔
1873

6✔
1874
        // We'll stop the timer after a new messages is received, and also
6✔
1875
        // reset it after we process the next message.
6✔
1876
        idleTimer := time.AfterFunc(idleTimeout, func() {
6✔
1877
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
1878
                        p, idleTimeout)
×
1879
                p.Disconnect(err)
×
1880
        })
×
1881

1882
        // Initialize our negotiated gossip sync method before reading messages
1883
        // off the wire. When using gossip queries, this ensures a gossip
1884
        // syncer is active by the time query messages arrive.
1885
        //
1886
        // TODO(conner): have peer store gossip syncer directly and bypass
1887
        // gossiper?
1888
        p.initGossipSync()
6✔
1889

6✔
1890
        discStream := newDiscMsgStream(p)
6✔
1891
        discStream.Start()
6✔
1892
        defer discStream.Stop()
6✔
1893
out:
6✔
1894
        for atomic.LoadInt32(&p.disconnect) == 0 {
13✔
1895
                nextMsg, err := p.readNextMessage()
7✔
1896
                if !idleTimer.Stop() {
7✔
1897
                        select {
×
1898
                        case <-idleTimer.C:
×
1899
                        default:
×
1900
                        }
1901
                }
1902
                if err != nil {
7✔
1903
                        p.log.Infof("unable to read message from peer: %v", err)
3✔
1904

3✔
1905
                        // If we could not read our peer's message due to an
3✔
1906
                        // unknown type or invalid alias, we continue processing
3✔
1907
                        // as normal. We store unknown message and address
3✔
1908
                        // types, as they may provide debugging insight.
3✔
1909
                        switch e := err.(type) {
3✔
1910
                        // If this is just a message we don't yet recognize,
1911
                        // we'll continue processing as normal as this allows
1912
                        // us to introduce new messages in a forwards
1913
                        // compatible manner.
1914
                        case *lnwire.UnknownMessage:
3✔
1915
                                p.storeError(e)
3✔
1916
                                idleTimer.Reset(idleTimeout)
3✔
1917
                                continue
3✔
1918

1919
                        // If they sent us an address type that we don't yet
1920
                        // know of, then this isn't a wire error, so we'll
1921
                        // simply continue parsing the remainder of their
1922
                        // messages.
1923
                        case *lnwire.ErrUnknownAddrType:
×
1924
                                p.storeError(e)
×
1925
                                idleTimer.Reset(idleTimeout)
×
1926
                                continue
×
1927

1928
                        // If the NodeAnnouncement has an invalid alias, then
1929
                        // we'll log that error above and continue so we can
1930
                        // continue to read messages from the peer. We do not
1931
                        // store this error because it is of little debugging
1932
                        // value.
1933
                        case *lnwire.ErrInvalidNodeAlias:
×
1934
                                idleTimer.Reset(idleTimeout)
×
1935
                                continue
×
1936

1937
                        // If the error we encountered wasn't just a message we
1938
                        // didn't recognize, then we'll stop all processing as
1939
                        // this is a fatal error.
1940
                        default:
3✔
1941
                                break out
3✔
1942
                        }
1943
                }
1944

1945
                // If a message router is active, then we'll try to have it
1946
                // handle this message. If it can, then we're able to skip the
1947
                // rest of the message handling logic.
1948
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
8✔
1949
                        return r.RouteMsg(msgmux.PeerMsg{
4✔
1950
                                PeerPub: *p.IdentityKey(),
4✔
1951
                                Message: nextMsg,
4✔
1952
                        })
4✔
1953
                })
4✔
1954

1955
                // No error occurred, and the message was handled by the
1956
                // router.
1957
                if err == nil {
4✔
1958
                        continue
×
1959
                }
1960

1961
                var (
4✔
1962
                        targetChan   lnwire.ChannelID
4✔
1963
                        isLinkUpdate bool
4✔
1964
                )
4✔
1965

4✔
1966
                switch msg := nextMsg.(type) {
4✔
1967
                case *lnwire.Pong:
1✔
1968
                        // When we receive a Pong message in response to our
1✔
1969
                        // last ping message, we send it to the pingManager
1✔
1970
                        p.pingManager.ReceivedPong(msg)
1✔
1971

1972
                case *lnwire.Ping:
1✔
1973
                        // First, we'll store their latest ping payload within
1✔
1974
                        // the relevant atomic variable.
1✔
1975
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
1✔
1976

1✔
1977
                        // Next, we'll send over the amount of specified pong
1✔
1978
                        // bytes.
1✔
1979
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
1✔
1980
                        p.queueMsg(pong, nil)
1✔
1981

1982
                case *lnwire.OpenChannel,
1983
                        *lnwire.AcceptChannel,
1984
                        *lnwire.FundingCreated,
1985
                        *lnwire.FundingSigned,
1986
                        *lnwire.ChannelReady:
3✔
1987

3✔
1988
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
1989

1990
                case *lnwire.Shutdown:
3✔
1991
                        select {
3✔
1992
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
1993
                        case <-p.quit:
×
1994
                                break out
×
1995
                        }
1996
                case *lnwire.ClosingSigned:
3✔
1997
                        select {
3✔
1998
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
1999
                        case <-p.quit:
×
2000
                                break out
×
2001
                        }
2002

2003
                case *lnwire.Warning:
×
2004
                        targetChan = msg.ChanID
×
2005
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2006

2007
                case *lnwire.Error:
3✔
2008
                        targetChan = msg.ChanID
3✔
2009
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
3✔
2010

2011
                case *lnwire.ChannelReestablish:
3✔
2012
                        targetChan = msg.ChanID
3✔
2013
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2014

3✔
2015
                        // If we failed to find the link in question, and the
3✔
2016
                        // message received was a channel sync message, then
3✔
2017
                        // this might be a peer trying to resync closed channel.
3✔
2018
                        // In this case we'll try to resend our last channel
3✔
2019
                        // sync message, such that the peer can recover funds
3✔
2020
                        // from the closed channel.
3✔
2021
                        if !isLinkUpdate {
6✔
2022
                                err := p.resendChanSyncMsg(targetChan)
3✔
2023
                                if err != nil {
6✔
2024
                                        // TODO(halseth): send error to peer?
3✔
2025
                                        p.log.Errorf("resend failed: %v",
3✔
2026
                                                err)
3✔
2027
                                }
3✔
2028
                        }
2029

2030
                // For messages that implement the LinkUpdater interface, we
2031
                // will consider them as link updates and send them to
2032
                // chanStream. These messages will be queued inside chanStream
2033
                // if the channel is not active yet.
2034
                case lnwire.LinkUpdater:
3✔
2035
                        targetChan = msg.TargetChanID()
3✔
2036
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2037

3✔
2038
                        // Log an error if we don't have this channel. This
3✔
2039
                        // means the peer has sent us a message with unknown
3✔
2040
                        // channel ID.
3✔
2041
                        if !isLinkUpdate {
6✔
2042
                                p.log.Errorf("Unknown channel ID: %v found "+
3✔
2043
                                        "in received msg=%s", targetChan,
3✔
2044
                                        nextMsg.MsgType())
3✔
2045
                        }
3✔
2046

2047
                case *lnwire.ChannelUpdate1,
2048
                        *lnwire.ChannelAnnouncement1,
2049
                        *lnwire.NodeAnnouncement,
2050
                        *lnwire.AnnounceSignatures1,
2051
                        *lnwire.GossipTimestampRange,
2052
                        *lnwire.QueryShortChanIDs,
2053
                        *lnwire.QueryChannelRange,
2054
                        *lnwire.ReplyChannelRange,
2055
                        *lnwire.ReplyShortChanIDsEnd:
3✔
2056

3✔
2057
                        discStream.AddMsg(msg)
3✔
2058

2059
                case *lnwire.Custom:
4✔
2060
                        err := p.handleCustomMessage(msg)
4✔
2061
                        if err != nil {
4✔
2062
                                p.storeError(err)
×
2063
                                p.log.Errorf("%v", err)
×
2064
                        }
×
2065

2066
                default:
×
2067
                        // If the message we received is unknown to us, store
×
2068
                        // the type to track the failure.
×
2069
                        err := fmt.Errorf("unknown message type %v received",
×
2070
                                uint16(msg.MsgType()))
×
2071
                        p.storeError(err)
×
2072

×
2073
                        p.log.Errorf("%v", err)
×
2074
                }
2075

2076
                if isLinkUpdate {
7✔
2077
                        // If this is a channel update, then we need to feed it
3✔
2078
                        // into the channel's in-order message stream.
3✔
2079
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
3✔
2080
                }
3✔
2081

2082
                idleTimer.Reset(idleTimeout)
4✔
2083
        }
2084

2085
        p.Disconnect(errors.New("read handler closed"))
3✔
2086

3✔
2087
        p.log.Trace("readHandler for peer done")
3✔
2088
}
2089

2090
// handleCustomMessage handles the given custom message if a handler is
2091
// registered.
2092
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
4✔
2093
        if p.cfg.HandleCustomMessage == nil {
4✔
2094
                return fmt.Errorf("no custom message handler for "+
×
2095
                        "message type %v", uint16(msg.MsgType()))
×
2096
        }
×
2097

2098
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
4✔
2099
}
2100

2101
// isLoadedFromDisk returns true if the provided channel ID is loaded from
2102
// disk.
2103
//
2104
// NOTE: only returns true for pending channels.
2105
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
3✔
2106
        // If this is a newly added channel, no need to reestablish.
3✔
2107
        _, added := p.addedChannels.Load(chanID)
3✔
2108
        if added {
6✔
2109
                return false
3✔
2110
        }
3✔
2111

2112
        // Return false if the channel is unknown.
2113
        channel, ok := p.activeChannels.Load(chanID)
3✔
2114
        if !ok {
3✔
2115
                return false
×
2116
        }
×
2117

2118
        // During startup, we will use a nil value to mark a pending channel
2119
        // that's loaded from disk.
2120
        return channel == nil
3✔
2121
}
2122

2123
// isActiveChannel returns true if the provided channel id is active, otherwise
2124
// returns false.
2125
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
11✔
2126
        // The channel would be nil if,
11✔
2127
        // - the channel doesn't exist, or,
11✔
2128
        // - the channel exists, but is pending. In this case, we don't
11✔
2129
        //   consider this channel active.
11✔
2130
        channel, _ := p.activeChannels.Load(chanID)
11✔
2131

11✔
2132
        return channel != nil
11✔
2133
}
11✔
2134

2135
// isPendingChannel returns true if the provided channel ID is pending, and
2136
// returns false if the channel is active or unknown.
2137
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
9✔
2138
        // Return false if the channel is unknown.
9✔
2139
        channel, ok := p.activeChannels.Load(chanID)
9✔
2140
        if !ok {
15✔
2141
                return false
6✔
2142
        }
6✔
2143

2144
        return channel == nil
3✔
2145
}
2146

2147
// hasChannel returns true if the peer has a pending/active channel specified
2148
// by the channel ID.
2149
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
3✔
2150
        _, ok := p.activeChannels.Load(chanID)
3✔
2151
        return ok
3✔
2152
}
3✔
2153

2154
// storeError stores an error in our peer's buffer of recent errors with the
2155
// current timestamp. Errors are only stored if we have at least one active
2156
// channel with the peer to mitigate a dos vector where a peer costlessly
2157
// connects to us and spams us with errors.
2158
func (p *Brontide) storeError(err error) {
3✔
2159
        var haveChannels bool
3✔
2160

3✔
2161
        p.activeChannels.Range(func(_ lnwire.ChannelID,
3✔
2162
                channel *lnwallet.LightningChannel) bool {
6✔
2163

3✔
2164
                // Pending channels will be nil in the activeChannels map.
3✔
2165
                if channel == nil {
6✔
2166
                        // Return true to continue the iteration.
3✔
2167
                        return true
3✔
2168
                }
3✔
2169

2170
                haveChannels = true
3✔
2171

3✔
2172
                // Return false to break the iteration.
3✔
2173
                return false
3✔
2174
        })
2175

2176
        // If we do not have any active channels with the peer, we do not store
2177
        // errors as a dos mitigation.
2178
        if !haveChannels {
6✔
2179
                p.log.Trace("no channels with peer, not storing err")
3✔
2180
                return
3✔
2181
        }
3✔
2182

2183
        p.cfg.ErrorBuffer.Add(
3✔
2184
                &TimestampedError{Timestamp: time.Now(), Error: err},
3✔
2185
        )
3✔
2186
}
2187

2188
// handleWarningOrError processes a warning or error msg and returns true if
2189
// msg should be forwarded to the associated channel link. False is returned if
2190
// any necessary forwarding of msg was already handled by this method. If msg is
2191
// an error from a peer with an active channel, we'll store it in memory.
2192
//
2193
// NOTE: This method should only be called from within the readHandler.
2194
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
2195
        msg lnwire.Message) bool {
3✔
2196

3✔
2197
        if errMsg, ok := msg.(*lnwire.Error); ok {
6✔
2198
                p.storeError(errMsg)
3✔
2199
        }
3✔
2200

2201
        switch {
3✔
2202
        // Connection wide messages should be forwarded to all channel links
2203
        // with this peer.
2204
        case chanID == lnwire.ConnectionWideID:
×
2205
                for _, chanStream := range p.activeMsgStreams {
×
2206
                        chanStream.AddMsg(msg)
×
2207
                }
×
2208

2209
                return false
×
2210

2211
        // If the channel ID for the message corresponds to a pending channel,
2212
        // then the funding manager will handle it.
2213
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
3✔
2214
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2215
                return false
3✔
2216

2217
        // If not we hand the message to the channel link for this channel.
2218
        case p.isActiveChannel(chanID):
3✔
2219
                return true
3✔
2220

2221
        default:
3✔
2222
                return false
3✔
2223
        }
2224
}
2225

2226
// messageSummary returns a human-readable string that summarizes a
2227
// incoming/outgoing message. Not all messages will have a summary, only those
2228
// which have additional data that can be informative at a glance.
2229
func messageSummary(msg lnwire.Message) string {
20✔
2230
        switch msg := msg.(type) {
20✔
2231
        case *lnwire.Init:
13✔
2232
                // No summary.
13✔
2233
                return ""
13✔
2234

2235
        case *lnwire.OpenChannel:
3✔
2236
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
3✔
2237
                        "push_amt=%v, reserve=%v, flags=%v",
3✔
2238
                        msg.PendingChannelID[:], msg.ChainHash,
3✔
2239
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
3✔
2240
                        msg.ChannelReserve, msg.ChannelFlags)
3✔
2241

2242
        case *lnwire.AcceptChannel:
3✔
2243
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
3✔
2244
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
3✔
2245
                        msg.MinAcceptDepth)
3✔
2246

2247
        case *lnwire.FundingCreated:
3✔
2248
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
3✔
2249
                        msg.PendingChannelID[:], msg.FundingPoint)
3✔
2250

2251
        case *lnwire.FundingSigned:
3✔
2252
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
3✔
2253

2254
        case *lnwire.ChannelReady:
3✔
2255
                return fmt.Sprintf("chan_id=%v, next_point=%x",
3✔
2256
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
3✔
2257

2258
        case *lnwire.Shutdown:
3✔
2259
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
3✔
2260
                        msg.Address[:])
3✔
2261

2262
        case *lnwire.ClosingSigned:
3✔
2263
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
3✔
2264
                        msg.FeeSatoshis)
3✔
2265

2266
        case *lnwire.UpdateAddHTLC:
3✔
2267
                var blindingPoint []byte
3✔
2268
                msg.BlindingPoint.WhenSome(
3✔
2269
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
3✔
2270
                                *btcec.PublicKey]) {
6✔
2271

3✔
2272
                                blindingPoint = b.Val.SerializeCompressed()
3✔
2273
                        },
3✔
2274
                )
2275

2276
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
3✔
2277
                        "hash=%x, blinding_point=%x, custom_records=%v",
3✔
2278
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
3✔
2279
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
3✔
2280

2281
        case *lnwire.UpdateFailHTLC:
3✔
2282
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
3✔
2283
                        msg.ID, msg.Reason)
3✔
2284

2285
        case *lnwire.UpdateFulfillHTLC:
3✔
2286
                return fmt.Sprintf("chan_id=%v, id=%v, pre_image=%x, "+
3✔
2287
                        "custom_records=%v", msg.ChanID, msg.ID,
3✔
2288
                        msg.PaymentPreimage[:], msg.CustomRecords)
3✔
2289

2290
        case *lnwire.CommitSig:
3✔
2291
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
3✔
2292
                        len(msg.HtlcSigs))
3✔
2293

2294
        case *lnwire.RevokeAndAck:
3✔
2295
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
3✔
2296
                        msg.ChanID, msg.Revocation[:],
3✔
2297
                        msg.NextRevocationKey.SerializeCompressed())
3✔
2298

2299
        case *lnwire.UpdateFailMalformedHTLC:
3✔
2300
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
3✔
2301
                        msg.ChanID, msg.ID, msg.FailureCode)
3✔
2302

2303
        case *lnwire.Warning:
×
2304
                return fmt.Sprintf("%v", msg.Warning())
×
2305

2306
        case *lnwire.Error:
3✔
2307
                return fmt.Sprintf("%v", msg.Error())
3✔
2308

2309
        case *lnwire.AnnounceSignatures1:
3✔
2310
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
3✔
2311
                        msg.ShortChannelID.ToUint64())
3✔
2312

2313
        case *lnwire.ChannelAnnouncement1:
3✔
2314
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
3✔
2315
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
3✔
2316

2317
        case *lnwire.ChannelUpdate1:
5✔
2318
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
5✔
2319
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
5✔
2320
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
5✔
2321
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
5✔
2322

2323
        case *lnwire.NodeAnnouncement:
3✔
2324
                return fmt.Sprintf("node=%x, update_time=%v",
3✔
2325
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
3✔
2326

2327
        case *lnwire.Ping:
2✔
2328
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
2✔
2329

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

2333
        case *lnwire.UpdateFee:
×
2334
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2335
                        msg.ChanID, int64(msg.FeePerKw))
×
2336

2337
        case *lnwire.ChannelReestablish:
5✔
2338
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
5✔
2339
                        "remote_tail_height=%v", msg.ChanID,
5✔
2340
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
5✔
2341

2342
        case *lnwire.ReplyShortChanIDsEnd:
3✔
2343
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
3✔
2344
                        msg.Complete)
3✔
2345

2346
        case *lnwire.ReplyChannelRange:
3✔
2347
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
3✔
2348
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
3✔
2349
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
3✔
2350
                        msg.EncodingType)
3✔
2351

2352
        case *lnwire.QueryShortChanIDs:
3✔
2353
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
3✔
2354
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
3✔
2355

2356
        case *lnwire.QueryChannelRange:
3✔
2357
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
3✔
2358
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
3✔
2359
                        msg.LastBlockHeight())
3✔
2360

2361
        case *lnwire.GossipTimestampRange:
3✔
2362
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
3✔
2363
                        "stamp_range=%v", msg.ChainHash,
3✔
2364
                        time.Unix(int64(msg.FirstTimestamp), 0),
3✔
2365
                        msg.TimestampRange)
3✔
2366

2367
        case *lnwire.Stfu:
×
2368
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
×
2369
                        msg.Initiator)
×
2370

2371
        case *lnwire.Custom:
5✔
2372
                return fmt.Sprintf("type=%d", msg.Type)
5✔
2373
        }
2374

2375
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2376
}
2377

2378
// logWireMessage logs the receipt or sending of particular wire message. This
2379
// function is used rather than just logging the message in order to produce
2380
// less spammy log messages in trace mode by setting the 'Curve" parameter to
2381
// nil. Doing this avoids printing out each of the field elements in the curve
2382
// parameters for secp256k1.
2383
func (p *Brontide) logWireMessage(msg lnwire.Message, read bool) {
20✔
2384
        summaryPrefix := "Received"
20✔
2385
        if !read {
36✔
2386
                summaryPrefix = "Sending"
16✔
2387
        }
16✔
2388

2389
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
40✔
2390
                // Debug summary of message.
20✔
2391
                summary := messageSummary(msg)
20✔
2392
                if len(summary) > 0 {
30✔
2393
                        summary = "(" + summary + ")"
10✔
2394
                }
10✔
2395

2396
                preposition := "to"
20✔
2397
                if read {
27✔
2398
                        preposition = "from"
7✔
2399
                }
7✔
2400

2401
                var msgType string
20✔
2402
                if msg.MsgType() < lnwire.CustomTypeStart {
38✔
2403
                        msgType = msg.MsgType().String()
18✔
2404
                } else {
23✔
2405
                        msgType = "custom"
5✔
2406
                }
5✔
2407

2408
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
20✔
2409
                        msgType, summary, preposition, p)
20✔
2410
        }))
2411

2412
        prefix := "readMessage from peer"
20✔
2413
        if !read {
36✔
2414
                prefix = "writeMessage to peer"
16✔
2415
        }
16✔
2416

2417
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
20✔
2418
}
2419

2420
// writeMessage writes and flushes the target lnwire.Message to the remote peer.
2421
// If the passed message is nil, this method will only try to flush an existing
2422
// message buffered on the connection. It is safe to call this method again
2423
// with a nil message iff a timeout error is returned. This will continue to
2424
// flush the pending message to the wire.
2425
//
2426
// NOTE:
2427
// Besides its usage in Start, this function should not be used elsewhere
2428
// except in writeHandler. If multiple goroutines call writeMessage at the same
2429
// time, panics can occur because WriteMessage and Flush don't use any locking
2430
// internally.
2431
func (p *Brontide) writeMessage(msg lnwire.Message) error {
16✔
2432
        // Only log the message on the first attempt.
16✔
2433
        if msg != nil {
32✔
2434
                p.logWireMessage(msg, false)
16✔
2435
        }
16✔
2436

2437
        noiseConn := p.cfg.Conn
16✔
2438

16✔
2439
        flushMsg := func() error {
32✔
2440
                // Ensure the write deadline is set before we attempt to send
16✔
2441
                // the message.
16✔
2442
                writeDeadline := time.Now().Add(
16✔
2443
                        p.scaleTimeout(writeMessageTimeout),
16✔
2444
                )
16✔
2445
                err := noiseConn.SetWriteDeadline(writeDeadline)
16✔
2446
                if err != nil {
16✔
2447
                        return err
×
2448
                }
×
2449

2450
                // Flush the pending message to the wire. If an error is
2451
                // encountered, e.g. write timeout, the number of bytes written
2452
                // so far will be returned.
2453
                n, err := noiseConn.Flush()
16✔
2454

16✔
2455
                // Record the number of bytes written on the wire, if any.
16✔
2456
                if n > 0 {
19✔
2457
                        atomic.AddUint64(&p.bytesSent, uint64(n))
3✔
2458
                }
3✔
2459

2460
                return err
16✔
2461
        }
2462

2463
        // If the current message has already been serialized, encrypted, and
2464
        // buffered on the underlying connection we will skip straight to
2465
        // flushing it to the wire.
2466
        if msg == nil {
16✔
2467
                return flushMsg()
×
2468
        }
×
2469

2470
        // Otherwise, this is a new message. We'll acquire a write buffer to
2471
        // serialize the message and buffer the ciphertext on the connection.
2472
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
32✔
2473
                // Using a buffer allocated by the write pool, encode the
16✔
2474
                // message directly into the buffer.
16✔
2475
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
16✔
2476
                if writeErr != nil {
16✔
2477
                        return writeErr
×
2478
                }
×
2479

2480
                // Finally, write the message itself in a single swoop. This
2481
                // will buffer the ciphertext on the underlying connection. We
2482
                // will defer flushing the message until the write pool has been
2483
                // released.
2484
                return noiseConn.WriteMessage(buf.Bytes())
16✔
2485
        })
2486
        if err != nil {
16✔
2487
                return err
×
2488
        }
×
2489

2490
        return flushMsg()
16✔
2491
}
2492

2493
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2494
// queue, and writing them out to the wire. This goroutine coordinates with the
2495
// queueHandler in order to ensure the incoming message queue is quickly
2496
// drained.
2497
//
2498
// NOTE: This method MUST be run as a goroutine.
2499
func (p *Brontide) writeHandler() {
6✔
2500
        // We'll stop the timer after a new messages is sent, and also reset it
6✔
2501
        // after we process the next message.
6✔
2502
        idleTimer := time.AfterFunc(idleTimeout, func() {
6✔
2503
                err := fmt.Errorf("peer %s no write for %s -- disconnecting",
×
2504
                        p, idleTimeout)
×
2505
                p.Disconnect(err)
×
2506
        })
×
2507

2508
        var exitErr error
6✔
2509

6✔
2510
out:
6✔
2511
        for {
16✔
2512
                select {
10✔
2513
                case outMsg := <-p.sendQueue:
7✔
2514
                        // Record the time at which we first attempt to send the
7✔
2515
                        // message.
7✔
2516
                        startTime := time.Now()
7✔
2517

7✔
2518
                retry:
7✔
2519
                        // Write out the message to the socket. If a timeout
2520
                        // error is encountered, we will catch this and retry
2521
                        // after backing off in case the remote peer is just
2522
                        // slow to process messages from the wire.
2523
                        err := p.writeMessage(outMsg.msg)
7✔
2524
                        if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
7✔
2525
                                p.log.Debugf("Write timeout detected for "+
×
2526
                                        "peer, first write for message "+
×
2527
                                        "attempted %v ago",
×
2528
                                        time.Since(startTime))
×
2529

×
2530
                                // If we received a timeout error, this implies
×
2531
                                // that the message was buffered on the
×
2532
                                // connection successfully and that a flush was
×
2533
                                // attempted. We'll set the message to nil so
×
2534
                                // that on a subsequent pass we only try to
×
2535
                                // flush the buffered message, and forgo
×
2536
                                // reserializing or reencrypting it.
×
2537
                                outMsg.msg = nil
×
2538

×
2539
                                goto retry
×
2540
                        }
2541

2542
                        // The write succeeded, reset the idle timer to prevent
2543
                        // us from disconnecting the peer.
2544
                        if !idleTimer.Stop() {
7✔
2545
                                select {
×
2546
                                case <-idleTimer.C:
×
2547
                                default:
×
2548
                                }
2549
                        }
2550
                        idleTimer.Reset(idleTimeout)
7✔
2551

7✔
2552
                        // If the peer requested a synchronous write, respond
7✔
2553
                        // with the error.
7✔
2554
                        if outMsg.errChan != nil {
11✔
2555
                                outMsg.errChan <- err
4✔
2556
                        }
4✔
2557

2558
                        if err != nil {
7✔
2559
                                exitErr = fmt.Errorf("unable to write "+
×
2560
                                        "message: %v", err)
×
2561
                                break out
×
2562
                        }
2563

2564
                case <-p.quit:
3✔
2565
                        exitErr = lnpeer.ErrPeerExiting
3✔
2566
                        break out
3✔
2567
                }
2568
        }
2569

2570
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2571
        // disconnect.
2572
        p.wg.Done()
3✔
2573

3✔
2574
        p.Disconnect(exitErr)
3✔
2575

3✔
2576
        p.log.Trace("writeHandler for peer done")
3✔
2577
}
2578

2579
// queueHandler is responsible for accepting messages from outside subsystems
2580
// to be eventually sent out on the wire by the writeHandler.
2581
//
2582
// NOTE: This method MUST be run as a goroutine.
2583
func (p *Brontide) queueHandler() {
6✔
2584
        defer p.wg.Done()
6✔
2585

6✔
2586
        // priorityMsgs holds an in order list of messages deemed high-priority
6✔
2587
        // to be added to the sendQueue. This predominately includes messages
6✔
2588
        // from the funding manager and htlcswitch.
6✔
2589
        priorityMsgs := list.New()
6✔
2590

6✔
2591
        // lazyMsgs holds an in order list of messages deemed low-priority to be
6✔
2592
        // added to the sendQueue only after all high-priority messages have
6✔
2593
        // been queued. This predominately includes messages from the gossiper.
6✔
2594
        lazyMsgs := list.New()
6✔
2595

6✔
2596
        for {
20✔
2597
                // Examine the front of the priority queue, if it is empty check
14✔
2598
                // the low priority queue.
14✔
2599
                elem := priorityMsgs.Front()
14✔
2600
                if elem == nil {
25✔
2601
                        elem = lazyMsgs.Front()
11✔
2602
                }
11✔
2603

2604
                if elem != nil {
21✔
2605
                        front := elem.Value.(outgoingMsg)
7✔
2606

7✔
2607
                        // There's an element on the queue, try adding
7✔
2608
                        // it to the sendQueue. We also watch for
7✔
2609
                        // messages on the outgoingQueue, in case the
7✔
2610
                        // writeHandler cannot accept messages on the
7✔
2611
                        // sendQueue.
7✔
2612
                        select {
7✔
2613
                        case p.sendQueue <- front:
7✔
2614
                                if front.priority {
13✔
2615
                                        priorityMsgs.Remove(elem)
6✔
2616
                                } else {
10✔
2617
                                        lazyMsgs.Remove(elem)
4✔
2618
                                }
4✔
2619
                        case msg := <-p.outgoingQueue:
3✔
2620
                                if msg.priority {
6✔
2621
                                        priorityMsgs.PushBack(msg)
3✔
2622
                                } else {
6✔
2623
                                        lazyMsgs.PushBack(msg)
3✔
2624
                                }
3✔
2625
                        case <-p.quit:
×
2626
                                return
×
2627
                        }
2628
                } else {
10✔
2629
                        // If there weren't any messages to send to the
10✔
2630
                        // writeHandler, then we'll accept a new message
10✔
2631
                        // into the queue from outside sub-systems.
10✔
2632
                        select {
10✔
2633
                        case msg := <-p.outgoingQueue:
7✔
2634
                                if msg.priority {
13✔
2635
                                        priorityMsgs.PushBack(msg)
6✔
2636
                                } else {
10✔
2637
                                        lazyMsgs.PushBack(msg)
4✔
2638
                                }
4✔
2639
                        case <-p.quit:
3✔
2640
                                return
3✔
2641
                        }
2642
                }
2643
        }
2644
}
2645

2646
// PingTime returns the estimated ping time to the peer in microseconds.
2647
func (p *Brontide) PingTime() int64 {
3✔
2648
        return p.pingManager.GetPingTimeMicroSeconds()
3✔
2649
}
3✔
2650

2651
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2652
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2653
// or failed to write, and nil otherwise.
2654
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
28✔
2655
        p.queue(true, msg, errChan)
28✔
2656
}
28✔
2657

2658
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2659
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2660
// queue or failed to write, and nil otherwise.
2661
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
4✔
2662
        p.queue(false, msg, errChan)
4✔
2663
}
4✔
2664

2665
// queue sends a given message to the queueHandler using the passed priority. If
2666
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2667
// failed to write, and nil otherwise.
2668
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2669
        errChan chan error) {
29✔
2670

29✔
2671
        select {
29✔
2672
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
28✔
2673
        case <-p.quit:
3✔
2674
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
3✔
2675
                        spew.Sdump(msg))
3✔
2676
                if errChan != nil {
3✔
2677
                        errChan <- lnpeer.ErrPeerExiting
×
2678
                }
×
2679
        }
2680
}
2681

2682
// ChannelSnapshots returns a slice of channel snapshots detailing all
2683
// currently active channels maintained with the remote peer.
2684
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
3✔
2685
        snapshots := make(
3✔
2686
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
3✔
2687
        )
3✔
2688

3✔
2689
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2690
                activeChan *lnwallet.LightningChannel) error {
6✔
2691

3✔
2692
                // If the activeChan is nil, then we skip it as the channel is
3✔
2693
                // pending.
3✔
2694
                if activeChan == nil {
6✔
2695
                        return nil
3✔
2696
                }
3✔
2697

2698
                // We'll only return a snapshot for channels that are
2699
                // *immediately* available for routing payments over.
2700
                if activeChan.RemoteNextRevocation() == nil {
6✔
2701
                        return nil
3✔
2702
                }
3✔
2703

2704
                snapshot := activeChan.StateSnapshot()
3✔
2705
                snapshots = append(snapshots, snapshot)
3✔
2706

3✔
2707
                return nil
3✔
2708
        })
2709

2710
        return snapshots
3✔
2711
}
2712

2713
// genDeliveryScript returns a new script to be used to send our funds to in
2714
// the case of a cooperative channel close negotiation.
2715
func (p *Brontide) genDeliveryScript() ([]byte, error) {
9✔
2716
        // We'll send a normal p2wkh address unless we've negotiated the
9✔
2717
        // shutdown-any-segwit feature.
9✔
2718
        addrType := lnwallet.WitnessPubKey
9✔
2719
        if p.taprootShutdownAllowed() {
12✔
2720
                addrType = lnwallet.TaprootPubkey
3✔
2721
        }
3✔
2722

2723
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
9✔
2724
                addrType, false, lnwallet.DefaultAccountName,
9✔
2725
        )
9✔
2726
        if err != nil {
9✔
2727
                return nil, err
×
2728
        }
×
2729
        p.log.Infof("Delivery addr for channel close: %v",
9✔
2730
                deliveryAddr)
9✔
2731

9✔
2732
        return txscript.PayToAddrScript(deliveryAddr)
9✔
2733
}
2734

2735
// channelManager is goroutine dedicated to handling all requests/signals
2736
// pertaining to the opening, cooperative closing, and force closing of all
2737
// channels maintained with the remote peer.
2738
//
2739
// NOTE: This method MUST be run as a goroutine.
2740
func (p *Brontide) channelManager() {
20✔
2741
        defer p.wg.Done()
20✔
2742

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

20✔
2748
out:
20✔
2749
        for {
61✔
2750
                select {
41✔
2751
                // A new pending channel has arrived which means we are about
2752
                // to complete a funding workflow and is waiting for the final
2753
                // `ChannelReady` messages to be exchanged. We will add this
2754
                // channel to the `activeChannels` with a nil value to indicate
2755
                // this is a pending channel.
2756
                case req := <-p.newPendingChannel:
4✔
2757
                        p.handleNewPendingChannel(req)
4✔
2758

2759
                // A new channel has arrived which means we've just completed a
2760
                // funding workflow. We'll initialize the necessary local
2761
                // state, and notify the htlc switch of a new link.
2762
                case req := <-p.newActiveChannel:
3✔
2763
                        p.handleNewActiveChannel(req)
3✔
2764

2765
                // The funding flow for a pending channel is failed, we will
2766
                // remove it from Brontide.
2767
                case req := <-p.removePendingChannel:
4✔
2768
                        p.handleRemovePendingChannel(req)
4✔
2769

2770
                // We've just received a local request to close an active
2771
                // channel. It will either kick of a cooperative channel
2772
                // closure negotiation, or be a notification of a breached
2773
                // contract that should be abandoned.
2774
                case req := <-p.localCloseChanReqs:
10✔
2775
                        p.handleLocalCloseReq(req)
10✔
2776

2777
                // We've received a link failure from a link that was added to
2778
                // the switch. This will initiate the teardown of the link, and
2779
                // initiate any on-chain closures if necessary.
2780
                case failure := <-p.linkFailures:
3✔
2781
                        p.handleLinkFailure(failure)
3✔
2782

2783
                // We've received a new cooperative channel closure related
2784
                // message from the remote peer, we'll use this message to
2785
                // advance the chan closer state machine.
2786
                case closeMsg := <-p.chanCloseMsgs:
16✔
2787
                        p.handleCloseMsg(closeMsg)
16✔
2788

2789
                // The channel reannounce delay has elapsed, broadcast the
2790
                // reenabled channel updates to the network. This should only
2791
                // fire once, so we set the reenableTimeout channel to nil to
2792
                // mark it for garbage collection. If the peer is torn down
2793
                // before firing, reenabling will not be attempted.
2794
                // TODO(conner): consolidate reenables timers inside chan status
2795
                // manager
2796
                case <-reenableTimeout:
3✔
2797
                        p.reenableActiveChannels()
3✔
2798

3✔
2799
                        // Since this channel will never fire again during the
3✔
2800
                        // lifecycle of the peer, we nil the channel to mark it
3✔
2801
                        // eligible for garbage collection, and make this
3✔
2802
                        // explicitly ineligible to receive in future calls to
3✔
2803
                        // select. This also shaves a few CPU cycles since the
3✔
2804
                        // select will ignore this case entirely.
3✔
2805
                        reenableTimeout = nil
3✔
2806

3✔
2807
                        // Once the reenabling is attempted, we also cancel the
3✔
2808
                        // channel event subscription to free up the overflow
3✔
2809
                        // queue used in channel notifier.
3✔
2810
                        //
3✔
2811
                        // NOTE: channelEventClient will be nil if the
3✔
2812
                        // reenableTimeout is greater than 1 minute.
3✔
2813
                        if p.channelEventClient != nil {
6✔
2814
                                p.channelEventClient.Cancel()
3✔
2815
                        }
3✔
2816

2817
                case <-p.quit:
3✔
2818
                        // As, we've been signalled to exit, we'll reset all
3✔
2819
                        // our active channel back to their default state.
3✔
2820
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2821
                                lc *lnwallet.LightningChannel) error {
6✔
2822

3✔
2823
                                // Exit if the channel is nil as it's a pending
3✔
2824
                                // channel.
3✔
2825
                                if lc == nil {
6✔
2826
                                        return nil
3✔
2827
                                }
3✔
2828

2829
                                lc.ResetState()
3✔
2830

3✔
2831
                                return nil
3✔
2832
                        })
2833

2834
                        break out
3✔
2835
                }
2836
        }
2837
}
2838

2839
// reenableActiveChannels searches the index of channels maintained with this
2840
// peer, and reenables each public, non-pending channel. This is done at the
2841
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
2842
// No message will be sent if the channel is already enabled.
2843
func (p *Brontide) reenableActiveChannels() {
3✔
2844
        // First, filter all known channels with this peer for ones that are
3✔
2845
        // both public and not pending.
3✔
2846
        activePublicChans := p.filterChannelsToEnable()
3✔
2847

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

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

3✔
2857
                switch {
3✔
2858
                // No error occurred, continue to request the next channel.
2859
                case err == nil:
3✔
2860
                        continue
3✔
2861

2862
                // Cannot auto enable a manually disabled channel so we do
2863
                // nothing but proceed to the next channel.
2864
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
3✔
2865
                        p.log.Debugf("Channel(%v) was manually disabled, "+
3✔
2866
                                "ignoring automatic enable request", chanPoint)
3✔
2867

3✔
2868
                        continue
3✔
2869

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

×
2887
                                continue
×
2888
                        }
2889

2890
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
2891
                                "ChanStatusManager reported inactive, retrying")
×
2892

×
2893
                        // Add the channel to the retry map.
×
2894
                        retryChans[chanPoint] = struct{}{}
×
2895
                }
2896
        }
2897

2898
        // Retry the channels if we have any.
2899
        if len(retryChans) != 0 {
3✔
2900
                p.retryRequestEnable(retryChans)
×
2901
        }
×
2902
}
2903

2904
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
2905
// for the target channel ID. If the channel isn't active an error is returned.
2906
// Otherwise, either an existing state machine will be returned, or a new one
2907
// will be created.
2908
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
2909
        *chancloser.ChanCloser, error) {
16✔
2910

16✔
2911
        chanCloser, found := p.activeChanCloses[chanID]
16✔
2912
        if found {
29✔
2913
                // An entry will only be found if the closer has already been
13✔
2914
                // created for a non-pending channel or for a channel that had
13✔
2915
                // previously started the shutdown process but the connection
13✔
2916
                // was restarted.
13✔
2917
                return chanCloser, nil
13✔
2918
        }
13✔
2919

2920
        // First, we'll ensure that we actually know of the target channel. If
2921
        // not, we'll ignore this message.
2922
        channel, ok := p.activeChannels.Load(chanID)
6✔
2923

6✔
2924
        // If the channel isn't in the map or the channel is nil, return
6✔
2925
        // ErrChannelNotFound as the channel is pending.
6✔
2926
        if !ok || channel == nil {
9✔
2927
                return nil, ErrChannelNotFound
3✔
2928
        }
3✔
2929

2930
        // We'll create a valid closing state machine in order to respond to
2931
        // the initiated cooperative channel closure. First, we set the
2932
        // delivery script that our funds will be paid out to. If an upfront
2933
        // shutdown script was set, we will use it. Otherwise, we get a fresh
2934
        // delivery script.
2935
        //
2936
        // TODO: Expose option to allow upfront shutdown script from watch-only
2937
        // accounts.
2938
        deliveryScript := channel.LocalUpfrontShutdownScript()
6✔
2939
        if len(deliveryScript) == 0 {
12✔
2940
                var err error
6✔
2941
                deliveryScript, err = p.genDeliveryScript()
6✔
2942
                if err != nil {
6✔
2943
                        p.log.Errorf("unable to gen delivery script: %v",
×
2944
                                err)
×
2945
                        return nil, fmt.Errorf("close addr unavailable")
×
2946
                }
×
2947
        }
2948

2949
        // In order to begin fee negotiations, we'll first compute our target
2950
        // ideal fee-per-kw.
2951
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
6✔
2952
                p.cfg.CoopCloseTargetConfs,
6✔
2953
        )
6✔
2954
        if err != nil {
6✔
2955
                p.log.Errorf("unable to query fee estimator: %v", err)
×
2956
                return nil, fmt.Errorf("unable to estimate fee")
×
2957
        }
×
2958

2959
        addr, err := p.addrWithInternalKey(deliveryScript)
6✔
2960
        if err != nil {
6✔
2961
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
2962
        }
×
2963
        chanCloser, err = p.createChanCloser(
6✔
2964
                channel, addr, feePerKw, nil, lntypes.Remote,
6✔
2965
        )
6✔
2966
        if err != nil {
6✔
2967
                p.log.Errorf("unable to create chan closer: %v", err)
×
2968
                return nil, fmt.Errorf("unable to create chan closer")
×
2969
        }
×
2970

2971
        p.activeChanCloses[chanID] = chanCloser
6✔
2972

6✔
2973
        return chanCloser, nil
6✔
2974
}
2975

2976
// filterChannelsToEnable filters a list of channels to be enabled upon start.
2977
// The filtered channels are active channels that's neither private nor
2978
// pending.
2979
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
3✔
2980
        var activePublicChans []wire.OutPoint
3✔
2981

3✔
2982
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
3✔
2983
                lnChan *lnwallet.LightningChannel) bool {
6✔
2984

3✔
2985
                // If the lnChan is nil, continue as this is a pending channel.
3✔
2986
                if lnChan == nil {
4✔
2987
                        return true
1✔
2988
                }
1✔
2989

2990
                dbChan := lnChan.State()
3✔
2991
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
2992
                if !isPublic || dbChan.IsPending {
3✔
2993
                        return true
×
2994
                }
×
2995

2996
                // We'll also skip any channels added during this peer's
2997
                // lifecycle since they haven't waited out the timeout. Their
2998
                // first announcement will be enabled, and the chan status
2999
                // manager will begin monitoring them passively since they exist
3000
                // in the database.
3001
                if _, ok := p.addedChannels.Load(chanID); ok {
3✔
3002
                        return true
×
3003
                }
×
3004

3005
                activePublicChans = append(
3✔
3006
                        activePublicChans, dbChan.FundingOutpoint,
3✔
3007
                )
3✔
3008

3✔
3009
                return true
3✔
3010
        })
3011

3012
        return activePublicChans
3✔
3013
}
3014

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

×
3022
        // retryEnable is a helper closure that sends an enable request and
×
3023
        // removes the channel from the map if it's matched.
×
3024
        retryEnable := func(chanPoint wire.OutPoint) error {
×
3025
                // If this is an active channel event, check whether it's in
×
3026
                // our targeted channels map.
×
3027
                _, found := activeChans[chanPoint]
×
3028

×
3029
                // If this channel is irrelevant, return nil so the loop can
×
3030
                // jump to next iteration.
×
3031
                if !found {
×
3032
                        return nil
×
3033
                }
×
3034

3035
                // Otherwise we've just received an active signal for a channel
3036
                // that's previously failed to be enabled, we send the request
3037
                // again.
3038
                //
3039
                // We only give the channel one more shot, so we delete it from
3040
                // our map first to keep it from being attempted again.
3041
                delete(activeChans, chanPoint)
×
3042

×
3043
                // Send the request.
×
3044
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3045
                if err != nil {
×
3046
                        return fmt.Errorf("request enabling channel %v "+
×
3047
                                "failed: %w", chanPoint, err)
×
3048
                }
×
3049

3050
                return nil
×
3051
        }
3052

3053
        for {
×
3054
                // If activeChans is empty, we've done processing all the
×
3055
                // channels.
×
3056
                if len(activeChans) == 0 {
×
3057
                        p.log.Debug("Finished retry enabling channels")
×
3058
                        return
×
3059
                }
×
3060

3061
                select {
×
3062
                // A new event has been sent by the ChannelNotifier. We now
3063
                // check whether it's an active or inactive channel event.
3064
                case e := <-p.channelEventClient.Updates():
×
3065
                        // If this is an active channel event, try enable the
×
3066
                        // channel then jump to the next iteration.
×
3067
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
3068
                        if ok {
×
3069
                                chanPoint := *active.ChannelPoint
×
3070

×
3071
                                // If we received an error for this particular
×
3072
                                // channel, we log an error and won't quit as
×
3073
                                // we still want to retry other channels.
×
3074
                                if err := retryEnable(chanPoint); err != nil {
×
3075
                                        p.log.Errorf("Retry failed: %v", err)
×
3076
                                }
×
3077

3078
                                continue
×
3079
                        }
3080

3081
                        // Otherwise check for inactive link event, and jump to
3082
                        // next iteration if it's not.
3083
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3084
                        if !ok {
×
3085
                                continue
×
3086
                        }
3087

3088
                        // Found an inactive link event, if this is our
3089
                        // targeted channel, remove it from our map.
3090
                        chanPoint := *inactive.ChannelPoint
×
3091
                        _, found := activeChans[chanPoint]
×
3092
                        if !found {
×
3093
                                continue
×
3094
                        }
3095

3096
                        delete(activeChans, chanPoint)
×
3097
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3098
                                "inactive link event", chanPoint)
×
3099

3100
                case <-p.quit:
×
3101
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3102
                        return
×
3103
                }
3104
        }
3105
}
3106

3107
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3108
// a suitable script to close out to. This may be nil if neither script is
3109
// set. If both scripts are set, this function will error if they do not match.
3110
func chooseDeliveryScript(upfront,
3111
        requested lnwire.DeliveryAddress) (lnwire.DeliveryAddress, error) {
15✔
3112

15✔
3113
        // If no upfront shutdown script was provided, return the user
15✔
3114
        // requested address (which may be nil).
15✔
3115
        if len(upfront) == 0 {
24✔
3116
                return requested, nil
9✔
3117
        }
9✔
3118

3119
        // If an upfront shutdown script was provided, and the user did not
3120
        // request a custom shutdown script, return the upfront address.
3121
        if len(requested) == 0 {
14✔
3122
                return upfront, nil
5✔
3123
        }
5✔
3124

3125
        // If both an upfront shutdown script and a custom close script were
3126
        // provided, error if the user provided shutdown script does not match
3127
        // the upfront shutdown script (because closing out to a different
3128
        // script would violate upfront shutdown).
3129
        if !bytes.Equal(upfront, requested) {
6✔
3130
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
3131
        }
2✔
3132

3133
        // The user requested script matches the upfront shutdown script, so we
3134
        // can return it without error.
3135
        return upfront, nil
2✔
3136
}
3137

3138
// restartCoopClose checks whether we need to restart the cooperative close
3139
// process for a given channel.
3140
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3141
        *lnwire.Shutdown, error) {
×
3142

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

3161
        var deliveryScript []byte
×
3162

×
3163
        shutdownInfo, err := c.ShutdownInfo()
×
3164
        switch {
×
3165
        // We have previously stored the delivery script that we need to use
3166
        // in the shutdown message. Re-use this script.
3167
        case err == nil:
×
3168
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
×
3169
                        deliveryScript = info.DeliveryScript.Val
×
3170
                })
×
3171

3172
        // An error other than ErrNoShutdownInfo was returned
3173
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3174
                return nil, err
×
3175

3176
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3177
                deliveryScript = c.LocalShutdownScript
×
3178
                if len(deliveryScript) == 0 {
×
3179
                        var err error
×
3180
                        deliveryScript, err = p.genDeliveryScript()
×
3181
                        if err != nil {
×
3182
                                p.log.Errorf("unable to gen delivery script: "+
×
3183
                                        "%v", err)
×
3184

×
3185
                                return nil, fmt.Errorf("close addr unavailable")
×
3186
                        }
×
3187
                }
3188
        }
3189

3190
        // Compute an ideal fee.
3191
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
3192
                p.cfg.CoopCloseTargetConfs,
×
3193
        )
×
3194
        if err != nil {
×
3195
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3196
                return nil, fmt.Errorf("unable to estimate fee")
×
3197
        }
×
3198

3199
        // Determine whether we or the peer are the initiator of the coop
3200
        // close attempt by looking at the channel's status.
3201
        closingParty := lntypes.Remote
×
3202
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3203
                closingParty = lntypes.Local
×
3204
        }
×
3205

3206
        addr, err := p.addrWithInternalKey(deliveryScript)
×
3207
        if err != nil {
×
3208
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3209
        }
×
3210
        chanCloser, err := p.createChanCloser(
×
3211
                lnChan, addr, feePerKw, nil, closingParty,
×
3212
        )
×
3213
        if err != nil {
×
3214
                p.log.Errorf("unable to create chan closer: %v", err)
×
3215
                return nil, fmt.Errorf("unable to create chan closer")
×
3216
        }
×
3217

3218
        // This does not need a mutex even though it is in a different
3219
        // goroutine since this is done before the channelManager goroutine is
3220
        // created.
3221
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
×
3222
        p.activeChanCloses[chanID] = chanCloser
×
3223

×
3224
        // Create the Shutdown message.
×
3225
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3226
        if err != nil {
×
3227
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3228
                delete(p.activeChanCloses, chanID)
×
3229
                return nil, err
×
3230
        }
×
3231

3232
        return shutdownMsg, nil
×
3233
}
3234

3235
// createChanCloser constructs a ChanCloser from the passed parameters and is
3236
// used to de-duplicate code.
3237
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3238
        deliveryScript *chancloser.DeliveryAddrWithKey,
3239
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3240
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
12✔
3241

12✔
3242
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
12✔
3243
        if err != nil {
12✔
3244
                p.log.Errorf("unable to obtain best block: %v", err)
×
3245
                return nil, fmt.Errorf("cannot obtain best block")
×
3246
        }
×
3247

3248
        // The req will only be set if we initiated the co-op closing flow.
3249
        var maxFee chainfee.SatPerKWeight
12✔
3250
        if req != nil {
21✔
3251
                maxFee = req.MaxFee
9✔
3252
        }
9✔
3253

3254
        chanCloser := chancloser.NewChanCloser(
12✔
3255
                chancloser.ChanCloseCfg{
12✔
3256
                        Channel:      channel,
12✔
3257
                        MusigSession: NewMusigChanCloser(channel),
12✔
3258
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
12✔
3259
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
12✔
3260
                        AuxCloser:    p.cfg.AuxChanCloser,
12✔
3261
                        DisableChannel: func(op wire.OutPoint) error {
24✔
3262
                                return p.cfg.ChanStatusMgr.RequestDisable(
12✔
3263
                                        op, false,
12✔
3264
                                )
12✔
3265
                        },
12✔
3266
                        MaxFee: maxFee,
3267
                        Disconnect: func() error {
×
3268
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
3269
                        },
×
3270
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3271
                        Quit:        p.quit,
3272
                },
3273
                *deliveryScript,
3274
                fee,
3275
                uint32(startingHeight),
3276
                req,
3277
                closer,
3278
        )
3279

3280
        return chanCloser, nil
12✔
3281
}
3282

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

10✔
3288
        channel, ok := p.activeChannels.Load(chanID)
10✔
3289

10✔
3290
        // Though this function can't be called for pending channels, we still
10✔
3291
        // check whether channel is nil for safety.
10✔
3292
        if !ok || channel == nil {
10✔
3293
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
×
3294
                        "unknown", chanID)
×
3295
                p.log.Errorf(err.Error())
×
3296
                req.Err <- err
×
3297
                return
×
3298
        }
×
3299

3300
        switch req.CloseType {
10✔
3301
        // A type of CloseRegular indicates that the user has opted to close
3302
        // out this channel on-chain, so we execute the cooperative channel
3303
        // closure workflow.
3304
        case contractcourt.CloseRegular:
10✔
3305
                // First, we'll choose a delivery address that we'll use to send the
10✔
3306
                // funds to in the case of a successful negotiation.
10✔
3307

10✔
3308
                // An upfront shutdown and user provided script are both optional,
10✔
3309
                // but must be equal if both set  (because we cannot serve a request
10✔
3310
                // to close out to a script which violates upfront shutdown). Get the
10✔
3311
                // appropriate address to close out to (which may be nil if neither
10✔
3312
                // are set) and error if they are both set and do not match.
10✔
3313
                deliveryScript, err := chooseDeliveryScript(
10✔
3314
                        channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
10✔
3315
                )
10✔
3316
                if err != nil {
11✔
3317
                        p.log.Errorf("cannot close channel %v: %v", req.ChanPoint, err)
1✔
3318
                        req.Err <- err
1✔
3319
                        return
1✔
3320
                }
1✔
3321

3322
                // If neither an upfront address or a user set address was
3323
                // provided, generate a fresh script.
3324
                if len(deliveryScript) == 0 {
15✔
3325
                        deliveryScript, err = p.genDeliveryScript()
6✔
3326
                        if err != nil {
6✔
3327
                                p.log.Errorf(err.Error())
×
3328
                                req.Err <- err
×
3329
                                return
×
3330
                        }
×
3331
                }
3332
                addr, err := p.addrWithInternalKey(deliveryScript)
9✔
3333
                if err != nil {
9✔
3334
                        err = fmt.Errorf("unable to parse addr for channel "+
×
3335
                                "%v: %w", req.ChanPoint, err)
×
3336
                        p.log.Errorf(err.Error())
×
3337
                        req.Err <- err
×
3338

×
3339
                        return
×
3340
                }
×
3341
                chanCloser, err := p.createChanCloser(
9✔
3342
                        channel, addr, req.TargetFeePerKw, req, lntypes.Local,
9✔
3343
                )
9✔
3344
                if err != nil {
9✔
3345
                        p.log.Errorf(err.Error())
×
3346
                        req.Err <- err
×
3347
                        return
×
3348
                }
×
3349

3350
                p.activeChanCloses[chanID] = chanCloser
9✔
3351

9✔
3352
                // Finally, we'll initiate the channel shutdown within the
9✔
3353
                // chanCloser, and send the shutdown message to the remote
9✔
3354
                // party to kick things off.
9✔
3355
                shutdownMsg, err := chanCloser.ShutdownChan()
9✔
3356
                if err != nil {
9✔
3357
                        p.log.Errorf(err.Error())
×
3358
                        req.Err <- err
×
3359
                        delete(p.activeChanCloses, chanID)
×
3360

×
3361
                        // As we were unable to shutdown the channel, we'll
×
3362
                        // return it back to its normal state.
×
3363
                        channel.ResetState()
×
3364
                        return
×
3365
                }
×
3366

3367
                link := p.fetchLinkFromKeyAndCid(chanID)
9✔
3368
                if link == nil {
9✔
3369
                        // If the link is nil then it means it was already
×
3370
                        // removed from the switch or it never existed in the
×
3371
                        // first place. The latter case is handled at the
×
3372
                        // beginning of this function, so in the case where it
×
3373
                        // has already been removed, we can skip adding the
×
3374
                        // commit hook to queue a Shutdown message.
×
3375
                        p.log.Warnf("link not found during attempted closure: "+
×
3376
                                "%v", chanID)
×
3377
                        return
×
3378
                }
×
3379

3380
                if !link.DisableAdds(htlcswitch.Outgoing) {
9✔
3381
                        p.log.Warnf("Outgoing link adds already "+
×
3382
                                "disabled: %v", link.ChanID())
×
3383
                }
×
3384

3385
                link.OnCommitOnce(htlcswitch.Outgoing, func() {
18✔
3386
                        p.queueMsg(shutdownMsg, nil)
9✔
3387
                })
9✔
3388

3389
        // A type of CloseBreach indicates that the counterparty has breached
3390
        // the channel therefore we need to clean up our local state.
3391
        case contractcourt.CloseBreach:
×
3392
                // TODO(roasbeef): no longer need with newer beach logic?
×
3393
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
×
3394
                        "channel", req.ChanPoint)
×
3395
                p.WipeChannel(req.ChanPoint)
×
3396
        }
3397
}
3398

3399
// linkFailureReport is sent to the channelManager whenever a link reports a
3400
// link failure, and is forced to exit. The report houses the necessary
3401
// information to clean up the channel state, send back the error message, and
3402
// force close if necessary.
3403
type linkFailureReport struct {
3404
        chanPoint   wire.OutPoint
3405
        chanID      lnwire.ChannelID
3406
        shortChanID lnwire.ShortChannelID
3407
        linkErr     htlcswitch.LinkFailureError
3408
}
3409

3410
// handleLinkFailure processes a link failure report when a link in the switch
3411
// fails. It facilitates the removal of all channel state within the peer,
3412
// force closing the channel depending on severity, and sending the error
3413
// message back to the remote party.
3414
func (p *Brontide) handleLinkFailure(failure linkFailureReport) {
3✔
3415
        // Retrieve the channel from the map of active channels. We do this to
3✔
3416
        // have access to it even after WipeChannel remove it from the map.
3✔
3417
        chanID := lnwire.NewChanIDFromOutPoint(failure.chanPoint)
3✔
3418
        lnChan, _ := p.activeChannels.Load(chanID)
3✔
3419

3✔
3420
        // We begin by wiping the link, which will remove it from the switch,
3✔
3421
        // such that it won't be attempted used for any more updates.
3✔
3422
        //
3✔
3423
        // TODO(halseth): should introduce a way to atomically stop/pause the
3✔
3424
        // link and cancel back any adds in its mailboxes such that we can
3✔
3425
        // safely force close without the link being added again and updates
3✔
3426
        // being applied.
3✔
3427
        p.WipeChannel(&failure.chanPoint)
3✔
3428

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

3✔
3434
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
3✔
3435
                        failure.chanPoint,
3✔
3436
                )
3✔
3437
                if err != nil {
6✔
3438
                        p.log.Errorf("unable to force close "+
3✔
3439
                                "link(%v): %v", failure.shortChanID, err)
3✔
3440
                } else {
6✔
3441
                        p.log.Infof("channel(%v) force "+
3✔
3442
                                "closed with txid %v",
3✔
3443
                                failure.shortChanID, closeTx.TxHash())
3✔
3444
                }
3✔
3445
        }
3446

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

×
3452
                if err := lnChan.State().MarkBorked(); err != nil {
×
3453
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
3454
                                failure.shortChanID, err)
×
3455
                }
×
3456
        }
3457

3458
        // Send an error to the peer, why we failed the channel.
3459
        if failure.linkErr.ShouldSendToPeer() {
6✔
3460
                // If SendData is set, send it to the peer. If not, we'll use
3✔
3461
                // the standard error messages in the payload. We only include
3✔
3462
                // sendData in the cases where the error data does not contain
3✔
3463
                // sensitive information.
3✔
3464
                data := []byte(failure.linkErr.Error())
3✔
3465
                if failure.linkErr.SendData != nil {
3✔
3466
                        data = failure.linkErr.SendData
×
3467
                }
×
3468

3469
                var networkMsg lnwire.Message
3✔
3470
                if failure.linkErr.Warning {
3✔
3471
                        networkMsg = &lnwire.Warning{
×
3472
                                ChanID: failure.chanID,
×
3473
                                Data:   data,
×
3474
                        }
×
3475
                } else {
3✔
3476
                        networkMsg = &lnwire.Error{
3✔
3477
                                ChanID: failure.chanID,
3✔
3478
                                Data:   data,
3✔
3479
                        }
3✔
3480
                }
3✔
3481

3482
                err := p.SendMessage(true, networkMsg)
3✔
3483
                if err != nil {
3✔
3484
                        p.log.Errorf("unable to send msg to "+
×
3485
                                "remote peer: %v", err)
×
3486
                }
×
3487
        }
3488

3489
        // If the failure action is disconnect, then we'll execute that now. If
3490
        // we had to send an error above, it was a sync call, so we expect the
3491
        // message to be flushed on the wire by now.
3492
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
3✔
3493
                p.Disconnect(fmt.Errorf("link requested disconnect"))
×
3494
        }
×
3495
}
3496

3497
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
3498
// public key and the channel id.
3499
func (p *Brontide) fetchLinkFromKeyAndCid(
3500
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
22✔
3501

22✔
3502
        var chanLink htlcswitch.ChannelUpdateHandler
22✔
3503

22✔
3504
        // We don't need to check the error here, and can instead just loop
22✔
3505
        // over the slice and return nil.
22✔
3506
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
22✔
3507
        for _, link := range links {
43✔
3508
                if link.ChanID() == cid {
42✔
3509
                        chanLink = link
21✔
3510
                        break
21✔
3511
                }
3512
        }
3513

3514
        return chanLink
22✔
3515
}
3516

3517
// finalizeChanClosure performs the final clean up steps once the cooperative
3518
// closure transaction has been fully broadcast. The finalized closing state
3519
// machine should be passed in. Once the transaction has been sufficiently
3520
// confirmed, the channel will be marked as fully closed within the database,
3521
// and any clients will be notified of updates to the closing state.
3522
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
7✔
3523
        closeReq := chanCloser.CloseRequest()
7✔
3524

7✔
3525
        // First, we'll clear all indexes related to the channel in question.
7✔
3526
        chanPoint := chanCloser.Channel().ChannelPoint()
7✔
3527
        p.WipeChannel(&chanPoint)
7✔
3528

7✔
3529
        // Also clear the activeChanCloses map of this channel.
7✔
3530
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
7✔
3531
        delete(p.activeChanCloses, cid)
7✔
3532

7✔
3533
        // Next, we'll launch a goroutine which will request to be notified by
7✔
3534
        // the ChainNotifier once the closure transaction obtains a single
7✔
3535
        // confirmation.
7✔
3536
        notifier := p.cfg.ChainNotifier
7✔
3537

7✔
3538
        // If any error happens during waitForChanToClose, forward it to
7✔
3539
        // closeReq. If this channel closure is not locally initiated, closeReq
7✔
3540
        // will be nil, so just ignore the error.
7✔
3541
        errChan := make(chan error, 1)
7✔
3542
        if closeReq != nil {
12✔
3543
                errChan = closeReq.Err
5✔
3544
        }
5✔
3545

3546
        closingTx, err := chanCloser.ClosingTx()
7✔
3547
        if err != nil {
7✔
3548
                if closeReq != nil {
×
3549
                        p.log.Error(err)
×
3550
                        closeReq.Err <- err
×
3551
                }
×
3552
        }
3553

3554
        closingTxid := closingTx.TxHash()
7✔
3555

7✔
3556
        // If this is a locally requested shutdown, update the caller with a
7✔
3557
        // new event detailing the current pending state of this request.
7✔
3558
        if closeReq != nil {
12✔
3559
                closeReq.Updates <- &PendingUpdate{
5✔
3560
                        Txid: closingTxid[:],
5✔
3561
                }
5✔
3562
        }
5✔
3563

3564
        localOut := chanCloser.LocalCloseOutput()
7✔
3565
        remoteOut := chanCloser.RemoteCloseOutput()
7✔
3566
        auxOut := chanCloser.AuxOutputs()
7✔
3567
        go WaitForChanToClose(
7✔
3568
                chanCloser.NegotiationHeight(), notifier, errChan,
7✔
3569
                &chanPoint, &closingTxid, closingTx.TxOut[0].PkScript, func() {
14✔
3570
                        // Respond to the local subsystem which requested the
7✔
3571
                        // channel closure.
7✔
3572
                        if closeReq != nil {
12✔
3573
                                closeReq.Updates <- &ChannelCloseUpdate{
5✔
3574
                                        ClosingTxid:       closingTxid[:],
5✔
3575
                                        Success:           true,
5✔
3576
                                        LocalCloseOutput:  localOut,
5✔
3577
                                        RemoteCloseOutput: remoteOut,
5✔
3578
                                        AuxOutputs:        auxOut,
5✔
3579
                                }
5✔
3580
                        }
5✔
3581
                },
3582
        )
3583
}
3584

3585
// WaitForChanToClose uses the passed notifier to wait until the channel has
3586
// been detected as closed on chain and then concludes by executing the
3587
// following actions: the channel point will be sent over the settleChan, and
3588
// finally the callback will be executed. If any error is encountered within
3589
// the function, then it will be sent over the errChan.
3590
func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
3591
        errChan chan error, chanPoint *wire.OutPoint,
3592
        closingTxID *chainhash.Hash, closeScript []byte, cb func()) {
7✔
3593

7✔
3594
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
7✔
3595
                "with txid: %v", chanPoint, closingTxID)
7✔
3596

7✔
3597
        // TODO(roasbeef): add param for num needed confs
7✔
3598
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
7✔
3599
                closingTxID, closeScript, 1, bestHeight,
7✔
3600
        )
7✔
3601
        if err != nil {
7✔
3602
                if errChan != nil {
×
3603
                        errChan <- err
×
3604
                }
×
3605
                return
×
3606
        }
3607

3608
        // In the case that the ChainNotifier is shutting down, all subscriber
3609
        // notification channels will be closed, generating a nil receive.
3610
        height, ok := <-confNtfn.Confirmed
7✔
3611
        if !ok {
10✔
3612
                return
3✔
3613
        }
3✔
3614

3615
        // The channel has been closed, remove it from any active indexes, and
3616
        // the database state.
3617
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
7✔
3618
                "height %v", chanPoint, height.BlockHeight)
7✔
3619

7✔
3620
        // Finally, execute the closure call back to mark the confirmation of
7✔
3621
        // the transaction closing the contract.
7✔
3622
        cb()
7✔
3623
}
3624

3625
// WipeChannel removes the passed channel point from all indexes associated with
3626
// the peer and the switch.
3627
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
7✔
3628
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
7✔
3629

7✔
3630
        p.activeChannels.Delete(chanID)
7✔
3631

7✔
3632
        // Instruct the HtlcSwitch to close this link as the channel is no
7✔
3633
        // longer active.
7✔
3634
        p.cfg.Switch.RemoveLink(chanID)
7✔
3635
}
7✔
3636

3637
// handleInitMsg handles the incoming init message which contains global and
3638
// local feature vectors. If feature vectors are incompatible then disconnect.
3639
func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
6✔
3640
        // First, merge any features from the legacy global features field into
6✔
3641
        // those presented in the local features fields.
6✔
3642
        err := msg.Features.Merge(msg.GlobalFeatures)
6✔
3643
        if err != nil {
6✔
3644
                return fmt.Errorf("unable to merge legacy global features: %w",
×
3645
                        err)
×
3646
        }
×
3647

3648
        // Then, finalize the remote feature vector providing the flattened
3649
        // feature bit namespace.
3650
        p.remoteFeatures = lnwire.NewFeatureVector(
6✔
3651
                msg.Features, lnwire.Features,
6✔
3652
        )
6✔
3653

6✔
3654
        // Now that we have their features loaded, we'll ensure that they
6✔
3655
        // didn't set any required bits that we don't know of.
6✔
3656
        err = feature.ValidateRequired(p.remoteFeatures)
6✔
3657
        if err != nil {
6✔
3658
                return fmt.Errorf("invalid remote features: %w", err)
×
3659
        }
×
3660

3661
        // Ensure the remote party's feature vector contains all transitive
3662
        // dependencies. We know ours are correct since they are validated
3663
        // during the feature manager's instantiation.
3664
        err = feature.ValidateDeps(p.remoteFeatures)
6✔
3665
        if err != nil {
6✔
3666
                return fmt.Errorf("invalid remote features: %w", err)
×
3667
        }
×
3668

3669
        // Now that we know we understand their requirements, we'll check to
3670
        // see if they don't support anything that we deem to be mandatory.
3671
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
6✔
3672
                return fmt.Errorf("data loss protection required")
×
3673
        }
×
3674

3675
        return nil
6✔
3676
}
3677

3678
// LocalFeatures returns the set of global features that has been advertised by
3679
// the local node. This allows sub-systems that use this interface to gate their
3680
// behavior off the set of negotiated feature bits.
3681
//
3682
// NOTE: Part of the lnpeer.Peer interface.
3683
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
3✔
3684
        return p.cfg.Features
3✔
3685
}
3✔
3686

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

3696
// hasNegotiatedScidAlias returns true if we've negotiated the
3697
// option-scid-alias feature bit with the peer.
3698
func (p *Brontide) hasNegotiatedScidAlias() bool {
6✔
3699
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
6✔
3700
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
6✔
3701
        return peerHas && localHas
6✔
3702
}
6✔
3703

3704
// sendInitMsg sends the Init message to the remote peer. This message contains
3705
// our currently supported local and global features.
3706
func (p *Brontide) sendInitMsg(legacyChan bool) error {
10✔
3707
        features := p.cfg.Features.Clone()
10✔
3708
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
10✔
3709

10✔
3710
        // If we have a legacy channel open with a peer, we downgrade static
10✔
3711
        // remote required to optional in case the peer does not understand the
10✔
3712
        // required feature bit. If we do not do this, the peer will reject our
10✔
3713
        // connection because it does not understand a required feature bit, and
10✔
3714
        // our channel will be unusable.
10✔
3715
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
11✔
3716
                p.log.Infof("Legacy channel open with peer, " +
1✔
3717
                        "downgrading static remote required feature bit to " +
1✔
3718
                        "optional")
1✔
3719

1✔
3720
                // Unset and set in both the local and global features to
1✔
3721
                // ensure both sets are consistent and merge able by old and
1✔
3722
                // new nodes.
1✔
3723
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3724
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3725

1✔
3726
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
3727
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
3728
        }
1✔
3729

3730
        msg := lnwire.NewInitMessage(
10✔
3731
                legacyFeatures.RawFeatureVector,
10✔
3732
                features.RawFeatureVector,
10✔
3733
        )
10✔
3734

10✔
3735
        return p.writeMessage(msg)
10✔
3736
}
3737

3738
// resendChanSyncMsg will attempt to find a channel sync message for the closed
3739
// channel and resend it to our peer.
3740
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
3✔
3741
        // If we already re-sent the mssage for this channel, we won't do it
3✔
3742
        // again.
3✔
3743
        if _, ok := p.resentChanSyncMsg[cid]; ok {
5✔
3744
                return nil
2✔
3745
        }
2✔
3746

3747
        // Check if we have any channel sync messages stored for this channel.
3748
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
3✔
3749
        if err != nil {
6✔
3750
                return fmt.Errorf("unable to fetch channel sync messages for "+
3✔
3751
                        "peer %v: %v", p, err)
3✔
3752
        }
3✔
3753

3754
        if c.LastChanSyncMsg == nil {
3✔
3755
                return fmt.Errorf("no chan sync message stored for channel %v",
×
3756
                        cid)
×
3757
        }
×
3758

3759
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
3✔
3760
                return fmt.Errorf("ignoring channel reestablish from "+
×
3761
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
3762
        }
×
3763

3764
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
3✔
3765
                "peer", cid)
3✔
3766

3✔
3767
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
3✔
3768
                return fmt.Errorf("failed resending channel sync "+
×
3769
                        "message to peer %v: %v", p, err)
×
3770
        }
×
3771

3772
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
3✔
3773
                cid)
3✔
3774

3✔
3775
        // Note down that we sent the message, so we won't resend it again for
3✔
3776
        // this connection.
3✔
3777
        p.resentChanSyncMsg[cid] = struct{}{}
3✔
3778

3✔
3779
        return nil
3✔
3780
}
3781

3782
// SendMessage sends a variadic number of high-priority messages to the remote
3783
// peer. The first argument denotes if the method should block until the
3784
// messages have been sent to the remote peer or an error is returned,
3785
// otherwise it returns immediately after queuing.
3786
//
3787
// NOTE: Part of the lnpeer.Peer interface.
3788
func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error {
6✔
3789
        return p.sendMessage(sync, true, msgs...)
6✔
3790
}
6✔
3791

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

3802
// sendMessage queues a variadic number of messages using the passed priority
3803
// to the remote peer. If sync is true, this method will block until the
3804
// messages have been sent to the remote peer or an error is returned, otherwise
3805
// it returns immediately after queueing.
3806
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
7✔
3807
        // Add all incoming messages to the outgoing queue. A list of error
7✔
3808
        // chans is populated for each message if the caller requested a sync
7✔
3809
        // send.
7✔
3810
        var errChans []chan error
7✔
3811
        if sync {
11✔
3812
                errChans = make([]chan error, 0, len(msgs))
4✔
3813
        }
4✔
3814
        for _, msg := range msgs {
14✔
3815
                // If a sync send was requested, create an error chan to listen
7✔
3816
                // for an ack from the writeHandler.
7✔
3817
                var errChan chan error
7✔
3818
                if sync {
11✔
3819
                        errChan = make(chan error, 1)
4✔
3820
                        errChans = append(errChans, errChan)
4✔
3821
                }
4✔
3822

3823
                if priority {
13✔
3824
                        p.queueMsg(msg, errChan)
6✔
3825
                } else {
10✔
3826
                        p.queueMsgLazy(msg, errChan)
4✔
3827
                }
4✔
3828
        }
3829

3830
        // Wait for all replies from the writeHandler. For async sends, this
3831
        // will be a NOP as the list of error chans is nil.
3832
        for _, errChan := range errChans {
11✔
3833
                select {
4✔
3834
                case err := <-errChan:
4✔
3835
                        return err
4✔
3836
                case <-p.quit:
×
3837
                        return lnpeer.ErrPeerExiting
×
3838
                case <-p.cfg.Quit:
×
3839
                        return lnpeer.ErrPeerExiting
×
3840
                }
3841
        }
3842

3843
        return nil
6✔
3844
}
3845

3846
// PubKey returns the pubkey of the peer in compressed serialized format.
3847
//
3848
// NOTE: Part of the lnpeer.Peer interface.
3849
func (p *Brontide) PubKey() [33]byte {
5✔
3850
        return p.cfg.PubKeyBytes
5✔
3851
}
5✔
3852

3853
// IdentityKey returns the public key of the remote peer.
3854
//
3855
// NOTE: Part of the lnpeer.Peer interface.
3856
func (p *Brontide) IdentityKey() *btcec.PublicKey {
18✔
3857
        return p.cfg.Addr.IdentityKey
18✔
3858
}
18✔
3859

3860
// Address returns the network address of the remote peer.
3861
//
3862
// NOTE: Part of the lnpeer.Peer interface.
3863
func (p *Brontide) Address() net.Addr {
3✔
3864
        return p.cfg.Addr.Address
3✔
3865
}
3✔
3866

3867
// AddNewChannel adds a new channel to the peer. The channel should fail to be
3868
// added if the cancel channel is closed.
3869
//
3870
// NOTE: Part of the lnpeer.Peer interface.
3871
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
3872
        cancel <-chan struct{}) error {
3✔
3873

3✔
3874
        errChan := make(chan error, 1)
3✔
3875
        newChanMsg := &newChannelMsg{
3✔
3876
                channel: newChan,
3✔
3877
                err:     errChan,
3✔
3878
        }
3✔
3879

3✔
3880
        select {
3✔
3881
        case p.newActiveChannel <- newChanMsg:
3✔
3882
        case <-cancel:
×
3883
                return errors.New("canceled adding new channel")
×
3884
        case <-p.quit:
×
3885
                return lnpeer.ErrPeerExiting
×
3886
        }
3887

3888
        // We pause here to wait for the peer to recognize the new channel
3889
        // before we close the channel barrier corresponding to the channel.
3890
        select {
3✔
3891
        case err := <-errChan:
3✔
3892
                return err
3✔
3893
        case <-p.quit:
×
3894
                return lnpeer.ErrPeerExiting
×
3895
        }
3896
}
3897

3898
// AddPendingChannel adds a pending open channel to the peer. The channel
3899
// should fail to be added if the cancel channel is closed.
3900
//
3901
// NOTE: Part of the lnpeer.Peer interface.
3902
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
3903
        cancel <-chan struct{}) error {
3✔
3904

3✔
3905
        errChan := make(chan error, 1)
3✔
3906
        newChanMsg := &newChannelMsg{
3✔
3907
                channelID: cid,
3✔
3908
                err:       errChan,
3✔
3909
        }
3✔
3910

3✔
3911
        select {
3✔
3912
        case p.newPendingChannel <- newChanMsg:
3✔
3913

3914
        case <-cancel:
×
3915
                return errors.New("canceled adding pending channel")
×
3916

3917
        case <-p.quit:
×
3918
                return lnpeer.ErrPeerExiting
×
3919
        }
3920

3921
        // We pause here to wait for the peer to recognize the new pending
3922
        // channel before we close the channel barrier corresponding to the
3923
        // channel.
3924
        select {
3✔
3925
        case err := <-errChan:
3✔
3926
                return err
3✔
3927

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

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

3936
// RemovePendingChannel removes a pending open channel from the peer.
3937
//
3938
// NOTE: Part of the lnpeer.Peer interface.
3939
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
3✔
3940
        errChan := make(chan error, 1)
3✔
3941
        newChanMsg := &newChannelMsg{
3✔
3942
                channelID: cid,
3✔
3943
                err:       errChan,
3✔
3944
        }
3✔
3945

3✔
3946
        select {
3✔
3947
        case p.removePendingChannel <- newChanMsg:
3✔
3948
        case <-p.quit:
×
3949
                return lnpeer.ErrPeerExiting
×
3950
        }
3951

3952
        // We pause here to wait for the peer to respond to the cancellation of
3953
        // the pending channel before we close the channel barrier
3954
        // corresponding to the channel.
3955
        select {
3✔
3956
        case err := <-errChan:
3✔
3957
                return err
3✔
3958

3959
        case <-p.quit:
×
3960
                return lnpeer.ErrPeerExiting
×
3961
        }
3962
}
3963

3964
// StartTime returns the time at which the connection was established if the
3965
// peer started successfully, and zero otherwise.
3966
func (p *Brontide) StartTime() time.Time {
3✔
3967
        return p.startTime
3✔
3968
}
3✔
3969

3970
// handleCloseMsg is called when a new cooperative channel closure related
3971
// message is received from the remote peer. We'll use this message to advance
3972
// the chan closer state machine.
3973
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
16✔
3974
        link := p.fetchLinkFromKeyAndCid(msg.cid)
16✔
3975

16✔
3976
        // We'll now fetch the matching closing state machine in order to continue,
16✔
3977
        // or finalize the channel closure process.
16✔
3978
        chanCloser, err := p.fetchActiveChanCloser(msg.cid)
16✔
3979
        if err != nil {
19✔
3980
                // If the channel is not known to us, we'll simply ignore this message.
3✔
3981
                if err == ErrChannelNotFound {
6✔
3982
                        return
3✔
3983
                }
3✔
3984

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

×
3987
                errMsg := &lnwire.Error{
×
3988
                        ChanID: msg.cid,
×
3989
                        Data:   lnwire.ErrorData(err.Error()),
×
3990
                }
×
3991
                p.queueMsg(errMsg, nil)
×
3992
                return
×
3993
        }
3994

3995
        handleErr := func(err error) {
16✔
UNCOV
3996
                err = fmt.Errorf("unable to process close msg: %w", err)
×
UNCOV
3997
                p.log.Error(err)
×
UNCOV
3998

×
UNCOV
3999
                // As the negotiations failed, we'll reset the channel state machine to
×
UNCOV
4000
                // ensure we act to on-chain events as normal.
×
UNCOV
4001
                chanCloser.Channel().ResetState()
×
UNCOV
4002

×
UNCOV
4003
                if chanCloser.CloseRequest() != nil {
×
4004
                        chanCloser.CloseRequest().Err <- err
×
4005
                }
×
UNCOV
4006
                delete(p.activeChanCloses, msg.cid)
×
UNCOV
4007

×
UNCOV
4008
                p.Disconnect(err)
×
4009
        }
4010

4011
        // Next, we'll process the next message using the target state machine.
4012
        // We'll either continue negotiation, or halt.
4013
        switch typed := msg.msg.(type) {
16✔
4014
        case *lnwire.Shutdown:
8✔
4015
                // Disable incoming adds immediately.
8✔
4016
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
8✔
4017
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
4018
                                link.ChanID())
×
4019
                }
×
4020

4021
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
8✔
4022
                if err != nil {
8✔
4023
                        handleErr(err)
×
4024
                        return
×
4025
                }
×
4026

4027
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
14✔
4028
                        // If the link is nil it means we can immediately queue
6✔
4029
                        // the Shutdown message since we don't have to wait for
6✔
4030
                        // commitment transaction synchronization.
6✔
4031
                        if link == nil {
7✔
4032
                                p.queueMsg(&msg, nil)
1✔
4033
                                return
1✔
4034
                        }
1✔
4035

4036
                        // Immediately disallow any new HTLC's from being added
4037
                        // in the outgoing direction.
4038
                        if !link.DisableAdds(htlcswitch.Outgoing) {
5✔
4039
                                p.log.Warnf("Outgoing link adds already "+
×
4040
                                        "disabled: %v", link.ChanID())
×
4041
                        }
×
4042

4043
                        // When we have a Shutdown to send, we defer it till the
4044
                        // next time we send a CommitSig to remain spec
4045
                        // compliant.
4046
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
10✔
4047
                                p.queueMsg(&msg, nil)
5✔
4048
                        })
5✔
4049
                })
4050

4051
                beginNegotiation := func() {
16✔
4052
                        oClosingSigned, err := chanCloser.BeginNegotiation()
8✔
4053
                        if err != nil {
8✔
4054
                                handleErr(err)
×
4055
                                return
×
4056
                        }
×
4057

4058
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
16✔
4059
                                p.queueMsg(&msg, nil)
8✔
4060
                        })
8✔
4061
                }
4062

4063
                if link == nil {
9✔
4064
                        beginNegotiation()
1✔
4065
                } else {
8✔
4066
                        // Now we register a flush hook to advance the
7✔
4067
                        // ChanCloser and possibly send out a ClosingSigned
7✔
4068
                        // when the link finishes draining.
7✔
4069
                        link.OnFlushedOnce(func() {
14✔
4070
                                // Remove link in goroutine to prevent deadlock.
7✔
4071
                                go p.cfg.Switch.RemoveLink(msg.cid)
7✔
4072
                                beginNegotiation()
7✔
4073
                        })
7✔
4074
                }
4075

4076
        case *lnwire.ClosingSigned:
11✔
4077
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
11✔
4078
                if err != nil {
11✔
UNCOV
4079
                        handleErr(err)
×
UNCOV
4080
                        return
×
UNCOV
4081
                }
×
4082

4083
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
22✔
4084
                        p.queueMsg(&msg, nil)
11✔
4085
                })
11✔
4086

4087
        default:
×
4088
                panic("impossible closeMsg type")
×
4089
        }
4090

4091
        // If we haven't finished close negotiations, then we'll continue as we
4092
        // can't yet finalize the closure.
4093
        if _, err := chanCloser.ClosingTx(); err != nil {
26✔
4094
                return
11✔
4095
        }
11✔
4096

4097
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
4098
        // the channel closure by notifying relevant sub-systems and launching a
4099
        // goroutine to wait for close tx conf.
4100
        p.finalizeChanClosure(chanCloser)
7✔
4101
}
4102

4103
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
4104
// the channelManager goroutine, which will shut down the link and possibly
4105
// close the channel.
4106
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
3✔
4107
        select {
3✔
4108
        case p.localCloseChanReqs <- req:
3✔
4109
                p.log.Info("Local close channel request is going to be " +
3✔
4110
                        "delivered to the peer")
3✔
4111
        case <-p.quit:
×
4112
                p.log.Info("Unable to deliver local close channel request " +
×
4113
                        "to peer")
×
4114
        }
4115
}
4116

4117
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
4118
func (p *Brontide) NetAddress() *lnwire.NetAddress {
3✔
4119
        return p.cfg.Addr
3✔
4120
}
3✔
4121

4122
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
4123
func (p *Brontide) Inbound() bool {
3✔
4124
        return p.cfg.Inbound
3✔
4125
}
3✔
4126

4127
// ConnReq is a getter for the Brontide's connReq in cfg.
4128
func (p *Brontide) ConnReq() *connmgr.ConnReq {
3✔
4129
        return p.cfg.ConnReq
3✔
4130
}
3✔
4131

4132
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
4133
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
3✔
4134
        return p.cfg.ErrorBuffer
3✔
4135
}
3✔
4136

4137
// SetAddress sets the remote peer's address given an address.
4138
func (p *Brontide) SetAddress(address net.Addr) {
×
4139
        p.cfg.Addr.Address = address
×
4140
}
×
4141

4142
// ActiveSignal returns the peer's active signal.
4143
func (p *Brontide) ActiveSignal() chan struct{} {
3✔
4144
        return p.activeSignal
3✔
4145
}
3✔
4146

4147
// Conn returns a pointer to the peer's connection struct.
4148
func (p *Brontide) Conn() net.Conn {
3✔
4149
        return p.cfg.Conn
3✔
4150
}
3✔
4151

4152
// BytesReceived returns the number of bytes received from the peer.
4153
func (p *Brontide) BytesReceived() uint64 {
3✔
4154
        return atomic.LoadUint64(&p.bytesReceived)
3✔
4155
}
3✔
4156

4157
// BytesSent returns the number of bytes sent to the peer.
4158
func (p *Brontide) BytesSent() uint64 {
3✔
4159
        return atomic.LoadUint64(&p.bytesSent)
3✔
4160
}
3✔
4161

4162
// LastRemotePingPayload returns the last payload the remote party sent as part
4163
// of their ping.
4164
func (p *Brontide) LastRemotePingPayload() []byte {
3✔
4165
        pingPayload := p.lastPingPayload.Load()
3✔
4166
        if pingPayload == nil {
6✔
4167
                return []byte{}
3✔
4168
        }
3✔
4169

4170
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
1✔
4171
        if !ok {
1✔
4172
                return nil
×
4173
        }
×
4174

4175
        return pingBytes
1✔
4176
}
4177

4178
// attachChannelEventSubscription creates a channel event subscription and
4179
// attaches to client to Brontide if the reenableTimeout is no greater than 1
4180
// minute.
4181
func (p *Brontide) attachChannelEventSubscription() error {
6✔
4182
        // If the timeout is greater than 1 minute, it's unlikely that the link
6✔
4183
        // hasn't yet finished its reestablishment. Return a nil without
6✔
4184
        // creating the client to specify that we don't want to retry.
6✔
4185
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
9✔
4186
                return nil
3✔
4187
        }
3✔
4188

4189
        // When the reenable timeout is less than 1 minute, it's likely the
4190
        // channel link hasn't finished its reestablishment yet. In that case,
4191
        // we'll give it a second chance by subscribing to the channel update
4192
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
4193
        // enabling the channel again.
4194
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
6✔
4195
        if err != nil {
6✔
4196
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
4197
        }
×
4198

4199
        p.channelEventClient = sub
6✔
4200

6✔
4201
        return nil
6✔
4202
}
4203

4204
// updateNextRevocation updates the existing channel's next revocation if it's
4205
// nil.
4206
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
6✔
4207
        chanPoint := c.FundingOutpoint
6✔
4208
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
6✔
4209

6✔
4210
        // Read the current channel.
6✔
4211
        currentChan, loaded := p.activeChannels.Load(chanID)
6✔
4212

6✔
4213
        // currentChan should exist, but we perform a check anyway to avoid nil
6✔
4214
        // pointer dereference.
6✔
4215
        if !loaded {
7✔
4216
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
4217
                        chanID)
1✔
4218
        }
1✔
4219

4220
        // currentChan should not be nil, but we perform a check anyway to
4221
        // avoid nil pointer dereference.
4222
        if currentChan == nil {
6✔
4223
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
4224
                        chanID)
1✔
4225
        }
1✔
4226

4227
        // If we're being sent a new channel, and our existing channel doesn't
4228
        // have the next revocation, then we need to update the current
4229
        // existing channel.
4230
        if currentChan.RemoteNextRevocation() != nil {
4✔
4231
                return nil
×
4232
        }
×
4233

4234
        p.log.Infof("Processing retransmitted ChannelReady for "+
4✔
4235
                "ChannelPoint(%v)", chanPoint)
4✔
4236

4✔
4237
        nextRevoke := c.RemoteNextRevocation
4✔
4238

4✔
4239
        err := currentChan.InitNextRevocation(nextRevoke)
4✔
4240
        if err != nil {
4✔
4241
                return fmt.Errorf("unable to init next revocation: %w", err)
×
4242
        }
×
4243

4244
        return nil
4✔
4245
}
4246

4247
// addActiveChannel adds a new active channel to the `activeChannels` map. It
4248
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
4249
// it and assembles it with a channel link.
4250
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
3✔
4251
        chanPoint := c.FundingOutpoint
3✔
4252
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4253

3✔
4254
        // If we've reached this point, there are two possible scenarios.  If
3✔
4255
        // the channel was in the active channels map as nil, then it was
3✔
4256
        // loaded from disk and we need to send reestablish. Else, it was not
3✔
4257
        // loaded from disk and we don't need to send reestablish as this is a
3✔
4258
        // fresh channel.
3✔
4259
        shouldReestablish := p.isLoadedFromDisk(chanID)
3✔
4260

3✔
4261
        chanOpts := c.ChanOpts
3✔
4262
        if shouldReestablish {
6✔
4263
                // If we have to do the reestablish dance for this channel,
3✔
4264
                // ensure that we don't try to call InitRemoteMusigNonces twice
3✔
4265
                // by calling SkipNonceInit.
3✔
4266
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
3✔
4267
        }
3✔
4268

4269
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
3✔
4270
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
4271
        })
×
4272
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
3✔
4273
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
4274
        })
×
4275
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
3✔
4276
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
4277
        })
×
4278

4279
        // If not already active, we'll add this channel to the set of active
4280
        // channels, so we can look it up later easily according to its channel
4281
        // ID.
4282
        lnChan, err := lnwallet.NewLightningChannel(
3✔
4283
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
3✔
4284
        )
3✔
4285
        if err != nil {
3✔
4286
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
4287
        }
×
4288

4289
        // Store the channel in the activeChannels map.
4290
        p.activeChannels.Store(chanID, lnChan)
3✔
4291

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

3✔
4294
        // Next, we'll assemble a ChannelLink along with the necessary items it
3✔
4295
        // needs to function.
3✔
4296
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
3✔
4297
        if err != nil {
3✔
4298
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
4299
                        err)
×
4300
        }
×
4301

4302
        // We'll query the channel DB for the new channel's initial forwarding
4303
        // policies to determine the policy we start out with.
4304
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
3✔
4305
        if err != nil {
3✔
4306
                return fmt.Errorf("unable to query for initial forwarding "+
×
4307
                        "policy: %v", err)
×
4308
        }
×
4309

4310
        // Create the link and add it to the switch.
4311
        err = p.addLink(
3✔
4312
                &chanPoint, lnChan, initialPolicy, chainEvents,
3✔
4313
                shouldReestablish, fn.None[lnwire.Shutdown](),
3✔
4314
        )
3✔
4315
        if err != nil {
3✔
4316
                return fmt.Errorf("can't register new channel link(%v) with "+
×
4317
                        "peer", chanPoint)
×
4318
        }
×
4319

4320
        return nil
3✔
4321
}
4322

4323
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
4324
// know this channel ID or not, we'll either add it to the `activeChannels` map
4325
// or init the next revocation for it.
4326
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
3✔
4327
        newChan := req.channel
3✔
4328
        chanPoint := newChan.FundingOutpoint
3✔
4329
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4330

3✔
4331
        // Only update RemoteNextRevocation if the channel is in the
3✔
4332
        // activeChannels map and if we added the link to the switch. Only
3✔
4333
        // active channels will be added to the switch.
3✔
4334
        if p.isActiveChannel(chanID) {
6✔
4335
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
3✔
4336
                        chanPoint)
3✔
4337

3✔
4338
                // Handle it and close the err chan on the request.
3✔
4339
                close(req.err)
3✔
4340

3✔
4341
                // Update the next revocation point.
3✔
4342
                err := p.updateNextRevocation(newChan.OpenChannel)
3✔
4343
                if err != nil {
3✔
4344
                        p.log.Errorf(err.Error())
×
4345
                }
×
4346

4347
                return
3✔
4348
        }
4349

4350
        // This is a new channel, we now add it to the map.
4351
        if err := p.addActiveChannel(req.channel); err != nil {
3✔
4352
                // Log and send back the error to the request.
×
4353
                p.log.Errorf(err.Error())
×
4354
                req.err <- err
×
4355

×
4356
                return
×
4357
        }
×
4358

4359
        // Close the err chan if everything went fine.
4360
        close(req.err)
3✔
4361
}
4362

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

7✔
4370
        chanID := req.channelID
7✔
4371

7✔
4372
        // If we already have this channel, something is wrong with the funding
7✔
4373
        // flow as it will only be marked as active after `ChannelReady` is
7✔
4374
        // handled. In this case, we will do nothing but log an error, just in
7✔
4375
        // case this is a legit channel.
7✔
4376
        if p.isActiveChannel(chanID) {
8✔
4377
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
4378
                        "pending channel request", chanID)
1✔
4379

1✔
4380
                return
1✔
4381
        }
1✔
4382

4383
        // The channel has already been added, we will do nothing and return.
4384
        if p.isPendingChannel(chanID) {
7✔
4385
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
4386
                        "pending channel request", chanID)
1✔
4387

1✔
4388
                return
1✔
4389
        }
1✔
4390

4391
        // This is a new channel, we now add it to the map `activeChannels`
4392
        // with nil value and mark it as a newly added channel in
4393
        // `addedChannels`.
4394
        p.activeChannels.Store(chanID, nil)
5✔
4395
        p.addedChannels.Store(chanID, struct{}{})
5✔
4396
}
4397

4398
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
4399
// from `activeChannels` map. The request will be ignored if the channel is
4400
// considered active by Brontide. Noop if the channel ID cannot be found.
4401
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
7✔
4402
        defer close(req.err)
7✔
4403

7✔
4404
        chanID := req.channelID
7✔
4405

7✔
4406
        // If we already have this channel, something is wrong with the funding
7✔
4407
        // flow as it will only be marked as active after `ChannelReady` is
7✔
4408
        // handled. In this case, we will log an error and exit.
7✔
4409
        if p.isActiveChannel(chanID) {
8✔
4410
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
4411
                        chanID)
1✔
4412
                return
1✔
4413
        }
1✔
4414

4415
        // The channel has not been added yet, we will log a warning as there
4416
        // is an unexpected call from funding manager.
4417
        if !p.isPendingChannel(chanID) {
10✔
4418
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
4✔
4419
        }
4✔
4420

4421
        // Remove the record of this pending channel.
4422
        p.activeChannels.Delete(chanID)
6✔
4423
        p.addedChannels.Delete(chanID)
6✔
4424
}
4425

4426
// sendLinkUpdateMsg sends a message that updates the channel to the
4427
// channel's message stream.
4428
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
3✔
4429
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
3✔
4430

3✔
4431
        chanStream, ok := p.activeMsgStreams[cid]
3✔
4432
        if !ok {
6✔
4433
                // If a stream hasn't yet been created, then we'll do so, add
3✔
4434
                // it to the map, and finally start it.
3✔
4435
                chanStream = newChanMsgStream(p, cid)
3✔
4436
                p.activeMsgStreams[cid] = chanStream
3✔
4437
                chanStream.Start()
3✔
4438

3✔
4439
                // Stop the stream when quit.
3✔
4440
                go func() {
6✔
4441
                        <-p.quit
3✔
4442
                        chanStream.Stop()
3✔
4443
                }()
3✔
4444
        }
4445

4446
        // With the stream obtained, add the message to the stream so we can
4447
        // continue processing message.
4448
        chanStream.AddMsg(msg)
3✔
4449
}
4450

4451
// scaleTimeout multiplies the argument duration by a constant factor depending
4452
// on variious heuristics. Currently this is only used to check whether our peer
4453
// appears to be connected over Tor and relaxes the timout deadline. However,
4454
// this is subject to change and should be treated as opaque.
4455
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
70✔
4456
        if p.isTorConnection {
73✔
4457
                return timeout * time.Duration(torTimeoutMultiplier)
3✔
4458
        }
3✔
4459

4460
        return timeout
67✔
4461
}
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