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

lightningnetwork / lnd / 12056196575

27 Nov 2024 06:23PM UTC coverage: 58.717% (-0.2%) from 58.921%
12056196575

Pull #9242

github

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

8 of 39 new or added lines in 3 files covered. (20.51%)

543 existing lines in 30 files now uncovered.

132924 of 226381 relevant lines covered (58.72%)

19504.16 hits per line

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

78.21
/peer/brontide.go
1
package peer
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

120
        err chan error
121
}
122

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

470
        pingManager *PingManager
471

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

479
        cfg Config
480

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

664
                return lastSerializedBlockHeader[:]
2✔
665
        }
666

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

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

696
        return p
27✔
697
}
698

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

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

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

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

725
        if len(activeChans) == 0 {
8✔
726
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
3✔
727
        }
3✔
728

729
        // Quickly check if we have any existing legacy channels with this
730
        // peer.
731
        haveLegacyChan := false
5✔
732
        for _, c := range activeChans {
9✔
733
                if c.ChanType.IsTweakless() {
8✔
734
                        continue
4✔
735
                }
736

737
                haveLegacyChan = true
2✔
738
                break
2✔
739
        }
740

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

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

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

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

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

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

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

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

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

819
        p.startTime = time.Now()
5✔
820

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

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

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

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

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

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

5✔
867
        return nil
5✔
868
}
869

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

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

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

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

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

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

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

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

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

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

5✔
953
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
5✔
954

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

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

983
                                chanID := lnwire.NewChanIDFromOutPoint(
2✔
984
                                        dbChan.FundingOutpoint,
2✔
985
                                )
2✔
986

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

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

2✔
999
                                msgs = append(msgs, channelReadyMsg)
2✔
1000
                        }
1001

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

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

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

1036
                chanPoint := dbChan.FundingOutpoint
4✔
1037

4✔
1038
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
1039

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

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

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

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

1065
                        msgs = append(msgs, chanSync)
4✔
1066

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

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

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

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

1091
                        continue
4✔
1092
                }
1093

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

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

2✔
1116
                        selfPolicy = p1
2✔
1117
                } else {
4✔
1118
                        selfPolicy = p2
2✔
1119
                }
2✔
1120

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

1134
                        inboundFee := models.NewInboundFeeFromWire(
2✔
1135
                                inboundWireFee,
2✔
1136
                        )
2✔
1137

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

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

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

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

2✔
1166
                        continue
2✔
1167
                }
1168

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

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

×
1187
                                return
×
1188
                        }
×
1189

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

×
1205
                                return
×
1206
                        }
×
1207

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

2✔
1212
                        p.activeChanCloses[chanID] = chanCloser
2✔
1213

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

×
1220
                                return
×
1221
                        }
×
1222

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

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

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

1246
                p.activeChannels.Store(chanID, lnChan)
2✔
1247
        }
1248

1249
        return msgs, nil
5✔
1250
}
1251

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

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

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

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

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

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

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

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

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

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

5✔
1352
        hasConfirmedPublicChan := false
5✔
1353
        for _, channel := range channels {
9✔
1354
                if channel.IsPending {
6✔
1355
                        continue
2✔
1356
                }
1357
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
8✔
1358
                        continue
4✔
1359
                }
1360

1361
                hasConfirmedPublicChan = true
2✔
1362
                break
2✔
1363
        }
1364
        if !hasConfirmedPublicChan {
10✔
1365
                return
5✔
1366
        }
5✔
1367

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

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

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

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

1389
        maybeSendUpd := func(cid lnwire.ChannelID,
4✔
1390
                lnChan *lnwallet.LightningChannel) error {
8✔
1391

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

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

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

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

2✔
1421
                        return nil
2✔
1422
                }
2✔
1423

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

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

×
1436
                        return err
×
1437
                }
×
1438

1439
                return nil
4✔
1440
        }
1441

1442
        p.activeChannels.ForEach(maybeSendUpd)
4✔
1443
}
1444

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

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

1467
        p.wg.Wait()
2✔
1468
}
1469

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

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

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

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

3✔
1497
        p.log.Infof(err.Error())
3✔
1498

3✔
1499
        // Stop PingManager before closing TCP connection.
3✔
1500
        p.pingManager.Stop()
3✔
1501

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

3✔
1505
        close(p.quit)
3✔
1506

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

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

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

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

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

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

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

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

1584
        p.logWireMessage(nextMsg, true)
6✔
1585

6✔
1586
        return nextMsg, nil
6✔
1587
}
1588

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

1597
        peer *Brontide
1598

