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

lightningnetwork / lnd / 12041760086

27 Nov 2024 01:02AM UTC coverage: 59.001% (+0.002%) from 58.999%
12041760086

Pull #9242

github

aakselrod
github workflow: save postgres log to zip file
Pull Request #9242: Reapply #8644

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

82 existing lines in 18 files now uncovered.

133176 of 225719 relevant lines covered (59.0%)

19559.01 hits per line

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

77.9
/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
        // ShouldFwdExpEndorsement is a closure that indicates whether
428
        // experimental endorsement signals should be set.
429
        ShouldFwdExpEndorsement func() bool
430

431
        // Quit is the server's quit channel. If this is closed, we halt operation.
432
        Quit chan struct{}
433
}
434

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

446
        // MUST be used atomically.
447
        bytesReceived uint64
448
        bytesSent     uint64
449

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

467
        pingManager *PingManager
468

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

476
        cfg Config
477

478
        // activeSignal when closed signals that the peer is now active and
479
        // ready to process messages.
480
        activeSignal chan struct{}
481

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

486
        // sendQueue is the channel which is used to queue outgoing messages to be
487
        // written onto the wire. Note that this channel is unbuffered.
488
        sendQueue chan outgoingMsg
489

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

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

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

513
        // newActiveChannel is used by the fundingManager to send fully opened
514
        // channels to the source peer which handled the funding workflow.
515
        newActiveChannel chan *newChannelMsg
516

517
        // newPendingChannel is used by the fundingManager to send pending open
518
        // channels to the source peer which handled the funding workflow.
519
        newPendingChannel chan *newChannelMsg
520

521
        // removePendingChannel is used by the fundingManager to cancel pending
522
        // open channels to the source peer when the funding flow is failed.
523
        removePendingChannel chan *newChannelMsg
524

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

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

535
        // localCloseChanReqs is a channel in which any local requests to close
536
        // a particular channel are sent over.
537
        localCloseChanReqs chan *htlcswitch.ChanClose
538

539
        // linkFailures receives all reported channel failures from the switch,
540
        // and instructs the channelManager to clean remaining channel state.
541
        linkFailures chan linkFailureReport
542

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

548
        // remoteFeatures is the feature vector received from the peer during
549
        // the connection handshake.
550
        remoteFeatures *lnwire.FeatureVector
551

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

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

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

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

576
        startReady chan struct{}
577
        quit       chan struct{}
578
        wg         sync.WaitGroup
579

580
        // log is a peer-specific logging instance.
581
        log btclog.Logger
582
}
583

584
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer interface.
585
var _ lnpeer.Peer = (*Brontide)(nil)
586

587
// NewBrontide creates a new Brontide from a peer.Config struct.
588
func NewBrontide(cfg Config) *Brontide {
29✔
589
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
29✔
590

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

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

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

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

29✔
628
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
33✔
629
                remoteAddr := cfg.Conn.RemoteAddr().String()
4✔
630
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
4✔
631
                        strings.Contains(remoteAddr, "127.0.0.1")
4✔
632
        }
4✔
633

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

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

661
                return lastSerializedBlockHeader[:]
2✔
662
        }
663

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

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

693
        return p
29✔
694
}
695

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

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

7✔
708
        p.log.Tracef("starting with conn[%v->%v]",
7✔
709
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
7✔
710

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

722
        if len(activeChans) == 0 {
12✔
723
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
5✔
724
        }
5✔
725

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

734
                haveLegacyChan = true
4✔
735
                break
4✔
736
        }
737

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

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

7✔
753
                msg, err := p.readNextMessage()
7✔
754
                if err != nil {
7✔
UNCOV
755
                        readErr <- err
×
UNCOV
756
                        msgChan <- nil
×
UNCOV
757
                        return
×
UNCOV
758
                }
×
759
                readErr <- nil
7✔
760
                msgChan <- msg
7✔
761
        }()
762

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

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

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

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

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

811
        msgs, err := p.loadActiveChannels(activeChans)
7✔
812
        if err != nil {
7✔
813
                return fmt.Errorf("unable to load channels: %w", err)
×
814
        }
×
815

816
        p.startTime = time.Now()
7✔
817

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

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

835
        err = p.pingManager.Start()
7✔
836
        if err != nil {
7✔
837
                return fmt.Errorf("could not start ping manager %w", err)
×
838
        }
×
839

840
        p.wg.Add(4)
7✔
841
        go p.queueHandler()
7✔
842
        go p.writeHandler()
7✔
843
        go p.channelManager()
7✔
844
        go p.readHandler()
7✔
845

7✔
846
        // Signal to any external processes that the peer is now active.
7✔
847
        close(p.activeSignal)
7✔
848

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

7✔
864
        return nil
7✔
865
}
866

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

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

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

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

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

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

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

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

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

7✔
946
        // Return a slice of messages to send to the peers in case the channel
7✔
947
        // cannot be loaded normally.
7✔
948
        var msgs []lnwire.Message
7✔
949

7✔
950
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
7✔
951

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

972
                                err = p.cfg.AddLocalAlias(
4✔
973
                                        aliasScid, dbChan.ShortChanID(), false,
4✔
974
                                        false,
4✔
975
                                )
4✔
976
                                if err != nil {
4✔
977
                                        return nil, err
×
978
                                }
×
979

980
                                chanID := lnwire.NewChanIDFromOutPoint(
4✔
981
                                        dbChan.FundingOutpoint,
4✔
982
                                )
4✔
983

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

991
                                channelReadyMsg := lnwire.NewChannelReady(
4✔
992
                                        chanID, second,
4✔
993
                                )
4✔
994
                                channelReadyMsg.AliasScid = &aliasScid
4✔
995

4✔
996
                                msgs = append(msgs, channelReadyMsg)
4✔
997
                        }
998

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

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

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

1033
                chanPoint := dbChan.FundingOutpoint
6✔
1034

6✔
1035
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
6✔
1036

6✔
1037
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
6✔
1038
                        chanPoint, lnChan.IsPending())
6✔
1039

6✔
1040
                // Skip adding any permanently irreconcilable channels to the
6✔
1041
                // htlcswitch.
6✔
1042
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
6✔
1043
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
12✔
1044

6✔
1045
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
6✔
1046
                                "start.", chanPoint, dbChan.ChanStatus())
6✔
1047

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

1062
                        msgs = append(msgs, chanSync)
6✔
1063

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

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

1079
                                if shutdownMsg == nil {
×
1080
                                        continue
×
1081
                                }
1082

1083
                                // Append the message to the set of messages to
1084
                                // send.
1085
                                msgs = append(msgs, shutdownMsg)
×
1086
                        }
1087

1088
                        continue
6✔
1089
                }
1090

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

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

4✔
1113
                        selfPolicy = p1
4✔
1114
                } else {
8✔
1115
                        selfPolicy = p2
4✔
1116
                }
4✔
1117

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

1131
                        inboundFee := models.NewInboundFeeFromWire(
4✔
1132
                                inboundWireFee,
4✔
1133
                        )
4✔
1134

4✔
1135
                        forwardingPolicy = &models.ForwardingPolicy{
4✔
1136
                                MinHTLCOut:    selfPolicy.MinHTLC,
4✔
1137
                                MaxHTLC:       selfPolicy.MaxHTLC,
4✔
1138
                                BaseFee:       selfPolicy.FeeBaseMSat,
4✔
1139
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
4✔
1140
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
4✔
1141

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

1151
                p.log.Tracef("Using link policy of: %v",
4✔
1152
                        spew.Sdump(forwardingPolicy))
4✔
1153

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

4✔
1163
                        continue
4✔
1164
                }
1165

1166
                shutdownInfo, err := lnChan.State().ShutdownInfo()
4✔
1167
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
4✔
1168
                        return nil, err
×
1169
                }
×
1170

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

×
1184
                                return
×
1185
                        }
×
1186

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

×
1202
                                return
×
1203
                        }
×
1204

1205
                        chanID := lnwire.NewChanIDFromOutPoint(
4✔
1206
                                lnChan.State().FundingOutpoint,
4✔
1207
                        )
4✔
1208

4✔
1209
                        p.activeChanCloses[chanID] = chanCloser
4✔
1210

4✔
1211
                        // Create the Shutdown message.
4✔
1212
                        shutdown, err := chanCloser.ShutdownChan()
4✔
1213
                        if err != nil {
4✔
1214
                                delete(p.activeChanCloses, chanID)
×
1215
                                shutdownInfoErr = err
×
1216

×
1217
                                return
×
1218
                        }
×
1219

1220
                        shutdownMsg = fn.Some(*shutdown)
4✔
1221
                })
1222
                if shutdownInfoErr != nil {
4✔
1223
                        return nil, shutdownInfoErr
×
1224
                }
×
1225

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

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

1243
                p.activeChannels.Store(chanID, lnChan)
4✔
1244
        }
1245

1246
        return msgs, nil
7✔
1247
}
1248

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

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

4✔
1262
                failure := linkFailureReport{
4✔
1263
                        chanPoint:   *chanPoint,
4✔
1264
                        chanID:      chanID,
4✔
1265
                        shortChanID: shortChanID,
4✔
1266
                        linkErr:     linkErr,
4✔
1267
                }
4✔
1268

4✔
1269
                select {
4✔
1270
                case p.linkFailures <- failure:
4✔
1271
                case <-p.quit:
×
1272
                case <-p.cfg.Quit:
×
1273
                }
1274
        }
1275

1276
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
8✔
1277
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
4✔
1278
        }
4✔
1279

1280
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
8✔
1281
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
4✔
1282
        }
4✔
1283

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

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

4✔
1336
        // With the channel link created, we'll now notify the htlc switch so
4✔
1337
        // this channel can be used to dispatch local payments and also
4✔
1338
        // passively forward payments.
