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

lightningnetwork / lnd / 11219354629

07 Oct 2024 03:56PM UTC coverage: 58.585% (-0.2%) from 58.814%
11219354629

Pull #9147

github

ziggie1984
fixup! sqlc: migration up script for payments.
Pull Request #9147: [Part 1|3] Introduce SQL Payment schema into LND

130227 of 222287 relevant lines covered (58.59%)

29106.19 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

122
        err chan error
123
}
124

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

411
        // MaxFeeExposure limits the number of outstanding fees in a channel.
412
        // This value will be passed to created links.
413
        MaxFeeExposure lnwire.MilliSatoshi
414

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

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

424
        // Quit is the server's quit channel. If this is closed, we halt operation.
425
        Quit chan struct{}
426
}
427

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

439
        // MUST be used atomically.
440
        bytesReceived uint64
441
        bytesSent     uint64
442

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

460
        pingManager *PingManager
461

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

469
        cfg Config
470

471
        // activeSignal when closed signals that the peer is now active and
472
        // ready to process messages.
473
        activeSignal chan struct{}
474

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

479
        // sendQueue is the channel which is used to queue outgoing messages to be
480
        // written onto the wire. Note that this channel is unbuffered.
481
        sendQueue chan outgoingMsg
482

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

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

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

506
        // newActiveChannel is used by the fundingManager to send fully opened
507
        // channels to the source peer which handled the funding workflow.
508
        newActiveChannel chan *newChannelMsg
509

510
        // newPendingChannel is used by the fundingManager to send pending open
511
        // channels to the source peer which handled the funding workflow.
512
        newPendingChannel chan *newChannelMsg
513

514
        // removePendingChannel is used by the fundingManager to cancel pending
515
        // open channels to the source peer when the funding flow is failed.
516
        removePendingChannel chan *newChannelMsg
517

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

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

528
        // localCloseChanReqs is a channel in which any local requests to close
529
        // a particular channel are sent over.
530
        localCloseChanReqs chan *htlcswitch.ChanClose
531

532
        // linkFailures receives all reported channel failures from the switch,
533
        // and instructs the channelManager to clean remaining channel state.
534
        linkFailures chan linkFailureReport
535

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

541
        // remoteFeatures is the feature vector received from the peer during
542
        // the connection handshake.
543
        remoteFeatures *lnwire.FeatureVector
544

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

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

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

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

569
        startReady chan struct{}
570
        quit       chan struct{}
571
        wg         sync.WaitGroup
572

573
        // log is a peer-specific logging instance.
574
        log btclog.Logger
575
}
576

577
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer interface.
578
var _ lnpeer.Peer = (*Brontide)(nil)
579

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

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

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

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

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

27✔
621
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
27✔
622
                remoteAddr := cfg.Conn.RemoteAddr().String()
27✔
623
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
27✔
624
                        strings.Contains(remoteAddr, "127.0.0.1")
29✔
625
        }
2✔
626

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

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

×
654
                return lastSerializedBlockHeader[:]
×
655
        }
×
656

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

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

×
686
        return p
×
687
}
688

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

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

701
        p.log.Tracef("starting with conn[%v->%v]",
702
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
5✔
703

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

×
715
        if len(activeChans) == 0 {
×
716
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
×
717
        }
718

8✔
719
        // Quickly check if we have any existing legacy channels with this
3✔
720
        // peer.
3✔
721
        haveLegacyChan := false
722
        for _, c := range activeChans {
723
                if c.ChanType.IsTweakless() {
724
                        continue
5✔
725
                }
9✔
726

8✔
727
                haveLegacyChan = true
4✔
728
                break
729
        }
730

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

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

5✔
746
                msg, err := p.readNextMessage()
10✔
747
                if err != nil {
5✔
748
                        readErr <- err
5✔
749
                        msgChan <- nil
5✔
750
                        return
6✔
751
                }
1✔
752
                readErr <- nil
1✔
753
                msgChan <- msg
1✔
754
        }()
1✔
755

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

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

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

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

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

10✔
804
        msgs, err := p.loadActiveChannels(activeChans)
5✔
805
        if err != nil {
5✔
806
                return fmt.Errorf("unable to load channels: %w", err)
807
        }
5✔
808

5✔
809
        p.startTime = time.Now()
×
810

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

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

×
828
        err = p.pingManager.Start()
829
        if err != nil {
830
                return fmt.Errorf("could not start ping manager %w", err)
831
        }
5✔
832

5✔
833
        p.wg.Add(4)
×
834
        go p.queueHandler()
×
835
        go p.writeHandler()
836
        go p.channelManager()
5✔
837
        go p.readHandler()
5✔
838

5✔
839
        // Signal to any external processes that the peer is now active.
5✔
840
        close(p.activeSignal)
5✔
841

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

5✔
857
        return nil
5✔
858
}
5✔
859

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

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

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

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

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

2✔
905
// internalKeyForAddr returns the internal key associated with a taproot
2✔
906
// address.
2✔
907
func internalKeyForAddr(wallet *lnwallet.LightningWallet,
908
        deliveryScript []byte) (fn.Option[btcec.PublicKey], error) {
909

910
        none := fn.None[btcec.PublicKey]()
911

912
        pkScript, err := txscript.ParsePkScript(deliveryScript)
11✔
913
        if err != nil {
11✔
914
                return none, err
11✔
915
        }
11✔
916
        addr, err := pkScript.Address(&wallet.Cfg.NetParams)
11✔
917
        if err != nil {
11✔
918
                return none, err
11✔
919
        }
11✔
920

11✔
921
        // If it's not a taproot address, we don't require to know the internal
11✔
922
        // key in the first place. So we don't return an error here, but also no
×
923
        // internal key.
×
924
        _, isTaproot := addr.(*btcutil.AddressTaproot)
925
        if !isTaproot {
11✔
926
                return none, nil
11✔
927
        }
11✔
928

13✔
929
        walletAddr, err := wallet.AddressInfo(addr)
2✔
930
        if err != nil {
2✔
931
                return none, err
932
        }
933

934
        // If the address isn't known to the wallet, we can't determine the
935
        // internal key.
936
        if walletAddr == nil {
937
                return none, nil
938
        }
939

940
        pubKeyAddr, ok := walletAddr.(waddrmgr.ManagedPubKeyAddress)
5✔
941
        if !ok {
5✔
942
                return none, fmt.Errorf("expected pubkey addr, got %T",
5✔
943
                        pubKeyAddr)
5✔
944
        }
5✔
945

5✔
946
        return fn.Some(*pubKeyAddr.PubKey()), nil
5✔
947
}
5✔
948

9✔
949
// addrWithInternalKey takes a delivery script, then attempts to supplement it
4✔
950
// with information related to the internal key for the addr, but only if it's
6✔
951
// a taproot addr.
2✔
952
func (p *Brontide) addrWithInternalKey(
2✔
953
        deliveryScript []byte) fn.Result[chancloser.DeliveryAddrWithKey] {
2✔
954

2✔
955
        // TODO(roasbeef): not compatible with external shutdown addr?
2✔
956
        // Currently, custom channels cannot be created with external upfront
2✔
957
        // shutdown addresses, so this shouldn't be an issue. We only require
2✔
958
        // the internal key for taproot addresses to be able to provide a non
2✔
959
        // inclusion proof of any scripts.
2✔
960

2✔
961
        internalKey, err := internalKeyForAddr(p.cfg.Wallet, deliveryScript)
2✔
962
        if err != nil {
4✔
963
                return fn.Err[chancloser.DeliveryAddrWithKey](err)
2✔
964
        }
2✔
965

×
966
        return fn.Ok(chancloser.DeliveryAddrWithKey{
×
967
                DeliveryAddress: deliveryScript,
968
                InternalKey:     internalKey,
2✔
969
        })
2✔
970
}
2✔
971

2✔
972
// loadActiveChannels creates indexes within the peer for tracking all active
2✔
973
// channels returned by the database. It returns a slice of channel reestablish
×
974
// messages that should be sent to the peer immediately, in case we have borked
×
975
// channels that haven't been closed yet.
976
func (p *Brontide) loadActiveChannels(chans []*channeldb.OpenChannel) (
2✔
977
        []lnwire.Message, error) {
2✔
978

2✔
979
        // Return a slice of messages to send to the peers in case the channel
2✔
980
        // cannot be loaded normally.
2✔
981
        var msgs []lnwire.Message
2✔
982

2✔
983
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
2✔
984

×
985
        for _, dbChan := range chans {
×
986
                hasScidFeature := dbChan.ChanType.HasScidAliasFeature()
987
                if scidAliasNegotiated && !hasScidFeature {
2✔
988
                        // We'll request and store an alias, making sure that a
2✔
989
                        // gossiper mapping is not created for the alias to the
2✔
990
                        // real SCID. This is done because the peer and funding
2✔
991
                        // manager are not aware of each other's states and if
2✔
992
                        // we did not do this, we would accept alias channel
2✔
993
                        // updates after 6 confirmations, which would be buggy.
994
                        // We'll queue a channel_ready message with the new
995
                        // alias. This should technically be done *after* the
996
                        // reestablish, but this behavior is pre-existing since
997
                        // the funding manager may already queue a
998
                        // channel_ready before the channel_reestablish.
999
                        if !dbChan.IsPending {
1000
                                aliasScid, err := p.cfg.RequestAlias()
2✔
1001
                                if err != nil {
2✔
1002
                                        return nil, err
×
1003
                                }
×
1004

1005
                                err = p.cfg.AddLocalAlias(
1006
                                        aliasScid, dbChan.ShortChanID(), false,
4✔
1007
                                        false,
4✔
1008
                                )
×
1009
                                if err != nil {
×
1010
                                        return nil, err
4✔
1011
                                }
×
1012

×
1013
                                chanID := lnwire.NewChanIDFromOutPoint(
4✔
1014
                                        dbChan.FundingOutpoint,
4✔
1015
                                )
×
1016

×
1017
                                // Fetch the second commitment point to send in
×
1018
                                // the channel_ready message.
×
1019
                                second, err := dbChan.SecondCommitmentPoint()
1020
                                if err != nil {
1021
                                        return nil, err
4✔
1022
                                }
4✔
1023

4✔
1024
                                channelReadyMsg := lnwire.NewChannelReady(
4✔
1025
                                        chanID, second,
×
1026
                                )
×
1027
                                channelReadyMsg.AliasScid = &aliasScid
×
1028

1029
                                msgs = append(msgs, channelReadyMsg)
4✔
1030
                        }
4✔
1031

4✔
1032
                        // If we've negotiated the option-scid-alias feature
4✔
1033
                        // and this channel does not have ScidAliasFeature set
4✔
1034
                        // to true due to an upgrade where the feature bit was
4✔
1035
                        // turned on, we'll update the channel's database
4✔
1036
                        // state.
4✔
1037
                        err := dbChan.MarkScidAliasNegotiated()
4✔
1038
                        if err != nil {
4✔
1039
                                return nil, err
8✔
1040
                        }
4✔
1041
                }
4✔
1042

4✔
1043
                var chanOpts []lnwallet.ChannelOpt
4✔
1044
                p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
4✔
1045
                        chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
4✔
1046
                })
4✔
1047
                p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
4✔
1048
                        chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
4✔
1049
                })
4✔
1050
                lnChan, err := lnwallet.NewLightningChannel(
4✔
1051
                        p.cfg.Signer, dbChan, p.cfg.SigPool, chanOpts...,
4✔
1052
                )
×
1053
                if err != nil {
×
1054
                        return nil, fmt.Errorf("unable to create channel "+
×
1055
                                "state machine: %w", err)
×
1056
                }
1057

1058
                chanPoint := dbChan.FundingOutpoint
4✔
1059

4✔
1060
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
1061

4✔
1062
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
4✔
1063
                        chanPoint, lnChan.IsPending())
4✔
1064

4✔
1065
                // Skip adding any permanently irreconcilable channels to the
4✔
1066
                // htlcswitch.
×
1067
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
×
1068
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
×
1069

×
1070
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
×
1071
                                "start.", chanPoint, dbChan.ChanStatus())
×
1072

×
1073
                        // To help our peer recover from a potential data loss,
1074
                        // we resend our channel reestablish message if the
1075
                        // channel is in a borked state. We won't process any
×
1076
                        // channel reestablish message sent from the peer, but
×
1077
                        // that's okay since the assumption is that we did when
1078
                        // marking the channel borked.
1079
                        chanSync, err := dbChan.ChanSyncMsg()
1080
                        if err != nil {
1081
                                p.log.Errorf("Unable to create channel "+
×
1082
                                        "reestablish message for channel %v: "+
1083
                                        "%v", chanPoint, err)
1084
                                continue
4✔
1085
                        }
1086

1087
                        msgs = append(msgs, chanSync)
1088

1089
                        // Check if this channel needs to have the cooperative
1090
                        // close process restarted. If so, we'll need to send
2✔
1091
                        // the Shutdown message that is returned.
2✔
1092
                        if dbChan.HasChanStatus(
2✔
1093
                                channeldb.ChanStatusCoopBroadcasted,
2✔
1094
                        ) {
2✔
1095

×
1096
                                shutdownMsg, err := p.restartCoopClose(lnChan)
×
1097
                                if err != nil {
1098
                                        p.log.Errorf("Unable to restart "+
1099
                                                "coop close for channel: %v",
1100
                                                err)
1101
                                        continue
1102
                                }
1103

1104
                                if shutdownMsg == nil {
1105
                                        continue
2✔
1106
                                }
2✔
1107

4✔
1108
                                // Append the message to the set of messages to
2✔
1109
                                // send.
2✔
1110
                                msgs = append(msgs, shutdownMsg)
4✔
1111
                        }
2✔
1112

2✔
1113
                        continue
1114
                }
1115

1116
                // Before we register this new link with the HTLC Switch, we'll
1117
                // need to fetch its current link-layer forwarding policy from
2✔
1118
                // the database.
4✔
1119
                graph := p.cfg.ChannelGraph
2✔
1120
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
2✔
1121
                        &chanPoint,
2✔
1122
                )
2✔
1123
                if err != nil && !errors.Is(err, channeldb.ErrEdgeNotFound) {
2✔
1124
                        return nil, err
×
1125
                }
×
1126

1127
                // We'll filter out our policy from the directional channel
2✔
1128
                // edges based whom the edge connects to. If it doesn't connect
2✔
1129
                // to us, then we know that we were the one that advertised the
2✔
1130
                // policy.
2✔
1131
                //
2✔
1132
                // TODO(roasbeef): can add helper method to get policy for
2✔
1133
                // particular channel.
2✔
1134
                var selfPolicy *models.ChannelEdgePolicy
2✔
1135
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
2✔
1136
                        p.cfg.ServerPubKey[:]) {
2✔
1137

2✔
1138
                        selfPolicy = p1
2✔
1139
                } else {
2✔
1140
                        selfPolicy = p2
2✔
1141
                }
2✔
1142

2✔
1143
                // If we don't yet have an advertised routing policy, then
2✔
1144
                // we'll use the current default, otherwise we'll translate the
2✔
1145
                // routing policy into a forwarding policy.
2✔
1146
                var forwardingPolicy *models.ForwardingPolicy
1147
                if selfPolicy != nil {
2✔
1148
                        var inboundWireFee lnwire.Fee
2✔
1149
                        _, err := selfPolicy.ExtraOpaqueData.ExtractRecords(
2✔
1150
                                &inboundWireFee,
2✔
1151
                        )
2✔
1152
                        if err != nil {
2✔
1153
                                return nil, err
2✔
1154
                        }
2✔
1155

2✔
1156
                        inboundFee := models.NewInboundFeeFromWire(
4✔
1157
                                inboundWireFee,
2✔
1158
                        )
2✔
1159

2✔
1160
                        forwardingPolicy = &models.ForwardingPolicy{
1161
                                MinHTLCOut:    selfPolicy.MinHTLC,
1162
                                MaxHTLC:       selfPolicy.MaxHTLC,
2✔
1163
                                BaseFee:       selfPolicy.FeeBaseMSat,
2✔
1164
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
×
1165
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
×
1166

1167
                                InboundFee: inboundFee,
2✔
1168
                        }
2✔
1169
                } else {
2✔
1170
                        p.log.Warnf("Unable to find our forwarding policy "+
2✔
1171
                                "for channel %v, using default values",
4✔
1172
                                chanPoint)
2✔
1173
                        forwardingPolicy = &p.cfg.RoutingPolicy
2✔
1174
                }
2✔
1175

2✔
1176
                p.log.Tracef("Using link policy of: %v",
2✔
1177
                        spew.Sdump(forwardingPolicy))
×
1178

×
1179
                // If the channel is pending, set the value to nil in the
×
1180
                // activeChannels map. This is done to signify that the channel
×
1181
                // is pending. We don't add the link to the switch here - it's
×
1182
                // the funding manager's responsibility to spin up pending
1183
                // channels. Adding them here would just be extra work as we'll
2✔
1184
                // tear them down when creating + adding the final link.
2✔
1185
                if lnChan.IsPending() {
2✔
1186
                        p.activeChannels.Store(chanID, nil)
2✔
1187

×
1188
                        continue
×
1189
                }
×
1190

×
1191
                shutdownInfo, err := lnChan.State().ShutdownInfo()
2✔
1192
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
2✔
1193
                        return nil, err
2✔
1194
                }
2✔
1195

×
1196
                var (
×
1197
                        shutdownMsg     fn.Option[lnwire.Shutdown]
×
1198
                        shutdownInfoErr error
×
1199
                )
×
1200
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
1201
                        // Compute an ideal fee.
2✔
1202
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
2✔
1203
                                p.cfg.CoopCloseTargetConfs,
2✔
1204
                        )
2✔
1205
                        if err != nil {
2✔
1206
                                shutdownInfoErr = fmt.Errorf("unable to "+
2✔
1207
                                        "estimate fee: %w", err)
2✔
1208

2✔
1209
                                return
2✔
1210
                        }
×
1211

×
1212
                        addr, err := p.addrWithInternalKey(
×
1213
                                info.DeliveryScript.Val,
×
1214
                        ).Unpack()
×
1215
                        if err != nil {
1216
                                shutdownInfoErr = fmt.Errorf("unable to make "+
2✔
1217
                                        "delivery addr: %w", err)
1218
                                return
2✔
1219
                        }
