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

lightningnetwork / lnd / 12456011944

22 Dec 2024 04:45PM UTC coverage: 58.556% (-0.04%) from 58.598%
12456011944

Pull #9232

github

Abdulkbk
chanbackup: test archiving chan backups
Pull Request #9232: chanbackup: archive old channel backups

46 of 58 new or added lines in 2 files covered. (79.31%)

324 existing lines in 30 files now uncovered.

134919 of 230410 relevant lines covered (58.56%)

19202.13 hits per line

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

76.15
/peer/brontide.go
1
package peer
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

121
        err chan error
122
}
123

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

463
        pingManager *PingManager
464

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

472
        cfg Config
473

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

27✔
630
        var (
27✔
631
                lastBlockHeader           *wire.BlockHeader
27✔
632
                lastSerializedBlockHeader [wire.MaxBlockHeaderPayload]byte
27✔
633
        )
27✔
634
        newPingPayload := func() []byte {
27✔
635
                // We query the BestBlockHeader from our BestBlockView each time
27✔
636
                // this is called, and update our serialized block header if
29✔
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()
642
                if err != nil && header == lastBlockHeader {
27✔
643
                        return lastSerializedBlockHeader[:]
27✔
644
                }
27✔
645

27✔
646
                buf := bytes.NewBuffer(lastSerializedBlockHeader[0:0])
27✔
647
                err = header.Serialize(buf)
×
648
                if err == nil {
×
649
                        lastBlockHeader = header
×
650
                } else {
×
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[:]
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 {
×
666
                return uint16(
×
667
                        // We don't need cryptographic randomness here.
×
668
                        /* #nosec */
669
                        rand.Intn(pongSizeCeiling) + 1,
×
670
                )
671
        }
672

673
        p.pingManager = NewPingManager(&PingManagerConfig{
674
                NewPingPayload:   newPingPayload,
675
                NewPongSize:      randPongSize,
676
                IntervalDuration: p.scaleTimeout(pingInterval),
677
                TimeoutDuration:  p.scaleTimeout(pingTimeout),
27✔
678
                SendPing: func(ping *lnwire.Ping) {
×
679
                        p.queueMsg(ping, nil)
×
680
                },
×
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))
27✔
686
                },
27✔
687
        })
27✔
688

27✔
689
        return p
27✔
690
}
27✔
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 {
×
695
        if atomic.AddInt32(&p.started, 1) != 1 {
×
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.
27✔
702
        defer close(p.startReady)
703

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

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

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

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

730
                haveLegacyChan = true
8✔
731
                break
3✔
732
        }
3✔
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 {
5✔
737
                return fmt.Errorf("unable to send init msg: %w", err)
9✔
738
        }
8✔
739

4✔
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.
2✔
743
        readErr := make(chan error, 1)
2✔
744
        msgChan := make(chan lnwire.Message, 1)
745
        p.wg.Add(1)
746
        go func() {
747
                defer p.wg.Done()
748

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

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

771
        // Once the init message arrives, we can parse it so we can figure out
5✔
772
        // the negotiation of features for this session.
773
        msg := <-msgChan
774
        if msg, ok := msg.(*lnwire.Init); ok {
×
775
                if err := p.handleInitMsg(msg); err != nil {
×
776
                        p.storeError(err)
×
777
                        return err
5✔
778
                }
5✔
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
5✔
786
        // goroutines required to operate them.
10✔
787
        p.log.Debugf("Loaded %v active channels from database",
5✔
788
                len(activeChans))
×
789

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

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

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

×
812
        p.startTime = time.Now()
813

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

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

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

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

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

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

5✔
860
        return nil
5✔
861
}
5✔
862

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

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

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

891
// taprootShutdownAllowed returns true if both parties have negotiated the
892
// shutdown-any-segwit feature.
893
func (p *Brontide) taprootShutdownAllowed() bool {
894
        return p.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
895
                p.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
896
}
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
2✔
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{} {
905
        return p.quit
8✔
906
}
8✔
907

8✔
908
// addrWithInternalKey takes a delivery script, then attempts to supplement it
8✔
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) {
913

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

11✔
925
        return &chancloser.DeliveryAddrWithKey{
11✔
926
                DeliveryAddress: deliveryScript,
11✔
927
                InternalKey: fn.MapOption(
11✔
928
                        func(desc keychain.KeyDescriptor) btcec.PublicKey {
11✔
929
                                return *desc.PubKey
11✔
930
                        },
11✔
931
                )(internalKeyDesc),
11✔
932
        }, nil
11✔
933
}
11✔
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
11✔
938
// channels that haven't been closed yet.
11✔
939
func (p *Brontide) loadActiveChannels(chans []*channeldb.OpenChannel) (
11✔
940
        []lnwire.Message, error) {
13✔
941

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

946
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
947

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

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

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

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

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

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

2✔
995
                        // If we've negotiated the option-scid-alias feature
2✔
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.
2✔
1000
                        err := dbChan.MarkScidAliasNegotiated()
2✔
1001
                        if err != nil {
2✔
1002
                                return nil, err
2✔
1003
                        }
2✔
1004
                }
2✔
1005

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

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

×
1029
                chanPoint := dbChan.FundingOutpoint
×
1030

×
1031
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
1032

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

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

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

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

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

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

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

4✔
1075
                                if shutdownMsg == nil {
4✔
1076
                                        continue
4✔
1077
                                }
4✔
1078

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

×
1084
                        continue
×
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
1091
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
1092
                        &chanPoint,
1093
                )