4✔
1339
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
4✔
1340
}
1341

1342
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1343
// one confirmed public channel exists with them.
1344
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
7✔
1345
        defer p.wg.Done()
7✔
1346

7✔
1347
        hasConfirmedPublicChan := false
7✔
1348
        for _, channel := range channels {
13✔
1349
                if channel.IsPending {
10✔
1350
                        continue
4✔
1351
                }
1352
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
12✔
1353
                        continue
6✔
1354
                }
1355

1356
                hasConfirmedPublicChan = true
4✔
1357
                break
4✔
1358
        }
1359
        if !hasConfirmedPublicChan {
14✔
1360
                return
7✔
1361
        }
7✔
1362

1363
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
4✔
1364
        if err != nil {
4✔
1365
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1366
                return
×
1367
        }
×
1368

1369
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
4✔
1370
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1371
        }
×
1372
}
1373

1374
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1375
// have any active channels with them.
1376
func (p *Brontide) maybeSendChannelUpdates() {
7✔
1377
        defer p.wg.Done()
7✔
1378

7✔
1379
        // If we don't have any active channels, then we can exit early.
7✔
1380
        if p.activeChannels.Len() == 0 {
12✔
1381
                return
5✔
1382
        }
5✔
1383

1384
        maybeSendUpd := func(cid lnwire.ChannelID,
6✔
1385
                lnChan *lnwallet.LightningChannel) error {
12✔
1386

6✔
1387
                // Nil channels are pending, so we'll skip them.
6✔
1388
                if lnChan == nil {
10✔
1389
                        return nil
4✔
1390
                }
4✔
1391

1392
                dbChan := lnChan.State()
6✔
1393
                scid := func() lnwire.ShortChannelID {
12✔
1394
                        switch {
6✔
1395
                        // Otherwise if it's a zero conf channel and confirmed,
1396
                        // then we need to use the "real" scid.
1397
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
4✔
1398
                                return dbChan.ZeroConfRealScid()
4✔
1399

1400
                        // Otherwise, we can use the normal scid.
1401
                        default:
6✔
1402
                                return dbChan.ShortChanID()
6✔
1403
                        }
1404
                }()
1405

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

4✔
1416
                        return nil
4✔
1417
                }
4✔
1418

1419
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
6✔
1420
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
6✔
1421

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

×
1431
                        return err
×
1432
                }
×
1433

1434
                return nil
6✔
1435
        }
1436

1437
        p.activeChannels.ForEach(maybeSendUpd)
6✔
1438
}
1439

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

1457
        select {
4✔
1458
        case <-ready:
4✔
UNCOV
1459
        case <-p.quit:
×
1460
        }
1461

1462
        p.wg.Wait()
4✔
1463
}
1464

1465
// Disconnect terminates the connection with the remote peer. Additionally, a
1466
// signal is sent to the server and htlcSwitch indicating the resources
1467
// allocated to the peer can now be cleaned up.
1468
func (p *Brontide) Disconnect(reason error) {
4✔
1469
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
8✔
1470
                return
4✔
1471
        }
4✔
1472

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

4✔
1482
                select {
4✔
1483
                case <-p.startReady:
4✔
1484
                case <-p.quit:
×
1485
                        return
×
1486
                }
1487
        }
1488

1489
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
4✔
1490
        p.storeError(err)
4✔
1491

4✔
1492
        p.log.Infof(err.Error())
4✔
1493

4✔
1494
        // Stop PingManager before closing TCP connection.
4✔
1495
        p.pingManager.Stop()
4✔
1496

4✔
1497
        // Ensure that the TCP connection is properly closed before continuing.
4✔
1498
        p.cfg.Conn.Close()
4✔
1499

4✔
1500
        close(p.quit)
4✔
1501

4✔
1502
        // If our msg router isn't global (local to this instance), then we'll
4✔
1503
        // stop it. Otherwise, we'll leave it running.
4✔
1504
        if !p.globalMsgRouter {
8✔
1505
                p.msgRouter.WhenSome(func(router msgmux.Router) {
8✔
1506
                        router.Stop()
4✔
1507
                })
4✔
1508
        }
1509
}
1510

1511
// String returns the string representation of this peer.
1512
func (p *Brontide) String() string {
21✔
1513
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
21✔
1514
}
21✔
1515

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

1525
        pktLen, err := noiseConn.ReadNextHeader()
11✔
1526
        if err != nil {
15✔
1527
                return nil, fmt.Errorf("read next header: %w", err)
4✔
1528
        }
4✔
1529

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

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

8✔
1562
                // Next, create a new io.Reader implementation from the raw
8✔
1563
                // message, and use this to decode the message directly from.
8✔
1564
                msgReader := bytes.NewReader(rawMsg)
8✔
1565
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
8✔
1566
                if err != nil {
12✔
1567
                        return err
4✔
1568
                }
4✔
1569

1570
                // At this point, rawMsg and buf will be returned back to the
1571
                // buffer pool for re-use.
1572
                return nil
8✔
1573
        })
1574
        atomic.AddUint64(&p.bytesReceived, msgLen)
8✔
1575
        if err != nil {
12✔
1576
                return nil, err
4✔
1577
        }
4✔
1578

1579
        p.logWireMessage(nextMsg, true)
8✔
1580

8✔
1581
        return nextMsg, nil
8✔
1582
}
1583

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

1592
        peer *Brontide
1593

1594
        apply func(lnwire.Message)
1595

1596
        startMsg string
1597
        stopMsg  string
1598

1599
        msgCond *sync.Cond
1600
        msgs    []lnwire.Message
1601

1602
        mtx sync.Mutex
1603

1604
        producerSema chan struct{}
1605

1606
        wg   sync.WaitGroup
1607
        quit chan struct{}
1608
}
1609

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

7✔
1618
        stream := &msgStream{
7✔
1619
                peer:         p,
7✔
1620
                apply:        apply,
7✔
1621
                startMsg:     startMsg,
7✔
1622
                stopMsg:      stopMsg,
7✔
1623
                producerSema: make(chan struct{}, bufSize),
7✔
1624
                quit:         make(chan struct{}),
7✔
1625
        }
7✔
1626
        stream.msgCond = sync.NewCond(&stream.mtx)
7✔
1627

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

1636
        return stream
7✔
1637
}
1638

1639
// Start starts the chanMsgStream.
1640
func (ms *msgStream) Start() {
7✔
1641
        ms.wg.Add(1)
7✔
1642
        go ms.msgConsumer()
7✔
1643
}
7✔
1644

1645
// Stop stops the chanMsgStream.
1646
func (ms *msgStream) Stop() {
4✔
1647
        // TODO(roasbeef): signal too?
4✔
1648

4✔
1649
        close(ms.quit)
4✔
1650

4✔
1651
        // Now that we've closed the channel, we'll repeatedly signal the msg
4✔
1652
        // consumer until we've detected that it has exited.
4✔
1653
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
8✔
1654
                ms.msgCond.Signal()
4✔
1655
                time.Sleep(time.Millisecond * 100)
4✔
1656
        }
4✔
1657

1658
        ms.wg.Wait()
4✔
1659
}
1660

1661
// msgConsumer is the main goroutine that streams messages from the peer's
1662
// readHandler directly to the target channel.
1663
func (ms *msgStream) msgConsumer() {
7✔
1664
        defer ms.wg.Done()
7✔
1665
        defer peerLog.Tracef(ms.stopMsg)
7✔
1666
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
7✔
1667

7✔
1668
        peerLog.Tracef(ms.startMsg)
7✔
1669

7✔
1670
        for {
14✔
1671
                // First, we'll check our condition. If the queue of messages
7✔
1672
                // is empty, then we'll wait until a new item is added.
7✔
1673
                ms.msgCond.L.Lock()
7✔
1674
                for len(ms.msgs) == 0 {
14✔
1675
                        ms.msgCond.Wait()
7✔
1676

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

1691
                // Grab the message off the front of the queue, shifting the
1692
                // slice's reference down one in order to remove the message
1693
                // from the queue.
1694
                msg := ms.msgs[0]
4✔
1695
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
4✔
1696
                ms.msgs = ms.msgs[1:]
4✔
1697

4✔
1698
                ms.msgCond.L.Unlock()
4✔
1699

4✔
1700
                ms.apply(msg)
4✔
1701

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

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

1732
        // Next, we'll lock the condition, and add the message to the end of
1733
        // the message queue.
1734
        ms.msgCond.L.Lock()
4✔
1735
        ms.msgs = append(ms.msgs, msg)
4✔
1736
        ms.msgCond.L.Unlock()
4✔
1737

4✔
1738
        // With the message added, we signal to the msgConsumer that there are
4✔
1739
        // additional messages to consume.
4✔
1740
        ms.msgCond.Signal()
4✔
1741
}
1742

1743
// waitUntilLinkActive waits until the target link is active and returns a
1744
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1745
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1746
func waitUntilLinkActive(p *Brontide,
1747
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
4✔
1748

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

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

4✔
1769
        // The link may already be active by this point, and we may have missed the
4✔
1770
        // ActiveLinkEvent. Check if the link exists.
4✔
1771
        link := p.fetchLinkFromKeyAndCid(cid)
4✔
1772
        if link != nil {
8✔
1773
                return link
4✔
1774
        }
4✔
1775

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

1790
                        chanPoint := event.ChannelPoint
4✔
1791

4✔
1792
                        // Check whether the retrieved chanPoint matches the target
4✔
1793
                        // channel id.
4✔
1794
                        if !cid.IsChanPoint(chanPoint) {
4✔
1795
                                continue
×
1796
                        }
1797

1798
                        // The link shouldn't be nil as we received an
1799
                        // ActiveLinkEvent. If it is nil, we return nil and the
1800
                        // calling function should catch it.
1801
                        return p.fetchLinkFromKeyAndCid(cid)
4✔
1802

1803
                case <-p.quit:
4✔
1804
                        return nil
4✔
1805
                }
1806
        }
1807
}
1808

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

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