×
1220
                        chanCloser, err := p.createChanCloser(
×
1221
                                lnChan, addr, feePerKw, nil, info.Closer(),
1222
                        )
1223
                        if err != nil {
2✔
1224
                                shutdownInfoErr = fmt.Errorf("unable to "+
2✔
1225
                                        "create chan closer: %w", err)
2✔
1226

2✔
1227
                                return
×
1228
                        }
×
1229

1230
                        chanID := lnwire.NewChanIDFromOutPoint(
2✔
1231
                                lnChan.State().FundingOutpoint,
2✔
1232
                        )
2✔
1233

2✔
1234
                        p.activeChanCloses[chanID] = chanCloser
2✔
1235

×
1236
                        // Create the Shutdown message.
×
1237
                        shutdown, err := chanCloser.ShutdownChan()
×
1238
                        if err != nil {
1239
                                delete(p.activeChanCloses, chanID)
2✔
1240
                                shutdownInfoErr = err
1241

1242
                                return
5✔
1243
                        }
1244

1245
                        shutdownMsg = fn.Some(*shutdown)
1246
                })
1247
                if shutdownInfoErr != nil {
1248
                        return nil, shutdownInfoErr
1249
                }
1250

2✔
1251
                // Subscribe to the set of on-chain events for this channel.
2✔
1252
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
2✔
1253
                        chanPoint,
2✔
1254
                )
2✔
1255
                if err != nil {
2✔
1256
                        return nil, err
4✔
1257
                }
2✔
1258

2✔
1259
                err = p.addLink(
2✔
1260
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
2✔
1261
                        true, shutdownMsg,
2✔
1262
                )
2✔
1263
                if err != nil {
2✔
1264
                        return nil, fmt.Errorf("unable to add link %v to "+
2✔
1265
                                "switch: %v", chanPoint, err)
2✔
1266
                }
2✔
1267

×
1268
                p.activeChannels.Store(chanID, lnChan)
×
1269
        }
1270

1271
        return msgs, nil
1272
}
4✔
1273

2✔
1274
// addLink creates and adds a new ChannelLink from the specified channel.
2✔
1275
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1276
        lnChan *lnwallet.LightningChannel,
4✔
1277
        forwardingPolicy *models.ForwardingPolicy,
2✔
1278
        chainEvents *contractcourt.ChainEventSubscription,
2✔
1279
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
1280

1281
        // onChannelFailure will be called by the link in case the channel
2✔
1282
        // fails for some reason.
2✔
1283
        onChannelFailure := func(chanID lnwire.ChannelID,
2✔
1284
                shortChanID lnwire.ShortChannelID,
2✔
1285
                linkErr htlcswitch.LinkFailureError) {
2✔
1286

2✔
1287
                failure := linkFailureReport{
2✔
1288
                        chanPoint:   *chanPoint,
2✔
1289
                        chanID:      chanID,
2✔
1290
                        shortChanID: shortChanID,
2✔
1291
                        linkErr:     linkErr,
2✔
1292
                }
2✔
1293

2✔
1294
                select {
2✔
1295
                case p.linkFailures <- failure:
2✔
1296
                case <-p.quit:
2✔
1297
                case <-p.cfg.Quit:
2✔
1298
                }
2✔
1299
        }
2✔
1300

2✔
1301
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
2✔
1302
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
2✔
1303
        }
2✔
1304

2✔
1305
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
2✔
1306
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
2✔
1307
        }
2✔
1308

2✔
1309
        //nolint:lll
2✔
1310
        linkCfg := htlcswitch.ChannelLinkConfig{
2✔
1311
                Peer:                   p,
2✔
1312
                DecodeHopIterators:     p.cfg.Sphinx.DecodeHopIterators,
2✔
1313
                ExtractErrorEncrypter:  p.cfg.Sphinx.ExtractErrorEncrypter,
2✔
1314
                FetchLastChannelUpdate: p.cfg.FetchLastChanUpdate,
2✔
1315
                HodlMask:               p.cfg.Hodl.Mask(),
2✔
1316
                Registry:               p.cfg.Invoices,
2✔
1317
                BestHeight:             p.cfg.Switch.BestHeight,
2✔
1318
                Circuits:               p.cfg.Switch.CircuitModifier(),
2✔
1319
                ForwardPackets:         p.cfg.InterceptSwitch.ForwardPackets,
2✔
1320
                FwrdingPolicy:          *forwardingPolicy,
2✔
1321
                FeeEstimator:           p.cfg.FeeEstimator,
2✔
1322
                PreimageCache:          p.cfg.WitnessBeacon,
2✔
1323
                ChainEvents:            chainEvents,
2✔
1324
                UpdateContractSignals:  updateContractSignals,
2✔
1325
                NotifyContractUpdate:   notifyContractUpdate,
2✔
1326
                OnChannelFailure:       onChannelFailure,
2✔
1327
                SyncStates:             syncStates,
2✔
1328
                BatchTicker:            ticker.New(p.cfg.ChannelCommitInterval),
2✔
1329
                FwdPkgGCTicker:         ticker.New(time.Hour),
2✔
1330
                PendingCommitTicker: ticker.New(
2✔
1331
                        p.cfg.PendingCommitInterval,
2✔
1332
                ),
2✔
1333
                BatchSize:               p.cfg.ChannelCommitBatchSize,
2✔
1334
                UnsafeReplay:            p.cfg.UnsafeReplay,
2✔
1335
                MinUpdateTimeout:        htlcswitch.DefaultMinLinkFeeUpdateTimeout,
1336
                MaxUpdateTimeout:        htlcswitch.DefaultMaxLinkFeeUpdateTimeout,
1337
                OutgoingCltvRejectDelta: p.cfg.OutgoingCltvRejectDelta,
1338
                TowerClient:             p.cfg.TowerClient,
1339
                MaxOutgoingCltvExpiry:   p.cfg.MaxOutgoingCltvExpiry,
5✔
1340
                MaxFeeAllocation:        p.cfg.MaxChannelFeeAllocation,
5✔
1341
                MaxAnchorsCommitFeeRate: p.cfg.MaxAnchorsCommitFeeRate,
5✔
1342
                NotifyActiveLink:        p.cfg.ChannelNotifier.NotifyActiveLinkEvent,
5✔
1343
                NotifyActiveChannel:     p.cfg.ChannelNotifier.NotifyActiveChannelEvent,
9✔
1344
                NotifyInactiveChannel:   p.cfg.ChannelNotifier.NotifyInactiveChannelEvent,
6✔
1345
                NotifyInactiveLinkEvent: p.cfg.ChannelNotifier.NotifyInactiveLinkEvent,
2✔
1346
                HtlcNotifier:            p.cfg.HtlcNotifier,
1347
                GetAliases:              p.cfg.GetAliases,
8✔
1348
                PreviouslySentShutdown:  shutdownMsg,
4✔
1349
                DisallowRouteBlinding:   p.cfg.DisallowRouteBlinding,
1350
                MaxFeeExposure:          p.cfg.MaxFeeExposure,
1351
        }
2✔
1352

2✔
1353
        // Before adding our new link, purge the switch of any pending or live
1354
        // links going by the same channel id. If one is found, we'll shut it
10✔
1355
        // down to ensure that the mailboxes are only ever under the control of
5✔
1356
        // one link.
5✔
1357
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
1358
        p.cfg.Switch.RemoveLink(chanID)
2✔
1359

2✔
1360
        // With the channel link created, we'll now notify the htlc switch so
×
1361
        // this channel can be used to dispatch local payments and also
×
1362
        // passively forward payments.
×
1363
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
1364
}
2✔
1365

×
1366
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
×
1367
// one confirmed public channel exists with them.
1368
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
1369
        defer p.wg.Done()
1370

1371
        hasConfirmedPublicChan := false
5✔
1372
        for _, channel := range channels {
5✔
1373
                if channel.IsPending {
5✔
1374
                        continue
5✔
1375
                }
8✔
1376
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
3✔
1377
                        continue
3✔
1378
                }
1379

4✔
1380
                hasConfirmedPublicChan = true
8✔
1381
                break
4✔
1382
        }
4✔
1383
        if !hasConfirmedPublicChan {
6✔
1384
                return
2✔
1385
        }
2✔
1386

1387
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
4✔
1388
        if err != nil {
8✔
1389
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
4✔
1390
                return
1391
        }
1392

2✔
1393
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
2✔
1394
                p.log.Debugf("Unable to resend node announcement: %v", err)
1395
        }
1396
}
4✔
1397

4✔
1398
// maybeSendChannelUpdates sends our channel updates to the remote peer if we
1399
// have any active channels with them.
1400
func (p *Brontide) maybeSendChannelUpdates() {
1401
        defer p.wg.Done()
1402

1403
        // If we don't have any active channels, then we can exit early.
1404
        if p.activeChannels.Len() == 0 {
1405
                return
4✔
1406
        }
6✔
1407

2✔
1408
        maybeSendUpd := func(cid lnwire.ChannelID,
2✔
1409
                lnChan *lnwallet.LightningChannel) error {
2✔
1410

2✔
1411
                // Nil channels are pending, so we'll skip them.
2✔
1412
                if lnChan == nil {
2✔
1413
                        return nil
1414
                }
4✔
1415

4✔
1416
                dbChan := lnChan.State()
4✔
1417
                scid := func() lnwire.ShortChannelID {
4✔
1418
                        switch {
4✔
1419
                        // Otherwise if it's a zero conf channel and confirmed,
4✔
1420
                        // then we need to use the "real" scid.
×
1421
                        case dbChan.IsZeroConf() && dbChan.ZeroConfConfirmed():
×
1422
                                return dbChan.ZeroConfRealScid()
×
1423

×
1424
                        // Otherwise, we can use the normal scid.
×
1425
                        default:
×
1426
                                return dbChan.ShortChanID()
×
1427
                        }
×
1428
                }()
1429

4✔
1430
                // Now that we know the channel is in a good state, we'll try
1431
                // to fetch the update to send to the remote peer. If the
1432
                // channel is pending, and not a zero conf channel, we'll get
4✔
1433
                // an error here which we'll ignore.
1434
                chanUpd, err := p.cfg.FetchLastChanUpdate(scid)
1435
                if err != nil {
1436
                        p.log.Debugf("Unable to fetch channel update for "+
1437
                                "ChannelPoint(%v), scid=%v: %v",
1438
                                dbChan.FundingOutpoint, dbChan.ShortChanID, err)
1439

1440
                        return nil
1441
                }
1442

1443
                p.log.Debugf("Sending channel update for ChannelPoint(%v), "+
2✔
1444
                        "scid=%v", dbChan.FundingOutpoint, dbChan.ShortChanID)
2✔
1445

2✔
1446
                // We'll send it as a normal message instead of using the lazy
2✔
1447
                // queue to prioritize transmission of the fresh update.
2✔
1448
                if err := p.SendMessage(false, chanUpd); err != nil {
×
1449
                        err := fmt.Errorf("unable to send channel update for "+
×
1450
                                "ChannelPoint(%v), scid=%v: %w",
1451
                                dbChan.FundingOutpoint, dbChan.ShortChanID(),
1452
                                err)
2✔
1453
                        p.log.Errorf(err.Error())
2✔
1454

1✔
1455
                        return err
1456
                }
1457

2✔
1458
                return nil
1459
        }
1460

1461
        p.activeChannels.ForEach(maybeSendUpd)
1462
}
1463

2✔
1464
// WaitForDisconnect waits until the peer has disconnected. A peer may be
4✔
1465
// disconnected if the local or remote side terminates the connection, or an
2✔
1466
// irrecoverable protocol error has been encountered. This method will only
2✔
1467
// begin watching the peer's waitgroup after the ready channel or the peer's
1468
// quit channel are signaled. The ready channel should only be signaled if a
1469
// call to Start returns no error. Otherwise, if the peer fails to start,
1470
// calling Disconnect will signal the quit channel and the method will not
2✔
1471
// block, since no goroutines were spawned.
2✔
1472
func (p *Brontide) WaitForDisconnect(ready chan struct{}) {
×
1473
        // Before we try to call the `Wait` goroutine, we'll make sure the main
×
1474
        // set of goroutines are already active.
1475
        select {
1476
        case <-p.startReady:
2✔
1477
        case <-p.quit:
2✔
1478
                return
2✔
1479
        }
2✔
1480

2✔
1481
        select {
2✔
1482
        case <-ready:
2✔
1483
        case <-p.quit:
2✔
1484
        }
2✔
1485

2✔
1486
        p.wg.Wait()
2✔
1487
}
2✔
1488

2✔
1489
// Disconnect terminates the connection with the remote peer. Additionally, a
2✔
1490
// signal is sent to the server and htlcSwitch indicating the resources
2✔
1491
// allocated to the peer can now be cleaned up.
4✔
1492
func (p *Brontide) Disconnect(reason error) {
4✔
1493
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
2✔
1494
                return
2✔
1495
        }
1496

1497
        // Make sure initialization has completed before we try to tear things
1498
        // down.
1499
        select {
2✔
1500
        case <-p.startReady:
2✔
1501
        case <-p.quit:
2✔
1502
                return
1503
        }
1504

1505
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
9✔
1506
        p.storeError(err)
9✔
1507

9✔
1508
        p.log.Infof(err.Error())
9✔
1509

×
1510
        // Stop PingManager before closing TCP connection.
×
1511
        p.pingManager.Stop()
1512

9✔
1513
        // Ensure that the TCP connection is properly closed before continuing.
11✔
1514
        p.cfg.Conn.Close()
2✔
1515

2✔
1516
        close(p.quit)
1517

1518
        // If our msg router isn't global (local to this instance), then we'll
1519
        // stop it. Otherwise, we'll leave it running.
1520
        if !p.globalMsgRouter {
1521
                p.msgRouter.WhenSome(func(router msgmux.Router) {
6✔
1522
                        router.Stop()
6✔
1523
                })
6✔
1524
        }
6✔
1525
}
12✔
1526

6✔
1527
// String returns the string representation of this peer.
6✔
1528
func (p *Brontide) String() string {
6✔
1529
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
6✔
1530
}
6✔
1531

6✔
1532
// readNextMessage reads, and returns the next message on the wire along with
6✔
1533
// any additional raw payload.
6✔
1534
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
6✔
1535
        noiseConn := p.cfg.Conn
6✔
1536
        err := noiseConn.SetReadDeadline(time.Time{})
×
1537
        if err != nil {
×
1538
                return nil, err
1539
        }
1540

1541
        pktLen, err := noiseConn.ReadNextHeader()
1542
        if err != nil {
1543
                return nil, fmt.Errorf("read next header: %w", err)
6✔
1544
        }
6✔
1545

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

6✔
1568
                // The ReadNextBody method will actually end up re-using the
6✔
1569
                // buffer, so within this closure, we can continue to use
1570
                // rawMsg as it's just a slice into the buf from the buffer
1571
                // pool.
1572
                rawMsg, readErr := noiseConn.ReadNextBody(buf[:pktLen])
1573
                if readErr != nil {
1574
                        return fmt.Errorf("read next body: %w", readErr)
1575
                }
1576
                msgLen = uint64(len(rawMsg))
1577

1578
                // Next, create a new io.Reader implementation from the raw
1579
                // message, and use this to decode the message directly from.
1580
                msgReader := bytes.NewReader(rawMsg)
1581
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
1582
                if err != nil {
1583
                        return err
1584
                }
1585

1586
                // At this point, rawMsg and buf will be returned back to the
1587
                // buffer pool for re-use.
1588
                return nil
1589
        })
1590
        atomic.AddUint64(&p.bytesReceived, msgLen)
1591
        if err != nil {
1592
                return nil, err
1593
        }
1594

1595
        p.logWireMessage(nextMsg, true)
1596

1597
        return nextMsg, nil
1598
}
1599

1600
// msgStream implements a goroutine-safe, in-order stream of messages to be
1601
// delivered via closure to a receiver. These messages MUST be in order due to
1602
// the nature of the lightning channel commitment and gossiper state machines.
1603
// TODO(conner): use stream handler interface to abstract out stream
5✔
1604
// state/logging.
5✔
1605
type msgStream struct {
5✔
1606
        streamShutdown int32 // To be used atomically.
5✔
1607

5✔
1608
        peer *Brontide
5✔
1609

5✔
1610
        apply func(lnwire.Message)
5✔
1611

5✔
1612
        startMsg string
5✔
1613
        stopMsg  string
5✔
1614

5✔
1615
        msgCond *sync.Cond
5✔
1616
        msgs    []lnwire.Message
5✔
1617

5✔
1618
        mtx sync.Mutex
5✔
1619

3,007✔
1620
        producerSema chan struct{}
3,002✔
1621

3,002✔
1622
        wg   sync.WaitGroup
1623
        quit chan struct{}
5✔
1624
}
1625

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

2✔
1634
        stream := &msgStream{
2✔
1635
                peer:         p,
2✔
1636
                apply:        apply,
2✔
1637
                startMsg:     startMsg,
2✔
1638
                stopMsg:      stopMsg,
2✔
1639
                producerSema: make(chan struct{}, bufSize),
2✔
1640
                quit:         make(chan struct{}),
4✔
1641
        }
2✔
1642
        stream.msgCond = sync.NewCond(&stream.mtx)
2✔
1643

2✔
1644
        // Before we return the active stream, we'll populate the producer's
1645
        // semaphore channel. We'll use this to ensure that the producer won't
2✔
1646
        // attempt to allocate memory in the queue for an item until it has
1647
        // sufficient extra space.
1648
        for i := uint32(0); i < bufSize; i++ {
1649
                stream.producerSema <- struct{}{}
1650
        }
5✔
1651

5✔
1652
        return stream
5✔
1653
}
5✔
1654

5✔
1655
// Start starts the chanMsgStream.
5✔
1656
func (ms *msgStream) Start() {
5✔
1657
        ms.wg.Add(1)
10✔
1658
        go ms.msgConsumer()
5✔
1659
}
5✔
1660

5✔
1661
// Stop stops the chanMsgStream.
10✔
1662
func (ms *msgStream) Stop() {
5✔
1663
        // TODO(roasbeef): signal too?
5✔
1664

5✔
1665
        close(ms.quit)
5✔
1666

5✔
1667
        // Now that we've closed the channel, we'll repeatedly signal the msg
5✔
1668
        // consumer until we've detected that it has exited.
2✔
1669
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
2✔
1670
                ms.msgCond.Signal()
2✔
1671
                time.Sleep(time.Millisecond * 100)
2✔
1672
        }
