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

lightningnetwork / lnd / 11388202384

17 Oct 2024 03:31PM UTC coverage: 58.81% (-0.07%) from 58.884%
11388202384

push

github

web-flow
Merge pull request #9196 from lightningnetwork/fn-context-guard

fn: add ContextGuard from tapd repo

131011 of 222771 relevant lines covered (58.81%)

28214.75 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

121
        err chan error
122
}
123

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

414
        // MaxFeeExposure limits the number of outstanding fees in a channel.
415
        // This value will be passed to created links.
416
        MaxFeeExposure lnwire.MilliSatoshi
417

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

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

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

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

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

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

463
        pingManager *PingManager
464

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

472
        cfg Config
473

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

657
                return lastSerializedBlockHeader[:]
2✔
658
        }
659

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

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

689
        return p
28✔
690
}
691

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

6✔
860
        return nil
6✔
861
}
862

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1029
                chanPoint := dbChan.FundingOutpoint
5✔
1030

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

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

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

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

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

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

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

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

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

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

1084
                        continue
5✔
1085
                }
1086

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

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

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

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

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

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

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

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

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

3✔
1159
                        continue
3✔
1160
                }
1161

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

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

×
1180
                                return
×
1181
                        }
×
1182

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

×
1198
                                return
×
1199
                        }
×
1200

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

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

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

×
1213
                                return
×
1214
                        }
×
1215

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

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

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

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

1242
        return msgs, nil
6✔
1243
}
1244

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1426
                        return err
×
1427
                }
×
1428

1429
                return nil
5✔
1430
        }
1431

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

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

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

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

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

1468
        // Make sure initialization has completed before we try to tear things
1469
        // down.
1470
        select {
4✔
1471
        case <-p.startReady:
3✔
1472
        case <-p.quit:
×
1473
                return
×
1474
        }
1475

1476
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
3✔
1477
        p.storeError(err)
3✔
1478

3✔
1479
        p.log.Infof(err.Error())
3✔
1480

3✔
1481
        // Stop PingManager before closing TCP connection.
3✔
1482
        p.pingManager.Stop()
3✔
1483

3✔
1484
        // Ensure that the TCP connection is properly closed before continuing.
3✔
1485
        p.cfg.Conn.Close()
3✔
1486

3✔
1487
        close(p.quit)
3✔
1488

3✔
1489
        // If our msg router isn't global (local to this instance), then we'll
3✔
1490
        // stop it. Otherwise, we'll leave it running.
3✔
1491
        if !p.globalMsgRouter {
6✔
1492
                p.msgRouter.WhenSome(func(router msgmux.Router) {
6✔
1493
                        router.Stop()
3✔
1494
                })
3✔
1495
        }
1496
}
1497

1498
// String returns the string representation of this peer.
1499
func (p *Brontide) String() string {
3✔
1500
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
3✔
1501
}
3✔
1502

1503
// readNextMessage reads, and returns the next message on the wire along with
1504
// any additional raw payload.
1505
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
10✔
1506
        noiseConn := p.cfg.Conn
10✔
1507
        err := noiseConn.SetReadDeadline(time.Time{})
10✔
1508
        if err != nil {
10✔
1509
                return nil, err
×
1510
        }
×
1511

1512
        pktLen, err := noiseConn.ReadNextHeader()
10✔
1513
        if err != nil {
13✔
1514
                return nil, fmt.Errorf("read next header: %w", err)
3✔
1515
        }
3✔
1516

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

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

7✔
1549
                // Next, create a new io.Reader implementation from the raw
7✔
1550
                // message, and use this to decode the message directly from.
7✔
1551
                msgReader := bytes.NewReader(rawMsg)
7✔
1552
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
7✔
1553
                if err != nil {
10✔
1554
                        return err
3✔
1555
                }
3✔
1556

1557
                // At this point, rawMsg and buf will be returned back to the
1558
                // buffer pool for re-use.
1559
                return nil
7✔
1560
        })
1561
        atomic.AddUint64(&p.bytesReceived, msgLen)
7✔
1562
        if err != nil {
10✔
1563
                return nil, err
3✔
1564
        }
3✔
1565

1566
        p.logWireMessage(nextMsg, true)
7✔
1567

7✔
1568
        return nextMsg, nil
7✔
1569
}
1570

1571
// msgStream implements a goroutine-safe, in-order stream of messages to be
1572
// delivered via closure to a receiver. These messages MUST be in order due to
1573
// the nature of the lightning channel commitment and gossiper state machines.
1574
// TODO(conner): use stream handler interface to abstract out stream
1575
// state/logging.
1576
type msgStream struct {
1577
        streamShutdown int32 // To be used atomically.
1578

1579
        peer *Brontide
1580

1581
        apply func(lnwire.Message)
1582

1583
        startMsg string
1584
        stopMsg  string
1585

1586
        msgCond *sync.Cond
1587
        msgs    []lnwire.Message
1588

1589
        mtx sync.Mutex
1590

1591
        producerSema chan struct{}
1592

1593
        wg   sync.WaitGroup
1594
        quit chan struct{}
1595
}
1596

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

6✔
1605
        stream := &msgStream{
6✔
1606
                peer:         p,
6✔
1607
                apply:        apply,
6✔
1608
                startMsg:     startMsg,
6✔
1609
                stopMsg:      stopMsg,
6✔
1610
                producerSema: make(chan struct{}, bufSize),
6✔
1611
                quit:         make(chan struct{}),
6✔
1612
        }
6✔
1613
        stream.msgCond = sync.NewCond(&stream.mtx)
6✔
1614

6✔
1615
        // Before we return the active stream, we'll populate the producer's
6✔
1616
        // semaphore channel. We'll use this to ensure that the producer won't
6✔
1617
        // attempt to allocate memory in the queue for an item until it has
6✔
1618
        // sufficient extra space.
6✔
1619
        for i := uint32(0); i < bufSize; i++ {
3,009✔
1620
                stream.producerSema <- struct{}{}
3,003✔
1621
        }
3,003✔
1622

1623
        return stream
6✔
1624
}
1625

1626
// Start starts the chanMsgStream.
1627
func (ms *msgStream) Start() {
6✔
1628
        ms.wg.Add(1)
6✔
1629
        go ms.msgConsumer()
6✔
1630
}
6✔
1631

1632
// Stop stops the chanMsgStream.
1633
func (ms *msgStream) Stop() {
3✔
1634
        // TODO(roasbeef): signal too?
3✔
1635

3✔
1636
        close(ms.quit)
3✔
1637

3✔
1638
        // Now that we've closed the channel, we'll repeatedly signal the msg
3✔
1639
        // consumer until we've detected that it has exited.
3✔
1640
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
6✔
1641
                ms.msgCond.Signal()
3✔
1642
                time.Sleep(time.Millisecond * 100)
3✔
1643
        }
3✔
1644

1645
        ms.wg.Wait()
3✔
1646
}
1647

1648
// msgConsumer is the main goroutine that streams messages from the peer's
1649
// readHandler directly to the target channel.
1650
func (ms *msgStream) msgConsumer() {
6✔
1651
        defer ms.wg.Done()
6✔
1652
        defer peerLog.Tracef(ms.stopMsg)
6✔
1653
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
6✔
1654

6✔
1655
        peerLog.Tracef(ms.startMsg)
6✔
1656

6✔
1657
        for {
12✔
1658
                // First, we'll check our condition. If the queue of messages
6✔
1659
                // is empty, then we'll wait until a new item is added.
6✔
1660
                ms.msgCond.L.Lock()
6✔
1661
                for len(ms.msgs) == 0 {
12✔
1662
                        ms.msgCond.Wait()
6✔
1663

6✔
1664
                        // If we woke up in order to exit, then we'll do so.
6✔
1665
                        // Otherwise, we'll check the message queue for any new
6✔
1666
                        // items.
6✔
1667
                        select {
6✔
1668
                        case <-ms.peer.quit:
3✔
1669
                                ms.msgCond.L.Unlock()
3✔
1670
                                return
3✔
1671
                        case <-ms.quit:
3✔
1672
                                ms.msgCond.L.Unlock()
3✔
1673
                                return
3✔
1674
                        default:
3✔
1675
                        }
1676
                }
1677

1678
                // Grab the message off the front of the queue, shifting the
1679
                // slice's reference down one in order to remove the message
1680
                // from the queue.
1681
                msg := ms.msgs[0]
3✔
1682
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
3✔
1683
                ms.msgs = ms.msgs[1:]
3✔
1684

3✔
1685
                ms.msgCond.L.Unlock()
3✔
1686

3✔
1687
                ms.apply(msg)
3✔
1688

3✔
1689
                // We've just successfully processed an item, so we'll signal
3✔
1690
                // to the producer that a new slot in the buffer. We'll use
3✔
1691
                // this to bound the size of the buffer to avoid allowing it to
3✔
1692
                // grow indefinitely.
3✔
1693
                select {
3✔
1694
                case ms.producerSema <- struct{}{}:
3✔
1695
                case <-ms.peer.quit:
3✔
1696
                        return
3✔
1697
                case <-ms.quit:
3✔
1698
                        return
3✔
1699
                }
1700
        }
1701
}
1702

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

1719
        // Next, we'll lock the condition, and add the message to the end of
1720
        // the message queue.
1721
        ms.msgCond.L.Lock()
3✔
1722
        ms.msgs = append(ms.msgs, msg)
3✔
1723
        ms.msgCond.L.Unlock()
3✔
1724

3✔
1725
        // With the message added, we signal to the msgConsumer that there are
3✔
1726
        // additional messages to consume.
3✔
1727
        ms.msgCond.Signal()
3✔
1728
}
1729

1730
// waitUntilLinkActive waits until the target link is active and returns a
1731
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1732
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1733
func waitUntilLinkActive(p *Brontide,
1734
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
3✔
1735

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

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

3✔
1756
        // The link may already be active by this point, and we may have missed the
3✔
1757
        // ActiveLinkEvent. Check if the link exists.
3✔
1758
        link := p.fetchLinkFromKeyAndCid(cid)
3✔
1759
        if link != nil {
6✔
1760
                return link
3✔
1761
        }
3✔
1762

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

1777
                        chanPoint := event.ChannelPoint
3✔
1778

3✔
1779
                        // Check whether the retrieved chanPoint matches the target
3✔
1780
                        // channel id.
3✔
1781
                        if !cid.IsChanPoint(chanPoint) {
3✔
1782
                                continue
×
1783
                        }
1784

1785
                        // The link shouldn't be nil as we received an
1786
                        // ActiveLinkEvent. If it is nil, we return nil and the
1787
                        // calling function should catch it.
1788
                        return p.fetchLinkFromKeyAndCid(cid)
3✔
1789

1790
                case <-p.quit:
3✔
1791
                        return nil
3✔
1792
                }
1793
        }
1794
}
1795

1796
// newChanMsgStream is used to create a msgStream between the peer and
1797
// particular channel link in the htlcswitch. We utilize additional
1798
// synchronization with the fundingManager to ensure we don't attempt to
1799
// dispatch a message to a channel before it is fully active. A reference to the
1800
// channel this stream forwards to is held in scope to prevent unnecessary
1801
// lookups.
1802
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
3✔
1803
        var chanLink htlcswitch.ChannelUpdateHandler
3✔
1804

3✔
1805
        apply := func(msg lnwire.Message) {
6✔
1806
                // This check is fine because if the link no longer exists, it will
3✔
1807
                // be removed from the activeChannels map and subsequent messages
3✔
1808
                // shouldn't reach the chan msg stream.
3✔
1809
                if chanLink == nil {
6✔
1810
                        chanLink = waitUntilLinkActive(p, cid)
3✔
1811

3✔
1812
                        // If the link is still not active and the calling function
3✔
1813
                        // errored out, just return.
3✔
1814
                        if chanLink == nil {
6✔
1815
                                p.log.Warnf("Link=%v is not active")
3✔
1816
                                return
3✔
1817
                        }
3✔
1818
                }
1819

1820
                // In order to avoid unnecessarily delivering message
1821
                // as the peer is exiting, we'll check quickly to see
1822
                // if we need to exit.
1823
                select {
3✔
1824
                case <-p.quit:
×
1825
                        return
×
1826
                default:
3✔
1827
                }
1828

1829
                chanLink.HandleChannelUpdate(msg)
3✔
1830
        }