4✔
1825
                        // If the link is still not active and the calling function
4✔
1826
                        // errored out, just return.
4✔
1827
                        if chanLink == nil {
8✔
1828
                                p.log.Warnf("Link=%v is not active", cid)
4✔
1829
                                return
4✔
1830
                        }
4✔
1831
                }
1832

1833
                // In order to avoid unnecessarily delivering message
1834
                // as the peer is exiting, we'll check quickly to see
1835
                // if we need to exit.
1836
                select {
4✔
1837
                case <-p.quit:
×
1838
                        return
×
1839
                default:
4✔
1840
                }
1841

1842
                chanLink.HandleChannelUpdate(msg)
4✔
1843
        }
1844

1845
        return newMsgStream(p,
4✔
1846
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
4✔
1847
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
4✔
1848
                1000,
4✔
1849
                apply,
4✔
1850
        )
4✔
1851
}
1852

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

1863
        return newMsgStream(
7✔
1864
                p,
7✔
1865
                "Update stream for gossiper created",
7✔
1866
                "Update stream for gossiper exited",
7✔
1867
                1000,
7✔
1868
                apply,
7✔
1869
        )
7✔
1870
}
1871

1872
// readHandler is responsible for reading messages off the wire in series, then
1873
// properly dispatching the handling of the message to the proper subsystem.
1874
//
1875
// NOTE: This method MUST be run as a goroutine.
1876
func (p *Brontide) readHandler() {
7✔
1877
        defer p.wg.Done()
7✔
1878

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

1887
        // Initialize our negotiated gossip sync method before reading messages
1888
        // off the wire. When using gossip queries, this ensures a gossip
1889
        // syncer is active by the time query messages arrive.
1890
        //
1891
        // TODO(conner): have peer store gossip syncer directly and bypass
1892
        // gossiper?
1893
        p.initGossipSync()
7✔
1894

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

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

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

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

1942
                        // If the error we encountered wasn't just a message we
1943
                        // didn't recognize, then we'll stop all processing as
1944
                        // this is a fatal error.
1945
                        default:
4✔
1946
                                break out
4✔
1947
                        }
1948
                }
1949

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

1960
                // No error occurred, and the message was handled by the
1961
                // router.
1962
                if err == nil {
5✔
1963
                        continue
×
1964
                }
1965

1966
                var (
5✔
1967
                        targetChan   lnwire.ChannelID
5✔
1968
                        isLinkUpdate bool
5✔
1969
                )
5✔
1970

5✔
1971
                switch msg := nextMsg.(type) {
5✔
1972
                case *lnwire.Pong:
2✔
1973
                        // When we receive a Pong message in response to our
2✔
1974
                        // last ping message, we send it to the pingManager
2✔
1975
                        p.pingManager.ReceivedPong(msg)
2✔
1976

1977
                case *lnwire.Ping:
2✔
1978
                        // First, we'll store their latest ping payload within
2✔
1979
                        // the relevant atomic variable.
2✔
1980
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
2✔
1981

2✔
1982
                        // Next, we'll send over the amount of specified pong
2✔
1983
                        // bytes.
2✔
1984
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
2✔
1985
                        p.queueMsg(pong, nil)
2✔
1986

1987
                case *lnwire.OpenChannel,
1988
                        *lnwire.AcceptChannel,
1989
                        *lnwire.FundingCreated,
1990
                        *lnwire.FundingSigned,
1991
                        *lnwire.ChannelReady:
4✔
1992

4✔
1993
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
4✔
1994

1995
                case *lnwire.Shutdown:
4✔
1996
                        select {
4✔
1997
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
4✔
1998
                        case <-p.quit:
×
1999
                                break out
×
2000
                        }
2001
                case *lnwire.ClosingSigned:
4✔
2002
                        select {
4✔
2003
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
4✔
2004
                        case <-p.quit:
×
2005
                                break out
×
2006
                        }
2007

2008
                case *lnwire.Warning:
×
2009
                        targetChan = msg.ChanID
×
2010
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
2011

2012
                case *lnwire.Error:
4✔
2013
                        targetChan = msg.ChanID
4✔
2014
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
4✔
2015

2016
                case *lnwire.ChannelReestablish:
4✔
2017
                        targetChan = msg.ChanID
4✔
2018
                        isLinkUpdate = p.hasChannel(targetChan)
4✔
2019

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

2035
                // For messages that implement the LinkUpdater interface, we
2036
                // will consider them as link updates and send them to
2037
                // chanStream. These messages will be queued inside chanStream
2038
                // if the channel is not active yet.
2039
                case lnwire.LinkUpdater:
4✔
2040
                        targetChan = msg.TargetChanID()
4✔
2041
                        isLinkUpdate = p.hasChannel(targetChan)
4✔
2042

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

2052
                case *lnwire.ChannelUpdate1,
2053
                        *lnwire.ChannelAnnouncement1,
2054
                        *lnwire.NodeAnnouncement,
2055
                        *lnwire.AnnounceSignatures1,
2056
                        *lnwire.GossipTimestampRange,
2057
                        *lnwire.QueryShortChanIDs,
2058
                        *lnwire.QueryChannelRange,
2059
                        *lnwire.ReplyChannelRange,
2060
                        *lnwire.ReplyShortChanIDsEnd:
4✔
2061

4✔
2062
                        discStream.AddMsg(msg)
4✔
2063

2064
                case *lnwire.Custom:
5✔
2065
                        err := p.handleCustomMessage(msg)
5✔
2066
                        if err != nil {
5✔
2067
                                p.storeError(err)
×
2068
                                p.log.Errorf("%v", err)
×
2069
                        }
×
2070

2071
                default:
×
2072
                        // If the message we received is unknown to us, store
×
2073
                        // the type to track the failure.
×
2074
                        err := fmt.Errorf("unknown message type %v received",
×
2075
                                uint16(msg.MsgType()))
×
2076
                        p.storeError(err)
×
2077

×
2078
                        p.log.Errorf("%v", err)
×
2079
                }
2080

2081
                if isLinkUpdate {
9✔
2082
                        // If this is a channel update, then we need to feed it
4✔
2083
                        // into the channel's in-order message stream.
4✔
2084
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
4✔
2085
                }
4✔
2086

2087
                idleTimer.Reset(idleTimeout)
5✔
2088
        }
2089

2090
        p.Disconnect(errors.New("read handler closed"))
4✔
2091

4✔
2092
        p.log.Trace("readHandler for peer done")
4✔
2093
}
2094

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

2103
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
5✔
2104
}
2105

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

2117
        // Return false if the channel is unknown.
2118
        channel, ok := p.activeChannels.Load(chanID)
4✔
2119
        if !ok {
4✔
2120
                return false
×
2121
        }
×
2122

2123
        // During startup, we will use a nil value to mark a pending channel
2124
        // that's loaded from disk.
2125
        return channel == nil
4✔
2126
}
2127

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

12✔
2137
        return channel != nil
12✔
2138
}
12✔
2139

2140
// isPendingChannel returns true if the provided channel ID is pending, and
2141
// returns false if the channel is active or unknown.
2142
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
10✔
2143
        // Return false if the channel is unknown.
10✔
2144
        channel, ok := p.activeChannels.Load(chanID)
10✔
2145
        if !ok {
17✔
2146
                return false
7✔
2147
        }
7✔
2148

2149
        return channel == nil
3✔
2150
}
2151

2152
// hasChannel returns true if the peer has a pending/active channel specified
2153
// by the channel ID.
2154
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
4✔
2155
        _, ok := p.activeChannels.Load(chanID)
4✔
2156
        return ok
4✔
2157
}
4✔
2158

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

4✔
2166
        p.activeChannels.Range(func(_ lnwire.ChannelID,
4✔
2167
                channel *lnwallet.LightningChannel) bool {
8✔
2168

4✔
2169
                // Pending channels will be nil in the activeChannels map.
4✔
2170
                if channel == nil {
8✔
2171
                        // Return true to continue the iteration.
4✔
2172
                        return true
4✔
2173
                }
4✔
2174

2175
                haveChannels = true
4✔
2176

4✔
2177
                // Return false to break the iteration.
4✔
2178
                return false
4✔
2179
        })
2180

2181
        // If we do not have any active channels with the peer, we do not store
2182
        // errors as a dos mitigation.
2183
        if !haveChannels {
8✔
2184
                p.log.Trace("no channels with peer, not storing err")
4✔
2185
                return
4✔
2186
        }
4✔
2187

2188
        p.cfg.ErrorBuffer.Add(
4✔
2189
                &TimestampedError{Timestamp: time.Now(), Error: err},
4✔
2190
        )
4✔
2191
}
2192

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

4✔
2202
        if errMsg, ok := msg.(*lnwire.Error); ok {
8✔
2203
                p.storeError(errMsg)
4✔
2204
        }
4✔
2205

2206
        switch {
4✔
2207
        // Connection wide messages should be forwarded to all channel links
2208
        // with this peer.
2209
        case chanID == lnwire.ConnectionWideID:
×
2210
                for _, chanStream := range p.activeMsgStreams {
×
2211
                        chanStream.AddMsg(msg)
×
2212
                }
×
2213

2214
                return false
×
2215

2216
        // If the channel ID for the message corresponds to a pending channel,
2217
        // then the funding manager will handle it.
2218
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
4✔
2219
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
4✔
2220
                return false
4✔
2221

2222
        // If not we hand the message to the channel link for this channel.
2223
        case p.isActiveChannel(chanID):
4✔
2224
                return true
4✔
2225

2226
        default:
4✔
2227
                return false
4✔
2228
        }