2✔
1673

2✔
1674
        ms.wg.Wait()
2✔
1675
}
1676

1677
// msgConsumer is the main goroutine that streams messages from the peer's
1678
// readHandler directly to the target channel.
1679
func (ms *msgStream) msgConsumer() {
1680
        defer ms.wg.Done()
1681
        defer peerLog.Tracef(ms.stopMsg)
2✔
1682
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
2✔
1683

2✔
1684
        peerLog.Tracef(ms.startMsg)
2✔
1685

2✔
1686
        for {
2✔
1687
                // First, we'll check our condition. If the queue of messages
2✔
1688
                // is empty, then we'll wait until a new item is added.
2✔
1689
                ms.msgCond.L.Lock()
2✔
1690
                for len(ms.msgs) == 0 {
2✔
1691
                        ms.msgCond.Wait()
2✔
1692

2✔
1693
                        // If we woke up in order to exit, then we'll do so.
2✔
1694
                        // Otherwise, we'll check the message queue for any new
2✔
1695
                        // items.
2✔
1696
                        select {
2✔
1697
                        case <-ms.peer.quit:
2✔
1698
                                ms.msgCond.L.Unlock()
2✔
1699
                                return
1700
                        case <-ms.quit:
1701
                                ms.msgCond.L.Unlock()
1702
                                return
1703
                        default:
1704
                        }
1705
                }
2✔
1706

2✔
1707
                // Grab the message off the front of the queue, shifting the
2✔
1708
                // slice's reference down one in order to remove the message
2✔
1709
                // from the queue.
2✔
1710
                msg := ms.msgs[0]
2✔
1711
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
2✔
1712
                ms.msgs = ms.msgs[1:]
2✔
1713

×
1714
                ms.msgCond.L.Unlock()
×
1715

×
1716
                ms.apply(msg)
×
1717

1718
                // We've just successfully processed an item, so we'll signal
1719
                // to the producer that a new slot in the buffer. We'll use
1720
                // this to bound the size of the buffer to avoid allowing it to
1721
                // grow indefinitely.
2✔
1722
                select {
2✔
1723
                case ms.producerSema <- struct{}{}:
2✔
1724
                case <-ms.peer.quit:
2✔
1725
                        return
2✔
1726
                case <-ms.quit:
2✔
1727
                        return
2✔
1728
                }
1729
        }
1730
}
1731

1732
// AddMsg adds a new message to the msgStream. This function is safe for
1733
// concurrent access.
1734
func (ms *msgStream) AddMsg(msg lnwire.Message) {
2✔
1735
        // First, we'll attempt to receive from the producerSema struct. This
2✔
1736
        // acts as a semaphore to prevent us from indefinitely buffering
2✔
1737
        // incoming items from the wire. Either the msg queue isn't full, and
2✔
1738
        // we'll not block, or the queue is full, and we'll block until either
2✔
1739
        // we're signalled to quit, or a slot is freed up.
2✔
1740
        select {
2✔
1741
        case <-ms.producerSema:
2✔
1742
        case <-ms.peer.quit:
2✔
1743
                return
2✔
1744
        case <-ms.quit:
2✔
1745
                return
2✔
1746
        }
2✔
1747

2✔
1748
        // Next, we'll lock the condition, and add the message to the end of
4✔
1749
        // the message queue.
2✔
1750
        ms.msgCond.L.Lock()
2✔
1751
        ms.msgs = append(ms.msgs, msg)
2✔
1752
        ms.msgCond.L.Unlock()
2✔
1753

2✔
1754
        // With the message added, we signal to the msgConsumer that there are
2✔
1755
        // additional messages to consume.
2✔
1756
        ms.msgCond.Signal()
2✔
1757
}
2✔
1758

2✔
1759
// waitUntilLinkActive waits until the target link is active and returns a
4✔
1760
// ChannelLink to pass messages to. It accomplishes this by subscribing to
2✔
1761
// an ActiveLinkEvent which is emitted by the link when it first starts up.
2✔
1762
func waitUntilLinkActive(p *Brontide,
1763
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
1764

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

1767
        // Subscribe to receive channel events.
1768
        //
1769
        // NOTE: If the link is already active by SubscribeChannelEvents, then
1770
        // GetLink will retrieve the link and we can send messages. If the link
2✔
1771
        // becomes active between SubscribeChannelEvents and GetLink, then GetLink
2✔
1772
        // will retrieve the link. If the link becomes active after GetLink, then
4✔
1773
        // we will get an ActiveLinkEvent notification and retrieve the link. If
2✔
1774
        // the call to GetLink is before SubscribeChannelEvents, however, there
2✔
1775
        // will be a race condition.
1776
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
1777
        if err != nil {
2✔
1778
                // If we have a non-nil error, then the server is shutting down and we
2✔
1779
                // can exit here and return nil. This means no message will be delivered
2✔
1780
                // to the link.
2✔
1781
                return nil
2✔
1782
        }
×
1783
        defer sub.Cancel()
1784

1785
        // The link may already be active by this point, and we may have missed the
1786
        // ActiveLinkEvent. Check if the link exists.
1787
        link := p.fetchLinkFromKeyAndCid(cid)
1788
        if link != nil {
2✔
1789
                return link
1790
        }
2✔
1791

2✔
1792
        // If the link is nil, we must wait for it to be active.
1793
        for {
1794
                select {
1795
                // A new event has been sent by the ChannelNotifier. We first check
1796
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1797
                // that the event is for this channel. Otherwise, we discard the
1798
                // message.
1799
                case e := <-sub.Updates():
1800
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
1801
                        if !ok {
1802
                                // Ignore this notification.
2✔
1803
                                continue
2✔
1804
                        }
2✔
1805

4✔
1806
                        chanPoint := event.ChannelPoint
2✔
1807

2✔
1808
                        // Check whether the retrieved chanPoint matches the target
2✔
1809
                        // channel id.
4✔
1810
                        if !cid.IsChanPoint(chanPoint) {
2✔
1811
                                continue
2✔
1812
                        }
2✔
1813

2✔
1814
                        // The link shouldn't be nil as we received an
4✔
1815
                        // ActiveLinkEvent. If it is nil, we return nil and the
2✔
1816
                        // calling function should catch it.
2✔
1817
                        return p.fetchLinkFromKeyAndCid(cid)
2✔
1818

1819
                case <-p.quit:
1820
                        return nil
1821
                }
1822
        }
1823
}
2✔
1824

×
1825
// newChanMsgStream is used to create a msgStream between the peer and
×
1826
// particular channel link in the htlcswitch. We utilize additional
2✔
1827
// synchronization with the fundingManager to ensure we don't attempt to
1828
// dispatch a message to a channel before it is fully active. A reference to the
1829
// channel this stream forwards to is held in scope to prevent unnecessary
2✔
1830
// lookups.
1831
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
1832
        var chanLink htlcswitch.ChannelUpdateHandler
2✔
1833

2✔
1834
        apply := func(msg lnwire.Message) {
2✔
1835
                // This check is fine because if the link no longer exists, it will
2✔
1836
                // be removed from the activeChannels map and subsequent messages
2✔
1837
                // shouldn't reach the chan msg stream.
2✔
1838
                if chanLink == nil {
1839
                        chanLink = waitUntilLinkActive(p, cid)
1840

1841
                        // If the link is still not active and the calling function
1842
                        // errored out, just return.
1843
                        if chanLink == nil {
5✔
1844
                                p.log.Warnf("Link=%v is not active")
7✔
1845
                                return
2✔
1846
                        }
2✔
1847
                }
2✔
1848

2✔
1849
                // In order to avoid unnecessarily delivering message
1850
                // as the peer is exiting, we'll check quickly to see
5✔
1851
                // if we need to exit.
5✔
1852
                select {
5✔
1853
                case <-p.quit:
5✔
1854
                        return
5✔
1855
                default:
5✔
1856
                }
5✔
1857

1858
                chanLink.HandleChannelUpdate(msg)
1859
        }
1860

1861
        return newMsgStream(p,
1862
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
1863
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
5✔
1864
                1000,
5✔
1865
                apply,
5✔
1866
        )
5✔
1867
}
5✔
1868

5✔
1869
// newDiscMsgStream is used to setup a msgStream between the peer and the
×
1870
// authenticated gossiper. This stream should be used to forward all remote
×
1871
// channel announcements.
×
1872
func newDiscMsgStream(p *Brontide) *msgStream {
×
1873
        apply := func(msg lnwire.Message) {
1874
                // TODO(yy): `ProcessRemoteAnnouncement` returns an error chan
1875
                // and we need to process it.
1876
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(msg, p)
1877
        }
1878

1879
        return newMsgStream(
1880
                p,
5✔
1881
                "Update stream for gossiper created",
5✔
1882
                "Update stream for gossiper exited",
5✔
1883
                1000,
5✔
1884
                apply,
5✔
1885
        )
5✔
1886
}
11✔
1887

6✔
1888
// readHandler is responsible for reading messages off the wire in series, then
6✔
1889
// properly dispatching the handling of the message to the proper subsystem.
×
1890
//
×
1891
// NOTE: This method MUST be run as a goroutine.
×
1892
func (p *Brontide) readHandler() {
1893
        defer p.wg.Done()
1894

5✔
1895
        // We'll stop the timer after a new messages is received, and also
2✔
1896
        // reset it after we process the next message.
2✔
1897
        idleTimer := time.AfterFunc(idleTimeout, func() {
2✔
1898
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
2✔
1899
                        p, idleTimeout)
2✔
1900
                p.Disconnect(err)
2✔
1901
        })
2✔
1902

1903
        // Initialize our negotiated gossip sync method before reading messages
1904
        // off the wire. When using gossip queries, this ensures a gossip
1905
        // syncer is active by the time query messages arrive.
1906
        //
2✔
1907
        // TODO(conner): have peer store gossip syncer directly and bypass
2✔
1908
        // gossiper?
2✔
1909
        p.initGossipSync()
2✔
1910

1911
        discStream := newDiscMsgStream(p)
1912
        discStream.Start()
1913
        defer discStream.Stop()
1914
out:
1915
        for atomic.LoadInt32(&p.disconnect) == 0 {
×
1916
                nextMsg, err := p.readNextMessage()
×
1917
                if !idleTimer.Stop() {
×
1918
                        select {
×
1919
                        case <-idleTimer.C:
1920
                        default:
1921
                        }
1922
                }
1923
                if err != nil {
1924
                        p.log.Infof("unable to read message from peer: %v", err)
1925

×
1926
                        // If we could not read our peer's message due to an
×
1927
                        // unknown type or invalid alias, we continue processing
×
1928
                        // as normal. We store unknown message and address
1929
                        // types, as they may provide debugging insight.
1930
                        switch e := err.(type) {
1931
                        // If this is just a message we don't yet recognize,
1932
                        // we'll continue processing as normal as this allows
2✔
1933
                        // us to introduce new messages in a forwards
2✔
1934
                        // compatible manner.
1935
                        case *lnwire.UnknownMessage:
1936
                                p.storeError(e)
1937
                                idleTimer.Reset(idleTimeout)
1938
                                continue
1939

1940
                        // If they sent us an address type that we don't yet
6✔
1941
                        // know of, then this isn't a wire error, so we'll
3✔
1942
                        // simply continue parsing the remainder of their
3✔
1943
                        // messages.
3✔
1944
                        case *lnwire.ErrUnknownAddrType:
3✔
1945
                                p.storeError(e)
3✔
1946
                                idleTimer.Reset(idleTimeout)
1947
                                continue
1948

1949
                        // If the NodeAnnouncement has an invalid alias, then
3✔
1950
                        // we'll log that error above and continue so we can
×
1951
                        // continue to read messages from the peer. We do not
1952
                        // store this error because it is of little debugging
1953
                        // value.
3✔
1954
                        case *lnwire.ErrInvalidNodeAlias:
3✔
1955
                                idleTimer.Reset(idleTimeout)
3✔
1956
                                continue
3✔
1957

3✔
1958
                        // If the error we encountered wasn't just a message we
3✔
1959
                        // didn't recognize, then we'll stop all processing as
2✔
1960
                        // this is a fatal error.
2✔
1961
                        default:
2✔
1962
                                break out
2✔
1963
                        }
1964
                }
2✔
1965

2✔
1966
                // If a message router is active, then we'll try to have it
2✔
1967
                // handle this message. If it can, then we're able to skip the
2✔
1968
                // rest of the message handling logic.
2✔
1969
                err = fn.MapOptionZ(p.msgRouter, func(r msgmux.Router) error {
2✔
1970
                        return r.RouteMsg(msgmux.PeerMsg{
2✔
1971
                                PeerPub: *p.IdentityKey(),
2✔
1972
                                Message: nextMsg,
2✔
1973
                        })
1974
                })
1975

1976
                // No error occurred, and the message was handled by the
1977
                // router.
1978
                if err == nil {
2✔
1979
                        continue
2✔
1980
                }
2✔
1981

1982
                var (
2✔
1983
                        targetChan   lnwire.ChannelID
2✔
1984
                        isLinkUpdate bool
2✔
1985
                )
×
1986

×
1987
                switch msg := nextMsg.(type) {
1988
                case *lnwire.Pong:
2✔
1989
                        // When we receive a Pong message in response to our
2✔
1990
                        // last ping message, we send it to the pingManager
2✔
1991
                        p.pingManager.ReceivedPong(msg)
×
1992

×
1993
                case *lnwire.Ping:
1994
                        // First, we'll store their latest ping payload within
1995
                        // the relevant atomic variable.
×
1996
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
1997

×
1998
                        // Next, we'll send over the amount of specified pong
1999
                        // bytes.
2✔
2000
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
2✔
2001
                        p.queueMsg(pong, nil)
2✔
2002

2003
                case *lnwire.OpenChannel,
2✔
2004
                        *lnwire.AcceptChannel,
2✔
2005
                        *lnwire.FundingCreated,
2✔
2006
                        *lnwire.FundingSigned,
2✔
2007
                        *lnwire.ChannelReady:
2✔
2008

2✔
2009
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
2✔
2010

2✔
2011
                case *lnwire.Shutdown:
2✔
2012
                        select {
2✔
2013
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
4✔
2014
                        case <-p.quit:
2✔
2015
                                break out
4✔
2016
                        }
2✔
2017
                case *lnwire.ClosingSigned:
2✔
2018
                        select {
2✔
2019
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
2✔
2020
                        case <-p.quit:
2021
                                break out
2022
                        }
2023

2024
                case *lnwire.Warning:
2025
                        targetChan = msg.ChanID
2026
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
2✔
2027

2✔
2028
                case *lnwire.Error:
2✔
2029
                        targetChan = msg.ChanID
2✔
2030
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
2✔
2031

2✔
2032
                case *lnwire.ChannelReestablish:
2✔
2033
                        targetChan = msg.ChanID
4✔
2034
                        isLinkUpdate = p.hasChannel(targetChan)
2✔
2035

2✔
2036
                        // If we failed to find the link in question, and the
2✔
2037
                        // message received was a channel sync message, then
2✔
2038
                        // this might be a peer trying to resync closed channel.
2039
                        // In this case we'll try to resend our last channel
2040
                        // sync message, such that the peer can recover funds
2041
                        // from the closed channel.
2042
                        if !isLinkUpdate {
2043
                                err := p.resendChanSyncMsg(targetChan)
2044
                                if err != nil {
2045
                                        // TODO(halseth): send error to peer?
2046
                                        p.log.Errorf("resend failed: %v",
2047
                                                err)
2✔
2048
                                }
2✔
2049
                        }
2✔
2050

2051
                // For messages that implement the LinkUpdater interface, we
3✔
2052
                // will consider them as link updates and send them to
3✔
2053
                // chanStream. These messages will be queued inside chanStream
3✔
2054
                // if the channel is not active yet.
×
2055
                case lnwire.LinkUpdater:
×
2056
                        targetChan = msg.TargetChanID()
×
2057
                        isLinkUpdate = p.hasChannel(targetChan)
2058

×
2059
                        // Log an error if we don't have this channel. This
×
2060
                        // means the peer has sent us a message with unknown
×
2061
                        // channel ID.
×
2062
                        if !isLinkUpdate {
×
2063
                                p.log.Errorf("Unknown channel ID: %v found "+
×
2064
                                        "in received msg=%s", targetChan,
×
2065
                                        nextMsg.MsgType())
×
2066
                        }
2067

2068
                case *lnwire.ChannelUpdate1,
5✔
2069
                        *lnwire.ChannelAnnouncement1,
2✔
2070
                        *lnwire.NodeAnnouncement,
2✔
2071
                        *lnwire.AnnounceSignatures1,
2✔
2072
                        *lnwire.GossipTimestampRange,
2✔
2073
                        *lnwire.QueryShortChanIDs,
2074
                        *lnwire.QueryChannelRange,
3✔
2075
                        *lnwire.ReplyChannelRange,
2076
                        *lnwire.ReplyShortChanIDsEnd:
2077

2✔
2078
                        discStream.AddMsg(msg)
2✔
2079

2✔
2080
                case *lnwire.Custom:
2081
                        err := p.handleCustomMessage(msg)
2082
                        if err != nil {
2083
                                p.storeError(err)
2084
                                p.log.Errorf("%v", err)
3✔
2085
                        }
3✔
2086

×
2087
                default:
×
2088
                        // If the message we received is unknown to us, store
×
2089
                        // the type to track the failure.
2090
                        err := fmt.Errorf("unknown message type %v received",
3✔
2091
                                uint16(msg.MsgType()))
2092
                        p.storeError(err)
2093

2094
                        p.log.Errorf("%v", err)
2095
                }
2096

2097
                if isLinkUpdate {
2✔
2098
                        // If this is a channel update, then we need to feed it
2✔
2099
                        // into the channel's in-order message stream.
2✔
2100
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
4✔
2101
                }
2✔
2102

2✔
2103
                idleTimer.Reset(idleTimeout)
2104
        }
2105

2✔
2106
        p.Disconnect(errors.New("read handler closed"))
2✔
2107

×
2108
        p.log.Trace("readHandler for peer done")
×
2109
}
2110

2111
// handleCustomMessage handles the given custom message if a handler is
2112
// registered.
2✔
2113
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
2114
        if p.cfg.HandleCustomMessage == nil {
2115
                return fmt.Errorf("no custom message handler for "+
2116
                        "message type %v", uint16(msg.MsgType()))
2117
        }