1831

1832
        return newMsgStream(p,
3✔
1833
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
3✔
1834
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
3✔
1835
                1000,
3✔
1836
                apply,
3✔
1837
        )
3✔
1838
}
1839

1840
// newDiscMsgStream is used to setup a msgStream between the peer and the
1841
// authenticated gossiper. This stream should be used to forward all remote
1842
// channel announcements.
1843
func newDiscMsgStream(p *Brontide) *msgStream {
6✔
1844
        apply := func(msg lnwire.Message) {
9✔
1845
                // TODO(yy): `ProcessRemoteAnnouncement` returns an error chan
3✔
1846
                // and we need to process it.
3✔
1847
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(msg, p)
3✔
1848
        }
3✔
1849

1850
        return newMsgStream(
6✔
1851
                p,
6✔
1852
                "Update stream for gossiper created",
6✔
1853
                "Update stream for gossiper exited",
6✔
1854
                1000,
6✔
1855
                apply,
6✔
1856
        )
6✔
1857
}
1858

1859
// readHandler is responsible for reading messages off the wire in series, then
1860
// properly dispatching the handling of the message to the proper subsystem.
1861
//
1862
// NOTE: This method MUST be run as a goroutine.
1863
func (p *Brontide) readHandler() {
6✔
1864
        defer p.wg.Done()
6✔
1865

6✔
1866
        // We'll stop the timer after a new messages is received, and also
6✔
1867
        // reset it after we process the next message.
6✔
1868
        idleTimer := time.AfterFunc(idleTimeout, func() {
6✔
1869
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
1870
                        p, idleTimeout)
×
1871
                p.Disconnect(err)
×
1872
        })
×
1873

1874
        // Initialize our negotiated gossip sync method before reading messages
1875
        // off the wire. When using gossip queries, this ensures a gossip
1876
        // syncer is active by the time query messages arrive.
1877
        //
1878
        // TODO(conner): have peer store gossip syncer directly and bypass
1879
        // gossiper?
1880
        p.initGossipSync()
6✔
1881

6✔
1882
        discStream := newDiscMsgStream(p)
6✔
1883
        discStream.Start()
6✔
1884
        defer discStream.Stop()
6✔
1885
out:
6✔
1886
        for atomic.LoadInt32(&p.disconnect) == 0 {
13✔
1887
                nextMsg, err := p.readNextMessage()
7✔
1888
                if !idleTimer.Stop() {
7✔
1889
                        select {
×
1890
                        case <-idleTimer.C:
×
1891
                        default:
×
1892
                        }
1893
                }
1894
                if err != nil {
7✔
1895
                        p.log.Infof("unable to read message from peer: %v", err)
3✔
1896

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

1911
                        // If they sent us an address type that we don't yet
1912
                        // know of, then this isn't a wire error, so we'll
1913
                        // simply continue parsing the remainder of their
1914
                        // messages.
1915
                        case *lnwire.ErrUnknownAddrType:
×
1916
                                p.storeError(e)
×
1917
                                idleTimer.Reset(idleTimeout)
×
1918
                                continue
×
1919

1920
                        // If the NodeAnnouncement has an invalid alias, then
1921
                        // we'll log that error above and continue so we can
1922
                        // continue to read messages from the peer. We do not
1923
                        // store this error because it is of little debugging
1924
                        // value.
1925
                        case *lnwire.ErrInvalidNodeAlias:
×
1926
                                idleTimer.Reset(idleTimeout)
×
1927
                                continue
×
1928

1929
                        // If the error we encountered wasn't just a message we
1930
                        // didn't recognize, then we'll stop all processing as
1931
                        // this is a fatal error.
1932
                        default:
3✔
1933
                                break out
3✔
1934
                        }
1935
                }
1936

1937
                // If a message router is active, then we'll try to have it
1938
                // handle this message. If it can, then we're able to skip the
1939
                // rest of the message handling logic.
1940
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
8✔
1941
                        return r.RouteMsg(msgmux.PeerMsg{
4✔
1942
                                PeerPub: *p.IdentityKey(),
4✔
1943
                                Message: nextMsg,
4✔
1944
                        })
4✔
1945
                })
4✔
1946

1947
                // No error occurred, and the message was handled by the
1948
                // router.
1949
                if err == nil {
4✔
1950
                        continue
×
1951
                }
1952

1953
                var (
4✔
1954
                        targetChan   lnwire.ChannelID
4✔
1955
                        isLinkUpdate bool
4✔
1956
                )
4✔
1957

4✔
1958
                switch msg := nextMsg.(type) {
4✔
1959
                case *lnwire.Pong:
2✔
1960
                        // When we receive a Pong message in response to our
2✔
1961
                        // last ping message, we send it to the pingManager
2✔
1962
                        p.pingManager.ReceivedPong(msg)
2✔
1963

1964
                case *lnwire.Ping:
2✔
1965
                        // First, we'll store their latest ping payload within
2✔
1966
                        // the relevant atomic variable.
2✔
1967
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
2✔
1968

2✔
1969
                        // Next, we'll send over the amount of specified pong
2✔
1970
                        // bytes.
2✔
1971
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
2✔
1972
                        p.queueMsg(pong, nil)
2✔
1973

1974
                case *lnwire.OpenChannel,
1975
                        *lnwire.AcceptChannel,
1976
                        *lnwire.FundingCreated,
1977
                        *lnwire.FundingSigned,
1978
                        *lnwire.ChannelReady:
3✔
1979

3✔
1980
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
1981

1982
                case *lnwire.Shutdown:
3✔
1983
                        select {
3✔
1984
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
1985
                        case <-p.quit:
×
1986
                                break out
×
1987
                        }
1988
                case *lnwire.ClosingSigned:
3✔
1989
                        select {
3✔
1990
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
3✔
1991
                        case <-p.quit:
×
1992
                                break out
×
1993
                        }
1994

1995
                case *lnwire.Warning:
×
1996
                        targetChan = msg.ChanID
×
1997
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
1998

1999
                case *lnwire.Error:
3✔
2000
                        targetChan = msg.ChanID
3✔
2001
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
3✔
2002

2003
                case *lnwire.ChannelReestablish:
3✔
2004
                        targetChan = msg.ChanID
3✔
2005
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2006

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

2022
                // For messages that implement the LinkUpdater interface, we
2023
                // will consider them as link updates and send them to
2024
                // chanStream. These messages will be queued inside chanStream
2025
                // if the channel is not active yet.
2026
                case lnwire.LinkUpdater:
3✔
2027
                        targetChan = msg.TargetChanID()
3✔
2028
                        isLinkUpdate = p.hasChannel(targetChan)
3✔
2029

3✔
2030
                        // Log an error if we don't have this channel. This
3✔
2031
                        // means the peer has sent us a message with unknown
3✔
2032
                        // channel ID.
3✔
2033
                        if !isLinkUpdate {
6✔
2034
                                p.log.Errorf("Unknown channel ID: %v found "+
3✔
2035
                                        "in received msg=%s", targetChan,
3✔
2036
                                        nextMsg.MsgType())
3✔
2037
                        }
3✔
2038

2039
                case *lnwire.ChannelUpdate1,
2040
                        *lnwire.ChannelAnnouncement1,
2041
                        *lnwire.NodeAnnouncement,
2042
                        *lnwire.AnnounceSignatures1,
2043
                        *lnwire.GossipTimestampRange,
2044
                        *lnwire.QueryShortChanIDs,
2045
                        *lnwire.QueryChannelRange,
2046
                        *lnwire.ReplyChannelRange,
2047
                        *lnwire.ReplyShortChanIDsEnd:
3✔
2048

3✔
2049
                        discStream.AddMsg(msg)
3✔
2050

2051
                case *lnwire.Custom:
4✔
2052
                        err := p.handleCustomMessage(msg)
4✔
2053
                        if err != nil {
4✔
2054
                                p.storeError(err)
×
2055
                                p.log.Errorf("%v", err)
×
2056
                        }
×
2057

2058
                default:
×
2059
                        // If the message we received is unknown to us, store
×
2060
                        // the type to track the failure.
×
2061
                        err := fmt.Errorf("unknown message type %v received",
×
2062
                                uint16(msg.MsgType()))
×
2063
                        p.storeError(err)
×
2064

×
2065
                        p.log.Errorf("%v", err)
×
2066
                }
2067

2068
                if isLinkUpdate {
7✔
2069
                        // If this is a channel update, then we need to feed it
3✔
2070
                        // into the channel's in-order message stream.
3✔
2071
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
3✔
2072
                }
3✔
2073

2074
                idleTimer.Reset(idleTimeout)
4✔
2075
        }
2076

2077
        p.Disconnect(errors.New("read handler closed"))
3✔
2078

3✔
2079
        p.log.Trace("readHandler for peer done")
3✔
2080
}
2081

2082
// handleCustomMessage handles the given custom message if a handler is
2083
// registered.
2084
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
4✔
2085
        if p.cfg.HandleCustomMessage == nil {
4✔
2086
                return fmt.Errorf("no custom message handler for "+
×
2087
                        "message type %v", uint16(msg.MsgType()))
×
2088
        }
×
2089

2090
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
4✔
2091
}
2092

2093
// isLoadedFromDisk returns true if the provided channel ID is loaded from
2094
// disk.
2095
//
2096
// NOTE: only returns true for pending channels.
2097
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
3✔
2098
        // If this is a newly added channel, no need to reestablish.
3✔
2099
        _, added := p.addedChannels.Load(chanID)
3✔
2100
        if added {
6✔
2101
                return false
3✔
2102
        }
3✔
2103

2104
        // Return false if the channel is unknown.
2105
        channel, ok := p.activeChannels.Load(chanID)
3✔
2106
        if !ok {
3✔
2107
                return false
×
2108
        }
×
2109

2110
        // During startup, we will use a nil value to mark a pending channel
2111
        // that's loaded from disk.
2112
        return channel == nil
3✔
2113
}
2114

2115
// isActiveChannel returns true if the provided channel id is active, otherwise
2116
// returns false.
2117
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
11✔
2118
        // The channel would be nil if,
11✔
2119
        // - the channel doesn't exist, or,
11✔
2120
        // - the channel exists, but is pending. In this case, we don't
11✔
2121
        //   consider this channel active.
11✔
2122
        channel, _ := p.activeChannels.Load(chanID)
11✔
2123

11✔
2124
        return channel != nil
11✔
2125
}
11✔
2126

2127
// isPendingChannel returns true if the provided channel ID is pending, and
2128
// returns false if the channel is active or unknown.
2129
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
9✔
2130
        // Return false if the channel is unknown.
9✔
2131
        channel, ok := p.activeChannels.Load(chanID)
9✔
2132
        if !ok {
15✔
2133
                return false
6✔
2134
        }
6✔
2135

2136
        return channel == nil
3✔
2137
}
2138

2139
// hasChannel returns true if the peer has a pending/active channel specified
2140
// by the channel ID.
2141
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
3✔
2142
        _, ok := p.activeChannels.Load(chanID)
3✔
2143
        return ok
3✔
2144
}
3✔
2145