2229
}
2230

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

2240
        case *lnwire.OpenChannel:
4✔
2241
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
4✔
2242
                        "push_amt=%v, reserve=%v, flags=%v",
4✔
2243
                        msg.PendingChannelID[:], msg.ChainHash,
4✔
2244
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
4✔
2245
                        msg.ChannelReserve, msg.ChannelFlags)
4✔
2246

2247
        case *lnwire.AcceptChannel:
4✔
2248
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
4✔
2249
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
4✔
2250
                        msg.MinAcceptDepth)
4✔
2251

2252
        case *lnwire.FundingCreated:
4✔
2253
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
4✔
2254
                        msg.PendingChannelID[:], msg.FundingPoint)
4✔
2255

2256
        case *lnwire.FundingSigned:
4✔
2257
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
4✔
2258

2259
        case *lnwire.ChannelReady:
4✔
2260
                return fmt.Sprintf("chan_id=%v, next_point=%x",
4✔
2261
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
4✔
2262

2263
        case *lnwire.Shutdown:
4✔
2264
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
4✔
2265
                        msg.Address[:])
4✔
2266

2267
        case *lnwire.ClosingSigned:
4✔
2268
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
4✔
2269
                        msg.FeeSatoshis)
4✔
2270

2271
        case *lnwire.UpdateAddHTLC:
4✔
2272
                var blindingPoint []byte
4✔
2273
                msg.BlindingPoint.WhenSome(
4✔
2274
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
4✔
2275
                                *btcec.PublicKey]) {
8✔
2276

4✔
2277
                                blindingPoint = b.Val.SerializeCompressed()
4✔
2278
                        },
4✔
2279
                )
2280

2281
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
4✔
2282
                        "hash=%x, blinding_point=%x, custom_records=%v",
4✔
2283
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
4✔
2284
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
4✔
2285

2286
        case *lnwire.UpdateFailHTLC:
4✔
2287
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
4✔
2288
                        msg.ID, msg.Reason)
4✔
2289

2290
        case *lnwire.UpdateFulfillHTLC:
4✔
2291
                return fmt.Sprintf("chan_id=%v, id=%v, pre_image=%x, "+
4✔
2292
                        "custom_records=%v", msg.ChanID, msg.ID,
4✔
2293
                        msg.PaymentPreimage[:], msg.CustomRecords)
4✔
2294

2295
        case *lnwire.CommitSig:
4✔
2296
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
4✔
2297
                        len(msg.HtlcSigs))
4✔
2298

2299
        case *lnwire.RevokeAndAck:
4✔
2300
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
4✔
2301
                        msg.ChanID, msg.Revocation[:],
4✔
2302
                        msg.NextRevocationKey.SerializeCompressed())
4✔
2303

2304
        case *lnwire.UpdateFailMalformedHTLC:
4✔
2305
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
4✔
2306
                        msg.ChanID, msg.ID, msg.FailureCode)
4✔
2307

2308
        case *lnwire.Warning:
×
2309
                return fmt.Sprintf("%v", msg.Warning())
×
2310

2311
        case *lnwire.Error:
4✔
2312
                return fmt.Sprintf("%v", msg.Error())
4✔
2313

2314
        case *lnwire.AnnounceSignatures1:
4✔
2315
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
4✔
2316
                        msg.ShortChannelID.ToUint64())
4✔
2317

2318
        case *lnwire.ChannelAnnouncement1:
4✔
2319
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
4✔
2320
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
4✔
2321

2322
        case *lnwire.ChannelUpdate1:
6✔
2323
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
6✔
2324
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
6✔
2325
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
6✔
2326
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
6✔
2327

2328
        case *lnwire.NodeAnnouncement:
4✔
2329
                return fmt.Sprintf("node=%x, update_time=%v",
4✔
2330
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
4✔
2331

2332
        case *lnwire.Ping:
3✔
2333
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
3✔
2334

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

2338
        case *lnwire.UpdateFee:
×
2339
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2340
                        msg.ChanID, int64(msg.FeePerKw))
×
2341

2342
        case *lnwire.ChannelReestablish:
6✔
2343
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
6✔
2344
                        "remote_tail_height=%v", msg.ChanID,
6✔
2345
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
6✔
2346

2347
        case *lnwire.ReplyShortChanIDsEnd:
4✔
2348
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
4✔
2349
                        msg.Complete)
4✔
2350

2351
        case *lnwire.ReplyChannelRange:
4✔
2352
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
4✔
2353
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
4✔
2354
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
4✔
2355
                        msg.EncodingType)
4✔
2356

2357
        case *lnwire.QueryShortChanIDs:
4✔
2358
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
4✔
2359
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
4✔
2360

2361
        case *lnwire.QueryChannelRange:
4✔
2362
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
4✔
2363
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
4✔
2364
                        msg.LastBlockHeight())
4✔
2365

2366
        case *lnwire.GossipTimestampRange:
4✔
2367
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
4✔
2368
                        "stamp_range=%v", msg.ChainHash,
4✔
2369
                        time.Unix(int64(msg.FirstTimestamp), 0),
4✔
2370
                        msg.TimestampRange)
4✔
2371

2372
        case *lnwire.Stfu:
×
2373
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
×
2374
                        msg.Initiator)
×
2375

2376
        case *lnwire.Custom:
6✔
2377
                return fmt.Sprintf("type=%d", msg.Type)
6✔
2378
        }
2379

2380
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2381
}
2382

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

2394
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
42✔
2395
                // Debug summary of message.
21✔
2396
                summary := messageSummary(msg)
21✔
2397
                if len(summary) > 0 {
32✔
2398
                        summary = "(" + summary + ")"
11✔
2399
                }
11✔
2400

2401
                preposition := "to"
21✔
2402
                if read {
29✔
2403
                        preposition = "from"
8✔
2404
                }
8✔
2405

2406
                var msgType string
21✔
2407
                if msg.MsgType() < lnwire.CustomTypeStart {
40✔
2408
                        msgType = msg.MsgType().String()
19✔
2409
                } else {
25✔
2410
                        msgType = "custom"
6✔
2411
                }
6✔
2412

2413
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
21✔
2414
                        msgType, summary, preposition, p)
21✔
2415
        }))
2416

2417
        prefix := "readMessage from peer"
21✔
2418
        if !read {
38✔
2419
                prefix = "writeMessage to peer"
17✔
2420
        }
17✔
2421

2422
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
21✔
2423
}
2424

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

2442
        noiseConn := p.cfg.Conn
17✔
2443

17✔
2444
        flushMsg := func() error {
34✔
2445
                // Ensure the write deadline is set before we attempt to send
17✔
2446
                // the message.
17✔
2447
                writeDeadline := time.Now().Add(
17✔
2448
                        p.scaleTimeout(writeMessageTimeout),
17✔
2449
                )
17✔
2450
                err := noiseConn.SetWriteDeadline(writeDeadline)
17✔
2451
                if err != nil {
17✔
2452
                        return err
×
2453
                }
×
2454

2455
                // Flush the pending message to the wire. If an error is
2456
                // encountered, e.g. write timeout, the number of bytes written
2457
                // so far will be returned.
2458
                n, err := noiseConn.Flush()
17✔
2459

17✔
2460
                // Record the number of bytes written on the wire, if any.
17✔
2461
                if n > 0 {
21✔
2462
                        atomic.AddUint64(&p.bytesSent, uint64(n))
4✔
2463
                }
4✔
2464

2465
                return err
17✔
2466
        }
2467

2468
        // If the current message has already been serialized, encrypted, and
2469
        // buffered on the underlying connection we will skip straight to
2470
        // flushing it to the wire.
2471
        if msg == nil {
17✔
2472
                return flushMsg()
×
2473
        }
×
2474

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

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

2495
        return flushMsg()
17✔
2496
}
2497

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

2513
        var exitErr error
7✔
2514

7✔
2515
out:
7✔
2516
        for {
18✔
2517
                select {
11✔
2518
                case outMsg := <-p.sendQueue:
8✔
2519
                        // Record the time at which we first attempt to send the
8✔
2520
                        // message.
8✔
2521
                        startTime := time.Now()
8✔
2522

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

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

×
2544
                                goto retry
×
2545
                        }
2546

2547
                        // The write succeeded, reset the idle timer to prevent
2548
                        // us from disconnecting the peer.
2549
                        if !idleTimer.Stop() {
8✔
2550
                                select {
×
2551
                                case <-idleTimer.C:
×
2552
                                default:
×
2553
                                }
2554
                        }
2555
                        idleTimer.Reset(idleTimeout)
8✔
2556

8✔
2557
                        // If the peer requested a synchronous write, respond
8✔
2558
                        // with the error.
8✔
2559
                        if outMsg.errChan != nil {
13✔
2560
                                outMsg.errChan <- err
5✔
2561
                        }
5✔
2562

2563
                        if err != nil {
8✔
2564
                                exitErr = fmt.Errorf("unable to write "+
×
2565
                                        "message: %v", err)
×
2566
                                break out
×
2567
                        }
2568

2569
                case <-p.quit:
4✔
2570
                        exitErr = lnpeer.ErrPeerExiting
4✔
2571
                        break out
4✔
2572
                }
2573
        }
2574

2575
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2576
        // disconnect.
2577
        p.wg.Done()
4✔
2578

4✔
2579
        p.Disconnect(exitErr)
4✔
2580

4✔
2581
        p.log.Trace("writeHandler for peer done")
4✔
2582
}
2583