10✔
2118

10✔
2119
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
10✔
2120
}
10✔
2121

10✔
2122
// isLoadedFromDisk returns true if the provided channel ID is loaded from
10✔
2123
// disk.
10✔
2124
//
10✔
2125
// NOTE: only returns true for pending channels.
10✔
2126
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
2127
        // If this is a newly added channel, no need to reestablish.
2128
        _, added := p.addedChannels.Load(chanID)
2129
        if added {
8✔
2130
                return false
8✔
2131
        }
8✔
2132

13✔
2133
        // Return false if the channel is unknown.
5✔
2134
        channel, ok := p.activeChannels.Load(chanID)
5✔
2135
        if !ok {
2136
                return false
3✔
2137
        }
2138

2139
        // During startup, we will use a nil value to mark a pending channel
2140
        // that's loaded from disk.
2141
        return channel == nil
2✔
2142
}
2✔
2143

2✔
2144
// isActiveChannel returns true if the provided channel id is active, otherwise
2✔
2145
// returns false.
2146
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
2147
        // The channel would be nil if,
2148
        // - the channel doesn't exist, or,
2149
        // - the channel exists, but is pending. In this case, we don't
2150
        //   consider this channel active.
2✔
2151
        channel, _ := p.activeChannels.Load(chanID)
2✔
2152

2✔
2153
        return channel != nil
2✔
2154
}
4✔
2155

2✔
2156
// isPendingChannel returns true if the provided channel ID is pending, and
2✔
2157
// returns false if the channel is active or unknown.
4✔
2158
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
2✔
2159
        // Return false if the channel is unknown.
2✔
2160
        channel, ok := p.activeChannels.Load(chanID)
2✔
2161
        if !ok {
2162
                return false
2✔
2163
        }
2✔
2164

2✔
2165
        return channel == nil
2✔
2166
}
2167

2168
// hasChannel returns true if the peer has a pending/active channel specified
2169
// by the channel ID.
2170
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
4✔
2171
        _, ok := p.activeChannels.Load(chanID)
2✔
2172
        return ok
2✔
2173
}
2✔
2174

2175
// storeError stores an error in our peer's buffer of recent errors with the
2✔
2176
// current timestamp. Errors are only stored if we have at least one active
2✔
2177
// channel with the peer to mitigate a dos vector where a peer costlessly
2✔
2178
// connects to us and spams us with errors.
2179
func (p *Brontide) storeError(err error) {
2180
        var haveChannels bool
2181

2182
        p.activeChannels.Range(func(_ lnwire.ChannelID,
2183
                channel *lnwallet.LightningChannel) bool {
2184

2185
                // Pending channels will be nil in the activeChannels map.
2186
                if channel == nil {
2187
                        // Return true to continue the iteration.
2✔
2188
                        return true
2✔
2189
                }
4✔
2190

2✔
2191
                haveChannels = true
2✔
2192

2193
                // Return false to break the iteration.
2✔
2194
                return false
2195
        })
2196

×
2197
        // If we do not have any active channels with the peer, we do not store
×
2198
        // errors as a dos mitigation.
×
2199
        if !haveChannels {
×
2200
                p.log.Trace("no channels with peer, not storing err")
2201
                return
×
2202
        }
2203

2204
        p.cfg.ErrorBuffer.Add(
2205
                &TimestampedError{Timestamp: time.Now(), Error: err},
2✔
2206
        )
2✔
2207
}
2✔
2208

2209
// handleWarningOrError processes a warning or error msg and returns true if
2210
// msg should be forwarded to the associated channel link. False is returned if
2✔
2211
// any necessary forwarding of msg was already handled by this method. If msg is
2✔
2212
// an error from a peer with an active channel, we'll store it in memory.
2213
//
2✔
2214
// NOTE: This method should only be called from within the readHandler.
2✔
2215
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
2216
        msg lnwire.Message) bool {
2217

2218
        if errMsg, ok := msg.(*lnwire.Error); ok {
2219
                p.storeError(errMsg)
2220
        }
2221

2✔
2222
        switch {
2✔
2223
        // Connection wide messages should be forwarded to all channel links
2✔
2224
        // with this peer.
2✔
2225
        case chanID == lnwire.ConnectionWideID:
2✔
2226
                for _, chanStream := range p.activeMsgStreams {
2227
                        chanStream.AddMsg(msg)
2✔
2228
                }
2✔
2229

2✔
2230
                return false
2✔
2231

2✔
2232
        // If the channel ID for the message corresponds to a pending channel,
2✔
2233
        // then the funding manager will handle it.
2234
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
2✔
2235
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
2✔
2236
                return false
2✔
2237

2✔
2238
        // If not we hand the message to the channel link for this channel.
2239
        case p.isActiveChannel(chanID):
2✔
2240
                return true
2✔
2241

2✔
2242
        default:
2243
                return false
2✔
2244
        }
2✔
2245
}
2246

2✔
2247
// messageSummary returns a human-readable string that summarizes a
2✔
2248
// incoming/outgoing message. Not all messages will have a summary, only those
2✔
2249
// which have additional data that can be informative at a glance.
2250
func messageSummary(msg lnwire.Message) string {
2✔
2251
        switch msg := msg.(type) {
2✔
2252
        case *lnwire.Init:
2✔
2253
                // No summary.
2254
                return ""
2✔
2255

2✔
2256
        case *lnwire.OpenChannel:
2✔
2257
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
2258
                        "push_amt=%v, reserve=%v, flags=%v",
2✔
2259
                        msg.PendingChannelID[:], msg.ChainHash,
2✔
2260
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
2✔
2261
                        msg.ChannelReserve, msg.ChannelFlags)
2✔
2262

4✔
2263
        case *lnwire.AcceptChannel:
2✔
2264
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
2✔
2265
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
2✔
2266
                        msg.MinAcceptDepth)
2267

2268
        case *lnwire.FundingCreated:
2✔
2269
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
2✔
2270
                        msg.PendingChannelID[:], msg.FundingPoint)
2✔
2271

2✔
2272
        case *lnwire.FundingSigned:
2273
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
2✔
2274

2✔
2275
        case *lnwire.ChannelReady:
2✔
2276
                return fmt.Sprintf("chan_id=%v, next_point=%x",
2277
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
2✔
2278

2✔
2279
        case *lnwire.Shutdown:
2✔
2280
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
2✔
2281
                        msg.Address[:])
2282

2✔
2283
        case *lnwire.ClosingSigned:
2✔
2284
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
2✔
2285
                        msg.FeeSatoshis)
2286

2✔
2287
        case *lnwire.UpdateAddHTLC:
2✔
2288
                var blindingPoint []byte
2✔
2289
                msg.BlindingPoint.WhenSome(
2✔
2290
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
2291
                                *btcec.PublicKey]) {
2✔
2292

2✔
2293
                                blindingPoint = b.Val.SerializeCompressed()
2✔
2294
                        },
2295
                )
×
2296

×
2297
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
2298
                        "hash=%x, blinding_point=%x, custom_records=%v",
2✔
2299
                        msg.ChanID, msg.ID, msg.Amount, msg.Expiry,
2✔
2300
                        msg.PaymentHash[:], blindingPoint, msg.CustomRecords)
2301

2✔
2302
        case *lnwire.UpdateFailHTLC:
2✔
2303
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
2✔
2304
                        msg.ID, msg.Reason)
2305

2✔
2306
        case *lnwire.UpdateFulfillHTLC:
2✔
2307
                return fmt.Sprintf("chan_id=%v, id=%v, pre_image=%x, "+
2✔
2308
                        "custom_records=%v", msg.ChanID, msg.ID,
2309
                        msg.PaymentPreimage[:], msg.CustomRecords)
2✔
2310

2✔
2311
        case *lnwire.CommitSig:
2✔
2312
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
2✔
2313
                        len(msg.HtlcSigs))
2✔
2314

2315
        case *lnwire.RevokeAndAck:
2✔
2316
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
2✔
2317
                        msg.ChanID, msg.Revocation[:],
2✔
2318
                        msg.NextRevocationKey.SerializeCompressed())
2319

2✔
2320
        case *lnwire.UpdateFailMalformedHTLC:
2✔
2321
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
2322
                        msg.ChanID, msg.ID, msg.FailureCode)
2✔
2323

2✔
2324
        case *lnwire.Warning:
2325
                return fmt.Sprintf("%v", msg.Warning())
×
2326

×
2327
        case *lnwire.Error:
×
2328
                return fmt.Sprintf("%v", msg.Error())
2329

2✔
2330
        case *lnwire.AnnounceSignatures1:
2✔
2331
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
2✔
2332
                        msg.ShortChannelID.ToUint64())
2✔
2333

2334
        case *lnwire.ChannelAnnouncement1:
2✔
2335
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
2✔
2336
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
2✔
2337

2338
        case *lnwire.ChannelUpdate1:
2✔
2339
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
2✔
2340
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
2✔
2341
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
2✔
2342
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
2✔
2343

2344
        case *lnwire.NodeAnnouncement:
2✔
2345
                return fmt.Sprintf("node=%x, update_time=%v",
2✔
2346
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
2✔
2347

2348
        case *lnwire.Ping:
2✔
2349
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
2✔
2350

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

2✔
2354
        case *lnwire.UpdateFee:
2✔
2355
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
2✔
2356
                        msg.ChanID, int64(msg.FeePerKw))
2✔
2357

2✔
2358
        case *lnwire.ChannelReestablish:
2359
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
×
2360
                        "remote_tail_height=%v", msg.ChanID,
×
2361
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
×
2362

2363
        case *lnwire.ReplyShortChanIDsEnd:
2✔
2364
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
2✔
2365
                        msg.Complete)
2366

2367
        case *lnwire.ReplyChannelRange:
×
2368
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
2369
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
2370
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
2371
                        msg.EncodingType)
2372

2373
        case *lnwire.QueryShortChanIDs:
2374
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
2375
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
19✔
2376

19✔
2377
        case *lnwire.QueryChannelRange:
34✔
2378
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
15✔
2379
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
15✔
2380
                        msg.LastBlockHeight())
2381

21✔
2382
        case *lnwire.GossipTimestampRange:
2✔
2383
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
2✔
2384
                        "stamp_range=%v", msg.ChainHash,
4✔
2385
                        time.Unix(int64(msg.FirstTimestamp), 0),
2✔
2386
                        msg.TimestampRange)
2✔
2387

2388
        case *lnwire.Stfu:
2✔
2389
                return fmt.Sprintf("chan_id=%v, initiator=%v", msg.ChanID,
4✔
2390
                        msg.Initiator)
2✔
2391

2✔
2392
        case *lnwire.Custom:
2393
                return fmt.Sprintf("type=%d", msg.Type)
2✔
2394
        }
4✔
2395

2✔
2396
        return fmt.Sprintf("unknown msg type=%T", msg)
4✔
2397
}
2✔
2398

2✔
2399
// logWireMessage logs the receipt or sending of particular wire message. This
2400
// function is used rather than just logging the message in order to produce
2✔
2401
// less spammy log messages in trace mode by setting the 'Curve" parameter to
2✔
2402
// nil. Doing this avoids printing out each of the field elements in the curve
2403
// parameters for secp256k1.
2404
func (p *Brontide) logWireMessage(msg lnwire.Message, read bool) {
19✔
2405
        summaryPrefix := "Received"
34✔
2406
        if !read {
15✔
2407
                summaryPrefix = "Sending"
15✔
2408
        }
2409

19✔
2410
        p.log.Debugf("%v", lnutils.NewLogClosure(func() string {
2411
                // Debug summary of message.
2412
                summary := messageSummary(msg)
2413
                if len(summary) > 0 {
2414
                        summary = "(" + summary + ")"
2415
                }
2416

2417
                preposition := "to"
2418
                if read {
2419
                        preposition = "from"
2420
                }
2421

2422
                var msgType string
2423
                if msg.MsgType() < lnwire.CustomTypeStart {
15✔
2424
                        msgType = msg.MsgType().String()
15✔
2425
                } else {
30✔
2426
                        msgType = "custom"
15✔
2427
                }
15✔
2428

2429
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
15✔
2430
                        msgType, summary, preposition, p)
15✔
2431
        }))
30✔
2432

15✔
2433
        prefix := "readMessage from peer"
15✔
2434
        if !read {
15✔
2435
                prefix = "writeMessage to peer"
15✔
2436
        }
15✔
2437

15✔
2438
        p.log.Tracef(prefix+": %v", lnutils.SpewLogClosure(msg))
15✔
2439
}
×
2440

×
2441
// writeMessage writes and flushes the target lnwire.Message to the remote peer.
2442
// If the passed message is nil, this method will only try to flush an existing
2443
// message buffered on the connection. It is safe to call this method again
2444
// with a nil message iff a timeout error is returned. This will continue to
2445
// flush the pending message to the wire.
15✔
2446
//
15✔
2447
// NOTE:
15✔
2448
// Besides its usage in Start, this function should not be used elsewhere
17✔
2449
// except in writeHandler. If multiple goroutines call writeMessage at the same
2✔
2450
// time, panics can occur because WriteMessage and Flush don't use any locking
2✔
2451
// internally.
2452
func (p *Brontide) writeMessage(msg lnwire.Message) error {
15✔
2453
        // Only log the message on the first attempt.
2454
        if msg != nil {
2455
                p.logWireMessage(msg, false)
2456
        }
2457

2458
        noiseConn := p.cfg.Conn
15✔
2459

×
2460
        flushMsg := func() error {
×
2461
                // Ensure the write deadline is set before we attempt to send
2462
                // the message.
2463
                writeDeadline := time.Now().Add(
2464
                        p.scaleTimeout(writeMessageTimeout),
30✔
2465
                )
15✔
2466
                err := noiseConn.SetWriteDeadline(writeDeadline)
15✔
2467
                if err != nil {
15✔
2468
                        return err
15✔
2469
                }
×
2470

×
2471
                // Flush the pending message to the wire. If an error is
2472
                // encountered, e.g. write timeout, the number of bytes written
2473
                // so far will be returned.
2474
                n, err := noiseConn.Flush()
2475

2476
                // Record the number of bytes written on the wire, if any.
15✔
2477
                if n > 0 {
2478
                        atomic.AddUint64(&p.bytesSent, uint64(n))
15✔
2479
                }
×
2480

×
2481
                return err
2482
        }
15✔
2483

2484
        // If the current message has already been serialized, encrypted, and
2485
        // buffered on the underlying connection we will skip straight to
2486
        // flushing it to the wire.
2487
        if msg == nil {
2488
                return flushMsg()
2489
        }
2490

2491
        // Otherwise, this is a new message. We'll acquire a write buffer to
5✔
2492
        // serialize the message and buffer the ciphertext on the connection.
5✔
2493
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
5✔
2494
                // Using a buffer allocated by the write pool, encode the
7✔
2495
                // message directly into the buffer.
2✔
2496
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
2✔
2497
                if writeErr != nil {
2✔
2498
                        return writeErr
2✔
2499
                }
2500

5✔
2501
                // Finally, write the message itself in a single swoop. This
5✔
2502
                // will buffer the ciphertext on the underlying connection. We
5✔
2503
                // will defer flushing the message until the write pool has been
14✔
2504
                // released.
9✔
2505
                return noiseConn.WriteMessage(buf.Bytes())
6✔
2506
        })
6✔
2507
        if err != nil {
6✔
2508
                return err
6✔
2509
        }
6✔
2510

6✔
2511
        return flushMsg()
2512
}
2513

2514
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2515
// queue, and writing them out to the wire. This goroutine coordinates with the
6✔
2516
// queueHandler in order to ensure the incoming message queue is quickly
6✔
2517
// drained.
×
2518
//
×
2519
// NOTE: This method MUST be run as a goroutine.
×
2520
func (p *Brontide) writeHandler() {
×
2521
        // We'll stop the timer after a new messages is sent, and also reset it
×
2522
        // after we process the next message.
×
2523
        idleTimer := time.AfterFunc(idleTimeout, func() {
×
2524
                err := fmt.Errorf("peer %s no write for %s -- disconnecting",
×
2525
                        p, idleTimeout)
×
2526
                p.Disconnect(err)
×
2527
        })
×
2528

×
2529
        var exitErr error
×
2530

×
2531
out:
×
2532
        for {
2533
                select {
2534
                case outMsg := <-p.sendQueue:
2535
                        // Record the time at which we first attempt to send the
2536
                        // message.
6✔
2537
                        startTime := time.Now()
×
2538

×
2539
                retry:
×
2540
                        // Write out the message to the socket. If a timeout
2541
                        // error is encountered, we will catch this and retry
2542
                        // after backing off in case the remote peer is just
6✔
2543
                        // slow to process messages from the wire.
6✔
2544
                        err := p.writeMessage(outMsg.msg)
6✔
2545
                        if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
6✔
2546
                                p.log.Debugf("Write timeout detected for "+
9✔
2547
                                        "peer, first write for message "+
3✔
2548
                                        "attempted %v ago",
3✔
2549
                                        time.Since(startTime))
2550

6✔
2551
                                // If we received a timeout error, this implies
×
2552
                                // that the message was buffered on the
×
2553
                                // connection successfully and that a flush was
×
2554
                                // attempted. We'll set the message to nil so
2555
                                // that on a subsequent pass we only try to
2556
                                // flush the buffered message, and forgo
2✔
2557
                                // reserializing or reencrypting it.
2✔
2558
                                outMsg.msg = nil
2✔
2559

2560
                                goto retry
2561
                        }
2562

2563
                        // The write succeeded, reset the idle timer to prevent
2564
                        // us from disconnecting the peer.
2✔
2565
                        if !idleTimer.Stop() {
2✔
2566
                                select {
2✔
2567
                                case <-idleTimer.C:
2✔
2568
                                default:
2✔
2569
                                }
2570
                        }
2571
                        idleTimer.Reset(idleTimeout)
2572

2573
                        // If the peer requested a synchronous write, respond
2574
                        // with the error.
2575
                        if outMsg.errChan != nil {
5✔
2576
                                outMsg.errChan <- err
5✔
2577
                        }
5✔
2578

5✔
2579
                        if err != nil {
5✔
2580
                                exitErr = fmt.Errorf("unable to write "+
5✔
2581
                                        "message: %v", err)
5✔
2582
                                break out
5✔
2583
                        }
5✔
2584

5✔
2585
                case <-p.quit:
5✔
2586
                        exitErr = lnpeer.ErrPeerExiting
5✔
2587
                        break out
5✔
2588
                }
18✔
2589
        }