2146
// storeError stores an error in our peer's buffer of recent errors with the
2147
// current timestamp. Errors are only stored if we have at least one active
2148
// channel with the peer to mitigate a dos vector where a peer costlessly
2149
// connects to us and spams us with errors.
2150
func (p *Brontide) storeError(err error) {
3✔
2151
        var haveChannels bool
3✔
2152

3✔
2153
        p.activeChannels.Range(func(_ lnwire.ChannelID,
3✔
2154
                channel *lnwallet.LightningChannel) bool {
6✔
2155

3✔
2156
                // Pending channels will be nil in the activeChannels map.
3✔
2157
                if channel == nil {
6✔
2158
                        // Return true to continue the iteration.
3✔
2159
                        return true
3✔
2160
                }
3✔
2161

2162
                haveChannels = true
3✔
2163

3✔
2164
                // Return false to break the iteration.
3✔
2165
                return false
3✔
2166
        })
2167

2168
        // If we do not have any active channels with the peer, we do not store
2169
        // errors as a dos mitigation.
2170
        if !haveChannels {
6✔
2171
                p.log.Trace("no channels with peer, not storing err")
3✔
2172
                return
3✔
2173
        }
3✔
2174

2175
        p.cfg.ErrorBuffer.Add(
3✔
2176
                &TimestampedError{Timestamp: time.Now(), Error: err},
3✔
2177
        )
3✔
2178
}
2179

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

3✔
2189
        if errMsg, ok := msg.(*lnwire.Error); ok {
6✔
2190
                p.storeError(errMsg)
3✔
2191
        }
3✔
2192

2193
        switch {
3✔
2194
        // Connection wide messages should be forwarded to all channel links
2195
        // with this peer.
2196
        case chanID == lnwire.ConnectionWideID:
×
2197
                for _, chanStream := range p.activeMsgStreams {
×
2198
                        chanStream.AddMsg(msg)
×
2199
                }
×
2200

2201
                return false
×
2202

2203
        // If the channel ID for the message corresponds to a pending channel,
2204
        // then the funding manager will handle it.
2205
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
3✔
2206
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
3✔
2207
                return false
3✔
2208

2209
        // If not we hand the message to the channel link for this channel.
2210
        case p.isActiveChannel(chanID):
3✔
2211
                return true
3✔
2212

2213
        default:
3✔
2214
                return false
3✔
2215
        }
2216
}
2217

2218
// messageSummary returns a human-readable string that summarizes a
2219
// incoming/outgoing message. Not all messages will have a summary, only those
2220
// which have additional data that can be informative at a glance.
2221
func messageSummary(msg lnwire.Message) string {
3✔
2222
        switch msg := msg.(type) {
3✔
2223
        case *lnwire.Init:
3✔
2224
                // No summary.
3✔
2225
                return ""
3✔
2226

2227
        case *lnwire.OpenChannel:
3✔
2228
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
3✔
2229
                        "push_amt=%v, reserve=%v, flags=%v",
3✔
2230
                        msg.PendingChannelID[:], msg.ChainHash,
3✔
2231
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
3✔
2232
                        msg.ChannelReserve, msg.ChannelFlags)
3✔
2233

2234
        case *lnwire.AcceptChannel:
3✔
2235
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
3✔
2236
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
3✔
2237
                        msg.MinAcceptDepth)
3✔
2238

2239
        case *lnwire.FundingCreated:
3✔
2240
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
3✔
2241
                        msg.PendingChannelID[:], msg.FundingPoint)
3✔
2242

2243
        case *lnwire.FundingSigned:
3✔
2244
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
3✔
2245

2246
        case *lnwire.ChannelReady:
3✔
2247
                return fmt.Sprintf("chan_id=%v, next_point=%x",
3✔
2248
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
3✔
2249

2250
        case *lnwire.Shutdown:
3✔
2251
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
3✔
2252
                        msg.Address[:])
3✔
2253

2254
        case *lnwire.ClosingSigned:
3✔
2255
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
3✔
2256
                        msg.FeeSatoshis)
3✔
2257

2258
        case *lnwire.UpdateAddHTLC:
3✔
2259
                var blindingPoint []byte
3✔
2260
                msg.BlindingPoint.WhenSome(
3✔
2261
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
3✔
2262
                                *btcec.PublicKey]) {
6✔
2263

3✔
2264
                                blindingPoint = b.Val.SerializeCompressed()
3✔
2265
                        },
3✔
2266
                )
2267

2268
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
3✔
2269
                        "hash=%x, blinding_point=%x, custom_records=%v",
3✔
2270
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
3✔
2271
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
3✔
2272

2273
        case *lnwire.UpdateFailHTLC:
3✔
2274
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
3✔
2275
                        msg.ID, msg.Reason)
3✔
2276

2277
        case *lnwire.UpdateFulfillHTLC:
3✔
2278
                return fmt.Sprintf("chan_id=%v, id=%v, pre_image=%x, "+
3✔
2279
                        "custom_records=%v", msg.ChanID, msg.ID,
3✔
2280
                        msg.PaymentPreimage[:], msg.CustomRecords)
3✔
2281

2282
        case *lnwire.CommitSig:
3✔
2283
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
3✔
2284
                        len(msg.HtlcSigs))
3✔
2285

2286
        case *lnwire.RevokeAndAck:
3✔
2287
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
3✔
2288
                        msg.ChanID, msg.Revocation[:],
3✔
2289
                        msg.NextRevocationKey.SerializeCompressed())
3✔
2290

2291
        case *lnwire.UpdateFailMalformedHTLC:
3✔
2292
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
3✔
2293
                        msg.ChanID, msg.ID, msg.FailureCode)
3✔
2294

2295
        case *lnwire.Warning:
×
2296
                return fmt.Sprintf("%v", msg.Warning())
×
2297

2298
        case *lnwire.Error:
3✔
2299
                return fmt.Sprintf("%v", msg.Error())
3✔
2300

2301
        case *lnwire.AnnounceSignatures1:
3✔
2302
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
3✔
2303
                        msg.ShortChannelID.ToUint64())
3✔
2304

2305
        case *lnwire.ChannelAnnouncement1:
3✔
2306
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
3✔
2307
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
3✔
2308

2309
        case *lnwire.ChannelUpdate1:
3✔
2310
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
3✔
2311
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
3✔
2312
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
3✔
2313
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
3✔
2314

2315
        case *lnwire.NodeAnnouncement:
3✔
2316
                return fmt.Sprintf("node=%x, update_time=%v",
3✔
2317
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
3✔
2318

2319
        case *lnwire.Ping:
2✔
2320
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
2✔
2321

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

2325
        case *lnwire.UpdateFee:
×
2326
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2327
                        msg.ChanID, int64(msg.FeePerKw))
×
2328

2329
        case *lnwire.ChannelReestablish:
3✔
2330
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
3✔
2331
                        "remote_tail_height=%v", msg.ChanID,
3✔
2332
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
3✔
2333

2334
        case *lnwire.ReplyShortChanIDsEnd:
3✔
2335
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
3✔
2336
                        msg.Complete)
3✔
2337

2338
        case *lnwire.ReplyChannelRange:
3✔
2339
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
3✔
2340
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
3✔
2341
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
3✔
2342
                        msg.EncodingType)
3✔
2343

2344
        case *lnwire.QueryShortChanIDs:
3✔
2345
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
3✔
2346
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
3✔
2347

2348
        case *lnwire.QueryChannelRange:
3✔
2349
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
3✔
2350
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
3✔
2351
                        msg.LastBlockHeight())
3✔
2352

2353
        case *lnwire.GossipTimestampRange:
3✔
2354
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
3✔
2355
                        "stamp_range=%v", msg.ChainHash,
3✔
2356
                        time.Unix(int64(msg.FirstTimestamp), 0),
3✔
2357
                        msg.TimestampRange)
3✔
2358

2359
        case *lnwire.Stfu:
×
2360
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
×
2361
                        msg.Initiator)
×
2362

2363
        case *lnwire.Custom:
3✔
2364
                return fmt.Sprintf("type=%d", msg.Type)
3✔
2365
        }
2366

2367
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2368
}
2369

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

2381
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
23✔
2382
                // Debug summary of message.
3✔
2383
                summary := messageSummary(msg)
3✔
2384
                if len(summary) > 0 {
6✔
2385
                        summary = "(" + summary + ")"
3✔
2386
                }
3✔
2387

2388
                preposition := "to"
3✔
2389
                if read {
6✔
2390
                        preposition = "from"
3✔
2391
                }
3✔
2392

2393
                var msgType string
3✔
2394
                if msg.MsgType() < lnwire.CustomTypeStart {
6✔
2395
                        msgType = msg.MsgType().String()
3✔
2396
                } else {
6✔
2397
                        msgType = "custom"
3✔
2398
                }
3✔
2399

2400
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
3✔
2401
                        msgType, summary, preposition, p)
3✔
2402
        }))
2403

2404
        prefix := "readMessage from peer"
20✔
2405
        if !read {
36✔
2406
                prefix = "writeMessage to peer"
16✔
2407
        }
16✔
2408

2409
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
20✔
2410
}
2411

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

2429
        noiseConn := p.cfg.Conn
16✔
2430

16✔
2431
        flushMsg := func() error {
32✔
2432
                // Ensure the write deadline is set before we attempt to send
16✔
2433
                // the message.
16✔
2434
                writeDeadline := time.Now().Add(
16✔
2435
                        p.scaleTimeout(writeMessageTimeout),
16✔
2436
                )
16✔
2437
                err := noiseConn.SetWriteDeadline(writeDeadline)
16✔
2438
                if err != nil {
16✔
2439
                        return err
×
2440
                }
×
2441

2442
                // Flush the pending message to the wire. If an error is
2443
                // encountered, e.g. write timeout, the number of bytes written
2444
                // so far will be returned.
2445
                n, err := noiseConn.Flush()
16✔
2446

16✔
2447
                // Record the number of bytes written on the wire, if any.
16✔
2448
                if n > 0 {
19✔
2449
                        atomic.AddUint64(&p.bytesSent, uint64(n))
3✔
2450
                }
3✔
2451

2452
                return err
16✔
2453
        }
2454

2455
        // If the current message has already been serialized, encrypted, and
2456
        // buffered on the underlying connection we will skip straight to
2457
        // flushing it to the wire.
2458
        if msg == nil {
16✔
2459
                return flushMsg()
×
2460
        }
×
2461

2462
        // Otherwise, this is a new message. We'll acquire a write buffer to
2463
        // serialize the message and buffer the ciphertext on the connection.
2464
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
32✔
2465
                // Using a buffer allocated by the write pool, encode the
16✔
2466
                // message directly into the buffer.
16✔
2467
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
16✔
2468
                if writeErr != nil {
16✔
2469
                        return writeErr
×
2470
                }
×
2471

2472
                // Finally, write the message itself in a single swoop. This
2473
                // will buffer the ciphertext on the underlying connection. We
2474
                // will defer flushing the message until the write pool has been
2475
                // released.
2476
                return noiseConn.WriteMessage(buf.Bytes())
16✔
2477
        })
2478
        if err != nil {
16✔
2479
                return err
×
2480
        }
×
2481

2482
        return flushMsg()
16✔
2483
}
2484

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

2500
        var exitErr error
6✔
2501

6✔
2502
out:
6✔
2503
        for {
16✔
2504
                select {
10✔
2505
                case outMsg := <-p.sendQueue:
7✔
2506
                        // Record the time at which we first attempt to send the
7✔
2507
                        // message.
7✔
2508
                        startTime := time.Now()
7✔
2509

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

×
2522
                                // If we received a timeout error, this implies
×
2523
                                // that the message was buffered on the
×
2524
                                // connection successfully and that a flush was
×
2525
                                // attempted. We'll set the message to nil so
×
2526
                                // that on a subsequent pass we only try to
×
2527
                                // flush the buffered message, and forgo
×
2528
                                // reserializing or reencrypting it.
×
2529
                                outMsg.msg = nil
×
2530

×
2531
                                goto retry
×
2532
                        }
2533

2534
                        // The write succeeded, reset the idle timer to prevent
2535
                        // us from disconnecting the peer.
2536
                        if !idleTimer.Stop() {
7✔
2537
                                select {
×
2538
                                case <-idleTimer.C:
×
2539
                                default:
×
2540
                                }
2541
                        }
2542
                        idleTimer.Reset(idleTimeout)
7✔
2543

7✔
2544
                        // If the peer requested a synchronous write, respond
7✔
2545
                        // with the error.
7✔
2546
                        if outMsg.errChan != nil {
11✔
2547
                                outMsg.errChan <- err
4✔
2548
                        }
4✔
2549

2550
                        if err != nil {
7✔
2551
                                exitErr = fmt.Errorf("unable to write "+
×
2552
                                        "message: %v", err)
×
2553
                                break out
×
2554
                        }
2555

2556
                case <-p.quit:
3✔
2557
                        exitErr = lnpeer.ErrPeerExiting
3✔
2558
                        break out
3✔
2559
                }