×
1094
                if err != nil && !errors.Is(err, channeldb.ErrEdgeNotFound) {
1095
                        return nil, err
1096
                }
4✔
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
                //
2✔
1103
                // TODO(roasbeef): can add helper method to get policy for
2✔
1104
                // particular channel.
2✔
1105
                var selfPolicy *models.ChannelEdgePolicy
2✔
1106
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
2✔
1107
                        p.cfg.ServerPubKey[:]) {
×
1108

×
1109
                        selfPolicy = p1
1110
                } else {
1111
                        selfPolicy = p2
1112
                }
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
2✔
1118
                if selfPolicy != nil {
2✔
1119
                        var inboundWireFee lnwire.Fee
4✔
1120
                        _, err := selfPolicy.ExtraOpaqueData.ExtractRecords(
2✔
1121
                                &inboundWireFee,
2✔
1122
                        )
4✔
1123
                        if err != nil {
2✔
1124
                                return nil, err
2✔
1125
                        }
1126

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

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

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

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

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

1159
                        continue
2✔
1160
                }
2✔
1161

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

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

2✔
1180
                                return
2✔
1181
                        }
2✔
1182

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

2✔
1198
                                return
2✔
1199
                        }
×
1200

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

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

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

1213
                                return
2✔
1214
                        }
2✔
1215

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

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

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

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

1242
        return msgs, nil
2✔
1243
}
2✔
1244

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

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

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

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

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

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

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

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

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

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

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

2✔
1351
                hasConfirmedPublicChan = true
1352
                break
1353
        }
1354
        if !hasConfirmedPublicChan {
1355
                return
5✔
1356
        }
5✔
1357

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

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

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

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

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

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

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

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

2✔
1401
                // Now that we know the channel is in a good state, we'll try
2✔
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
4✔
1404
                // an error here which we'll ignore.
8✔
1405
                chanUpd, err := p.cfg.FetchLastChanUpdate(scid)
4✔
1406
                if err != nil {
1407
                        p.log.Debugf("Unable to fetch channel update for "+
1408
                                "ChannelPoint(%v), scid=%v: %v",
2✔
1409
                                dbChan.FundingOutpoint, dbChan.ShortChanID, err)
2✔
1410

1411
                        return nil
1412
                }
4✔
1413

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

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

2✔
1426
                        return err
2✔
1427
                }
2✔
1428

2✔
1429
                return nil
1430
        }
4✔
1431

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

4✔
1435
// WaitForDisconnect waits until the peer has disconnected. A peer may be
4✔
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{}) {
×
1444
        // Before we try to call the `Wait` goroutine, we'll make sure the main
1445
        // set of goroutines are already active.
4✔
1446
        select {
1447
        case <-p.startReady:
1448
        case <-p.quit:
4✔
1449
                return
1450
        }
1451

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

1457
        p.wg.Wait()
1458
}
1459

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

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

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

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

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

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

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

2✔
1495
        close(p.quit)
×
1496

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

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

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

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

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

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

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

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

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

6✔
1576
        return nextMsg, nil
6✔
1577
}
8✔
1578

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

8✔
1587
        peer *Brontide
2✔
1588

2✔
1589
        apply func(lnwire.Message)
1590

6✔
1591
        startMsg string
6✔
1592
        stopMsg  string
6✔
1593

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

1597
        mtx sync.Mutex
1598

1599
        producerSema chan struct{}
1600

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

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

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

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

5✔
1631
        return stream
5✔
1632
}
5✔
1633

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

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

3,007✔
1644
        close(ms.quit)
3,002✔
1645

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2✔
1785
                        chanPoint := event.ChannelPoint
2✔
1786

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

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

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

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

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

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

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