13✔
2590

13✔
2591
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
13✔
2592
        // disconnect.
23✔
2593
        p.wg.Done()
10✔
2594

10✔
2595
        p.Disconnect(exitErr)
2596

19✔
2597
        p.log.Trace("writeHandler for peer done")
6✔
2598
}
6✔
2599

6✔
2600
// queueHandler is responsible for accepting messages from outside subsystems
6✔
2601
// to be eventually sent out on the wire by the writeHandler.
6✔
2602
//
6✔
2603
// NOTE: This method MUST be run as a goroutine.
6✔
2604
func (p *Brontide) queueHandler() {
6✔
2605
        defer p.wg.Done()
6✔
2606

11✔
2607
        // priorityMsgs holds an in order list of messages deemed high-priority
5✔
2608
        // to be added to the sendQueue. This predominately includes messages
8✔
2609
        // from the funding manager and htlcswitch.
3✔
2610
        priorityMsgs := list.New()
3✔
2611

2✔
2612
        // lazyMsgs holds an in order list of messages deemed low-priority to be
4✔
2613
        // added to the sendQueue only after all high-priority messages have
2✔
2614
        // been queued. This predominately includes messages from the gossiper.
4✔
2615
        lazyMsgs := list.New()
2✔
2616

2✔
2617
        for {
×
2618
                // Examine the front of the priority queue, if it is empty check
×
2619
                // the low priority queue.
2620
                elem := priorityMsgs.Front()
9✔
2621
                if elem == nil {
9✔
2622
                        elem = lazyMsgs.Front()
9✔
2623
                }
9✔
2624

9✔
2625
                if elem != nil {
6✔
2626
                        front := elem.Value.(outgoingMsg)
11✔
2627

5✔
2628
                        // There's an element on the queue, try adding
8✔
2629
                        // it to the sendQueue. We also watch for
3✔
2630
                        // messages on the outgoingQueue, in case the
3✔
2631
                        // writeHandler cannot accept messages on the
2✔
2632
                        // sendQueue.
2✔
2633
                        select {
2634
                        case p.sendQueue <- front:
2635
                                if front.priority {
2636
                                        priorityMsgs.Remove(elem)
2637
                                } else {
2638
                                        lazyMsgs.Remove(elem)
2639
                                }
2✔
2640
                        case msg := <-p.outgoingQueue:
2✔
2641
                                if msg.priority {
2✔
2642
                                        priorityMsgs.PushBack(msg)
2643
                                } else {
2644
                                        lazyMsgs.PushBack(msg)
2645
                                }
2646
                        case <-p.quit:
27✔
2647
                                return
27✔
2648
                        }
27✔
2649
                } else {
2650
                        // If there weren't any messages to send to the
2651
                        // writeHandler, then we'll accept a new message
2652
                        // into the queue from outside sub-systems.
2653
                        select {
3✔
2654
                        case msg := <-p.outgoingQueue:
3✔
2655
                                if msg.priority {
3✔
2656
                                        priorityMsgs.PushBack(msg)
2657
                                } else {
2658
                                        lazyMsgs.PushBack(msg)
2659
                                }
2660
                        case <-p.quit:
2661
                                return
28✔
2662
                        }
28✔
2663
                }
28✔
2664
        }
27✔
2665
}
2✔
2666

2✔
2667
// PingTime returns the estimated ping time to the peer in microseconds.
2✔
2668
func (p *Brontide) PingTime() int64 {
2✔
2669
        return p.pingManager.GetPingTimeMicroSeconds()
×
2670
}
×
2671

2672
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2673
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2674
// or failed to write, and nil otherwise.
2675
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
2676
        p.queue(true, msg, errChan)
2✔
2677
}
2✔
2678

2✔
2679
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2✔
2680
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2✔
2681
// queue or failed to write, and nil otherwise.
2✔
2682
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
4✔
2683
        p.queue(false, msg, errChan)
2✔
2684
}
2✔
2685

2✔
2686
// queue sends a given message to the queueHandler using the passed priority. If
4✔
2687
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2✔
2688
// failed to write, and nil otherwise.
2✔
2689
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2690
        errChan chan error) {
2691

2692
        select {
4✔
2693
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
2✔
2694
        case <-p.quit:
2✔
2695
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
2696
                        spew.Sdump(msg))
2✔
2697
                if errChan != nil {
2✔
2698
                        errChan <- lnpeer.ErrPeerExiting
2✔
2699
                }
2✔
2700
        }
2701
}
2702

2✔
2703
// ChannelSnapshots returns a slice of channel snapshots detailing all
2704
// currently active channels maintained with the remote peer.
2705
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
2706
        snapshots := make(
2707
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
8✔
2708
        )
8✔
2709

8✔
2710
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
8✔
2711
                activeChan *lnwallet.LightningChannel) error {
10✔
2712

2✔
2713
                // If the activeChan is nil, then we skip it as the channel is
2✔
2714
                // pending.
2715
                if activeChan == nil {
8✔
2716
                        return nil
8✔
2717
                }
8✔
2718

8✔
2719
                // We'll only return a snapshot for channels that are
×
2720
                // *immediately* available for routing payments over.
×
2721
                if activeChan.RemoteNextRevocation() == nil {
8✔
2722
                        return nil
8✔
2723
                }
8✔
2724

8✔
2725
                snapshot := activeChan.StateSnapshot()
2726
                snapshots = append(snapshots, snapshot)
2727

2728
                return nil
2729
        })
2730

2731
        return snapshots
2732
}
19✔
2733

19✔
2734
// genDeliveryScript returns a new script to be used to send our funds to in
19✔
2735
// the case of a cooperative channel close negotiation.
19✔
2736
func (p *Brontide) genDeliveryScript() ([]byte, error) {
19✔
2737
        // We'll send a normal p2wkh address unless we've negotiated the
19✔
2738
        // shutdown-any-segwit feature.
19✔
2739
        addrType := lnwallet.WitnessPubKey
19✔
2740
        if p.taprootShutdownAllowed() {
19✔
2741
                addrType = lnwallet.TaprootPubkey
59✔
2742
        }
40✔
2743

2744
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
2745
                addrType, false, lnwallet.DefaultAccountName,
2746
        )
2747
        if err != nil {
2748
                return nil, err
3✔
2749
        }
3✔
2750
        p.log.Infof("Delivery addr for channel close: %v",
2751
                deliveryAddr)
2752

2753
        return txscript.PayToAddrScript(deliveryAddr)
2754
}
2✔
2755

2✔
2756
// channelManager is goroutine dedicated to handling all requests/signals
2757
// pertaining to the opening, cooperative closing, and force closing of all
2758
// channels maintained with the remote peer.
2759
//
3✔
2760
// NOTE: This method MUST be run as a goroutine.
3✔
2761
func (p *Brontide) channelManager() {
2762
        defer p.wg.Done()
2763

2764
        // reenableTimeout will fire once after the configured channel status
2765
        // interval has elapsed. This will trigger us to sign new channel
2766
        // updates and broadcast them with the "disabled" flag unset.
9✔
2767
        reenableTimeout := time.After(p.cfg.ChanActiveTimeout)
9✔
2768

2769
out:
2770
        for {
2771
                select {
2772
                // A new pending channel has arrived which means we are about
2✔
2773
                // to complete a funding workflow and is waiting for the final
2✔
2774
                // `ChannelReady` messages to be exchanged. We will add this
2775
                // channel to the `activeChannels` with a nil value to indicate
2776
                // this is a pending channel.
2777
                case req := <-p.newPendingChannel:
2778
                        p.handleNewPendingChannel(req)
15✔
2779

15✔
2780
                // A new channel has arrived which means we've just completed a
2781
                // funding workflow. We'll initialize the necessary local
2782
                // state, and notify the htlc switch of a new link.
2783
                case req := <-p.newActiveChannel:
2784
                        p.handleNewActiveChannel(req)
2785

2786
                // The funding flow for a pending channel is failed, we will
2787
                // remove it from Brontide.
2788
                case req := <-p.removePendingChannel:
2✔
2789
                        p.handleRemovePendingChannel(req)
2✔
2790

2✔
2791
                // We've just received a local request to close an active
2✔
2792
                // channel. It will either kick of a cooperative channel
2✔
2793
                // closure negotiation, or be a notification of a breached
2✔
2794
                // contract that should be abandoned.
2✔
2795
                case req := <-p.localCloseChanReqs:
2✔
2796
                        p.handleLocalCloseReq(req)
2✔
2797

2✔
2798
                // We've received a link failure from a link that was added to
2✔
2799
                // the switch. This will initiate the teardown of the link, and
2✔
2800
                // initiate any on-chain closures if necessary.
2✔
2801
                case failure := <-p.linkFailures:
2✔
2802
                        p.handleLinkFailure(failure)
2✔
2803

2✔
2804
                // We've received a new cooperative channel closure related
2✔
2805
                // message from the remote peer, we'll use this message to
4✔
2806
                // advance the chan closer state machine.
2✔
2807
                case closeMsg := <-p.chanCloseMsgs:
2✔
2808
                        p.handleCloseMsg(closeMsg)
2809

2✔
2810
                // The channel reannounce delay has elapsed, broadcast the
2✔
2811
                // reenabled channel updates to the network. This should only
2✔
2812
                // fire once, so we set the reenableTimeout channel to nil to
2✔
2813
                // mark it for garbage collection. If the peer is torn down
4✔
2814
                // before firing, reenabling will not be attempted.
2✔
2815
                // TODO(conner): consolidate reenables timers inside chan status
2✔
2816
                // manager
2✔
2817
                case <-reenableTimeout:
4✔
2818
                        p.reenableActiveChannels()
2✔
2819

2✔
2820
                        // Since this channel will never fire again during the
2821
                        // lifecycle of the peer, we nil the channel to mark it
2✔
2822
                        // eligible for garbage collection, and make this
2✔
2823
                        // explicitly ineligible to receive in future calls to
2✔
2824
                        // select. This also shaves a few CPU cycles since the
2825
                        // select will ignore this case entirely.
2826
                        reenableTimeout = nil
2✔
2827

2828
                        // Once the reenabling is attempted, we also cancel the
2829
                        // channel event subscription to free up the overflow
2830
                        // queue used in channel notifier.
2831
                        //
2832
                        // NOTE: channelEventClient will be nil if the
2833
                        // reenableTimeout is greater than 1 minute.
2834
                        if p.channelEventClient != nil {
2835
                                p.channelEventClient.Cancel()
2✔
2836
                        }
2✔
2837

2✔
2838
                case <-p.quit:
2✔
2839
                        // As, we've been signalled to exit, we'll reset all
2✔
2840
                        // our active channel back to their default state.
2✔
2841
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
2✔
2842
                                lc *lnwallet.LightningChannel) error {
2✔
2843

2✔
2844
                                // Exit if the channel is nil as it's a pending
2✔
2845
                                // channel.
2✔
2846
                                if lc == nil {
4✔
2847
                                        return nil
2✔
2848
                                }
2✔
2849

2✔
2850
                                lc.ResetState()
2851

2✔
2852
                                return nil
2✔
2853
                        })
2854

2855
                        break out
2856
                }
2✔
2857
        }
2✔
2858
}
2✔
2859

2✔
2860
// reenableActiveChannels searches the index of channels maintained with this
2✔
2861
// peer, and reenables each public, non-pending channel. This is done at the
2862
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
2863
// No message will be sent if the channel is already enabled.
2864
func (p *Brontide) reenableActiveChannels() {
2865
        // First, filter all known channels with this peer for ones that are
2866
        // both public and not pending.
2867
        activePublicChans := p.filterChannelsToEnable()
2868

2869
        // Create a map to hold channels that needs to be retried.
2870
        retryChans := make(map[wire.OutPoint]struct{}, len(activePublicChans))
2871

×
2872
        // For each of the public, non-pending channels, set the channel
×
2873
        // disabled bit to false and send out a new ChannelUpdate. If this
×
2874
        // channel is already active, the update won't be sent.
×
2875
        for _, chanPoint := range activePublicChans {
×
2876
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
2877

×
2878
                switch {
×
2879
                // No error occurred, continue to request the next channel.
×
2880
                case err == nil:
2881
                        continue
2882

×
2883
                // Cannot auto enable a manually disabled channel so we do
×
2884
                // nothing but proceed to the next channel.
×
2885
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
×
2886
                        p.log.Debugf("Channel(%v) was manually disabled, "+
×
2887
                                "ignoring automatic enable request", chanPoint)
2888

2889
                        continue
2890

2891
                // If the channel is reported as inactive, we will give it
2✔
2892
                // another chance. When handling the request, ChanStatusManager
×
2893
                // will check whether the link is active or not. One of the
×
2894
                // conditions is whether the link has been marked as
2895
                // reestablished, which happens inside a goroutine(htlcManager)
2896
                // after the link is started. And we may get a false negative
2897
                // saying the link is not active because that goroutine hasn't
2898
                // reached the line to mark the reestablishment. Thus we give
2899
                // it a second chance to send the request.
2900
                case errors.Is(err, netann.ErrEnableInactiveChan):
2901
                        // If we don't have a client created, it means we
15✔
2902
                        // shouldn't retry enabling the channel.
15✔
2903
                        if p.channelEventClient == nil {
15✔
2904
                                p.log.Errorf("Channel(%v) request enabling "+
27✔
2905
                                        "failed due to inactive link",
12✔
2906
                                        chanPoint)
12✔
2907

12✔
2908
                                continue
12✔
2909
                        }
12✔
2910

12✔
2911
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
2912
                                "ChanStatusManager reported inactive, retrying")
2913

2914
                        // Add the channel to the retry map.
5✔
2915
                        retryChans[chanPoint] = struct{}{}
5✔
2916
                }
5✔
2917
        }
5✔
2918

7✔
2919
        // Retry the channels if we have any.
2✔
2920
        if len(retryChans) != 0 {
2✔
2921
                p.retryRequestEnable(retryChans)
2922
        }
2923
}
2924

2925
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
2926
// for the target channel ID. If the channel isn't active an error is returned.
2927
// Otherwise, either an existing state machine will be returned, or a new one
2928
// will be created.
2929
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
2930
        *chancloser.ChanCloser, error) {
5✔
2931

10✔
2932
        chanCloser, found := p.activeChanCloses[chanID]
5✔
2933
        if found {
5✔
2934
                // An entry will only be found if the closer has already been
5✔
2935
                // created for a non-pending channel or for a channel that had
×
2936
                // previously started the shutdown process but the connection
×
2937
                // was restarted.
×
2938
                return chanCloser, nil
×
2939
        }
2940

2941
        // First, we'll ensure that we actually know of the target channel. If
2942
        // not, we'll ignore this message.
2943
        channel, ok := p.activeChannels.Load(chanID)
5✔
2944

5✔
2945
        // If the channel isn't in the map or the channel is nil, return
5✔
2946
        // ErrChannelNotFound as the channel is pending.
5✔
2947
        if !ok || channel == nil {
×
2948
                return nil, ErrChannelNotFound
×
2949
        }
×
2950

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

2970
        // In order to begin fee negotiations, we'll first compute our target
2971
        // ideal fee-per-kw.
2✔
2972
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
2✔
2973
                p.cfg.CoopCloseTargetConfs,
2✔
2974
        )
2✔
2975
        if err != nil {
4✔
2976
                p.log.Errorf("unable to query fee estimator: %v", err)
2✔
2977
                return nil, fmt.Errorf("unable to estimate fee")
2✔
2978
        }
4✔
2979

2✔
2980
        addr, err := p.addrWithInternalKey(deliveryScript).Unpack()
2✔
2981
        if err != nil {
2982
                return nil, fmt.Errorf("unable to parse addr: %w", err)
2✔
2983
        }
2✔
2984
        chanCloser, err = p.createChanCloser(
2✔
2985
                channel, addr, feePerKw, nil, lntypes.Remote,
×
2986
        )
×
2987
        if err != nil {
2988
                p.log.Errorf("unable to create chan closer: %v", err)
2989
                return nil, fmt.Errorf("unable to create chan closer")
2990
        }
2991

2992
        p.activeChanCloses[chanID] = chanCloser
2993

2✔
2994
        return chanCloser, nil
×
2995
}
×
2996

2997
// filterChannelsToEnable filters a list of channels to be enabled upon start.
2✔
2998
// The filtered channels are active channels that's neither private nor
2✔
2999
// pending.
2✔
3000
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
2✔
3001
        var activePublicChans []wire.OutPoint
2✔
3002

3003
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
3004
                lnChan *lnwallet.LightningChannel) bool {
2✔
3005

3006
                // If the lnChan is nil, continue as this is a pending channel.
3007
                if lnChan == nil {
3008
                        return true
3009
                }
3010

3011
                dbChan := lnChan.State()
×
3012
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
×
3013
                if !isPublic || dbChan.IsPending {
×
3014
                        return true
×
3015
                }
×
3016

×
3017
                // We'll also skip any channels added during this peer's
×
3018
                // lifecycle since they haven't waited out the timeout. Their
×
3019
                // first announcement will be enabled, and the chan status
×
3020
                // manager will begin monitoring them passively since they exist
×
3021
                // in the database.
×
3022
                if _, ok := p.addedChannels.Load(chanID); ok {
×
3023
                        return true
×
3024
                }
×
3025

×
3026
                activePublicChans = append(
3027
                        activePublicChans, dbChan.FundingOutpoint,
3028
                )
3029

3030
                return true
3031
        })
3032

3033
        return activePublicChans
×
3034
}
×
3035

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

×
3043
        // retryEnable is a helper closure that sends an enable request and
3044
        // removes the channel from the map if it's matched.