2560
        }
2561

2562
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2563
        // disconnect.
2564
        p.wg.Done()
3✔
2565

3✔
2566
        p.Disconnect(exitErr)
3✔
2567

3✔
2568
        p.log.Trace("writeHandler for peer done")
3✔
2569
}
2570

2571
// queueHandler is responsible for accepting messages from outside subsystems
2572
// to be eventually sent out on the wire by the writeHandler.
2573
//
2574
// NOTE: This method MUST be run as a goroutine.
2575
func (p *Brontide) queueHandler() {
6✔
2576
        defer p.wg.Done()
6✔
2577

6✔
2578
        // priorityMsgs holds an in order list of messages deemed high-priority
6✔
2579
        // to be added to the sendQueue. This predominately includes messages
6✔
2580
        // from the funding manager and htlcswitch.
6✔
2581
        priorityMsgs := list.New()
6✔
2582

6✔
2583
        // lazyMsgs holds an in order list of messages deemed low-priority to be
6✔
2584
        // added to the sendQueue only after all high-priority messages have
6✔
2585
        // been queued. This predominately includes messages from the gossiper.
6✔
2586
        lazyMsgs := list.New()
6✔
2587

6✔
2588
        for {
20✔
2589
                // Examine the front of the priority queue, if it is empty check
14✔
2590
                // the low priority queue.
14✔
2591
                elem := priorityMsgs.Front()
14✔
2592
                if elem == nil {
25✔
2593
                        elem = lazyMsgs.Front()
11✔
2594
                }
11✔
2595

2596
                if elem != nil {
21✔
2597
                        front := elem.Value.(outgoingMsg)
7✔
2598

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

2638
// PingTime returns the estimated ping time to the peer in microseconds.
2639
func (p *Brontide) PingTime() int64 {
3✔
2640
        return p.pingManager.GetPingTimeMicroSeconds()
3✔
2641
}
3✔
2642

2643
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2644
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2645
// or failed to write, and nil otherwise.
2646
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
27✔
2647
        p.queue(true, msg, errChan)
27✔
2648
}
27✔
2649

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

2657
// queue sends a given message to the queueHandler using the passed priority. If
2658
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2659
// failed to write, and nil otherwise.
2660
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2661
        errChan chan error) {
28✔
2662

28✔
2663
        select {
28✔
2664
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
28✔
2665
        case <-p.quit:
3✔
2666
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
3✔
2667
                        spew.Sdump(msg))
3✔
2668
                if errChan != nil {
3✔
2669
                        errChan <- lnpeer.ErrPeerExiting
×
2670
                }
×
2671
        }
2672
}
2673

2674
// ChannelSnapshots returns a slice of channel snapshots detailing all
2675
// currently active channels maintained with the remote peer.
2676
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
3✔
2677
        snapshots := make(
3✔
2678
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
3✔
2679
        )
3✔
2680

3✔
2681
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2682
                activeChan *lnwallet.LightningChannel) error {
6✔
2683

3✔
2684
                // If the activeChan is nil, then we skip it as the channel is
3✔
2685
                // pending.
3✔
2686
                if activeChan == nil {
6✔
2687
                        return nil
3✔
2688
                }
3✔
2689

2690
                // We'll only return a snapshot for channels that are
2691
                // *immediately* available for routing payments over.
2692
                if activeChan.RemoteNextRevocation() == nil {
6✔
2693
                        return nil
3✔
2694
                }
3✔
2695

2696
                snapshot := activeChan.StateSnapshot()
3✔
2697
                snapshots = append(snapshots, snapshot)
3✔
2698

3✔
2699
                return nil
3✔
2700
        })
2701

2702
        return snapshots
3✔
2703
}
2704

2705
// genDeliveryScript returns a new script to be used to send our funds to in
2706
// the case of a cooperative channel close negotiation.
2707
func (p *Brontide) genDeliveryScript() ([]byte, error) {
9✔
2708
        // We'll send a normal p2wkh address unless we've negotiated the
9✔
2709
        // shutdown-any-segwit feature.
9✔
2710
        addrType := lnwallet.WitnessPubKey
9✔
2711
        if p.taprootShutdownAllowed() {
12✔
2712
                addrType = lnwallet.TaprootPubkey
3✔
2713
        }
3✔
2714

2715
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
9✔
2716
                addrType, false, lnwallet.DefaultAccountName,
9✔
2717
        )
9✔
2718
        if err != nil {
9✔
2719
                return nil, err
×
2720
        }
×
2721
        p.log.Infof("Delivery addr for channel close: %v",
9✔
2722
                deliveryAddr)
9✔
2723

9✔
2724
        return txscript.PayToAddrScript(deliveryAddr)
9✔
2725
}
2726

2727
// channelManager is goroutine dedicated to handling all requests/signals
2728
// pertaining to the opening, cooperative closing, and force closing of all
2729
// channels maintained with the remote peer.
2730
//
2731
// NOTE: This method MUST be run as a goroutine.
2732
func (p *Brontide) channelManager() {
20✔
2733
        defer p.wg.Done()
20✔
2734

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

20✔
2740
out:
20✔
2741
        for {
61✔
2742
                select {
41✔
2743
                // A new pending channel has arrived which means we are about
2744
                // to complete a funding workflow and is waiting for the final
2745
                // `ChannelReady` messages to be exchanged. We will add this
2746
                // channel to the `activeChannels` with a nil value to indicate
2747
                // this is a pending channel.
2748
                case req := <-p.newPendingChannel:
4✔
2749
                        p.handleNewPendingChannel(req)
4✔
2750

2751
                // A new channel has arrived which means we've just completed a
2752
                // funding workflow. We'll initialize the necessary local
2753
                // state, and notify the htlc switch of a new link.
2754
                case req := <-p.newActiveChannel:
3✔
2755
                        p.handleNewActiveChannel(req)
3✔
2756

2757
                // The funding flow for a pending channel is failed, we will
2758
                // remove it from Brontide.
2759
                case req := <-p.removePendingChannel:
4✔
2760
                        p.handleRemovePendingChannel(req)
4✔
2761

2762
                // We've just received a local request to close an active
2763
                // channel. It will either kick of a cooperative channel
2764
                // closure negotiation, or be a notification of a breached
2765
                // contract that should be abandoned.
2766
                case req := <-p.localCloseChanReqs:
10✔
2767
                        p.handleLocalCloseReq(req)
10✔
2768

2769
                // We've received a link failure from a link that was added to
2770
                // the switch. This will initiate the teardown of the link, and
2771
                // initiate any on-chain closures if necessary.
2772
                case failure := <-p.linkFailures:
3✔
2773
                        p.handleLinkFailure(failure)
3✔
2774

2775
                // We've received a new cooperative channel closure related
2776
                // message from the remote peer, we'll use this message to
2777
                // advance the chan closer state machine.
2778
                case closeMsg := <-p.chanCloseMsgs:
16✔
2779
                        p.handleCloseMsg(closeMsg)
16✔
2780

2781
                // The channel reannounce delay has elapsed, broadcast the
2782
                // reenabled channel updates to the network. This should only
2783
                // fire once, so we set the reenableTimeout channel to nil to
2784
                // mark it for garbage collection. If the peer is torn down
2785
                // before firing, reenabling will not be attempted.
2786
                // TODO(conner): consolidate reenables timers inside chan status
2787
                // manager
2788
                case <-reenableTimeout:
3✔
2789
                        p.reenableActiveChannels()
3✔
2790

3✔
2791
                        // Since this channel will never fire again during the
3✔
2792
                        // lifecycle of the peer, we nil the channel to mark it
3✔
2793
                        // eligible for garbage collection, and make this
3✔
2794
                        // explicitly ineligible to receive in future calls to
3✔
2795
                        // select. This also shaves a few CPU cycles since the
3✔
2796
                        // select will ignore this case entirely.
3✔
2797
                        reenableTimeout = nil
3✔
2798

3✔
2799
                        // Once the reenabling is attempted, we also cancel the
3✔
2800
                        // channel event subscription to free up the overflow
3✔
2801
                        // queue used in channel notifier.
3✔
2802
                        //
3✔
2803
                        // NOTE: channelEventClient will be nil if the
3✔
2804
                        // reenableTimeout is greater than 1 minute.
3✔
2805
                        if p.channelEventClient != nil {
6✔
2806
                                p.channelEventClient.Cancel()
3✔
2807
                        }
3✔
2808

2809
                case <-p.quit:
3✔
2810
                        // As, we've been signalled to exit, we'll reset all
3✔
2811
                        // our active channel back to their default state.
3✔
2812
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
3✔
2813
                                lc *lnwallet.LightningChannel) error {
6✔
2814

3✔
2815
                                // Exit if the channel is nil as it's a pending
3✔
2816
                                // channel.
3✔
2817
                                if lc == nil {
6✔
2818
                                        return nil
3✔
2819
                                }
3✔
2820

2821
                                lc.ResetState()
3✔
2822

3✔
2823
                                return nil
3✔
2824
                        })
2825

2826
                        break out
3✔
2827
                }
2828
        }
2829
}
2830

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

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

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

3✔
2849
                switch {
3✔
2850
                // No error occurred, continue to request the next channel.
2851
                case err == nil:
3✔
2852
                        continue
3✔
2853

2854
                // Cannot auto enable a manually disabled channel so we do
2855
                // nothing but proceed to the next channel.
2856
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
3✔
2857
                        p.log.Debugf("Channel(%v) was manually disabled, "+
3✔
2858
                                "ignoring automatic enable request", chanPoint)
3✔
2859

3✔
2860
                        continue
3✔
2861

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

×
2879
                                continue
×
2880
                        }
2881

2882
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
2883
                                "ChanStatusManager reported inactive, retrying")
×
2884

×
2885
                        // Add the channel to the retry map.
×
2886
                        retryChans[chanPoint] = struct{}{}
×
2887
                }
2888
        }
2889

2890
        // Retry the channels if we have any.
2891
        if len(retryChans) != 0 {
3✔
2892
                p.retryRequestEnable(retryChans)
×
2893
        }
×
2894
}
2895

2896
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
2897
// for the target channel ID. If the channel isn't active an error is returned.
2898
// Otherwise, either an existing state machine will be returned, or a new one
2899
// will be created.
2900
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
2901
        *chancloser.ChanCloser, error) {
16✔
2902

16✔
2903
        chanCloser, found := p.activeChanCloses[chanID]
16✔
2904
        if found {
29✔
2905
                // An entry will only be found if the closer has already been
13✔
2906
                // created for a non-pending channel or for a channel that had
13✔
2907
                // previously started the shutdown process but the connection
13✔
2908
                // was restarted.
13✔
2909
                return chanCloser, nil
13✔
2910
        }
13✔
2911

2912
        // First, we'll ensure that we actually know of the target channel. If
2913
        // not, we'll ignore this message.
2914
        channel, ok := p.activeChannels.Load(chanID)
6✔
2915

6✔
2916
        // If the channel isn't in the map or the channel is nil, return
6✔
2917
        // ErrChannelNotFound as the channel is pending.
6✔
2918
        if !ok || channel == nil {
9✔
2919
                return nil, ErrChannelNotFound
3✔
2920
        }
3✔
2921

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

2941
        // In order to begin fee negotiations, we'll first compute our target
2942
        // ideal fee-per-kw.
2943
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
6✔
2944
                p.cfg.CoopCloseTargetConfs,
6✔
2945
        )