1599
        apply func(lnwire.Message)
1600

1601
        startMsg string
1602
        stopMsg  string
1603

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

1607
        mtx sync.Mutex
1608

1609
        producerSema chan struct{}
1610

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

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

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

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

1641
        return stream
5✔
1642
}
1643

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

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

2✔
1654
        close(ms.quit)
2✔
1655

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

1663
        ms.wg.Wait()
2✔
1664
}
1665

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

5✔
1673
        peerLog.Tracef(ms.startMsg)
5✔
1674

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

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

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

2✔
1703
                ms.msgCond.L.Unlock()
2✔
1704

2✔
1705
                ms.apply(msg)
2✔
1706

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

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

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

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

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

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

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

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

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

1795
                        chanPoint := event.ChannelPoint
2✔
1796

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

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

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

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

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

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

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

1847
                chanLink.HandleChannelUpdate(msg)
2✔
1848
        }
1849

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

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

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

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

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

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

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

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

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

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

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

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

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

1971
                var (
3✔
1972
                        targetChan   lnwire.ChannelID
3✔
1973
                        isLinkUpdate bool
3✔
1974
                )
3✔
1975

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

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

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

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

2✔
1998
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
2✔
1999

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

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

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

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

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

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

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

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

2✔
2067
                        discStream.AddMsg(msg)
2✔
2068

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

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

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

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

2092
                idleTimer.Reset(idleTimeout)
3✔
2093
        }
2094

2095
        p.Disconnect(errors.New("read handler closed"))
2✔
2096

2✔
2097
        p.log.Trace("readHandler for peer done")
2✔
2098
}
2099

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

2108
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
3✔
2109
}
2110

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

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

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

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

10✔
2142
        return channel != nil
10✔
2143
}
10✔
2144

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

2154
        return channel == nil
3✔
2155
}
2156

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

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

3✔
2171
        p.activeChannels.Range(func(_ lnwire.ChannelID,
3✔
2172
                channel *lnwallet.LightningChannel) bool {
6✔
2173

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

2180
                haveChannels = true
3✔
2181

3✔
2182
                // Return false to break the iteration.
3✔
2183
                return false
3✔
2184
        })
2185

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

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

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

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

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

2219
                return false
×
2220

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

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

2231
        default:
2✔
2232
                return false
2✔
2233
        }
2234
}
2235

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

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

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

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

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

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

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

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

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

2✔
2282
                                blindingPoint = b.Val.SerializeCompressed()
2✔
2283
                        },
2✔
2284
                )
2285

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2422
        prefix := "readMessage from peer"
19✔
2423
        if !read {
34✔
2424
                prefix = "writeMessage to peer"
15✔
2425
        }
15✔
2426

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

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

2447
        noiseConn := p.cfg.Conn
15✔
2448

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

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

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

2470
                return err
15✔
2471
        }
2472

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

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

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

2500
        return flushMsg()
15✔
2501
}
2502

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

2518
        var exitErr error
5✔
2519

5✔
2520
out:
5✔
2521
        for {
14✔
2522
                select {
9✔
2523
                case outMsg := <-p.sendQueue:
6✔
2524
                        // Record the time at which we first attempt to send the
6✔
2525
                        // message.
6✔
2526
                        startTime := time.Now()
6✔
2527

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

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

×
2549
                                goto retry
×
2550
                        }
2551

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

6✔
2562
                        // If the peer requested a synchronous write, respond
6✔
2563
                        // with the error.
6✔
2564
                        if outMsg.errChan != nil {
9✔
2565
                                outMsg.errChan <- err
3✔
2566
                        }
3✔
2567

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

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

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

2✔
2584
        p.Disconnect(exitErr)
2✔
2585

2✔
2586
        p.log.Trace("writeHandler for peer done")
2✔
2587
}
2588

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

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

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

5✔
2606
        for {
18✔
2607
                // Examine the front of the priority queue, if it is empty check
13✔
2608
                // the low priority queue.
13✔
2609
                elem := priorityMsgs.Front()
13✔
2610
                if elem == nil {
23✔
2611
                        elem = lazyMsgs.Front()
10✔
2612
                }
10✔
2613

2614
                if elem != nil {
19✔
2615
                        front := elem.Value.(outgoingMsg)
6✔
2616

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

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

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

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

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

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

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

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

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

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

2714
                snapshot := activeChan.StateSnapshot()
2✔
2715
                snapshots = append(snapshots, snapshot)
2✔
2716

2✔
2717
                return nil
2✔
2718
        })
2719

2720
        return snapshots
2✔
2721
}
2722

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

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