3045
        retryEnable := func(chanPoint wire.OutPoint) error {
×
3046
                // If this is an active channel event, check whether it's in
×
3047
                // our targeted channels map.
×
3048
                _, found := activeChans[chanPoint]
×
3049

×
3050
                // If this channel is irrelevant, return nil so the loop can
×
3051
                // jump to next iteration.
×
3052
                if !found {
3053
                        return nil
×
3054
                }
3055

3056
                // Otherwise we've just received an active signal for a channel
×
3057
                // that's previously failed to be enabled, we send the request
×
3058
                // again.
×
3059
                //
×
3060
                // We only give the channel one more shot, so we delete it from
×
3061
                // our map first to keep it from being attempted again.
×
3062
                delete(activeChans, chanPoint)
×
3063

×
3064
                // Send the request.
×
3065
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
3066
                if err != nil {
×
3067
                        return fmt.Errorf("request enabling channel %v "+
×
3068
                                "failed: %w", chanPoint, err)
×
3069
                }
3070

×
3071
                return nil
3072
        }
3073

3074
        for {
3075
                // If activeChans is empty, we've done processing all the
×
3076
                // channels.
×
3077
                if len(activeChans) == 0 {
×
3078
                        p.log.Debug("Finished retry enabling channels")
3079
                        return
3080
                }
3081

3082
                select {
×
3083
                // A new event has been sent by the ChannelNotifier. We now
×
3084
                // check whether it's an active or inactive channel event.
×
3085
                case e := <-p.channelEventClient.Updates():
×
3086
                        // If this is an active channel event, try enable the
3087
                        // channel then jump to the next iteration.
3088
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
3089
                        if ok {
×
3090
                                chanPoint := *active.ChannelPoint
×
3091

3092
                                // If we received an error for this particular
×
3093
                                // channel, we log an error and won't quit as
×
3094
                                // we still want to retry other channels.
×
3095
                                if err := retryEnable(chanPoint); err != nil {
3096
                                        p.log.Errorf("Retry failed: %v", err)
3097
                                }
3098

3099
                                continue
3100
                        }
3101

3102
                        // Otherwise check for inactive link event, and jump to
3103
                        // next iteration if it's not.
14✔
3104
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
14✔
3105
                        if !ok {
14✔
3106
                                continue
14✔
3107
                        }
22✔
3108

8✔
3109
                        // Found an inactive link event, if this is our
8✔
3110
                        // targeted channel, remove it from our map.
3111
                        chanPoint := *inactive.ChannelPoint
3112
                        _, found := activeChans[chanPoint]
3113
                        if !found {
12✔
3114
                                continue
4✔
3115
                        }
4✔
3116

3117
                        delete(activeChans, chanPoint)
3118
                        p.log.Warnf("Re-enable channel %v failed, received "+
3119
                                "inactive link event", chanPoint)
3120

3121
                case <-p.quit:
6✔
3122
                        p.log.Debugf("Peer shutdown during retry enabling")
2✔
3123
                        return
2✔
3124
                }
3125
        }
3126
}
3127

2✔
3128
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
3129
// a suitable script to close out to. This may be nil if neither script is
3130
// set. If both scripts are set, this function will error if they do not match.
3131
func chooseDeliveryScript(upfront,
3132
        requested lnwire.DeliveryAddress) (lnwire.DeliveryAddress, error) {
3133

×
3134
        // If no upfront shutdown script was provided, return the user
×
3135
        // requested address (which may be nil).
×
3136
        if len(upfront) == 0 {
×
3137
                return requested, nil
×
3138
        }
×
3139

×
3140
        // If an upfront shutdown script was provided, and the user did not
×
3141
        // request a custom shutdown script, return the upfront address.
×
3142
        if len(requested) == 0 {
×
3143
                return upfront, nil
×
3144
        }
×
3145

×
3146
        // If both an upfront shutdown script and a custom close script were
×
3147
        // provided, error if the user provided shutdown script does not match
×
3148
        // the upfront shutdown script (because closing out to a different
×
3149
        // script would violate upfront shutdown).
×
3150
        if !bytes.Equal(upfront, requested) {
×
3151
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
×
3152
        }
3153

×
3154
        // The user requested script matches the upfront shutdown script, so we
×
3155
        // can return it without error.
×
3156
        return upfront, nil
×
3157
}
3158

3159
// restartCoopClose checks whether we need to restart the cooperative close
×
3160
// process for a given channel.
×
3161
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
×
3162
        *lnwire.Shutdown, error) {
×
3163

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

3182
        var deliveryScript []byte
3183

×
3184
        shutdownInfo, err := c.ShutdownInfo()
×
3185
        switch {
×
3186
        // We have previously stored the delivery script that we need to use
×
3187
        // in the shutdown message. Re-use this script.
×
3188
        case err == nil:
×
3189
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
×
3190
                        deliveryScript = info.DeliveryScript.Val
3191
                })
3192

3193
        // An error other than ErrNoShutdownInfo was returned
×
3194
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
3195
                return nil, err
×
3196

×
3197
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
3198
                deliveryScript = c.LocalShutdownScript
×
3199
                if len(deliveryScript) == 0 {
×
3200
                        var err error
×
3201
                        deliveryScript, err = p.genDeliveryScript()
×
3202
                        if err != nil {
×
3203
                                p.log.Errorf("unable to gen delivery script: "+
×
3204
                                        "%v", err)
×
3205

×
3206
                                return nil, fmt.Errorf("close addr unavailable")
×
3207
                        }
×
3208
                }
×
3209
        }
3210

3211
        // Compute an ideal fee.
3212
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
3213
                p.cfg.CoopCloseTargetConfs,
×
3214
        )
×
3215
        if err != nil {
×
3216
                p.log.Errorf("unable to query fee estimator: %v", err)
×
3217
                return nil, fmt.Errorf("unable to estimate fee")
×
3218
        }
×
3219

×
3220
        // Determine whether we or the peer are the initiator of the coop
×
3221
        // close attempt by looking at the channel's status.
×
3222
        closingParty := lntypes.Remote
×
3223
        if c.HasChanStatus(channeldb.ChanStatusLocalCloseInitiator) {
3224
                closingParty = lntypes.Local
×
3225
        }
3226

3227
        addr, err := p.addrWithInternalKey(deliveryScript).Unpack()
3228
        if err != nil {
3229
                return nil, fmt.Errorf("unable to parse addr: %w", err)
3230
        }
3231
        chanCloser, err := p.createChanCloser(
3232
                lnChan, addr, feePerKw, nil, closingParty,
11✔
3233
        )
11✔
3234
        if err != nil {
11✔
3235
                p.log.Errorf("unable to create chan closer: %v", err)
11✔
3236
                return nil, fmt.Errorf("unable to create chan closer")
×
3237
        }
×
3238

×
3239
        // This does not need a mutex even though it is in a different
3240
        // goroutine since this is done before the channelManager goroutine is
3241
        // created.
11✔
3242
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
19✔
3243
        p.activeChanCloses[chanID] = chanCloser
8✔
3244

8✔
3245
        // Create the Shutdown message.
3246
        shutdownMsg, err := chanCloser.ShutdownChan()
11✔
3247
        if err != nil {
11✔
3248
                p.log.Errorf("unable to create shutdown message: %v", err)
11✔
3249
                delete(p.activeChanCloses, chanID)
11✔
3250
                return nil, err
11✔
3251
        }
11✔
3252

11✔
3253
        return shutdownMsg, nil
22✔
3254
}
11✔
3255

11✔
3256
// createChanCloser constructs a ChanCloser from the passed parameters and is
11✔
3257
// used to de-duplicate code.
11✔
3258
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3259
        deliveryScript chancloser.DeliveryAddrWithKey,
×
3260
        fee chainfee.SatPerKWeight, req *htlcswitch.ChanClose,
×
3261
        closer lntypes.ChannelParty) (*chancloser.ChanCloser, error) {
×
3262

3263
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
3264
        if err != nil {
3265
                p.log.Errorf("unable to obtain best block: %v", err)
3266
                return nil, fmt.Errorf("cannot obtain best block")
3267
        }
3268

3269
        // The req will only be set if we initiated the co-op closing flow.
3270
        var maxFee chainfee.SatPerKWeight
3271
        if req != nil {
3272
                maxFee = req.MaxFee
11✔
3273
        }
3274

3275
        chanCloser := chancloser.NewChanCloser(
3276
                chancloser.ChanCloseCfg{
3277
                        Channel:      channel,
9✔
3278
                        MusigSession: NewMusigChanCloser(channel),
9✔
3279
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
9✔
3280
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
9✔
3281
                        AuxCloser:    p.cfg.AuxChanCloser,
9✔
3282
                        DisableChannel: func(op wire.OutPoint) error {
9✔
3283
                                return p.cfg.ChanStatusMgr.RequestDisable(
9✔
3284
                                        op, false,
9✔
3285
                                )
×
3286
                        },
×
3287
                        MaxFee: maxFee,
×
3288
                        Disconnect: func() error {
×
3289
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
3290
                        },
×
3291
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3292
                        Quit:        p.quit,
9✔
3293
                },
3294
                deliveryScript,
3295
                fee,
3296
                uint32(startingHeight),
9✔
3297
                req,
9✔
3298
                closer,
9✔
3299
        )
9✔
3300

9✔
3301
        return chanCloser, nil
9✔
3302
}
9✔
3303

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

10✔
3309
        channel, ok := p.activeChannels.Load(chanID)
1✔
3310

1✔
3311
        // Though this function can't be called for pending channels, we still
1✔
3312
        // check whether channel is nil for safety.
1✔
3313
        if !ok || channel == nil {
3314
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
3315
                        "unknown", chanID)
3316
                p.log.Errorf(err.Error())
13✔
3317
                req.Err <- err
5✔
3318
                return
5✔
3319
        }
×
3320

×
3321
        switch req.CloseType {
×
3322
        // A type of CloseRegular indicates that the user has opted to close
×
3323
        // out this channel on-chain, so we execute the cooperative channel
3324
        // closure workflow.
8✔
3325
        case contractcourt.CloseRegular:
8✔
3326
                // First, we'll choose a delivery address that we'll use to send the
×
3327
                // funds to in the case of a successful negotiation.
×
3328

×
3329
                // An upfront shutdown and user provided script are both optional,
×
3330
                // but must be equal if both set  (because we cannot serve a request
×
3331
                // to close out to a script which violates upfront shutdown). Get the
×
3332
                // appropriate address to close out to (which may be nil if neither
×
3333
                // are set) and error if they are both set and do not match.
8✔
3334
                deliveryScript, err := chooseDeliveryScript(
8✔
3335
                        channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
8✔
3336
                )
8✔
3337
                if err != nil {
×
3338
                        p.log.Errorf("cannot close channel %v: %v", req.ChanPoint, err)
×
3339
                        req.Err <- err
×
3340
                        return
×
3341
                }
3342

8✔
3343
                // If neither an upfront address or a user set address was
8✔
3344
                // provided, generate a fresh script.
8✔
3345
                if len(deliveryScript) == 0 {
8✔
3346
                        deliveryScript, err = p.genDeliveryScript()
8✔
3347
                        if err != nil {
8✔
3348
                                p.log.Errorf(err.Error())
8✔
3349
                                req.Err <- err
×
3350
                                return
×
3351
                        }
×
3352
                }
×
3353
                addr, err := p.addrWithInternalKey(deliveryScript).Unpack()
×
3354
                if err != nil {
×
3355
                        err = fmt.Errorf("unable to parse addr for channel "+
×
3356
                                "%v: %w", req.ChanPoint, err)
×
3357
                        p.log.Errorf(err.Error())
×
3358
                        req.Err <- err
3359

8✔
3360
                        return
8✔
3361
                }
×
3362
                chanCloser, err := p.createChanCloser(
×
3363
                        channel, addr, req.TargetFeePerKw, req, lntypes.Local,
×
3364
                )
×
3365
                if err != nil {
×
3366
                        p.log.Errorf(err.Error())
×
3367
                        req.Err <- err
×
3368
                        return
×
3369
                }
×
3370

×
3371
                p.activeChanCloses[chanID] = chanCloser
3372

8✔
3373
                // Finally, we'll initiate the channel shutdown within the
×
3374
                // chanCloser, and send the shutdown message to the remote
×
3375
                // party to kick things off.
×
3376
                shutdownMsg, err := chanCloser.ShutdownChan()
3377
                if err != nil {
16✔
3378
                        p.log.Errorf(err.Error())
8✔
3379
                        req.Err <- err
8✔
3380
                        delete(p.activeChanCloses, chanID)
3381

3382
                        // As we were unable to shutdown the channel, we'll
3383
                        // return it back to its normal state.
1✔
3384
                        channel.ResetState()
1✔
3385
                        return
1✔
3386
                }
1✔
3387

1✔
3388
                link := p.fetchLinkFromKeyAndCid(chanID)
3389
                if link == nil {
3390
                        // If the link is nil then it means it was already
3391
                        // removed from the switch or it never existed in the
3392
                        // first place. The latter case is handled at the
3393
                        // beginning of this function, so in the case where it
3394
                        // has already been removed, we can skip adding the
3395
                        // commit hook to queue a Shutdown message.
3396
                        p.log.Warnf("link not found during attempted closure: "+
3397
                                "%v", chanID)
3398
                        return
3399
                }
3400

3401
                if !link.DisableAdds(htlcswitch.Outgoing) {
3402
                        p.log.Warnf("Outgoing link adds already "+
3403
                                "disabled: %v", link.ChanID())
3404
                }
3405

3406
                link.OnCommitOnce(htlcswitch.Outgoing, func() {
2✔
3407
                        p.queueMsg(shutdownMsg, nil)
2✔
3408
                })
2✔
3409

2✔
3410
        // A type of CloseBreach indicates that the counterparty has breached
2✔
3411
        // the channel therefore we need to clean up our local state.
2✔
3412
        case contractcourt.CloseBreach:
2✔
3413
                // TODO(roasbeef): no longer need with newer beach logic?
2✔
3414
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
2✔
3415
                        "channel", req.ChanPoint)
2✔
3416
                p.WipeChannel(req.ChanPoint)
2✔
3417
        }
2✔
3418
}
2✔
3419

2✔
3420
// linkFailureReport is sent to the channelManager whenever a link reports a
2✔
3421
// link failure, and is forced to exit. The report houses the necessary
2✔
3422
// information to clean up the channel state, send back the error message, and
2✔
3423
// force close if necessary.
4✔
3424
type linkFailureReport struct {
2✔
3425
        chanPoint   wire.OutPoint
2✔
3426
        chanID      lnwire.ChannelID
2✔
3427
        shortChanID lnwire.ShortChannelID
2✔
3428
        linkErr     htlcswitch.LinkFailureError
2✔
3429
}
4✔
3430

2✔
3431
// handleLinkFailure processes a link failure report when a link in the switch
2✔
3432
// fails. It facilitates the removal of all channel state within the peer,
4✔
3433
// force closing the channel depending on severity, and sending the error
2✔
3434
// message back to the remote party.
2✔
3435
func (p *Brontide) handleLinkFailure(failure linkFailureReport) {
2✔
3436
        // Retrieve the channel from the map of active channels. We do this to
2✔
3437
        // have access to it even after WipeChannel remove it from the map.
3438
        chanID := lnwire.NewChanIDFromOutPoint(failure.chanPoint)
3439
        lnChan, _ := p.activeChannels.Load(chanID)
3440

2✔
3441
        // We begin by wiping the link, which will remove it from the switch,
×
3442
        // such that it won't be attempted used for any more updates.
×
3443
        //
×
3444
        // TODO(halseth): should introduce a way to atomically stop/pause the
×
3445
        // link and cancel back any adds in its mailboxes such that we can
×
3446
        // safely force close without the link being added again and updates
×
3447
        // being applied.
×
3448
        p.WipeChannel(&failure.chanPoint)
3449

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

2✔
3455
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
2✔
3456
                        failure.chanPoint,
2✔
3457
                )
2✔
3458
                if err != nil {
×
3459
                        p.log.Errorf("unable to force close "+
×
3460
                                "link(%v): %v", failure.shortChanID, err)
3461
                } else {
2✔
3462
                        p.log.Infof("channel(%v) force "+
2✔
3463
                                "closed with txid %v",
×
3464
                                failure.shortChanID, closeTx.TxHash())
×
3465
                }
×
3466
        }
×
3467

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

2✔
3473
                if err := lnChan.State().MarkBorked(); err != nil {
3474
                        p.log.Errorf("Unable to mark channel %v borked: %v",
2✔
3475
                                failure.shortChanID, err)
2✔
3476
                }
×
3477
        }
×
3478

×
3479
        // Send an error to the peer, why we failed the channel.
3480
        if failure.linkErr.ShouldSendToPeer() {
3481
                // If SendData is set, send it to the peer. If not, we'll use
3482
                // the standard error messages in the payload. We only include
3483
                // sendData in the cases where the error data does not contain
3484
                // sensitive information.
2✔
3485
                data := []byte(failure.linkErr.Error())
×
3486
                if failure.linkErr.SendData != nil {
×
3487
                        data = failure.linkErr.SendData
3488
                }
3489

3490
                var networkMsg lnwire.Message
3491
                if failure.linkErr.Warning {
3492
                        networkMsg = &lnwire.Warning{
21✔
3493
                                ChanID: failure.chanID,
21✔
3494
                                Data:   data,
21✔
3495
                        }
21✔
3496
                } else {
21✔
3497
                        networkMsg = &lnwire.Error{
21✔
3498
                                ChanID: failure.chanID,
21✔
3499
                                Data:   data,
41✔
3500
                        }
40✔
3501
                }
20✔
3502

20✔
3503
                err := p.SendMessage(true, networkMsg)
3504
                if err != nil {
3505
                        p.log.Errorf("unable to send msg to "+
3506
                                "remote peer: %v", err)
21✔
3507
                }
3508
        }
3509

3510
        // If the failure action is disconnect, then we'll execute that now. If
3511
        // we had to send an error above, it was a sync call, so we expect the
3512
        // message to be flushed on the wire by now.
3513
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
3514
                p.Disconnect(fmt.Errorf("link requested disconnect"))
6✔
3515
        }
6✔
3516
}
6✔
3517

6✔
3518
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
6✔
3519
// public key and the channel id.
6✔
3520
func (p *Brontide) fetchLinkFromKeyAndCid(
6✔
3521
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
6✔
3522

6✔
3523
        var chanLink htlcswitch.ChannelUpdateHandler
6✔
3524

6✔
3525
        // We don't need to check the error here, and can instead just loop
6✔
3526
        // over the slice and return nil.
6✔
3527
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
6✔
3528
        for _, link := range links {
6✔
3529
                if link.ChanID() == cid {
6✔
3530
                        chanLink = link
6✔
3531
                        break
6✔
3532
                }
6✔
3533
        }
6✔
3534

10✔
3535
        return chanLink
4✔
3536
}
4✔
3537