6✔
2946
        if err != nil {
6✔
2947
                p.log.Errorf("unable to query fee estimator: %v", err)
×
2948
                return nil, fmt.Errorf("unable to estimate fee")
×
2949
        }
×
2950

2951
        addr, err := p.addrWithInternalKey(deliveryScript)
6✔
2952
        if err != nil {
6✔
2953
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
2954
        }
×
2955
        chanCloser, err = p.createChanCloser(
6✔
2956
                channel, addr, feePerKw, nil, lntypes.Remote,
6✔
2957
        )
6✔
2958
        if err != nil {
6✔
2959
                p.log.Errorf("unable to create chan closer: %v", err)
×
2960
                return nil, fmt.Errorf("unable to create chan closer")
×
2961
        }
×
2962

2963
        p.activeChanCloses[chanID] = chanCloser
6✔
2964

6✔
2965
        return chanCloser, nil
6✔
2966
}
2967

2968
// filterChannelsToEnable filters a list of channels to be enabled upon start.
2969
// The filtered channels are active channels that's neither private nor
2970
// pending.
2971
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
3✔
2972
        var activePublicChans []wire.OutPoint
3✔
2973

3✔
2974
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
3✔
2975
                lnChan *lnwallet.LightningChannel) bool {
6✔
2976

3✔
2977
                // If the lnChan is nil, continue as this is a pending channel.
3✔
2978
                if lnChan == nil {
3✔
2979
                        return true
×
2980
                }
×
2981

2982
                dbChan := lnChan.State()
3✔
2983
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
2984
                if !isPublic || dbChan.IsPending {
3✔
2985
                        return true
×
2986
                }
×
2987

2988
                // We'll also skip any channels added during this peer's
2989
                // lifecycle since they haven't waited out the timeout. Their
2990
                // first announcement will be enabled, and the chan status
2991
                // manager will begin monitoring them passively since they exist
2992
                // in the database.
2993
                if _, ok := p.addedChannels.Load(chanID); ok {
6✔
2994
                        return true
3✔
2995
                }
3✔
2996

2997
                activePublicChans = append(
3✔
2998
                        activePublicChans, dbChan.FundingOutpoint,
3✔
2999
                )
3✔
3000

3✔
3001
                return true
3✔
3002
        })
3003

3004
        return activePublicChans
3✔
3005
}
3006

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

×
3014
        // retryEnable is a helper closure that sends an enable request and
×
3015
        // removes the channel from the map if it's matched.
×
3016
        retryEnable := func(chanPoint wire.OutPoint) error {
×
3017
                // If this is an active channel event, check whether it's in
×
3018
                // our targeted channels map.
×
3019
                _, found := activeChans[chanPoint]
×
3020

×
3021
                // If this channel is irrelevant, return nil so the loop can
×
3022
                // jump to next iteration.
×
3023
                if !found {
×
3024
                        return nil
×
3025
                }
×
3026

3027
                // Otherwise we've just received an active signal for a channel
3028
                // that's previously failed to be enabled, we send the request
3029
                // again.
3030
                //
3031
                // We only give the channel one more shot, so we delete it from
3032
                // our map first to keep it from being attempted again.
3033
                delete(activeChans, chanPoint)
×
3034

×
3035
                // Send the request.
×
3036
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3037
                if err != nil {
×
3038
                        return fmt.Errorf("request enabling channel %v "+
×
3039
                                "failed: %w", chanPoint, err)
×
3040
                }
×
3041

3042
                return nil
×
3043
        }
3044

3045
        for {
×
3046
                // If activeChans is empty, we've done processing all the
×
3047
                // channels.
×
3048
                if len(activeChans) == 0 {
×
3049
                        p.log.Debug("Finished retry enabling channels")
×
3050
                        return
×
3051
                }
×
3052

3053
                select {
×
3054
                // A new event has been sent by the ChannelNotifier. We now
3055
                // check whether it's an active or inactive channel event.
3056
                case e := <-p.channelEventClient.Updates():
×
3057
                        // If this is an active channel event, try enable the
×
3058
                        // channel then jump to the next iteration.
×
3059
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
3060
                        if ok {
×
3061
                                chanPoint := *active.ChannelPoint
×
3062

×
3063
                                // If we received an error for this particular
×
3064
                                // channel, we log an error and won't quit as
×
3065
                                // we still want to retry other channels.
×
3066
                                if err := retryEnable(chanPoint); err != nil {
×
3067
                                        p.log.Errorf("Retry failed: %v", err)
×
3068
                                }
×
3069

3070
                                continue
×
3071
                        }
3072

3073
                        // Otherwise check for inactive link event, and jump to
3074
                        // next iteration if it's not.
3075
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3076
                        if !ok {
×
3077
                                continue
×
3078
                        }
3079

3080
                        // Found an inactive link event, if this is our
3081
                        // targeted channel, remove it from our map.
3082
                        chanPoint := *inactive.ChannelPoint
×
3083
                        _, found := activeChans[chanPoint]
×
3084
                        if !found {
×
3085
                                continue
×
3086
                        }
3087

3088
                        delete(activeChans, chanPoint)
×
3089
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3090
                                "inactive link event", chanPoint)
×
3091

3092
                case <-p.quit:
×
3093
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3094
                        return
×
3095
                }
3096
        }
3097
}
3098

3099
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3100
// a suitable script to close out to. This may be nil if neither script is
3101
// set. If both scripts are set, this function will error if they do not match.
3102
func chooseDeliveryScript(upfront,
3103
        requested lnwire.DeliveryAddress) (lnwire.DeliveryAddress, error) {
15✔
3104

15✔
3105
        // If no upfront shutdown script was provided, return the user
15✔
3106
        // requested address (which may be nil).
15✔
3107
        if len(upfront) == 0 {
24✔
3108
                return requested, nil
9✔
3109
        }
9✔
3110

3111
        // If an upfront shutdown script was provided, and the user did not
3112
        // request a custom shutdown script, return the upfront address.
3113
        if len(requested) == 0 {
14✔
3114
                return upfront, nil
5✔
3115
        }
5✔
3116

3117
        // If both an upfront shutdown script and a custom close script were
3118
        // provided, error if the user provided shutdown script does not match
3119
        // the upfront shutdown script (because closing out to a different
3120
        // script would violate upfront shutdown).
3121
        if !bytes.Equal(upfront, requested) {
6✔
3122
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
3123
        }
2✔
3124

3125
        // The user requested script matches the upfront shutdown script, so we
3126
        // can return it without error.
3127
        return upfront, nil
2✔
3128
}
3129

3130
// restartCoopClose checks whether we need to restart the cooperative close
3131
// process for a given channel.
3132
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3133
        *lnwire.Shutdown, error) {
×
3134

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

3153
        var deliveryScript []byte
×
3154

×
3155
        shutdownInfo, err := c.ShutdownInfo()
×
3156
        switch {
×
3157
        // We have previously stored the delivery script that we need to use
3158
        // in the shutdown message. Re-use this script.
3159
        case err == nil:
×
3160
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
×
3161
                        deliveryScript = info.DeliveryScript.Val
×
3162
                })
×
3163

3164
        // An error other than ErrNoShutdownInfo was returned
3165
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3166
                return nil, err
×
3167

3168
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3169
                deliveryScript = c.LocalShutdownScript
×
3170
                if len(deliveryScript) == 0 {
×
3171
                        var err error
×
3172
                        deliveryScript, err = p.genDeliveryScript()
×
3173
                        if err != nil {
×
3174
                                p.log.Errorf("unable to gen delivery script: "+
×
3175
                                        "%v", err)
×
3176

×
3177
                                return nil, fmt.Errorf("close addr unavailable")
×
3178
                        }
×
3179
                }
3180
        }
3181

3182
        // Compute an ideal fee.
3183
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
3184
                p.cfg.CoopCloseTargetConfs,
×
3185
        )
×
3186
        if err != nil {
×
3187
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3188
                return nil, fmt.Errorf("unable to estimate fee")
×
3189
        }
×
3190

3191
        // Determine whether we or the peer are the initiator of the coop
3192
        // close attempt by looking at the channel's status.
3193
        closingParty := lntypes.Remote
×
3194
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3195
                closingParty = lntypes.Local
×
3196
        }
×
3197

3198
        addr, err := p.addrWithInternalKey(deliveryScript)
×
3199
        if err != nil {
×
3200
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
3201
        }
×
3202
        chanCloser, err := p.createChanCloser(
×
3203
                lnChan, addr, feePerKw, nil, closingParty,
×
3204
        )
×
3205
        if err != nil {
×
3206
                p.log.Errorf("unable to create chan closer: %v", err)
×
3207
                return nil, fmt.Errorf("unable to create chan closer")
×
3208
        }
×
3209

3210
        // This does not need a mutex even though it is in a different
3211
        // goroutine since this is done before the channelManager goroutine is
3212
        // created.
3213
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
×
3214
        p.activeChanCloses[chanID] = chanCloser
×
3215

×
3216
        // Create the Shutdown message.
×
3217
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3218
        if err != nil {
×
3219
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3220
                delete(p.activeChanCloses, chanID)
×
3221
                return nil, err
×
3222
        }
×
3223

3224
        return shutdownMsg, nil
×
3225
}
3226

3227
// createChanCloser constructs a ChanCloser from the passed parameters and is
3228
// used to de-duplicate code.
3229
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3230
        deliveryScript *chancloser.DeliveryAddrWithKey,
3231
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3232
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
12✔
3233

12✔
3234
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
12✔
3235
        if err != nil {
12✔
3236
                p.log.Errorf("unable to obtain best block: %v", err)
×
3237
                return nil, fmt.Errorf("cannot obtain best block")
×
3238
        }
×
3239

3240
        // The req will only be set if we initiated the co-op closing flow.
3241
        var maxFee chainfee.SatPerKWeight
12✔
3242
        if req != nil {
21✔
3243
                maxFee = req.MaxFee
9✔
3244
        }
9✔
3245

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

3272
        return chanCloser, nil
12✔
3273
}
3274

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

10✔
3280
        channel, ok := p.activeChannels.Load(chanID)
10✔
3281

10✔
3282
        // Though this function can't be called for pending channels, we still
10✔
3283
        // check whether channel is nil for safety.
10✔
3284
        if !ok || channel == nil {
10✔
3285
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
×
3286
                        "unknown", chanID)
×
3287
                p.log.Errorf(err.Error())
×
3288
                req.Err <- err
×
3289
                return
×
3290
        }
×
3291

3292
        switch req.CloseType {
10✔
3293
        // A type of CloseRegular indicates that the user has opted to close
3294
        // out this channel on-chain, so we execute the cooperative channel
3295
        // closure workflow.
3296
        case contractcourt.CloseRegular:
10✔
3297
                // First, we'll choose a delivery address that we'll use to send the
10✔
3298
                // funds to in the case of a successful negotiation.
10✔
3299

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

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

×
3331
                        return
×
3332
                }
×
3333
                chanCloser, err := p.createChanCloser(
9✔
3334
                        channel, addr, req.TargetFeePerKw, req, lntypes.Local,
9✔
3335
                )
9✔
3336
                if err != nil {
9✔
3337
                        p.log.Errorf(err.Error())
×
3338
                        req.Err <- err
×
3339
                        return
×
3340
                }
×
3341

3342
                p.activeChanCloses[chanID] = chanCloser
9✔
3343

9✔
3344
                // Finally, we'll initiate the channel shutdown within the
9✔
3345
                // chanCloser, and send the shutdown message to the remote
9✔
3346
                // party to kick things off.
9✔
3347
                shutdownMsg, err := chanCloser.ShutdownChan()