2584
// queueHandler is responsible for accepting messages from outside subsystems
2585
// to be eventually sent out on the wire by the writeHandler.
2586
//
2587
// NOTE: This method MUST be run as a goroutine.
2588
func (p *Brontide) queueHandler() {
7✔
2589
        defer p.wg.Done()
7✔
2590

7✔
2591
        // priorityMsgs holds an in order list of messages deemed high-priority
7✔
2592
        // to be added to the sendQueue. This predominately includes messages
7✔
2593
        // from the funding manager and htlcswitch.
7✔
2594
        priorityMsgs := list.New()
7✔
2595

7✔
2596
        // lazyMsgs holds an in order list of messages deemed low-priority to be
7✔
2597
        // added to the sendQueue only after all high-priority messages have
7✔
2598
        // been queued. This predominately includes messages from the gossiper.
7✔
2599
        lazyMsgs := list.New()
7✔
2600

7✔
2601
        for {
22✔
2602
                // Examine the front of the priority queue, if it is empty check
15✔
2603
                // the low priority queue.
15✔
2604
                elem := priorityMsgs.Front()
15✔
2605
                if elem == nil {
27✔
2606
                        elem = lazyMsgs.Front()
12✔
2607
                }
12✔
2608

2609
                if elem != nil {
23✔
2610
                        front := elem.Value.(outgoingMsg)
8✔
2611

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

2651
// PingTime returns the estimated ping time to the peer in microseconds.
2652
func (p *Brontide) PingTime() int64 {
4✔
2653
        return p.pingManager.GetPingTimeMicroSeconds()
4✔
2654
}
4✔
2655

2656
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2657
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2658
// or failed to write, and nil otherwise.
2659
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
29✔
2660
        p.queue(true, msg, errChan)
29✔
2661
}
29✔
2662

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

2670
// queue sends a given message to the queueHandler using the passed priority. If
2671
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2672
// failed to write, and nil otherwise.
2673
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2674
        errChan chan error) {
30✔
2675

30✔
2676
        select {
30✔
2677
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
29✔
2678
        case <-p.quit:
4✔
2679
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
4✔
2680
                        spew.Sdump(msg))
4✔
2681
                if errChan != nil {
4✔
2682
                        errChan <- lnpeer.ErrPeerExiting
×
2683
                }
×
2684
        }
2685
}
2686

2687
// ChannelSnapshots returns a slice of channel snapshots detailing all
2688
// currently active channels maintained with the remote peer.
2689
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
4✔
2690
        snapshots := make(
4✔
2691
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
4✔
2692
        )
4✔
2693

4✔
2694
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
4✔
2695
                activeChan *lnwallet.LightningChannel) error {
8✔
2696

4✔
2697
                // If the activeChan is nil, then we skip it as the channel is
4✔
2698
                // pending.
4✔
2699
                if activeChan == nil {
8✔
2700
                        return nil
4✔
2701
                }
4✔
2702

2703
                // We'll only return a snapshot for channels that are
2704
                // *immediately* available for routing payments over.
2705
                if activeChan.RemoteNextRevocation() == nil {
8✔
2706
                        return nil
4✔
2707
                }
4✔
2708

2709
                snapshot := activeChan.StateSnapshot()
4✔
2710
                snapshots = append(snapshots, snapshot)
4✔
2711

4✔
2712
                return nil
4✔
2713
        })
2714

2715
        return snapshots
4✔
2716
}
2717

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

2728
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
10✔
2729
                addrType, false, lnwallet.DefaultAccountName,
10✔
2730
        )
10✔
2731
        if err != nil {
10✔
2732
                return nil, err
×
2733
        }
×
2734
        p.log.Infof("Delivery addr for channel close: %v",
10✔
2735
                deliveryAddr)
10✔
2736

10✔
2737
        return txscript.PayToAddrScript(deliveryAddr)
10✔
2738
}
2739

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

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

21✔
2753
out:
21✔
2754
        for {
63✔
2755
                select {
42✔
2756
                // A new pending channel has arrived which means we are about
2757
                // to complete a funding workflow and is waiting for the final
2758
                // `ChannelReady` messages to be exchanged. We will add this
2759
                // channel to the `activeChannels` with a nil value to indicate
2760
                // this is a pending channel.
2761
                case req := <-p.newPendingChannel:
5✔
2762
                        p.handleNewPendingChannel(req)
5✔
2763

2764
                // A new channel has arrived which means we've just completed a
2765
                // funding workflow. We'll initialize the necessary local
2766
                // state, and notify the htlc switch of a new link.
2767
                case req := <-p.newActiveChannel:
4✔
2768
                        p.handleNewActiveChannel(req)
4✔
2769

2770
                // The funding flow for a pending channel is failed, we will
2771
                // remove it from Brontide.
2772
                case req := <-p.removePendingChannel:
5✔
2773
                        p.handleRemovePendingChannel(req)
5✔
2774

2775
                // We've just received a local request to close an active
2776
                // channel. It will either kick of a cooperative channel
2777
                // closure negotiation, or be a notification of a breached
2778
                // contract that should be abandoned.
2779
                case req := <-p.localCloseChanReqs:
11✔
2780
                        p.handleLocalCloseReq(req)
11✔
2781

2782
                // We've received a link failure from a link that was added to
2783
                // the switch. This will initiate the teardown of the link, and
2784
                // initiate any on-chain closures if necessary.
2785
                case failure := <-p.linkFailures:
4✔
2786
                        p.handleLinkFailure(failure)
4✔
2787

2788
                // We've received a new cooperative channel closure related
2789
                // message from the remote peer, we'll use this message to
2790
                // advance the chan closer state machine.
2791
                case closeMsg := <-p.chanCloseMsgs:
17✔
2792
                        p.handleCloseMsg(closeMsg)
17✔
2793

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

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

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

2822
                case <-p.quit:
4✔
2823
                        // As, we've been signalled to exit, we'll reset all
4✔
2824
                        // our active channel back to their default state.
4✔
2825
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
4✔
2826
                                lc *lnwallet.LightningChannel) error {
8✔
2827

4✔
2828
                                // Exit if the channel is nil as it's a pending
4✔
2829
                                // channel.
4✔
2830
                                if lc == nil {
8✔
2831
                                        return nil
4✔
2832
                                }
4✔
2833

2834
                                lc.ResetState()
4✔
2835

4✔
2836
                                return nil
4✔
2837
                        })
2838

2839
                        break out
4✔
2840
                }
2841
        }
2842
}
2843

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

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

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

4✔
2862
                switch {
4✔
2863
                // No error occurred, continue to request the next channel.
2864
                case err == nil:
4✔
2865
                        continue
4✔
2866

2867
                // Cannot auto enable a manually disabled channel so we do
2868
                // nothing but proceed to the next channel.
2869
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
4✔
2870
                        p.log.Debugf("Channel(%v) was manually disabled, "+
4✔
2871
                                "ignoring automatic enable request", chanPoint)
4✔
2872

4✔
2873
                        continue
4✔
2874

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

×
2892
                                continue
×
2893
                        }
2894

2895
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
2896
                                "ChanStatusManager reported inactive, retrying")
×
2897

×
2898
                        // Add the channel to the retry map.
×
2899
                        retryChans[chanPoint] = struct{}{}
×
2900
                }
2901
        }
2902

2903
        // Retry the channels if we have any.
2904
        if len(retryChans) != 0 {
4✔
2905
                p.retryRequestEnable(retryChans)
×
2906
        }
×
2907
}
2908

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

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

2925
        // First, we'll ensure that we actually know of the target channel. If
2926
        // not, we'll ignore this message.
2927
        channel, ok := p.activeChannels.Load(chanID)
7✔
2928

7✔
2929
        // If the channel isn't in the map or the channel is nil, return
7✔
2930
        // ErrChannelNotFound as the channel is pending.
7✔
2931
        if !ok || channel == nil {
11✔
2932
                return nil, ErrChannelNotFound
4✔
2933
        }
4✔
2934

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

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

2964
        addr, err := p.addrWithInternalKey(deliveryScript)
7✔
2965
        if err != nil {
7✔
2966
                return nil, fmt.Errorf("unable to parse addr: %w", err)
×
2967
        }
×
2968
        chanCloser, err = p.createChanCloser(
7✔
2969
                channel, addr, feePerKw, nil, lntypes.Remote,
7✔
2970
        )
7✔
2971
        if err != nil {
7✔
2972
                p.log.Errorf("unable to create chan closer: %v", err)
×
2973
                return nil, fmt.Errorf("unable to create chan closer")
×
2974
        }
×
2975

2976
        p.activeChanCloses[chanID] = chanCloser
7✔
2977

7✔
2978
        return chanCloser, nil
7✔
2979
}
2980

2981
// filterChannelsToEnable filters a list of channels to be enabled upon start.
2982
// The filtered channels are active channels that's neither private nor
2983
// pending.
2984
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
4✔
2985
        var activePublicChans []wire.OutPoint
4✔
2986

4✔
2987
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
4✔
2988
                lnChan *lnwallet.LightningChannel) bool {
8✔
2989

4✔
2990
                // If the lnChan is nil, continue as this is a pending channel.
4✔
2991
                if lnChan == nil {
6✔
2992
                        return true
2✔
2993
                }
2✔
2994

2995
                dbChan := lnChan.State()
4✔
2996
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
4✔
2997
                if !isPublic || dbChan.IsPending {
4✔
2998
                        return true
×
2999
                }
×
3000

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

3010
                activePublicChans = append(
4✔
3011
                        activePublicChans, dbChan.FundingOutpoint,
4✔
3012
                )
4✔
3013

4✔
3014
                return true
4✔
3015
        })
3016

3017
        return activePublicChans
4✔
3018
}
3019

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

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

×
3034
                // If this channel is irrelevant, return nil so the loop can
×
3035
                // jump to next iteration.
×
3036
                if !found {
×
3037
                        return nil
×
3038
                }
×
3039

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

×
3048
                // Send the request.
×
3049
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3050
                if err != nil {
×
3051
                        return fmt.Errorf("request enabling channel %v "+
×
3052
                                "failed: %w", chanPoint, err)
×
3053
                }