3538
// finalizeChanClosure performs the final clean up steps once the cooperative
6✔
3539
// closure transaction has been fully broadcast. The finalized closing state
6✔
3540
// machine should be passed in. Once the transaction has been sufficiently
×
3541
// confirmed, the channel will be marked as fully closed within the database,
×
3542
// and any clients will be notified of updates to the closing state.
×
3543
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
×
3544
        closeReq := chanCloser.CloseRequest()
3545

3546
        // First, we'll clear all indexes related to the channel in question.
6✔
3547
        chanPoint := chanCloser.Channel().ChannelPoint()
6✔
3548
        p.WipeChannel(&chanPoint)
6✔
3549

6✔
3550
        // Also clear the activeChanCloses map of this channel.
10✔
3551
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
3552
        delete(p.activeChanCloses, cid)
4✔
3553

4✔
3554
        // Next, we'll launch a goroutine which will request to be notified by
4✔
3555
        // the ChainNotifier once the closure transaction obtains a single
3556
        // confirmation.
6✔
3557
        notifier := p.cfg.ChainNotifier
6✔
3558

6✔
3559
        // If any error happens during waitForChanToClose, forward it to
6✔
3560
        // closeReq. If this channel closure is not locally initiated, closeReq
6✔
3561
        // will be nil, so just ignore the error.
12✔
3562
        errChan := make(chan error, 1)
6✔
3563
        if closeReq != nil {
6✔
3564
                errChan = closeReq.Err
10✔
3565
        }
4✔
3566

4✔
3567
        closingTx, err := chanCloser.ClosingTx()
4✔
3568
        if err != nil {
4✔
3569
                if closeReq != nil {
4✔
3570
                        p.log.Error(err)
4✔
3571
                        closeReq.Err <- err
4✔
3572
                }
4✔
3573
        }
3574

3575
        closingTxid := closingTx.TxHash()
3576

3577
        // If this is a locally requested shutdown, update the caller with a
3578
        // new event detailing the current pending state of this request.
3579
        if closeReq != nil {
3580
                closeReq.Updates <- &PendingUpdate{
3581
                        Txid: closingTxid[:],
3582
                }
3583
        }
3584

6✔
3585
        localOut := chanCloser.LocalCloseOutput()
6✔
3586
        remoteOut := chanCloser.RemoteCloseOutput()
6✔
3587
        auxOut := chanCloser.AuxOutputs()
6✔
3588
        go WaitForChanToClose(
6✔
3589
                chanCloser.NegotiationHeight(), notifier, errChan,
6✔
3590
                &chanPoint, &closingTxid, closingTx.TxOut[0].PkScript, func() {
6✔
3591
                        // Respond to the local subsystem which requested the
6✔
3592
                        // channel closure.
6✔
3593
                        if closeReq != nil {
6✔
3594
                                closeReq.Updates <- &ChannelCloseUpdate{
×
3595
                                        ClosingTxid:       closingTxid[:],
×
3596
                                        Success:           true,
×
3597
                                        LocalCloseOutput:  localOut,
×
3598
                                        RemoteCloseOutput: remoteOut,
3599
                                        AuxOutputs:        auxOut,
3600
                                }
3601
                        }
3602
                },
6✔
3603
        )
8✔
3604
}
2✔
3605

2✔
3606
// WaitForChanToClose uses the passed notifier to wait until the channel has
3607
// been detected as closed on chain and then concludes by executing the
3608
// following actions: the channel point will be sent over the settleChan, and
3609
// finally the callback will be executed. If any error is encountered within
6✔
3610
// the function, then it will be sent over the errChan.
6✔
3611
func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
6✔
3612
        errChan chan error, chanPoint *wire.OutPoint,
6✔
3613
        closingTxID *chainhash.Hash, closeScript []byte, cb func()) {
6✔
3614

6✔
3615
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
3616
                "with txid: %v", chanPoint, closingTxID)
3617

3618
        // TODO(roasbeef): add param for num needed confs
3619
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
6✔
3620
                closingTxID, closeScript, 1, bestHeight,
6✔
3621
        )
6✔
3622
        if err != nil {
6✔
3623
                if errChan != nil {
6✔
3624
                        errChan <- err
6✔
3625
                }
6✔
3626
                return
6✔
3627
        }
6✔
3628

3629
        // In the case that the ChainNotifier is shutting down, all subscriber
3630
        // notification channels will be closed, generating a nil receive.
3631
        height, ok := <-confNtfn.Confirmed
5✔
3632
        if !ok {
5✔
3633
                return
5✔
3634
        }
5✔
3635

5✔
3636
        // The channel has been closed, remove it from any active indexes, and
×
3637
        // the database state.
×
3638
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
×
3639
                "height %v", chanPoint, height.BlockHeight)
3640

3641
        // Finally, execute the closure call back to mark the confirmation of
3642
        // the transaction closing the contract.
5✔
3643
        cb()
5✔
3644
}
5✔
3645

5✔
3646
// WipeChannel removes the passed channel point from all indexes associated with
5✔
3647
// the peer and the switch.
5✔
3648
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
5✔
3649
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
5✔
3650

×
3651
        p.activeChannels.Delete(chanID)
×
3652

3653
        // Instruct the HtlcSwitch to close this link as the channel is no
3654
        // longer active.
3655
        p.cfg.Switch.RemoveLink(chanID)
3656
}
5✔
3657

5✔
3658
// handleInitMsg handles the incoming init message which contains global and
×
3659
// local feature vectors. If feature vectors are incompatible then disconnect.
×
3660
func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
3661
        // First, merge any features from the legacy global features field into
3662
        // those presented in the local features fields.
3663
        err := msg.Features.Merge(msg.GlobalFeatures)
5✔
3664
        if err != nil {
×
3665
                return fmt.Errorf("unable to merge legacy global features: %w",
×
3666
                        err)
3667
        }
5✔
3668

3669
        // Then, finalize the remote feature vector providing the flattened
3670
        // feature bit namespace.
3671
        p.remoteFeatures = lnwire.NewFeatureVector(
3672
                msg.Features, lnwire.Features,
3673
        )
3674

3675
        // Now that we have their features loaded, we'll ensure that they
2✔
3676
        // didn't set any required bits that we don't know of.
2✔
3677
        err = feature.ValidateRequired(p.remoteFeatures)
2✔
3678
        if err != nil {
3679
                return fmt.Errorf("invalid remote features: %w", err)
3680
        }
3681

3682
        // Ensure the remote party's feature vector contains all transitive
3683
        // dependencies. We know ours are correct since they are validated
3684
        // during the feature manager's instantiation.
8✔
3685
        err = feature.ValidateDeps(p.remoteFeatures)
8✔
3686
        if err != nil {
8✔
3687
                return fmt.Errorf("invalid remote features: %w", err)
3688
        }
3689

3690
        // Now that we know we understand their requirements, we'll check to
5✔
3691
        // see if they don't support anything that we deem to be mandatory.
5✔
3692
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
5✔
3693
                return fmt.Errorf("data loss protection required")
5✔
3694
        }
5✔
3695

3696
        return nil
3697
}
3698

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

10✔
3708
// RemoteFeatures returns the set of global features that has been advertised by
1✔
3709
// the remote node. This allows sub-systems that use this interface to gate
1✔
3710
// their behavior off the set of negotiated feature bits.
1✔
3711
//
1✔
3712
// NOTE: Part of the lnpeer.Peer interface.
1✔
3713
func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector {
1✔
3714
        return p.remoteFeatures
1✔
3715
}
1✔
3716

1✔
3717
// hasNegotiatedScidAlias returns true if we've negotiated the
1✔
3718
// option-scid-alias feature bit with the peer.
1✔
3719
func (p *Brontide) hasNegotiatedScidAlias() bool {
1✔
3720
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
1✔
3721
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
3722
        return peerHas && localHas
9✔
3723
}
9✔
3724

9✔
3725
// sendInitMsg sends the Init message to the remote peer. This message contains
9✔
3726
// our currently supported local and global features.
9✔
3727
func (p *Brontide) sendInitMsg(legacyChan bool) error {
9✔
3728
        features := p.cfg.Features.Clone()
3729
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
3730

3731
        // If we have a legacy channel open with a peer, we downgrade static
3732
        // remote required to optional in case the peer does not understand the
2✔
3733
        // required feature bit. If we do not do this, the peer will reject our
2✔
3734
        // connection because it does not understand a required feature bit, and
2✔
3735
        // our channel will be unusable.
3✔
3736
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
1✔
3737
                p.log.Infof("Legacy channel open with peer, " +
1✔
3738
                        "downgrading static remote required feature bit to " +
3739
                        "optional")
3740

2✔
3741
                // Unset and set in both the local and global features to
4✔
3742
                // ensure both sets are consistent and merge able by old and
2✔
3743
                // new nodes.
2✔
3744
                features.Unset(lnwire.StaticRemoteKeyRequired)
2✔
3745
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
3746

2✔
3747
                features.Set(lnwire.StaticRemoteKeyOptional)
×
3748
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
×
3749
        }
×
3750

3751
        msg := lnwire.NewInitMessage(
2✔
3752
                legacyFeatures.RawFeatureVector,
×
3753
                features.RawFeatureVector,
×
3754
        )
×
3755

3756
        return p.writeMessage(msg)
2✔
3757
}
2✔
3758

2✔
3759
// resendChanSyncMsg will attempt to find a channel sync message for the closed
2✔
3760
// channel and resend it to our peer.
×
3761
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
×
3762
        // If we already re-sent the mssage for this channel, we won't do it
×
3763
        // again.
3764
        if _, ok := p.resentChanSyncMsg[cid]; ok {
2✔
3765
                return nil
2✔
3766
        }
2✔
3767

2✔
3768
        // Check if we have any channel sync messages stored for this channel.
2✔
3769
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
2✔
3770
        if err != nil {
2✔
3771
                return fmt.Errorf("unable to fetch channel sync messages for "+
2✔
3772
                        "peer %v: %v", p, err)
3773
        }
3774

3775
        if c.LastChanSyncMsg == nil {
3776
                return fmt.Errorf("no chan sync message stored for channel %v",
3777
                        cid)
3778
        }
3779

3780
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
5✔
3781
                return fmt.Errorf("ignoring channel reestablish from "+
5✔
3782
                        "peer=%x", p.IdentityKey().SerializeCompressed())
5✔
3783
        }
3784

3785
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
3786
                "peer", cid)
3787

3788
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
3789
                return fmt.Errorf("failed resending channel sync "+
3790
                        "message to peer %v: %v", p, err)
3✔
3791
        }
3✔
3792

3✔
3793
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
3794
                cid)
3795

3796
        // Note down that we sent the message, so we won't resend it again for
3797
        // this connection.
3798
        p.resentChanSyncMsg[cid] = struct{}{}
6✔
3799

6✔
3800
        return nil
6✔
3801
}
6✔
3802

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

3✔
3813
// SendMessageLazy sends a variadic number of low-priority messages to the
3✔
3814
// remote peer. The first argument denotes if the method should block until
3815
// the messages have been sent to the remote peer or an error is returned,
11✔
3816
// otherwise it returns immediately after queueing.
5✔
3817
//
8✔
3818
// NOTE: Part of the lnpeer.Peer interface.
3✔
3819
func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
3✔
3820
        return p.sendMessage(sync, false, msgs...)
3821
}
3822

3823
// sendMessage queues a variadic number of messages using the passed priority
3824
// to the remote peer. If sync is true, this method will block until the
9✔
3825
// messages have been sent to the remote peer or an error is returned, otherwise
3✔
3826
// it returns immediately after queueing.
3✔
3827
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
3✔
3828
        // Add all incoming messages to the outgoing queue. A list of error
×
3829
        // chans is populated for each message if the caller requested a sync
×
3830
        // send.
×
3831
        var errChans []chan error
×
3832
        if sync {
3833
                errChans = make([]chan error, 0, len(msgs))
3834
        }
3835
        for _, msg := range msgs {
5✔
3836
                // If a sync send was requested, create an error chan to listen
3837
                // for an ack from the writeHandler.
3838
                var errChan chan error
3839
                if sync {
3840
                        errChan = make(chan error, 1)
3841
                        errChans = append(errChans, errChan)
4✔
3842
                }
4✔
3843

4✔
3844
                if priority {
3845
                        p.queueMsg(msg, errChan)
3846
                } else {
3847
                        p.queueMsgLazy(msg, errChan)
3848
                }
17✔
3849
        }
17✔
3850

17✔
3851
        // Wait for all replies from the writeHandler. For async sends, this
3852
        // will be a NOP as the list of error chans is nil.
3853
        for _, errChan := range errChans {
3854
                select {
3855
                case err := <-errChan:
2✔
3856
                        return err
2✔
3857
                case <-p.quit:
2✔
3858
                        return lnpeer.ErrPeerExiting
3859
                case <-p.cfg.Quit:
3860
                        return lnpeer.ErrPeerExiting
3861
                }
3862
        }
3863

3864
        return nil
2✔
3865
}
2✔
3866

2✔
3867
// PubKey returns the pubkey of the peer in compressed serialized format.
2✔
3868
//
2✔
3869
// NOTE: Part of the lnpeer.Peer interface.
2✔
3870
func (p *Brontide) PubKey() [33]byte {
2✔
3871
        return p.cfg.PubKeyBytes
2✔
3872
}
2✔
3873

2✔
3874
// IdentityKey returns the public key of the remote peer.
×
3875
//
×
3876
// NOTE: Part of the lnpeer.Peer interface.
×
3877
func (p *Brontide) IdentityKey() *btcec.PublicKey {
×
3878
        return p.cfg.Addr.IdentityKey
3879
}
3880

3881
// Address returns the network address of the remote peer.
3882
//
2✔
3883
// NOTE: Part of the lnpeer.Peer interface.
2✔
3884
func (p *Brontide) Address() net.Addr {
2✔
3885
        return p.cfg.Addr.Address
×
3886
}
×
3887

3888
// AddNewChannel adds a new channel to the peer. The channel should fail to be
3889
// added if the cancel channel is closed.
3890
//
3891
// NOTE: Part of the lnpeer.Peer interface.
3892
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
3893
        cancel <-chan struct{}) error {
3894

3895
        errChan := make(chan error, 1)
2✔
3896
        newChanMsg := &newChannelMsg{
2✔
3897
                channel: newChan,
2✔
3898
                err:     errChan,
2✔
3899
        }
2✔
3900

2✔
3901
        select {
2✔
3902
        case p.newActiveChannel <- newChanMsg:
2✔
3903
        case <-cancel:
2✔
3904
                return errors.New("canceled adding new channel")
2✔
3905
        case <-p.quit:
3906
                return lnpeer.ErrPeerExiting
×
3907
        }
×
3908

3909
        // We pause here to wait for the peer to recognize the new channel
×
3910
        // before we close the channel barrier corresponding to the channel.
×
3911
        select {
3912
        case err := <-errChan:
3913
                return err
3914
        case <-p.quit:
3915
                return lnpeer.ErrPeerExiting
3916
        }
2✔
3917
}
2✔
3918

2✔
3919
// AddPendingChannel adds a pending open channel to the peer. The channel
3920
// should fail to be added if the cancel channel is closed.
×
3921
//
×
3922
// NOTE: Part of the lnpeer.Peer interface.
3923
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
×
3924
        cancel <-chan struct{}) error {
×
3925

3926
        errChan := make(chan error, 1)
3927
        newChanMsg := &newChannelMsg{
3928
                channelID: cid,
3929
                err:       errChan,
3930
        }
3931

2✔
3932
        select {
2✔
3933
        case p.newPendingChannel <- newChanMsg:
2✔
3934

2✔
3935
        case <-cancel:
2✔
3936
                return errors.New("canceled adding pending channel")
2✔
3937

2✔
3938
        case <-p.quit:
2✔
3939
                return lnpeer.ErrPeerExiting
2✔
3940
        }
×
3941

×
3942
        // We pause here to wait for the peer to recognize the new pending
3943
        // channel before we close the channel barrier corresponding to the
3944
        // channel.
3945
        select {
3946
        case err := <-errChan:
3947
                return err
2✔
3948

2✔
3949
        case <-cancel:
2✔
3950
                return errors.New("canceled adding pending channel")
3951

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

3957
// RemovePendingChannel removes a pending open channel from the peer.
3958
//
2✔
3959
// NOTE: Part of the lnpeer.Peer interface.
2✔
3960
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
2✔
3961
        errChan := make(chan error, 1)
3962
        newChanMsg := &newChannelMsg{
3963
                channelID: cid,
3964
                err:       errChan,
3965
        }
15✔
3966

15✔
3967
        select {
15✔
3968
        case p.removePendingChannel <- newChanMsg:
15✔
3969
        case <-p.quit:
15✔
3970
                return lnpeer.ErrPeerExiting
15✔
3971
        }
17✔
3972

2✔
3973
        // We pause here to wait for the peer to respond to the cancellation of
4✔
3974
        // the pending channel before we close the channel barrier
2✔
3975
        // corresponding to the channel.
2✔
3976
        select {
3977
        case err := <-errChan:
×
3978
                return err
×
3979

×
3980
        case <-p.quit:
×
3981
                return lnpeer.ErrPeerExiting
×
3982
        }
×
3983
}
×
3984

×
3985
// StartTime returns the time at which the connection was established if the
3986
// peer started successfully, and zero otherwise.
3987
func (p *Brontide) StartTime() time.Time {
15✔
3988
        return p.startTime
×
3989
}
×
3990

×
3991
// handleCloseMsg is called when a new cooperative channel closure related
×
3992
// message is received from the remote peer. We'll use this message to advance
×
3993
// the chan closer state machine.
×
3994
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
×
3995
        link := p.fetchLinkFromKeyAndCid(msg.cid)
×
3996

×
3997
        // We'll now fetch the matching closing state machine in order to continue,
×
3998
        // or finalize the channel closure process.
×
3999
        chanCloser, err := p.fetchActiveChanCloser(msg.cid)
×
4000
        if err != nil {
×
4001
                // If the channel is not known to us, we'll simply ignore this message.
4002
                if err == ErrChannelNotFound {
4003
                        return
4004
                }
4005

15✔
4006
                p.log.Errorf("Unable to respond to remote close msg: %v", err)
7✔
4007

7✔
4008
                errMsg := &lnwire.Error{
7✔
4009
                        ChanID: msg.cid,
×
4010
                        Data:   lnwire.ErrorData(err.Error()),
×
4011
                }
×
4012
                p.queueMsg(errMsg, nil)
4013
                return
7✔
4014
        }
7✔
4015

×
4016
        handleErr := func(err error) {
×
4017
                err = fmt.Errorf("unable to process close msg: %w", err)
×
4018
                p.log.Error(err)
4019

12✔
4020
                // As the negotiations failed, we'll reset the channel state machine to
5✔
4021
                // ensure we act to on-chain events as normal.
5✔
4022
                chanCloser.Channel().ResetState()
5✔
4023

6✔
4024
                if chanCloser.CloseRequest() != nil {
1✔
4025
                        chanCloser.CloseRequest().Err <- err
1✔
4026
                }
1✔
4027
                delete(p.activeChanCloses, msg.cid)
4028

4029
                p.Disconnect(err)
4030
        }
4✔
4031

×
4032
        // Next, we'll process the next message using the target state machine.
×
4033
        // We'll either continue negotiation, or halt.
×
4034
        switch typed := msg.msg.(type) {
4035
        case *lnwire.Shutdown:
4036
                // Disable incoming adds immediately.
4037
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
4038
                        p.log.Warnf("Incoming link adds already disabled: %v",
8✔
4039
                                link.ChanID())
4✔
4040
                }
4✔
4041

4042
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
4043
                if err != nil {
14✔
4044
                        handleErr(err)
7✔
4045
                        return
7✔
4046
                }
×
4047

×
4048
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
×
4049
                        // If the link is nil it means we can immediately queue
4050
                        // the Shutdown message since we don't have to wait for
14✔
4051
                        // commitment transaction synchronization.
7✔
4052
                        if link == nil {
7✔
4053
                                p.queueMsg(&msg, nil)
4054
                                return
4055
                        }
8✔
4056

1✔
4057
                        // Immediately disallow any new HTLC's from being added
7✔
4058
                        // in the outgoing direction.
6✔
4059
                        if !link.DisableAdds(htlcswitch.Outgoing) {
6✔
4060
                                p.log.Warnf("Outgoing link adds already "+
6✔
4061
                                        "disabled: %v", link.ChanID())
12✔
4062
                        }
6✔
4063

6✔
4064
                        // When we have a Shutdown to send, we defer it till the
6✔
4065
                        // next time we send a CommitSig to remain spec
6✔
4066
                        // compliant.
4067
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
4068
                                p.queueMsg(&msg, nil)
10✔
4069
                        })