9✔
3348
                if err != nil {
9✔
3349
                        p.log.Errorf(err.Error())
×
3350
                        req.Err <- err
×
3351
                        delete(p.activeChanCloses, chanID)
×
3352

×
3353
                        // As we were unable to shutdown the channel, we'll
×
3354
                        // return it back to its normal state.
×
3355
                        channel.ResetState()
×
3356
                        return
×
3357
                }
×
3358

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

3372
                if !link.DisableAdds(htlcswitch.Outgoing) {
9✔
3373
                        p.log.Warnf("Outgoing link adds already "+
×
3374
                                "disabled: %v", link.ChanID())
×
3375
                }
×
3376

3377
                link.OnCommitOnce(htlcswitch.Outgoing, func() {
18✔
3378
                        p.queueMsg(shutdownMsg, nil)
9✔
3379
                })
9✔
3380

3381
        // A type of CloseBreach indicates that the counterparty has breached
3382
        // the channel therefore we need to clean up our local state.
3383
        case contractcourt.CloseBreach:
1✔
3384
                // TODO(roasbeef): no longer need with newer beach logic?
1✔
3385
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
1✔
3386
                        "channel", req.ChanPoint)
1✔
3387
                p.WipeChannel(req.ChanPoint)
1✔
3388
        }
3389
}
3390

3391
// linkFailureReport is sent to the channelManager whenever a link reports a
3392
// link failure, and is forced to exit. The report houses the necessary
3393
// information to clean up the channel state, send back the error message, and
3394
// force close if necessary.
3395
type linkFailureReport struct {
3396
        chanPoint   wire.OutPoint
3397
        chanID      lnwire.ChannelID
3398
        shortChanID lnwire.ShortChannelID
3399
        linkErr     htlcswitch.LinkFailureError
3400
}
3401

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

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

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

3✔
3426
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
3✔
3427
                        failure.chanPoint,
3✔
3428
                )
3✔
3429
                if err != nil {
6✔
3430
                        p.log.Errorf("unable to force close "+
3✔
3431
                                "link(%v): %v", failure.shortChanID, err)
3✔
3432
                } else {
6✔
3433
                        p.log.Infof("channel(%v) force "+
3✔
3434
                                "closed with txid %v",
3✔
3435
                                failure.shortChanID, closeTx.TxHash())
3✔
3436
                }
3✔
3437
        }
3438

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

×
3444
                if err := lnChan.State().MarkBorked(); err != nil {
×
3445
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
3446
                                failure.shortChanID, err)
×
3447
                }
×
3448
        }
3449

3450
        // Send an error to the peer, why we failed the channel.
3451
        if failure.linkErr.ShouldSendToPeer() {
6✔
3452
                // If SendData is set, send it to the peer. If not, we'll use
3✔
3453
                // the standard error messages in the payload. We only include
3✔
3454
                // sendData in the cases where the error data does not contain
3✔
3455
                // sensitive information.
3✔
3456
                data := []byte(failure.linkErr.Error())
3✔
3457
                if failure.linkErr.SendData != nil {
3✔
3458
                        data = failure.linkErr.SendData
×
3459
                }
×
3460

3461
                var networkMsg lnwire.Message
3✔
3462
                if failure.linkErr.Warning {
3✔
3463
                        networkMsg = &lnwire.Warning{
×
3464
                                ChanID: failure.chanID,
×
3465
                                Data:   data,
×
3466
                        }
×
3467
                } else {
3✔
3468
                        networkMsg = &lnwire.Error{
3✔
3469
                                ChanID: failure.chanID,
3✔
3470
                                Data:   data,
3✔
3471
                        }
3✔
3472
                }
3✔
3473

3474
                err := p.SendMessage(true, networkMsg)
3✔
3475
                if err != nil {
3✔
3476
                        p.log.Errorf("unable to send msg to "+
×
3477
                                "remote peer: %v", err)
×
3478
                }
×
3479
        }
3480

3481
        // If the failure action is disconnect, then we'll execute that now. If
3482
        // we had to send an error above, it was a sync call, so we expect the
3483
        // message to be flushed on the wire by now.
3484
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
3✔
3485
                p.Disconnect(fmt.Errorf("link requested disconnect"))
×
3486
        }
×
3487
}
3488

3489
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
3490
// public key and the channel id.
3491
func (p *Brontide) fetchLinkFromKeyAndCid(
3492
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
22✔
3493

22✔
3494
        var chanLink htlcswitch.ChannelUpdateHandler
22✔
3495

22✔
3496
        // We don't need to check the error here, and can instead just loop
22✔
3497
        // over the slice and return nil.
22✔
3498
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
22✔
3499
        for _, link := range links {
43✔
3500
                if link.ChanID() == cid {
42✔
3501
                        chanLink = link
21✔
3502
                        break
21✔
3503
                }
3504
        }
3505

3506
        return chanLink
22✔
3507
}
3508

3509
// finalizeChanClosure performs the final clean up steps once the cooperative
3510
// closure transaction has been fully broadcast. The finalized closing state
3511
// machine should be passed in. Once the transaction has been sufficiently
3512
// confirmed, the channel will be marked as fully closed within the database,
3513
// and any clients will be notified of updates to the closing state.
3514
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
7✔
3515
        closeReq := chanCloser.CloseRequest()
7✔
3516

7✔
3517
        // First, we'll clear all indexes related to the channel in question.
7✔
3518
        chanPoint := chanCloser.Channel().ChannelPoint()
7✔
3519
        p.WipeChannel(&chanPoint)
7✔
3520

7✔
3521
        // Also clear the activeChanCloses map of this channel.
7✔
3522
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
7✔
3523
        delete(p.activeChanCloses, cid)
7✔
3524

7✔
3525
        // Next, we'll launch a goroutine which will request to be notified by
7✔
3526
        // the ChainNotifier once the closure transaction obtains a single
7✔
3527
        // confirmation.
7✔
3528
        notifier := p.cfg.ChainNotifier
7✔
3529

7✔
3530
        // If any error happens during waitForChanToClose, forward it to
7✔
3531
        // closeReq. If this channel closure is not locally initiated, closeReq
7✔
3532
        // will be nil, so just ignore the error.
7✔
3533
        errChan := make(chan error, 1)
7✔
3534
        if closeReq != nil {
12✔
3535
                errChan = closeReq.Err
5✔
3536
        }
5✔
3537

3538
        closingTx, err := chanCloser.ClosingTx()
7✔
3539
        if err != nil {
7✔
3540
                if closeReq != nil {
×
3541
                        p.log.Error(err)
×
3542
                        closeReq.Err <- err
×
3543
                }
×
3544
        }
3545

3546
        closingTxid := closingTx.TxHash()
7✔
3547

7✔
3548
        // If this is a locally requested shutdown, update the caller with a
7✔
3549
        // new event detailing the current pending state of this request.
7✔
3550
        if closeReq != nil {
12✔
3551
                closeReq.Updates <- &PendingUpdate{
5✔
3552
                        Txid: closingTxid[:],
5✔
3553
                }
5✔
3554
        }
5✔
3555

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

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

7✔
3586
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
7✔
3587
                "with txid: %v", chanPoint, closingTxID)
7✔
3588

7✔
3589
        // TODO(roasbeef): add param for num needed confs
7✔
3590
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
7✔
3591
                closingTxID, closeScript, 1, bestHeight,
7✔
3592
        )
7✔
3593
        if err != nil {
7✔
3594
                if errChan != nil {
×
3595
                        errChan <- err
×
3596
                }
×
3597
                return
×
3598
        }
3599

3600
        // In the case that the ChainNotifier is shutting down, all subscriber
3601
        // notification channels will be closed, generating a nil receive.
3602
        height, ok := <-confNtfn.Confirmed
7✔
3603
        if !ok {
10✔
3604
                return
3✔
3605
        }
3✔
3606

3607
        // The channel has been closed, remove it from any active indexes, and
3608
        // the database state.
3609
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
7✔
3610
                "height %v", chanPoint, height.BlockHeight)
7✔
3611

7✔
3612
        // Finally, execute the closure call back to mark the confirmation of
7✔
3613
        // the transaction closing the contract.
7✔
3614
        cb()
7✔
3615
}
3616

3617
// WipeChannel removes the passed channel point from all indexes associated with
3618
// the peer and the switch.
3619
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
7✔
3620
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
7✔
3621

7✔
3622
        p.activeChannels.Delete(chanID)
7✔
3623

7✔
3624
        // Instruct the HtlcSwitch to close this link as the channel is no
7✔
3625
        // longer active.
7✔
3626
        p.cfg.Switch.RemoveLink(chanID)
7✔
3627
}
7✔
3628

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

3640
        // Then, finalize the remote feature vector providing the flattened
3641
        // feature bit namespace.
3642
        p.remoteFeatures = lnwire.NewFeatureVector(
6✔
3643
                msg.Features, lnwire.Features,
6✔
3644
        )
6✔
3645

6✔
3646
        // Now that we have their features loaded, we'll ensure that they
6✔
3647
        // didn't set any required bits that we don't know of.
6✔
3648
        err = feature.ValidateRequired(p.remoteFeatures)
6✔
3649
        if err != nil {
6✔
3650
                return fmt.Errorf("invalid remote features: %w", err)
×
3651
        }
×
3652

3653
        // Ensure the remote party's feature vector contains all transitive
3654
        // dependencies. We know ours are correct since they are validated
3655
        // during the feature manager's instantiation.
3656
        err = feature.ValidateDeps(p.remoteFeatures)
6✔
3657
        if err != nil {
6✔
3658
                return fmt.Errorf("invalid remote features: %w", err)
×
3659
        }
×
3660

3661
        // Now that we know we understand their requirements, we'll check to
3662
        // see if they don't support anything that we deem to be mandatory.
3663
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
6✔
3664
                return fmt.Errorf("data loss protection required")
×
3665
        }
×
3666

3667
        return nil
6✔
3668
}
3669

3670
// LocalFeatures returns the set of global features that has been advertised by
3671
// the local node. This allows sub-systems that use this interface to gate their
3672
// behavior off the set of negotiated feature bits.
3673
//
3674
// NOTE: Part of the lnpeer.Peer interface.
3675
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
3✔
3676
        return p.cfg.Features
3✔
3677
}
3✔
3678

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

3688
// hasNegotiatedScidAlias returns true if we've negotiated the
3689
// option-scid-alias feature bit with the peer.
3690
func (p *Brontide) hasNegotiatedScidAlias() bool {
6✔
3691
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
6✔
3692
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
6✔
3693
        return peerHas && localHas
6✔
3694
}
6✔
3695

3696
// sendInitMsg sends the Init message to the remote peer. This message contains
3697
// our currently supported local and global features.
3698
func (p *Brontide) sendInitMsg(legacyChan bool) error {
10✔
3699
        features := p.cfg.Features.Clone()
10✔
3700
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
10✔
3701

10✔
3702
        // If we have a legacy channel open with a peer, we downgrade static
10✔
3703
        // remote required to optional in case the peer does not understand the
10✔
3704
        // required feature bit. If we do not do this, the peer will reject our
10✔
3705
        // connection because it does not understand a required feature bit, and
10✔
3706
        // our channel will be unusable.
10✔
3707
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
11✔
3708
                p.log.Infof("Legacy channel open with peer, " +
1✔
3709
                        "downgrading static remote required feature bit to " +
1✔
3710
                        "optional")
1✔
3711

1✔
3712
                // Unset and set in both the local and global features to
1✔
3713
                // ensure both sets are consistent and merge able by old and
1✔
3714
                // new nodes.
1✔
3715
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3716
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3717

1✔
3718
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
3719
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
3720
        }
1✔
3721

3722
        msg := lnwire.NewInitMessage(
10✔
3723
                legacyFeatures.RawFeatureVector,
10✔
3724
                features.RawFeatureVector,
10✔
3725
        )
10✔
3726

10✔
3727
        return p.writeMessage(msg)
10✔
3728
}
3729

3730
// resendChanSyncMsg will attempt to find a channel sync message for the closed
3731
// channel and resend it to our peer.
3732
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
3✔
3733
        // If we already re-sent the mssage for this channel, we won't do it