2✔
1837
                chanLink.HandleChannelUpdate(msg)
2✔
1838
        }
4✔
1839

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1988
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
×
1989

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

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

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

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

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

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

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

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

2✔
2057
                        discStream.AddMsg(msg)
4✔
2058

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

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

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

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

2082
                idleTimer.Reset(idleTimeout)
×
2083
        }
×
2084

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

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

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

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

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

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

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

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

×
2132
        return channel != nil
×
2133
}
2134

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

10✔
2144
        return channel == nil
10✔
2145
}
10✔
2146

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

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

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

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

2170
                haveChannels = true
2171

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

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

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

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

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

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

2209
                return false
2210

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

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

×
2221
        default:
×
2222
                return false
×
2223
        }
×
2224
}
2225

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2✔
2396
                preposition := "to"
2397
                if read {
2398
                        preposition = "from"
×
2399
                }
2400

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

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

2412
        prefix := "readMessage from peer"
21✔
2413
        if !read {
2✔
2414
                prefix = "writeMessage to peer"
2✔
2415
        }
4✔
2416

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

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

34✔
2437
        noiseConn := p.cfg.Conn
15✔
2438

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

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

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

2460
                return err
15✔
2461
        }
15✔
2462

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

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

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

15✔
2490
        return flushMsg()
×
2491
}
×
2492

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

15✔
2508
        var exitErr error
2509

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

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

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

6✔
2539
                                goto retry
6✔
2540
                        }
6✔
2541

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2707
                return nil
2✔
2708
        })
2✔
2709

2✔
2710
        return snapshots
2✔
2711
}
2✔
2712

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2✔
2829
                                lc.ResetState()
2✔
2830

2✔
2831
                                return nil
2✔
2832
                        })
2✔
2833

2✔
2834
                        break out
2✔
2835
                }
2✔
2836
        }
4✔
2837
}
2✔
2838

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

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

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

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

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

2✔
2868
                        continue
2✔
2869

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

2887
                                continue
2✔
2888
                        }
2✔
2889

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

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

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

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

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

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

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

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

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

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

2971
        p.activeChanCloses[chanID] = chanCloser
2972

2973
        return chanCloser, nil
2974
}
5✔
2975

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

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

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

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

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

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

2✔
3009
                return true
4✔
3010
        })
2✔
3011

2✔
3012
        return activePublicChans
3013
}
2✔
3014

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

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

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

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

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

×
3050
                return nil
×
3051
        }
×
3052

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

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

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

×
3078
                                continue
×
3079
                        }
×
3080

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

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

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

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

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

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

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

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

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

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

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

3161
        var deliveryScript []byte
3162

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

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

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

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

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

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

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

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

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

×
3232
        return shutdownMsg, nil
×
3233
}
×
3234

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

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

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

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

11✔
3280
        return chanCloser, nil
11✔
3281
}
11✔
3282

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

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

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

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

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

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

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

5✔
3350
                p.activeChanCloses[chanID] = chanCloser
×
3351

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2✔
3502
        var chanLink htlcswitch.ChannelUpdateHandler
2✔
3503

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

3514
        return chanLink
3515
}
2✔
3516

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3630
        p.activeChannels.Delete(chanID)
3631

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

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

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

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

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

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

5✔
3675
        return nil
5✔
3676
}
5✔
3677

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
3779
        return nil
×
3780
}
×
3781

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

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

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

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

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

3✔
3843
        return nil
3✔
3844
}
3✔
3845

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

12✔
4051
                beginNegotiation := func() {
5✔
4052
                        oClosingSigned, err := chanCloser.BeginNegotiation()
5✔
4053
                        if err != nil {
5✔
4054
                                handleErr(err)
6✔
4055
                                return
1✔
4056
                        }
1✔
4057

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

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

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

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

8✔
4087
        default:
1✔
4088
                panic("impossible closeMsg type")
7✔
4089
        }
6✔
4090

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4175
        return pingBytes
4176
}
2✔
4177

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

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

×
4199
        p.channelEventClient = sub
4200

4201
        return nil
4202
}
4203

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

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

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

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

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

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

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

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

4244
        return nil
4245
}
5✔
4246

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

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

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

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

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

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

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

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

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

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

2✔
4320
        return nil
2✔
4321
}
×
4322

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

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

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

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

4347
                return
4348
        }
4349

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

2✔
4356
                return
2✔
4357
        }
4✔
4358

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

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

4370
        chanID := req.channelID
2✔
4371

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

×
4380
                return
×
4381
        }
4382

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

4388
                return
4389
        }
4390

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

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

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

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

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

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

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

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

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

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

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

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