8✔
2742
        return txscript.PayToAddrScript(deliveryAddr)
8✔
2743
}
2744

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

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

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

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

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

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

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

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

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

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

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

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

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

2839
                                lc.ResetState()
3✔
2840

3✔
2841
                                return nil
3✔
2842
                        })
2843

2844
                        break out
3✔
2845
                }
2846
        }
2847
}
2848

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

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

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

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

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

2✔
2878
                        continue
2✔
2879

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

×
2897
                                continue
×
2898
                        }
2899

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

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

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

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

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

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

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

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

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

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

2981
        p.activeChanCloses[chanID] = chanCloser
5✔
2982

5✔
2983
        return chanCloser, nil
5✔
2984
}
2985

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

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

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

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

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

3015
                activePublicChans = append(
2✔
3016
                        activePublicChans, dbChan.FundingOutpoint,
2✔
3017
                )
2✔
3018

2✔
3019
                return true
2✔
3020
        })
3021

3022
        return activePublicChans
2✔
3023
}
3024

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

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

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

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

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

3060
                return nil
×
3061
        }
3062

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

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

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

3088
                                continue
×
3089
                        }
3090

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

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

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

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

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

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

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

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

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

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

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

3171
        var deliveryScript []byte
×
3172

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

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

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

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

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

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

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

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

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

3242
        return shutdownMsg, nil
×
3243
}
3244

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

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

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

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

3290
        return chanCloser, nil
11✔
3291
}
3292

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

9✔
3298
        channel, ok := p.activeChannels.Load(chanID)
9✔
3299

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

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

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

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

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

3360
                p.activeChanCloses[chanID] = chanCloser
8✔
3361

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

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

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

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

3395
                link.OnCommitOnce(htlcswitch.Outgoing, func() {
16✔
3396
                        p.queueMsg(shutdownMsg, nil)
8✔
3397
                })
8✔
3398

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

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

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

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

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

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

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

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

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

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

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

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

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

21✔
3512
        var chanLink htlcswitch.ChannelUpdateHandler
21✔
3513

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

3524
        return chanLink
21✔
3525
}
3526

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

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

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

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

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

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

3564
        closingTxid := closingTx.TxHash()
6✔
3565

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

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

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

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

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

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

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

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

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

6✔
3640
        p.activeChannels.Delete(chanID)
6✔
3641

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

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

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

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

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

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

3685
        return nil
5✔
3686
}
3687

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

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

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

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

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

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

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

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

9✔
3745
        return p.writeMessage(msg)
9✔
3746
}
3747

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

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

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

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

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

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

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

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

2✔
3789
        return nil
2✔
3790
}
3791

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

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

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

3833
                if priority {
11✔
3834
                        p.queueMsg(msg, errChan)
5✔
3835
                } else {
8✔
3836
                        p.queueMsgLazy(msg, errChan)
3✔
3837
                }
3✔
3838
        }
3839

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

3853
        return nil
5✔
3854
}
3855

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

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

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

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

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

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

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

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

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

2✔
3921
        select {
2✔
3922
        case p.newPendingChannel <- newChanMsg:
2✔
3923

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4061
                beginNegotiation := func() {
14✔
4062
                        oClosingSigned, err := chanCloser.BeginNegotiation()
7✔
4063
                        if err != nil {
8✔
4064
                                handleErr(err)
1✔
4065
                                return
1✔
4066
                        }
1✔
4067

4068
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
12✔
4069
                                p.queueMsg(&msg, nil)
6✔
4070
                        })
6✔
4071
                }
4072

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

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

4093
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
20✔
4094
                        p.queueMsg(&msg, nil)
10✔
4095
                })
10✔
4096

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4185
        return pingBytes
2✔
4186
}
4187

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

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

4209
        p.channelEventClient = sub
5✔
4210

5✔
4211
        return nil
5✔
4212
}
4213

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

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

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

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

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

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

3✔
4247
        nextRevoke := c.RemoteNextRevocation
3✔
4248

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

4254
        return nil
3✔
4255
}
4256

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

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

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

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

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

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

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

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

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

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

4330
        return nil
2✔
4331
}
4332

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

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

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

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

4357
                return
2✔
4358
        }
4359

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

×
4366
                return
×
4367
        }
×
4368

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

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

6✔
4380
        chanID := req.channelID
6✔
4381

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

1✔
4390
                return
1✔
4391
        }
1✔
4392

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

1✔
4398
                return
1✔
4399
        }
1✔
4400

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

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

6✔
4414
        chanID := req.channelID
6✔
4415

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

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

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

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

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

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

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

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

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