3✔
3734
        // again.
3✔
3735
        if _, ok := p.resentChanSyncMsg[cid]; ok {
4✔
3736
                return nil
1✔
3737
        }
1✔
3738

3739
        // Check if we have any channel sync messages stored for this channel.
3740
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
3✔
3741
        if err != nil {
6✔
3742
                return fmt.Errorf("unable to fetch channel sync messages for "+
3✔
3743
                        "peer %v: %v", p, err)
3✔
3744
        }
3✔
3745

3746
        if c.LastChanSyncMsg == nil {
3✔
3747
                return fmt.Errorf("no chan sync message stored for channel %v",
×
3748
                        cid)
×
3749
        }
×
3750

3751
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
3✔
3752
                return fmt.Errorf("ignoring channel reestablish from "+
×
3753
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
3754
        }
×
3755

3756
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
3✔
3757
                "peer", cid)
3✔
3758

3✔
3759
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
3✔
3760
                return fmt.Errorf("failed resending channel sync "+
×
3761
                        "message to peer %v: %v", p, err)
×
3762
        }
×
3763

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

3✔
3767
        // Note down that we sent the message, so we won't resend it again for
3✔
3768
        // this connection.
3✔
3769
        p.resentChanSyncMsg[cid] = struct{}{}
3✔
3770

3✔
3771
        return nil
3✔
3772
}
3773

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

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

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

3815
                if priority {
13✔
3816
                        p.queueMsg(msg, errChan)
6✔
3817
                } else {
10✔
3818
                        p.queueMsgLazy(msg, errChan)
4✔
3819
                }
4✔
3820
        }
3821

3822
        // Wait for all replies from the writeHandler. For async sends, this
3823
        // will be a NOP as the list of error chans is nil.
3824
        for _, errChan := range errChans {
11✔
3825
                select {
4✔
3826
                case err := <-errChan:
4✔
3827
                        return err
4✔
3828
                case <-p.quit:
×
3829
                        return lnpeer.ErrPeerExiting
×
3830
                case <-p.cfg.Quit:
×
3831
                        return lnpeer.ErrPeerExiting
×
3832
                }
3833
        }
3834

3835
        return nil
6✔
3836
}
3837

3838
// PubKey returns the pubkey of the peer in compressed serialized format.
3839
//
3840
// NOTE: Part of the lnpeer.Peer interface.
3841
func (p *Brontide) PubKey() [33]byte {
5✔
3842
        return p.cfg.PubKeyBytes
5✔
3843
}
5✔
3844

3845
// IdentityKey returns the public key of the remote peer.
3846
//
3847
// NOTE: Part of the lnpeer.Peer interface.
3848
func (p *Brontide) IdentityKey() *btcec.PublicKey {
18✔
3849
        return p.cfg.Addr.IdentityKey
18✔
3850
}
18✔
3851

3852
// Address returns the network address of the remote peer.
3853
//
3854
// NOTE: Part of the lnpeer.Peer interface.
3855
func (p *Brontide) Address() net.Addr {
3✔
3856
        return p.cfg.Addr.Address
3✔
3857
}
3✔
3858

3859
// AddNewChannel adds a new channel to the peer. The channel should fail to be
3860
// added if the cancel channel is closed.
3861
//
3862
// NOTE: Part of the lnpeer.Peer interface.
3863
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
3864
        cancel <-chan struct{}) error {
3✔
3865

3✔
3866
        errChan := make(chan error, 1)
3✔
3867
        newChanMsg := &newChannelMsg{
3✔
3868
                channel: newChan,
3✔
3869
                err:     errChan,
3✔
3870
        }
3✔
3871

3✔
3872
        select {
3✔
3873
        case p.newActiveChannel <- newChanMsg:
3✔
3874
        case <-cancel:
×
3875
                return errors.New("canceled adding new channel")
×
3876
        case <-p.quit:
×
3877
                return lnpeer.ErrPeerExiting
×
3878
        }
3879

3880
        // We pause here to wait for the peer to recognize the new channel
3881
        // before we close the channel barrier corresponding to the channel.
3882
        select {
3✔
3883
        case err := <-errChan:
3✔
3884
                return err
3✔
3885
        case <-p.quit:
×
3886
                return lnpeer.ErrPeerExiting
×
3887
        }
3888
}
3889

3890
// AddPendingChannel adds a pending open channel to the peer. The channel
3891
// should fail to be added if the cancel channel is closed.
3892
//
3893
// NOTE: Part of the lnpeer.Peer interface.
3894
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
3895
        cancel <-chan struct{}) error {
3✔
3896

3✔
3897
        errChan := make(chan error, 1)
3✔
3898
        newChanMsg := &newChannelMsg{
3✔
3899
                channelID: cid,
3✔
3900
                err:       errChan,
3✔
3901
        }
3✔
3902

3✔
3903
        select {
3✔
3904
        case p.newPendingChannel <- newChanMsg:
3✔
3905

3906
        case <-cancel:
×
3907
                return errors.New("canceled adding pending channel")
×
3908

3909
        case <-p.quit:
×
3910
                return lnpeer.ErrPeerExiting
×
3911
        }
3912

3913
        // We pause here to wait for the peer to recognize the new pending
3914
        // channel before we close the channel barrier corresponding to the
3915
        // channel.
3916
        select {
3✔
3917
        case err := <-errChan:
3✔
3918
                return err
3✔
3919

3920
        case <-cancel:
×
3921
                return errors.New("canceled adding pending channel")
×
3922

3923
        case <-p.quit:
×
3924
                return lnpeer.ErrPeerExiting
×
3925
        }
3926
}
3927

3928
// RemovePendingChannel removes a pending open channel from the peer.
3929
//
3930
// NOTE: Part of the lnpeer.Peer interface.
3931
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
3✔
3932
        errChan := make(chan error, 1)
3✔
3933
        newChanMsg := &newChannelMsg{
3✔
3934
                channelID: cid,
3✔
3935
                err:       errChan,
3✔
3936
        }
3✔
3937

3✔
3938
        select {
3✔
3939
        case p.removePendingChannel <- newChanMsg:
3✔
3940
        case <-p.quit:
×
3941
                return lnpeer.ErrPeerExiting
×
3942
        }
3943

3944
        // We pause here to wait for the peer to respond to the cancellation of
3945
        // the pending channel before we close the channel barrier
3946
        // corresponding to the channel.
3947
        select {
3✔
3948
        case err := <-errChan:
3✔
3949
                return err
3✔
3950

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

3956
// StartTime returns the time at which the connection was established if the
3957
// peer started successfully, and zero otherwise.
3958
func (p *Brontide) StartTime() time.Time {
3✔
3959
        return p.startTime
3✔
3960
}
3✔
3961

3962
// handleCloseMsg is called when a new cooperative channel closure related
3963
// message is received from the remote peer. We'll use this message to advance
3964
// the chan closer state machine.
3965
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
16✔
3966
        link := p.fetchLinkFromKeyAndCid(msg.cid)
16✔
3967

16✔
3968
        // We'll now fetch the matching closing state machine in order to continue,
16✔
3969
        // or finalize the channel closure process.
16✔
3970
        chanCloser, err := p.fetchActiveChanCloser(msg.cid)
16✔
3971
        if err != nil {
19✔
3972
                // If the channel is not known to us, we'll simply ignore this message.
3✔
3973
                if err == ErrChannelNotFound {
6✔
3974
                        return
3✔
3975
                }
3✔
3976

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

×
3979
                errMsg := &lnwire.Error{
×
3980
                        ChanID: msg.cid,
×
3981
                        Data:   lnwire.ErrorData(err.Error()),
×
3982
                }
×
3983
                p.queueMsg(errMsg, nil)
×
3984
                return
×
3985
        }
3986

3987
        handleErr := func(err error) {
17✔
3988
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
3989
                p.log.Error(err)
1✔
3990

1✔
3991
                // As the negotiations failed, we'll reset the channel state machine to
1✔
3992
                // ensure we act to on-chain events as normal.
1✔
3993
                chanCloser.Channel().ResetState()
1✔
3994

1✔
3995
                if chanCloser.CloseRequest() != nil {
1✔
3996
                        chanCloser.CloseRequest().Err <- err
×
3997
                }
×
3998
                delete(p.activeChanCloses, msg.cid)
1✔
3999

1✔
4000
                p.Disconnect(err)
1✔
4001
        }
4002

4003
        // Next, we'll process the next message using the target state machine.
4004
        // We'll either continue negotiation, or halt.
4005
        switch typed := msg.msg.(type) {
16✔
4006
        case *lnwire.Shutdown:
8✔
4007
                // Disable incoming adds immediately.
8✔
4008
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
8✔
4009
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
4010
                                link.ChanID())
×
4011
                }
×
4012

4013
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
8✔
4014
                if err != nil {
8✔
4015
                        handleErr(err)
×
4016
                        return
×
4017
                }
×
4018

4019
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
14✔
4020
                        // If the link is nil it means we can immediately queue
6✔
4021
                        // the Shutdown message since we don't have to wait for
6✔
4022
                        // commitment transaction synchronization.
6✔
4023
                        if link == nil {
7✔
4024
                                p.queueMsg(&msg, nil)
1✔
4025
                                return
1✔
4026
                        }
1✔
4027

4028
                        // Immediately disallow any new HTLC's from being added
4029
                        // in the outgoing direction.
4030
                        if !link.DisableAdds(htlcswitch.Outgoing) {
5✔
4031
                                p.log.Warnf("Outgoing link adds already "+
×
4032
                                        "disabled: %v", link.ChanID())
×
4033
                        }
×
4034

4035
                        // When we have a Shutdown to send, we defer it till the
4036
                        // next time we send a CommitSig to remain spec
4037
                        // compliant.
4038
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
10✔
4039
                                p.queueMsg(&msg, nil)
5✔
4040
                        })
5✔
4041
                })
4042

4043
                beginNegotiation := func() {
16✔
4044
                        oClosingSigned, err := chanCloser.BeginNegotiation()
8✔
4045
                        if err != nil {
9✔
4046
                                handleErr(err)
1✔
4047
                                return
1✔
4048
                        }
1✔
4049

4050
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
14✔
4051
                                p.queueMsg(&msg, nil)
7✔
4052
                        })
7✔
4053
                }
4054

4055
                if link == nil {
9✔
4056
                        beginNegotiation()
1✔
4057
                } else {
8✔
4058
                        // Now we register a flush hook to advance the
7✔
4059
                        // ChanCloser and possibly send out a ClosingSigned
7✔
4060
                        // when the link finishes draining.
7✔
4061
                        link.OnFlushedOnce(func() {
14✔
4062
                                // Remove link in goroutine to prevent deadlock.
7✔
4063
                                go p.cfg.Switch.RemoveLink(msg.cid)
7✔
4064
                                beginNegotiation()
7✔
4065
                        })
7✔
4066
                }
4067

4068
        case *lnwire.ClosingSigned:
11✔
4069
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
11✔
4070
                if err != nil {
11✔
4071
                        handleErr(err)
×
4072
                        return
×
4073
                }
×
4074

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

4079
        default:
×
4080
                panic("impossible closeMsg type")
×
4081
        }
4082

4083
        // If we haven't finished close negotiations, then we'll continue as we
4084
        // can't yet finalize the closure.
4085
        if _, err := chanCloser.ClosingTx(); err != nil {
26✔
4086
                return
11✔
4087
        }
11✔
4088

4089
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
4090
        // the channel closure by notifying relevant sub-systems and launching a
4091
        // goroutine to wait for close tx conf.
4092
        p.finalizeChanClosure(chanCloser)
7✔
4093
}
4094

4095
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
4096
// the channelManager goroutine, which will shut down the link and possibly
4097
// close the channel.
4098
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
3✔
4099
        select {
3✔
4100
        case p.localCloseChanReqs <- req:
3✔
4101
                p.log.Info("Local close channel request is going to be " +
3✔
4102
                        "delivered to the peer")
3✔
4103
        case <-p.quit:
×
4104
                p.log.Info("Unable to deliver local close channel request " +
×
4105
                        "to peer")
×
4106
        }