×
3054

3055
                return nil
×
3056
        }
3057

3058
        for {
×
3059
                // If activeChans is empty, we've done processing all the
×
3060
                // channels.
×
3061
                if len(activeChans) == 0 {
×
3062
                        p.log.Debug("Finished retry enabling channels")
×
3063
                        return
×
3064
                }
×
3065

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

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

3083
                                continue
×
3084
                        }
3085

3086
                        // Otherwise check for inactive link event, and jump to
3087
                        // next iteration if it's not.
3088
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
3089
                        if !ok {
×
3090
                                continue
×
3091
                        }
3092

3093
                        // Found an inactive link event, if this is our
3094
                        // targeted channel, remove it from our map.
3095
                        chanPoint := *inactive.ChannelPoint
×
3096
                        _, found := activeChans[chanPoint]
×
3097
                        if !found {
×
3098
                                continue
×
3099
                        }
3100

3101
                        delete(activeChans, chanPoint)
×
3102
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
3103
                                "inactive link event", chanPoint)
×
3104

3105
                case <-p.quit:
×
3106
                        p.log.Debugf("Peer shutdown during retry enabling")
×
3107
                        return
×
3108
                }
3109
        }
3110
}
3111

3112
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3113
// a suitable script to close out to. This may be nil if neither script is
3114
// set. If both scripts are set, this function will error if they do not match.
3115
func chooseDeliveryScript(upfront,
3116
        requested lnwire.DeliveryAddress) (lnwire.DeliveryAddress, error) {
16✔
3117

16✔
3118
        // If no upfront shutdown script was provided, return the user
16✔
3119
        // requested address (which may be nil).
16✔
3120
        if len(upfront) == 0 {
26✔
3121
                return requested, nil
10✔
3122
        }
10✔
3123

3124
        // If an upfront shutdown script was provided, and the user did not
3125
        // request a custom shutdown script, return the upfront address.
3126
        if len(requested) == 0 {
16✔
3127
                return upfront, nil
6✔
3128
        }
6✔
3129

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

3138
        // The user requested script matches the upfront shutdown script, so we
3139
        // can return it without error.
3140
        return upfront, nil
2✔
3141
}
3142

3143
// restartCoopClose checks whether we need to restart the cooperative close
3144
// process for a given channel.
3145
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
3146
        *lnwire.Shutdown, error) {
×
3147

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

3166
        var deliveryScript []byte
×
3167

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

3177
        // An error other than ErrNoShutdownInfo was returned
3178
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3179
                return nil, err
×
3180

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

×
3190
                                return nil, fmt.Errorf("close addr unavailable")
×
3191
                        }
×
3192
                }
3193
        }
3194

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

3204
        // Determine whether we or the peer are the initiator of the coop
3205
        // close attempt by looking at the channel's status.
3206
        closingParty := lntypes.Remote
×
3207
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
×
3208
                closingParty = lntypes.Local
×
3209
        }
×
3210

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

3223
        // This does not need a mutex even though it is in a different
3224
        // goroutine since this is done before the channelManager goroutine is
3225
        // created.
3226
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
×
3227
        p.activeChanCloses[chanID] = chanCloser
×
3228

×
3229
        // Create the Shutdown message.
×
3230
        shutdownMsg, err := chanCloser.ShutdownChan()
×
3231
        if err != nil {
×
3232
                p.log.Errorf("unable to create shutdown message: %v", err)
×
3233
                delete(p.activeChanCloses, chanID)
×
3234
                return nil, err
×
3235
        }
×
3236

3237
        return shutdownMsg, nil
×
3238
}
3239

3240
// createChanCloser constructs a ChanCloser from the passed parameters and is
3241
// used to de-duplicate code.
3242
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3243
        deliveryScript *chancloser.DeliveryAddrWithKey,
3244
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
3245
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
13✔
3246

13✔
3247
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
13✔
3248
        if err != nil {
13✔
3249
                p.log.Errorf("unable to obtain best block: %v", err)
×
3250
                return nil, fmt.Errorf("cannot obtain best block")
×
3251
        }
×
3252

3253
        // The req will only be set if we initiated the co-op closing flow.
3254
        var maxFee chainfee.SatPerKWeight
13✔
3255
        if req != nil {
23✔
3256
                maxFee = req.MaxFee
10✔
3257
        }
10✔
3258

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

3285
        return chanCloser, nil
13✔
3286
}
3287

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

11✔
3293
        channel, ok := p.activeChannels.Load(chanID)
11✔
3294

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

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

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

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

×
3344
                        return
×
3345
                }
×
3346
                chanCloser, err := p.createChanCloser(
10✔
3347
                        channel, addr, req.TargetFeePerKw, req, lntypes.Local,
10✔
3348
                )
10✔
3349
                if err != nil {
10✔
3350
                        p.log.Errorf(err.Error())
×
3351
                        req.Err <- err
×
3352
                        return
×
3353
                }
×
3354

3355
                p.activeChanCloses[chanID] = chanCloser
10✔
3356

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

×
3366
                        // As we were unable to shutdown the channel, we'll
×
3367
                        // return it back to its normal state.
×
3368
                        channel.ResetState()
×
3369
                        return
×
3370
                }
×
3371

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

3385
                if !link.DisableAdds(htlcswitch.Outgoing) {
10✔
3386
                        p.log.Warnf("Outgoing link adds already "+
×
3387
                                "disabled: %v", link.ChanID())
×
3388
                }
×
3389

3390
                link.OnCommitOnce(htlcswitch.Outgoing, func() {
20✔
3391
                        p.queueMsg(shutdownMsg, nil)
10✔
3392
                })
10✔
3393

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

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

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

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

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

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

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

×
3457
                if err := lnChan.State().MarkBorked(); err != nil {
×
3458
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
3459
                                failure.shortChanID, err)
×
3460
                }
×
3461
        }
3462

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

3474
                var networkMsg lnwire.Message
4✔
3475
                if failure.linkErr.Warning {
4✔
3476
                        networkMsg = &lnwire.Warning{
×
3477
                                ChanID: failure.chanID,
×
3478
                                Data:   data,
×
3479
                        }
×
3480
                } else {
4✔
3481
                        networkMsg = &lnwire.Error{
4✔
3482
                                ChanID: failure.chanID,
4✔
3483
                                Data:   data,
4✔
3484
                        }
4✔
3485
                }
4✔
3486

3487
                err := p.SendMessage(true, networkMsg)
4✔
3488
                if err != nil {
4✔
3489
                        p.log.Errorf("unable to send msg to "+
×
3490
                                "remote peer: %v", err)
×
3491
                }
×
3492
        }
3493

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

3502
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
3503
// public key and the channel id.
3504
func (p *Brontide) fetchLinkFromKeyAndCid(
3505
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
23✔
3506

23✔
3507
        var chanLink htlcswitch.ChannelUpdateHandler
23✔
3508

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

3519
        return chanLink
23✔
3520
}
3521

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

8✔
3530
        // First, we'll clear all indexes related to the channel in question.
8✔
3531
        chanPoint := chanCloser.Channel().ChannelPoint()
8✔
3532
        p.WipeChannel(&chanPoint)
8✔
3533

8✔
3534
        // Also clear the activeChanCloses map of this channel.
8✔
3535
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
8✔
3536
        delete(p.activeChanCloses, cid)
8✔
3537

8✔
3538
        // Next, we'll launch a goroutine which will request to be notified by
8✔
3539
        // the ChainNotifier once the closure transaction obtains a single
8✔
3540
        // confirmation.
8✔
3541
        notifier := p.cfg.ChainNotifier
8✔
3542

8✔
3543
        // If any error happens during waitForChanToClose, forward it to
8✔
3544
        // closeReq. If this channel closure is not locally initiated, closeReq
8✔
3545
        // will be nil, so just ignore the error.
8✔
3546
        errChan := make(chan error, 1)
8✔
3547
        if closeReq != nil {
14✔
3548
                errChan = closeReq.Err
6✔
3549
        }
6✔
3550

3551
        closingTx, err := chanCloser.ClosingTx()
8✔
3552
        if err != nil {
8✔
3553
                if closeReq != nil {
×
3554
                        p.log.Error(err)
×
3555
                        closeReq.Err <- err
×
3556
                }
×
3557
        }
3558

3559
        closingTxid := closingTx.TxHash()
8✔
3560

8✔
3561
        // If this is a locally requested shutdown, update the caller with a
8✔
3562
        // new event detailing the current pending state of this request.
8✔
3563
        if closeReq != nil {
14✔
3564
                closeReq.Updates <- &PendingUpdate{
6✔
3565
                        Txid: closingTxid[:],
6✔
3566
                }
6✔
3567
        }
6✔
3568

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

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

8✔
3599
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
8✔
3600
                "with txid: %v", chanPoint, closingTxID)
8✔
3601

8✔
3602
        // TODO(roasbeef): add param for num needed confs
8✔
3603
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
8✔
3604
                closingTxID, closeScript, 1, bestHeight,
8✔
3605
        )
8✔
3606
        if err != nil {
8✔
3607
                if errChan != nil {
×
3608
                        errChan <- err
×
3609
                }
×
3610
                return
×
3611
        }
3612

3613
        // In the case that the ChainNotifier is shutting down, all subscriber
3614
        // notification channels will be closed, generating a nil receive.
3615
        height, ok := <-confNtfn.Confirmed
8✔
3616
        if !ok {
12✔
3617
                return
4✔
3618
        }
4✔
3619

3620
        // The channel has been closed, remove it from any active indexes, and
3621
        // the database state.
3622
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
8✔
3623
                "height %v", chanPoint, height.BlockHeight)
8✔
3624

8✔
3625
        // Finally, execute the closure call back to mark the confirmation of