10✔
4070
                })
10✔
4071

×
4072
                beginNegotiation := func() {
×
4073
                        oClosingSigned, err := chanCloser.BeginNegotiation()
×
4074
                        if err != nil {
4075
                                handleErr(err)
20✔
4076
                                return
10✔
4077
                        }
10✔
4078

4079
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
×
4080
                                p.queueMsg(&msg, nil)
×
4081
                        })
4082
                }
4083

4084
                if link == nil {
4085
                        beginNegotiation()
24✔
4086
                } else {
10✔
4087
                        // Now we register a flush hook to advance the
10✔
4088
                        // ChanCloser and possibly send out a ClosingSigned
4089
                        // when the link finishes draining.
4090
                        link.OnFlushedOnce(func() {
4091
                                // Remove link in goroutine to prevent deadlock.
4092
                                go p.cfg.Switch.RemoveLink(msg.cid)
6✔
4093
                                beginNegotiation()
4094
                        })
4095
                }
4096

4097
        case *lnwire.ClosingSigned:
4098
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
2✔
4099
                if err != nil {
2✔
4100
                        handleErr(err)
2✔
4101
                        return
2✔
4102
                }
2✔
4103

×
4104
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
×
4105
                        p.queueMsg(&msg, nil)
×
4106
                })
4107

4108
        default:
4109
                panic("impossible closeMsg type")
4110
        }
2✔
4111

2✔
4112
        // If we haven't finished close negotiations, then we'll continue as we
2✔
4113
        // can't yet finalize the closure.
4114
        if _, err := chanCloser.ClosingTx(); err != nil {
4115
                return
2✔
4116
        }
2✔
4117

2✔
4118
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
4119
        // the channel closure by notifying relevant sub-systems and launching a
4120
        // goroutine to wait for close tx conf.
2✔
4121
        p.finalizeChanClosure(chanCloser)
2✔
4122
}
2✔
4123

4124
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
4125
// the channelManager goroutine, which will shut down the link and possibly
2✔
4126
// close the channel.
2✔
4127
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
2✔
4128
        select {
4129
        case p.localCloseChanReqs <- req:
4130
                p.log.Info("Local close channel request is going to be " +
×
4131
                        "delivered to the peer")
×
4132
        case <-p.quit:
×
4133
                p.log.Info("Unable to deliver local close channel request " +
4134
                        "to peer")
4135
        }
2✔
4136
}
2✔
4137

2✔
4138
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
4139
func (p *Brontide) NetAddress() *lnwire.NetAddress {
4140
        return p.cfg.Addr
2✔
4141
}
2✔
4142

2✔
4143
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
4144
func (p *Brontide) Inbound() bool {
4145
        return p.cfg.Inbound
2✔
4146
}
2✔
4147

2✔
4148
// ConnReq is a getter for the Brontide's connReq in cfg.
4149
func (p *Brontide) ConnReq() *connmgr.ConnReq {
4150
        return p.cfg.ConnReq
2✔
4151
}
2✔
4152

2✔
4153
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
4154
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
4155
        return p.cfg.ErrorBuffer
4156
}
2✔
4157

2✔
4158
// SetAddress sets the remote peer's address given an address.
4✔
4159
func (p *Brontide) SetAddress(address net.Addr) {
2✔
4160
        p.cfg.Addr.Address = address
2✔
4161
}
4162

×
4163
// ActiveSignal returns the peer's active signal.
×
4164
func (p *Brontide) ActiveSignal() chan struct{} {
×
4165
        return p.activeSignal
×
4166
}
4167

×
4168
// Conn returns a pointer to the peer's connection struct.
4169
func (p *Brontide) Conn() net.Conn {
4170
        return p.cfg.Conn
4171
}
4172

4173
// BytesReceived returns the number of bytes received from the peer.
5✔
4174
func (p *Brontide) BytesReceived() uint64 {
5✔
4175
        return atomic.LoadUint64(&p.bytesReceived)
5✔
4176
}
5✔
4177

7✔
4178
// BytesSent returns the number of bytes sent to the peer.
2✔
4179
func (p *Brontide) BytesSent() uint64 {
2✔
4180
        return atomic.LoadUint64(&p.bytesSent)
4181
}
4182

4183
// LastRemotePingPayload returns the last payload the remote party sent as part
4184
// of their ping.
4185
func (p *Brontide) LastRemotePingPayload() []byte {
4186
        pingPayload := p.lastPingPayload.Load()
5✔
4187
        if pingPayload == nil {
5✔
4188
                return []byte{}
×
4189
        }
×
4190

4191
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
5✔
4192
        if !ok {
5✔
4193
                return nil
5✔
4194
        }
4195

4196
        return pingBytes
4197
}
4198

5✔
4199
// attachChannelEventSubscription creates a channel event subscription and
5✔
4200
// attaches to client to Brontide if the reenableTimeout is no greater than 1
5✔
4201
// minute.
5✔
4202
func (p *Brontide) attachChannelEventSubscription() error {
5✔
4203
        // If the timeout is greater than 1 minute, it's unlikely that the link
5✔
4204
        // hasn't yet finished its reestablishment. Return a nil without
5✔
4205
        // creating the client to specify that we don't want to retry.
5✔
4206
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
5✔
4207
                return nil
6✔
4208
        }
1✔
4209

1✔
4210
        // When the reenable timeout is less than 1 minute, it's likely the
1✔
4211
        // channel link hasn't finished its reestablishment yet. In that case,
4212
        // we'll give it a second chance by subscribing to the channel update
4213
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
4214
        // enabling the channel again.
5✔
4215
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
1✔
4216
        if err != nil {
1✔
4217
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
1✔
4218
        }
4219

4220
        p.channelEventClient = sub
4221

4222
        return nil
3✔
4223
}
×
4224

×
4225
// updateNextRevocation updates the existing channel's next revocation if it's
4226
// nil.
3✔
4227
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
3✔
4228
        chanPoint := c.FundingOutpoint
3✔
4229
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
4230

3✔
4231
        // Read the current channel.
3✔
4232
        currentChan, loaded := p.activeChannels.Load(chanID)
3✔
4233

×
4234
        // currentChan should exist, but we perform a check anyway to avoid nil
×
4235
        // pointer dereference.
4236
        if !loaded {
3✔
4237
                return fmt.Errorf("missing active channel with chanID=%v",
4238
                        chanID)
4239
        }
4240

4241
        // currentChan should not be nil, but we perform a check anyway to
4242
        // avoid nil pointer dereference.
2✔
4243
        if currentChan == nil {
2✔
4244
                return fmt.Errorf("found nil active channel with chanID=%v",
2✔
4245
                        chanID)
2✔
4246
        }
2✔
4247

2✔
4248
        // If we're being sent a new channel, and our existing channel doesn't
2✔
4249
        // have the next revocation, then we need to update the current
2✔
4250
        // existing channel.
2✔
4251
        if currentChan.RemoteNextRevocation() != nil {
2✔
4252
                return nil
2✔
4253
        }
2✔
4254

4✔
4255
        p.log.Infof("Processing retransmitted ChannelReady for "+
2✔
4256
                "ChannelPoint(%v)", chanPoint)
2✔
4257

2✔
4258
        nextRevoke := c.RemoteNextRevocation
2✔
4259

2✔
4260
        err := currentChan.InitNextRevocation(nextRevoke)
4261
        if err != nil {
2✔
4262
                return fmt.Errorf("unable to init next revocation: %w", err)
×
4263
        }
×
4264

2✔
4265
        return nil
×
4266
}
×
4267

2✔
4268
// addActiveChannel adds a new active channel to the `activeChannels` map. It
×
4269
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
×
4270
// it and assembles it with a channel link.
4271
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
4272
        chanPoint := c.FundingOutpoint
4273
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
4274

2✔
4275
        // If we've reached this point, there are two possible scenarios.  If
2✔
4276
        // the channel was in the active channels map as nil, then it was
2✔
4277
        // loaded from disk and we need to send reestablish. Else, it was not
2✔
4278
        // loaded from disk and we don't need to send reestablish as this is a
×
4279
        // fresh channel.
×
4280
        shouldReestablish := p.isLoadedFromDisk(chanID)
4281

4282
        chanOpts := c.ChanOpts
2✔
4283
        if shouldReestablish {
2✔
4284
                // If we have to do the reestablish dance for this channel,
2✔
4285
                // ensure that we don't try to call InitRemoteMusigNonces twice
2✔
4286
                // by calling SkipNonceInit.
2✔
4287
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
2✔
4288
        }
2✔
4289

2✔
4290
        p.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
×
4291
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
4292
        })
×
4293
        p.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
4294
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
4295
        })
4296

2✔
4297
        // If not already active, we'll add this channel to the set of active
2✔
4298
        // channels, so we can look it up later easily according to its channel
×
4299
        // ID.
×
4300
        lnChan, err := lnwallet.NewLightningChannel(
×
4301
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
4302
        )
4303
        if err != nil {
2✔
4304
                return fmt.Errorf("unable to create LightningChannel: %w", err)
2✔
4305
        }
2✔
4306

2✔
4307
        // Store the channel in the activeChannels map.
2✔
4308
        p.activeChannels.Store(chanID, lnChan)
×
4309

×
4310
        p.log.Infof("New channel active ChannelPoint(%v) with peer", chanPoint)
×
4311

4312
        // Next, we'll assemble a ChannelLink along with the necessary items it
2✔
4313
        // needs to function.
4314
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
4315
        if err != nil {
4316
                return fmt.Errorf("unable to subscribe to chain events: %w",
4317
                        err)
4318
        }
2✔
4319

2✔
4320
        // We'll query the channel DB for the new channel's initial forwarding
2✔
4321
        // policies to determine the policy we start out with.
2✔
4322
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
2✔
4323
        if err != nil {
2✔
4324
                return fmt.Errorf("unable to query for initial forwarding "+
2✔
4325
                        "policy: %v", err)
2✔
4326
        }
4✔
4327

2✔
4328
        // Create the link and add it to the switch.
2✔
4329
        err = p.addLink(
2✔
4330
                &chanPoint, lnChan, initialPolicy, chainEvents,
2✔
4331
                shouldReestablish, fn.None[lnwire.Shutdown](),
2✔
4332
        )
2✔
4333
        if err != nil {
2✔
4334
                return fmt.Errorf("can't register new channel link(%v) with "+
2✔
4335
                        "peer", chanPoint)
2✔
4336
        }
×
4337

×
4338
        return nil
4339
}
2✔
4340

4341
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
4342
// know this channel ID or not, we'll either add it to the `activeChannels` map
4343
// or init the next revocation for it.
2✔
4344
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
×
4345
        newChan := req.channel
×
4346
        chanPoint := newChan.FundingOutpoint
×
4347
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
4348

×
4349
        // Only update RemoteNextRevocation if the channel is in the
×
4350
        // activeChannels map and if we added the link to the switch. Only
4351
        // active channels will be added to the switch.
4352
        if p.isActiveChannel(chanID) {
2✔
4353
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
4354
                        chanPoint)
4355

4356
                // Handle it and close the err chan on the request.
4357
                close(req.err)
4358

4359
                // Update the next revocation point.
6✔
4360
                err := p.updateNextRevocation(newChan.OpenChannel)
6✔
4361
                if err != nil {
6✔
4362
                        p.log.Errorf(err.Error())
6✔
4363
                }
6✔
4364

6✔
4365
                return
6✔
4366
        }
6✔
4367

6✔
4368
        // This is a new channel, we now add it to the map.
7✔
4369
        if err := p.addActiveChannel(req.channel); err != nil {
1✔
4370
                // Log and send back the error to the request.
1✔
4371
                p.log.Errorf(err.Error())
1✔
4372
                req.err <- err
1✔
4373

1✔
4374
                return
4375
        }
4376

6✔
4377
        // Close the err chan if everything went fine.
1✔
4378
        close(req.err)
1✔
4379
}
1✔
4380

1✔
4381
// handleNewPendingChannel takes a `newChannelMsg` request and add it to
1✔
4382
// `activeChannels` map with nil value. This pending channel will be saved as
4383
// it may become active in the future. Once active, the funding manager will
4384
// send it again via `AddNewChannel`, and we'd handle the link creation there.
4385
func (p *Brontide) handleNewPendingChannel(req *newChannelMsg) {
4386
        defer close(req.err)
4✔
4387

4✔
4388
        chanID := req.channelID
4389

4390
        // If we already have this channel, something is wrong with the funding
4391
        // flow as it will only be marked as active after `ChannelReady` is
4392
        // handled. In this case, we will do nothing but log an error, just in
4393
        // case this is a legit channel.
6✔
4394
        if p.isActiveChannel(chanID) {
6✔
4395
                p.log.Errorf("Channel(%v) is already active, ignoring "+
6✔
4396
                        "pending channel request", chanID)
6✔
4397

6✔
4398
                return
6✔
4399
        }
6✔
4400

6✔
4401
        // The channel has already been added, we will do nothing and return.
7✔
4402
        if p.isPendingChannel(chanID) {
1✔
4403
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
4404
                        "pending channel request", chanID)
1✔
4405

1✔
4406
                return
4407
        }
4408

4409
        // This is a new channel, we now add it to the map `activeChannels`
8✔
4410
        // with nil value and mark it as a newly added channel in
3✔
4411
        // `addedChannels`.
3✔
4412
        p.activeChannels.Store(chanID, nil)
4413
        p.addedChannels.Store(chanID, struct{}{})
4414
}
5✔
4415

5✔
4416
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
4417
// from `activeChannels` map. The request will be ignored if the channel is
4418
// considered active by Brontide. Noop if the channel ID cannot be found.
4419
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
4420
        defer close(req.err)
2✔
4421

2✔
4422
        chanID := req.channelID
2✔
4423

2✔
4424
        // If we already have this channel, something is wrong with the funding
4✔
4425
        // flow as it will only be marked as active after `ChannelReady` is
2✔
4426
        // handled. In this case, we will log an error and exit.
2✔
4427
        if p.isActiveChannel(chanID) {
2✔
4428
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
2✔
4429
                        chanID)
2✔
4430
                return
2✔
4431
        }
2✔
4432

4✔
4433
        // The channel has not been added yet, we will log a warning as there
2✔
4434
        // is an unexpected call from funding manager.
2✔
4435
        if !p.isPendingChannel(chanID) {
2✔
4436
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
4437
        }
4438

4439
        // Remove the record of this pending channel.
4440
        p.activeChannels.Delete(chanID)
2✔
4441
        p.addedChannels.Delete(chanID)
4442
}
4443

4444
// sendLinkUpdateMsg sends a message that updates the channel to the
4445
// channel's message stream.
4446
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
4447
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
69✔
4448

71✔
4449
        chanStream, ok := p.activeMsgStreams[cid]
2✔
4450
        if !ok {
2✔
4451
                // If a stream hasn't yet been created, then we'll do so, add
4452
                // it to the map, and finally start it.
67✔
4453
                chanStream = newChanMsgStream(p, cid)
4454
                p.activeMsgStreams[cid] = chanStream
4455
                chanStream.Start()
4456

4457
                // Stop the stream when quit.
4458
                go func() {
4459
                        <-p.quit
4460
                        chanStream.Stop()
4461
                }()
4462
        }
4463

4464
        // With the stream obtained, add the message to the stream so we can
4465
        // continue processing message.
4466
        chanStream.AddMsg(msg)
4467
}
4468

4469
// scaleTimeout multiplies the argument duration by a constant factor depending
4470
// on variious heuristics. Currently this is only used to check whether our peer
4471
// appears to be connected over Tor and relaxes the timout deadline. However,
4472
// this is subject to change and should be treated as opaque.
4473
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
4474
        if p.isTorConnection {
4475
                return timeout * time.Duration(torTimeoutMultiplier)
4476
        }
4477

4478
        return timeout
4479
}
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