4107
}
4108

4109
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
4110
func (p *Brontide) NetAddress() *lnwire.NetAddress {
3✔
4111
        return p.cfg.Addr
3✔
4112
}
3✔
4113

4114
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
4115
func (p *Brontide) Inbound() bool {
3✔
4116
        return p.cfg.Inbound
3✔
4117
}
3✔
4118

4119
// ConnReq is a getter for the Brontide's connReq in cfg.
4120
func (p *Brontide) ConnReq() *connmgr.ConnReq {
3✔
4121
        return p.cfg.ConnReq
3✔
4122
}
3✔
4123

4124
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
4125
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
3✔
4126
        return p.cfg.ErrorBuffer
3✔
4127
}
3✔
4128

4129
// SetAddress sets the remote peer's address given an address.
4130
func (p *Brontide) SetAddress(address net.Addr) {
×
4131
        p.cfg.Addr.Address = address
×
4132
}
×
4133

4134
// ActiveSignal returns the peer's active signal.
4135
func (p *Brontide) ActiveSignal() chan struct{} {
3✔
4136
        return p.activeSignal
3✔
4137
}
3✔
4138

4139
// Conn returns a pointer to the peer's connection struct.
4140
func (p *Brontide) Conn() net.Conn {
3✔
4141
        return p.cfg.Conn
3✔
4142
}
3✔
4143

4144
// BytesReceived returns the number of bytes received from the peer.
4145
func (p *Brontide) BytesReceived() uint64 {
3✔
4146
        return atomic.LoadUint64(&p.bytesReceived)
3✔
4147
}
3✔
4148

4149
// BytesSent returns the number of bytes sent to the peer.
4150
func (p *Brontide) BytesSent() uint64 {
3✔
4151
        return atomic.LoadUint64(&p.bytesSent)
3✔
4152
}
3✔
4153

4154
// LastRemotePingPayload returns the last payload the remote party sent as part
4155
// of their ping.
4156
func (p *Brontide) LastRemotePingPayload() []byte {
3✔
4157
        pingPayload := p.lastPingPayload.Load()
3✔
4158
        if pingPayload == nil {
6✔
4159
                return []byte{}
3✔
4160
        }
3✔
4161

4162
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
2✔
4163
        if !ok {
2✔
4164
                return nil
×
4165
        }
×
4166

4167
        return pingBytes
2✔
4168
}
4169

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

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

4191
        p.channelEventClient = sub
6✔
4192

6✔
4193
        return nil
6✔
4194
}
4195

4196
// updateNextRevocation updates the existing channel's next revocation if it's
4197
// nil.
4198
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
6✔
4199
        chanPoint := c.FundingOutpoint
6✔
4200
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
6✔
4201

6✔
4202
        // Read the current channel.
6✔
4203
        currentChan, loaded := p.activeChannels.Load(chanID)
6✔
4204

6✔
4205
        // currentChan should exist, but we perform a check anyway to avoid nil
6✔
4206
        // pointer dereference.
6✔
4207
        if !loaded {
7✔
4208
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
4209
                        chanID)
1✔
4210
        }
1✔
4211

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

4219
        // If we're being sent a new channel, and our existing channel doesn't
4220
        // have the next revocation, then we need to update the current
4221
        // existing channel.
4222
        if currentChan.RemoteNextRevocation() != nil {
4✔
4223
                return nil
×
4224
        }
×
4225

4226
        p.log.Infof("Processing retransmitted ChannelReady for "+
4✔
4227
                "ChannelPoint(%v)", chanPoint)
4✔
4228

4✔
4229
        nextRevoke := c.RemoteNextRevocation
4✔
4230

4✔
4231
        err := currentChan.InitNextRevocation(nextRevoke)
4✔
4232
        if err != nil {
4✔
4233
                return fmt.Errorf("unable to init next revocation: %w", err)
×
4234
        }
×
4235

4236
        return nil
4✔
4237
}
4238

4239
// addActiveChannel adds a new active channel to the `activeChannels` map. It
4240
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
4241
// it and assembles it with a channel link.
4242
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
3✔
4243
        chanPoint := c.FundingOutpoint
3✔
4244
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4245

3✔
4246
        // If we've reached this point, there are two possible scenarios.  If
3✔
4247
        // the channel was in the active channels map as nil, then it was
3✔
4248
        // loaded from disk and we need to send reestablish. Else, it was not
3✔
4249
        // loaded from disk and we don't need to send reestablish as this is a
3✔
4250
        // fresh channel.
3✔
4251
        shouldReestablish := p.isLoadedFromDisk(chanID)
3✔
4252

3✔
4253
        chanOpts := c.ChanOpts
3✔
4254
        if shouldReestablish {
6✔
4255
                // If we have to do the reestablish dance for this channel,
3✔
4256
                // ensure that we don't try to call InitRemoteMusigNonces twice
3✔
4257
                // by calling SkipNonceInit.
3✔
4258
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
3✔
4259
        }
3✔
4260

4261
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
3✔
4262
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
4263
        })
×
4264
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
3✔
4265
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
4266
        })
×
4267
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
3✔
4268
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
4269
        })
×
4270

4271
        // If not already active, we'll add this channel to the set of active
4272
        // channels, so we can look it up later easily according to its channel
4273
        // ID.
4274
        lnChan, err := lnwallet.NewLightningChannel(
3✔
4275
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
3✔
4276
        )
3✔
4277
        if err != nil {
3✔
4278
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
4279
        }
×
4280

4281
        // Store the channel in the activeChannels map.
4282
        p.activeChannels.Store(chanID, lnChan)
3✔
4283

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

3✔
4286
        // Next, we'll assemble a ChannelLink along with the necessary items it
3✔
4287
        // needs to function.
3✔
4288
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
3✔
4289
        if err != nil {
3✔
4290
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
4291
                        err)
×
4292
        }
×
4293

4294
        // We'll query the channel DB for the new channel's initial forwarding
4295
        // policies to determine the policy we start out with.
4296
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
3✔
4297
        if err != nil {
3✔
4298
                return fmt.Errorf("unable to query for initial forwarding "+
×
4299
                        "policy: %v", err)
×
4300
        }
×
4301

4302
        // Create the link and add it to the switch.
4303
        err = p.addLink(
3✔
4304
                &chanPoint, lnChan, initialPolicy, chainEvents,
3✔
4305
                shouldReestablish, fn.None[lnwire.Shutdown](),
3✔
4306
        )
3✔
4307
        if err != nil {
3✔
4308
                return fmt.Errorf("can't register new channel link(%v) with "+
×
4309
                        "peer", chanPoint)
×
4310
        }
×
4311

4312
        return nil
3✔
4313
}
4314

4315
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
4316
// know this channel ID or not, we'll either add it to the `activeChannels` map
4317
// or init the next revocation for it.
4318
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
3✔
4319
        newChan := req.channel
3✔
4320
        chanPoint := newChan.FundingOutpoint
3✔
4321
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4322

3✔
4323
        // Only update RemoteNextRevocation if the channel is in the
3✔
4324
        // activeChannels map and if we added the link to the switch. Only
3✔
4325
        // active channels will be added to the switch.
3✔
4326
        if p.isActiveChannel(chanID) {
6✔
4327
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
3✔
4328
                        chanPoint)
3✔
4329

3✔
4330
                // Handle it and close the err chan on the request.
3✔
4331
                close(req.err)
3✔
4332

3✔
4333
                // Update the next revocation point.
3✔
4334
                err := p.updateNextRevocation(newChan.OpenChannel)
3✔
4335
                if err != nil {
3✔
4336
                        p.log.Errorf(err.Error())
×
4337
                }
×
4338

4339
                return
3✔
4340
        }
4341

4342
        // This is a new channel, we now add it to the map.
4343
        if err := p.addActiveChannel(req.channel); err != nil {
3✔
4344
                // Log and send back the error to the request.
×
4345
                p.log.Errorf(err.Error())
×
4346
                req.err <- err
×
4347

×
4348
                return
×
4349
        }
×
4350

4351
        // Close the err chan if everything went fine.
4352
        close(req.err)
3✔
4353
}
4354

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

7✔
4362
        chanID := req.channelID
7✔
4363

7✔
4364
        // If we already have this channel, something is wrong with the funding
7✔
4365
        // flow as it will only be marked as active after `ChannelReady` is
7✔
4366
        // handled. In this case, we will do nothing but log an error, just in
7✔
4367
        // case this is a legit channel.
7✔
4368
        if p.isActiveChannel(chanID) {
8✔
4369
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
4370
                        "pending channel request", chanID)
1✔
4371

1✔
4372
                return
1✔
4373
        }
1✔
4374

4375
        // The channel has already been added, we will do nothing and return.
4376
        if p.isPendingChannel(chanID) {
7✔
4377
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
4378
                        "pending channel request", chanID)
1✔
4379

1✔
4380
                return
1✔
4381
        }
1✔
4382

4383
        // This is a new channel, we now add it to the map `activeChannels`
4384
        // with nil value and mark it as a newly added channel in
4385
        // `addedChannels`.
4386
        p.activeChannels.Store(chanID, nil)
5✔
4387
        p.addedChannels.Store(chanID, struct{}{})
5✔
4388
}
4389

4390
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
4391
// from `activeChannels` map. The request will be ignored if the channel is
4392
// considered active by Brontide. Noop if the channel ID cannot be found.
4393
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
7✔
4394
        defer close(req.err)
7✔
4395

7✔
4396
        chanID := req.channelID
7✔
4397

7✔
4398
        // If we already have this channel, something is wrong with the funding
7✔
4399
        // flow as it will only be marked as active after `ChannelReady` is
7✔
4400
        // handled. In this case, we will log an error and exit.
7✔
4401
        if p.isActiveChannel(chanID) {
8✔
4402
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
4403
                        chanID)
1✔
4404
                return
1✔
4405
        }
1✔
4406

4407
        // The channel has not been added yet, we will log a warning as there
4408
        // is an unexpected call from funding manager.
4409
        if !p.isPendingChannel(chanID) {
10✔
4410
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
4✔
4411
        }
4✔
4412

4413
        // Remove the record of this pending channel.
4414
        p.activeChannels.Delete(chanID)
6✔
4415
        p.addedChannels.Delete(chanID)
6✔
4416
}
4417

4418
// sendLinkUpdateMsg sends a message that updates the channel to the
4419
// channel's message stream.
4420
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
3✔
4421
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
3✔
4422

3✔
4423
        chanStream, ok := p.activeMsgStreams[cid]
3✔
4424
        if !ok {
6✔
4425
                // If a stream hasn't yet been created, then we'll do so, add
3✔
4426
                // it to the map, and finally start it.
3✔
4427
                chanStream = newChanMsgStream(p, cid)
3✔
4428
                p.activeMsgStreams[cid] = chanStream
3✔
4429
                chanStream.Start()
3✔
4430

3✔
4431
                // Stop the stream when quit.
3✔
4432
                go func() {
6✔
4433
                        <-p.quit
3✔
4434
                        chanStream.Stop()
3✔
4435
                }()
3✔
4436
        }
4437

4438
        // With the stream obtained, add the message to the stream so we can
4439
        // continue processing message.
4440
        chanStream.AddMsg(msg)
3✔
4441
}
4442

4443
// scaleTimeout multiplies the argument duration by a constant factor depending
4444
// on variious heuristics. Currently this is only used to check whether our peer
4445
// appears to be connected over Tor and relaxes the timout deadline. However,
4446
// this is subject to change and should be treated as opaque.
4447
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
70✔
4448
        if p.isTorConnection {
73✔
4449
                return timeout * time.Duration(torTimeoutMultiplier)
3✔
4450
        }
3✔
4451

4452
        return timeout
67✔
4453
}
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