8✔
3626
        // the transaction closing the contract.
8✔
3627
        cb()
8✔
3628
}
3629

3630
// WipeChannel removes the passed channel point from all indexes associated with
3631
// the peer and the switch.
3632
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
8✔
3633
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
8✔
3634

8✔
3635
        p.activeChannels.Delete(chanID)
8✔
3636

8✔
3637
        // Instruct the HtlcSwitch to close this link as the channel is no
8✔
3638
        // longer active.
8✔
3639
        p.cfg.Switch.RemoveLink(chanID)
8✔
3640
}
8✔
3641

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

3653
        // Then, finalize the remote feature vector providing the flattened
3654
        // feature bit namespace.
3655
        p.remoteFeatures = lnwire.NewFeatureVector(
7✔
3656
                msg.Features, lnwire.Features,
7✔
3657
        )
7✔
3658

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

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

3674
        // Now that we know we understand their requirements, we'll check to
3675
        // see if they don't support anything that we deem to be mandatory.
3676
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
7✔
3677
                return fmt.Errorf("data loss protection required")
×
3678
        }
×
3679

3680
        return nil
7✔
3681
}
3682

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

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

3701
// hasNegotiatedScidAlias returns true if we've negotiated the
3702
// option-scid-alias feature bit with the peer.
3703
func (p *Brontide) hasNegotiatedScidAlias() bool {
7✔
3704
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
7✔
3705
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
7✔
3706
        return peerHas && localHas
7✔
3707
}
7✔
3708

3709
// sendInitMsg sends the Init message to the remote peer. This message contains
3710
// our currently supported local and global features.
3711
func (p *Brontide) sendInitMsg(legacyChan bool) error {
11✔
3712
        features := p.cfg.Features.Clone()
11✔
3713
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
11✔
3714

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

1✔
3725
                // Unset and set in both the local and global features to
1✔
3726
                // ensure both sets are consistent and merge able by old and
1✔
3727
                // new nodes.
1✔
3728
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3729
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3730

1✔
3731
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
3732
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
3733
        }
1✔
3734

3735
        msg := lnwire.NewInitMessage(
11✔
3736
                legacyFeatures.RawFeatureVector,
11✔
3737
                features.RawFeatureVector,
11✔
3738
        )
11✔
3739

11✔
3740
        return p.writeMessage(msg)
11✔
3741
}
3742

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

3752
        // Check if we have any channel sync messages stored for this channel.
3753
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
4✔
3754
        if err != nil {
8✔
3755
                return fmt.Errorf("unable to fetch channel sync messages for "+
4✔
3756
                        "peer %v: %v", p, err)
4✔
3757
        }
4✔
3758

3759
        if c.LastChanSyncMsg == nil {
4✔
3760
                return fmt.Errorf("no chan sync message stored for channel %v",
×
3761
                        cid)
×
3762
        }
×
3763

3764
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
4✔
3765
                return fmt.Errorf("ignoring channel reestablish from "+
×
3766
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
3767
        }
×
3768

3769
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
4✔
3770
                "peer", cid)
4✔
3771

4✔
3772
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
4✔
3773
                return fmt.Errorf("failed resending channel sync "+
×
3774
                        "message to peer %v: %v", p, err)
×
3775
        }
×
3776

3777
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
4✔
3778
                cid)
4✔
3779

4✔
3780
        // Note down that we sent the message, so we won't resend it again for
4✔
3781
        // this connection.
4✔
3782
        p.resentChanSyncMsg[cid] = struct{}{}
4✔
3783

4✔
3784
        return nil
4✔
3785
}
3786

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

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

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

3828
                if priority {
15✔
3829
                        p.queueMsg(msg, errChan)
7✔
3830
                } else {
12✔
3831
                        p.queueMsgLazy(msg, errChan)
5✔
3832
                }
5✔
3833
        }
3834

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

3848
        return nil
7✔
3849
}
3850

3851
// PubKey returns the pubkey of the peer in compressed serialized format.
3852
//
3853
// NOTE: Part of the lnpeer.Peer interface.
3854
func (p *Brontide) PubKey() [33]byte {
6✔
3855
        return p.cfg.PubKeyBytes
6✔
3856
}
6✔
3857

3858
// IdentityKey returns the public key of the remote peer.
3859
//
3860
// NOTE: Part of the lnpeer.Peer interface.
3861
func (p *Brontide) IdentityKey() *btcec.PublicKey {
19✔
3862
        return p.cfg.Addr.IdentityKey
19✔
3863
}
19✔
3864

3865
// Address returns the network address of the remote peer.
3866
//
3867
// NOTE: Part of the lnpeer.Peer interface.
3868
func (p *Brontide) Address() net.Addr {
4✔
3869
        return p.cfg.Addr.Address
4✔
3870
}
4✔
3871

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

4✔
3879
        errChan := make(chan error, 1)
4✔
3880
        newChanMsg := &newChannelMsg{
4✔
3881
                channel: newChan,
4✔
3882
                err:     errChan,
4✔
3883
        }
4✔
3884

4✔
3885
        select {
4✔
3886
        case p.newActiveChannel <- newChanMsg:
4✔
3887
        case <-cancel:
×
3888
                return errors.New("canceled adding new channel")
×
3889
        case <-p.quit:
×
3890
                return lnpeer.ErrPeerExiting
×
3891
        }
3892

3893
        // We pause here to wait for the peer to recognize the new channel
3894
        // before we close the channel barrier corresponding to the channel.
3895
        select {
4✔
3896
        case err := <-errChan:
4✔
3897
                return err
4✔
3898
        case <-p.quit:
×
3899
                return lnpeer.ErrPeerExiting
×
3900
        }
3901
}
3902

3903
// AddPendingChannel adds a pending open channel to the peer. The channel
3904
// should fail to be added if the cancel channel is closed.
3905
//
3906
// NOTE: Part of the lnpeer.Peer interface.
3907
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
3908
        cancel <-chan struct{}) error {
4✔
3909

4✔
3910
        errChan := make(chan error, 1)
4✔
3911
        newChanMsg := &newChannelMsg{
4✔
3912
                channelID: cid,
4✔
3913
                err:       errChan,
4✔
3914
        }
4✔
3915

4✔
3916
        select {
4✔
3917
        case p.newPendingChannel <- newChanMsg:
4✔
3918

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

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

3926
        // We pause here to wait for the peer to recognize the new pending
3927
        // channel before we close the channel barrier corresponding to the
3928
        // channel.
3929
        select {
4✔
3930
        case err := <-errChan:
4✔
3931
                return err
4✔
3932

3933
        case <-cancel:
×
3934
                return errors.New("canceled adding pending channel")
×
3935

3936
        case <-p.quit:
×
3937
                return lnpeer.ErrPeerExiting
×
3938
        }
3939
}
3940

3941
// RemovePendingChannel removes a pending open channel from the peer.
3942
//
3943
// NOTE: Part of the lnpeer.Peer interface.
3944
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
4✔
3945
        errChan := make(chan error, 1)
4✔
3946
        newChanMsg := &newChannelMsg{
4✔
3947
                channelID: cid,
4✔
3948
                err:       errChan,
4✔
3949
        }
4✔
3950

4✔
3951
        select {
4✔
3952
        case p.removePendingChannel <- newChanMsg:
4✔
3953
        case <-p.quit:
×
3954
                return lnpeer.ErrPeerExiting
×
3955
        }
3956

3957
        // We pause here to wait for the peer to respond to the cancellation of
3958
        // the pending channel before we close the channel barrier
3959
        // corresponding to the channel.
3960
        select {
4✔
3961
        case err := <-errChan:
4✔
3962
                return err
4✔
3963

3964
        case <-p.quit:
×
3965
                return lnpeer.ErrPeerExiting
×
3966
        }
3967
}
3968

3969
// StartTime returns the time at which the connection was established if the
3970
// peer started successfully, and zero otherwise.
3971
func (p *Brontide) StartTime() time.Time {
4✔
3972
        return p.startTime
4✔
3973
}
4✔
3974

3975
// handleCloseMsg is called when a new cooperative channel closure related
3976
// message is received from the remote peer. We'll use this message to advance
3977
// the chan closer state machine.
3978
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
17✔
3979
        link := p.fetchLinkFromKeyAndCid(msg.cid)
17✔
3980

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

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

×
3992
                errMsg := &lnwire.Error{
×
3993
                        ChanID: msg.cid,
×
3994
                        Data:   lnwire.ErrorData(err.Error()),
×
3995
                }
×
3996
                p.queueMsg(errMsg, nil)
×
3997
                return
×
3998
        }
3999

4000
        handleErr := func(err error) {
18✔
4001
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
4002
                p.log.Error(err)
1✔
4003

1✔
4004
                // As the negotiations failed, we'll reset the channel state machine to
1✔
4005
                // ensure we act to on-chain events as normal.
1✔
4006
                chanCloser.Channel().ResetState()
1✔
4007

1✔
4008
                if chanCloser.CloseRequest() != nil {
1✔
4009
                        chanCloser.CloseRequest().Err <- err
×
4010
                }
×
4011
                delete(p.activeChanCloses, msg.cid)
1✔
4012

1✔
4013
                p.Disconnect(err)
1✔
4014
        }
4015

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

4026
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
9✔
4027
                if err != nil {
9✔
4028
                        handleErr(err)
×
4029
                        return
×
4030
                }
×
4031

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

4041
                        // Immediately disallow any new HTLC's from being added
4042
                        // in the outgoing direction.
4043
                        if !link.DisableAdds(htlcswitch.Outgoing) {
6✔
4044
                                p.log.Warnf("Outgoing link adds already "+
×
4045
                                        "disabled: %v", link.ChanID())
×
4046
                        }
×
4047

4048
                        // When we have a Shutdown to send, we defer it till the
4049
                        // next time we send a CommitSig to remain spec
4050
                        // compliant.
4051
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
12✔
4052
                                p.queueMsg(&msg, nil)
6✔
4053
                        })
6✔
4054
                })
4055

4056
                beginNegotiation := func() {
18✔
4057
                        oClosingSigned, err := chanCloser.BeginNegotiation()
9✔
4058
                        if err != nil {
9✔
4059
                                handleErr(err)
×
4060
                                return
×
4061
                        }
×
4062

4063
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
18✔
4064
                                p.queueMsg(&msg, nil)
9✔
4065
                        })
9✔
4066
                }
4067

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

4081
        case *lnwire.ClosingSigned:
12✔
4082
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
12✔
4083
                if err != nil {
13✔
4084
                        handleErr(err)
1✔
4085
                        return
1✔
4086
                }
1✔
4087

4088
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
24✔
4089
                        p.queueMsg(&msg, nil)
12✔
4090
                })
12✔
4091

4092
        default:
×
4093
                panic("impossible closeMsg type")
×
4094
        }
4095

4096
        // If we haven't finished close negotiations, then we'll continue as we
4097
        // can't yet finalize the closure.
4098
        if _, err := chanCloser.ClosingTx(); err != nil {
28✔
4099
                return
12✔
4100
        }
12✔
4101

4102
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
4103
        // the channel closure by notifying relevant sub-systems and launching a
4104
        // goroutine to wait for close tx conf.
4105
        p.finalizeChanClosure(chanCloser)
8✔
4106
}
4107

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

4122
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
4123
func (p *Brontide) NetAddress() *lnwire.NetAddress {
4✔
4124
        return p.cfg.Addr
4✔
4125
}
4✔
4126

4127
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
4128
func (p *Brontide) Inbound() bool {
4✔
4129
        return p.cfg.Inbound
4✔
4130
}
4✔
4131

4132
// ConnReq is a getter for the Brontide's connReq in cfg.
4133
func (p *Brontide) ConnReq() *connmgr.ConnReq {
4✔
4134
        return p.cfg.ConnReq
4✔
4135
}
4✔
4136

4137
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
4138
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
4✔
4139
        return p.cfg.ErrorBuffer
4✔
4140
}
4✔
4141

4142
// SetAddress sets the remote peer's address given an address.
4143
func (p *Brontide) SetAddress(address net.Addr) {
×
4144
        p.cfg.Addr.Address = address
×
4145
}
×
4146

4147
// ActiveSignal returns the peer's active signal.
4148
func (p *Brontide) ActiveSignal() chan struct{} {
4✔
4149
        return p.activeSignal
4✔
4150
}
4✔
4151

4152
// Conn returns a pointer to the peer's connection struct.
4153
func (p *Brontide) Conn() net.Conn {
4✔
4154
        return p.cfg.Conn
4✔
4155
}
4✔
4156

4157
// BytesReceived returns the number of bytes received from the peer.
4158
func (p *Brontide) BytesReceived() uint64 {
4✔
4159
        return atomic.LoadUint64(&p.bytesReceived)
4✔
4160
}
4✔
4161

4162
// BytesSent returns the number of bytes sent to the peer.
4163
func (p *Brontide) BytesSent() uint64 {
4✔
4164
        return atomic.LoadUint64(&p.bytesSent)
4✔
4165
}
4✔
4166

4167
// LastRemotePingPayload returns the last payload the remote party sent as part
4168
// of their ping.
4169
func (p *Brontide) LastRemotePingPayload() []byte {
4✔
4170
        pingPayload := p.lastPingPayload.Load()
4✔
4171
        if pingPayload == nil {
8✔
4172
                return []byte{}
4✔
4173
        }
4✔
4174

4175
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
2✔
4176
        if !ok {
2✔
4177
                return nil
×
4178
        }
×
4179

4180
        return pingBytes
2✔
4181
}
4182

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

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

4204
        p.channelEventClient = sub
7✔
4205

7✔
4206
        return nil
7✔
4207
}
4208

4209
// updateNextRevocation updates the existing channel's next revocation if it's
4210
// nil.
4211
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
7✔
4212
        chanPoint := c.FundingOutpoint
7✔
4213
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
7✔
4214

7✔
4215
        // Read the current channel.
7✔
4216
        currentChan, loaded := p.activeChannels.Load(chanID)
7✔
4217

7✔
4218
        // currentChan should exist, but we perform a check anyway to avoid nil
7✔
4219
        // pointer dereference.
7✔
4220
        if !loaded {
8✔
4221
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
4222
                        chanID)
1✔
4223
        }
1✔
4224

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

4232
        // If we're being sent a new channel, and our existing channel doesn't
4233
        // have the next revocation, then we need to update the current
4234
        // existing channel.
4235
        if currentChan.RemoteNextRevocation() != nil {
5✔
4236
                return nil
×
4237
        }
×
4238

4239
        p.log.Infof("Processing retransmitted ChannelReady for "+
5✔
4240
                "ChannelPoint(%v)", chanPoint)
5✔
4241

5✔
4242
        nextRevoke := c.RemoteNextRevocation
5✔
4243

5✔
4244
        err := currentChan.InitNextRevocation(nextRevoke)
5✔
4245
        if err != nil {
5✔
4246
                return fmt.Errorf("unable to init next revocation: %w", err)
×
4247
        }
×
4248

4249
        return nil
5✔
4250
}
4251

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

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

4✔
4266
        chanOpts := c.ChanOpts
4✔
4267
        if shouldReestablish {
8✔
4268
                // If we have to do the reestablish dance for this channel,
4✔
4269
                // ensure that we don't try to call InitRemoteMusigNonces twice
4✔
4270
                // by calling SkipNonceInit.
4✔
4271
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
4✔
4272
        }
4✔
4273

4274
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
4✔
4275
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
4276
        })
×
4277
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
4✔
4278
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
4279
        })
×
4280
        p.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
4✔
4281
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
4282
        })
×
4283

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

4294
        // Store the channel in the activeChannels map.
4295
        p.activeChannels.Store(chanID, lnChan)
4✔
4296

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

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

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

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

4325
        return nil
4✔
4326
}
4327

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

4✔
4336
        // Only update RemoteNextRevocation if the channel is in the
4✔
4337
        // activeChannels map and if we added the link to the switch. Only
4✔
4338
        // active channels will be added to the switch.
4✔
4339
        if p.isActiveChannel(chanID) {
8✔
4340
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
4✔
4341
                        chanPoint)
4✔
4342

4✔
4343
                // Handle it and close the err chan on the request.
4✔
4344
                close(req.err)
4✔
4345

4✔
4346
                // Update the next revocation point.
4✔
4347
                err := p.updateNextRevocation(newChan.OpenChannel)
4✔
4348
                if err != nil {
4✔
4349
                        p.log.Errorf(err.Error())
×
4350
                }
×
4351

4352
                return
4✔
4353
        }
4354

4355
        // This is a new channel, we now add it to the map.
4356
        if err := p.addActiveChannel(req.channel); err != nil {
4✔
4357
                // Log and send back the error to the request.
×
4358
                p.log.Errorf(err.Error())
×
4359
                req.err <- err
×
4360

×
4361
                return
×
4362
        }
×
4363

4364
        // Close the err chan if everything went fine.
4365
        close(req.err)
4✔
4366
}
4367

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

8✔
4375
        chanID := req.channelID
8✔
4376

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

1✔
4385
                return
1✔
4386
        }
1✔
4387

4388
        // The channel has already been added, we will do nothing and return.
4389
        if p.isPendingChannel(chanID) {
8✔
4390
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
4391
                        "pending channel request", chanID)
1✔
4392

1✔
4393
                return
1✔
4394
        }
1✔
4395

4396
        // This is a new channel, we now add it to the map `activeChannels`
4397
        // with nil value and mark it as a newly added channel in
4398
        // `addedChannels`.
4399
        p.activeChannels.Store(chanID, nil)
6✔
4400
        p.addedChannels.Store(chanID, struct{}{})
6✔
4401
}
4402

4403
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
4404
// from `activeChannels` map. The request will be ignored if the channel is
4405
// considered active by Brontide. Noop if the channel ID cannot be found.
4406
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
8✔
4407
        defer close(req.err)
8✔
4408

8✔
4409
        chanID := req.channelID
8✔
4410

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

4420
        // The channel has not been added yet, we will log a warning as there
4421
        // is an unexpected call from funding manager.
4422
        if !p.isPendingChannel(chanID) {
12✔
4423
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
5✔
4424
        }
5✔
4425

4426
        // Remove the record of this pending channel.
4427
        p.activeChannels.Delete(chanID)
7✔
4428
        p.addedChannels.Delete(chanID)
7✔
4429
}
4430

4431
// sendLinkUpdateMsg sends a message that updates the channel to the
4432
// channel's message stream.
4433
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
4✔
4434
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
4✔
4435

4✔
4436
        chanStream, ok := p.activeMsgStreams[cid]
4✔
4437
        if !ok {
8✔
4438
                // If a stream hasn't yet been created, then we'll do so, add
4✔
4439
                // it to the map, and finally start it.
4✔
4440
                chanStream = newChanMsgStream(p, cid)
4✔
4441
                p.activeMsgStreams[cid] = chanStream
4✔
4442
                chanStream.Start()
4✔
4443

4✔
4444
                // Stop the stream when quit.
4✔
4445
                go func() {
8✔
4446
                        <-p.quit
4✔
4447
                        chanStream.Stop()
4✔
4448
                }()
4✔
4449
        }
4450

4451
        // With the stream obtained, add the message to the stream so we can
4452
        // continue processing message.
4453
        chanStream.AddMsg(msg)
4✔
4454
}
4455

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

4465
        return timeout
67✔
4466
}
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