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

lightningnetwork / lnd / 9840691252

08 Jul 2024 01:34PM UTC coverage: 58.404% (+0.08%) from 58.325%
9840691252

Pull #8900

github

guggero
Makefile: add GOCC variable
Pull Request #8900: Makefile: add GOCC variable

123350 of 211200 relevant lines covered (58.4%)

27929.2 hits per line

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

77.03
/peer/brontide.go
1
package peer
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

118
        err chan error
119
}
120

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

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

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

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

146
// TimestampedError is a timestamped error that is used to store the most recent
147
// errors we have experienced with our peers.
148
type TimestampedError struct {
149
        Error     error
150
        Timestamp time.Time
151
}
152

153
// Config defines configuration fields that are necessary for a peer object
154
// to function.
155
type Config struct {
156
        // Conn is the underlying network connection for this peer.
157
        Conn MessageConn
158

159
        // ConnReq stores information related to the persistent connection request
160
        // for this peer.
161
        ConnReq *connmgr.ConnReq
162

163
        // PubKeyBytes is the serialized, compressed public key of this peer.
164
        PubKeyBytes [33]byte
165

166
        // Addr is the network address of the peer.
167
        Addr *lnwire.NetAddress
168

169
        // Inbound indicates whether or not the peer is an inbound peer.
170
        Inbound bool
171

172
        // Features is the set of features that we advertise to the remote party.
173
        Features *lnwire.FeatureVector
174

175
        // LegacyFeatures is the set of features that we advertise to the remote
176
        // peer for backwards compatibility. Nodes that have not implemented
177
        // flat features will still be able to read our feature bits from the
178
        // legacy global field, but we will also advertise everything in the
179
        // default features field.
180
        LegacyFeatures *lnwire.FeatureVector
181

182
        // OutgoingCltvRejectDelta defines the number of blocks before expiry of
183
        // an htlc where we don't offer it anymore.
184
        OutgoingCltvRejectDelta uint32
185

186
        // ChanActiveTimeout specifies the duration the peer will wait to request
187
        // a channel reenable, beginning from the time the peer was started.
188
        ChanActiveTimeout time.Duration
189

190
        // ErrorBuffer stores a set of errors related to a peer. It contains error
191
        // messages that our peer has recently sent us over the wire and records of
192
        // unknown messages that were sent to us so that we can have a full track
193
        // record of the communication errors we have had with our peer. If we
194
        // choose to disconnect from a peer, it also stores the reason we had for
195
        // disconnecting.
196
        ErrorBuffer *queue.CircularBuffer
197

198
        // WritePool is the task pool that manages reuse of write buffers. Write
199
        // tasks are submitted to the pool in order to conserve the total number of
200
        // write buffers allocated at any one time, and decouple write buffer
201
        // allocation from the peer life cycle.
202
        WritePool *pool.Write
203

204
        // ReadPool is the task pool that manages reuse of read buffers.
205
        ReadPool *pool.Read
206

207
        // Switch is a pointer to the htlcswitch. It is used to setup, get, and
208
        // tear-down ChannelLinks.
209
        Switch messageSwitch
210

211
        // InterceptSwitch is a pointer to the InterceptableSwitch, a wrapper around
212
        // the regular Switch. We only export it here to pass ForwardPackets to the
213
        // ChannelLinkConfig.
214
        InterceptSwitch *htlcswitch.InterceptableSwitch
215

216
        // ChannelDB is used to fetch opened channels, and closed channels.
217
        ChannelDB *channeldb.ChannelStateDB
218

219
        // ChannelGraph is a pointer to the channel graph which is used to
220
        // query information about the set of known active channels.
221
        ChannelGraph *channeldb.ChannelGraph
222

223
        // ChainArb is used to subscribe to channel events, update contract signals,
224
        // and force close channels.
225
        ChainArb *contractcourt.ChainArbitrator
226

227
        // AuthGossiper is needed so that the Brontide impl can register with the
228
        // gossiper and process remote channel announcements.
229
        AuthGossiper *discovery.AuthenticatedGossiper
230

231
        // ChanStatusMgr is used to set or un-set the disabled bit in channel
232
        // updates.
233
        ChanStatusMgr *netann.ChanStatusManager
234

235
        // ChainIO is used to retrieve the best block.
236
        ChainIO lnwallet.BlockChainIO
237

238
        // FeeEstimator is used to compute our target ideal fee-per-kw when
239
        // initializing the coop close process.
240
        FeeEstimator chainfee.Estimator
241

242
        // Signer is used when creating *lnwallet.LightningChannel instances.
243
        Signer input.Signer
244

245
        // SigPool is used when creating *lnwallet.LightningChannel instances.
246
        SigPool *lnwallet.SigPool
247

248
        // Wallet is used to publish transactions and generates delivery
249
        // scripts during the coop close process.
250
        Wallet *lnwallet.LightningWallet
251

252
        // ChainNotifier is used to receive confirmations of a coop close
253
        // transaction.
254
        ChainNotifier chainntnfs.ChainNotifier
255

256
        // BestBlockView is used to efficiently query for up-to-date
257
        // blockchain state information
258
        BestBlockView chainntnfs.BestBlockView
259

260
        // RoutingPolicy is used to set the forwarding policy for links created by
261
        // the Brontide.
262
        RoutingPolicy models.ForwardingPolicy
263

264
        // Sphinx is used when setting up ChannelLinks so they can decode sphinx
265
        // onion blobs.
266
        Sphinx *hop.OnionProcessor
267

268
        // WitnessBeacon is used when setting up ChannelLinks so they can add any
269
        // preimages that they learn.
270
        WitnessBeacon contractcourt.WitnessBeacon
271

272
        // Invoices is passed to the ChannelLink on creation and handles all
273
        // invoice-related logic.
274
        Invoices *invoices.InvoiceRegistry
275

276
        // ChannelNotifier is used by the link to notify other sub-systems about
277
        // channel-related events and by the Brontide to subscribe to
278
        // ActiveLinkEvents.
279
        ChannelNotifier *channelnotifier.ChannelNotifier
280

281
        // HtlcNotifier is used when creating a ChannelLink.
282
        HtlcNotifier *htlcswitch.HtlcNotifier
283

284
        // TowerClient is used to backup revoked states.
285
        TowerClient wtclient.ClientManager
286

287
        // DisconnectPeer is used to disconnect this peer if the cooperative close
288
        // process fails.
289
        DisconnectPeer func(*btcec.PublicKey) error
290

291
        // GenNodeAnnouncement is used to send our node announcement to the remote
292
        // on startup.
293
        GenNodeAnnouncement func(...netann.NodeAnnModifier) (
294
                lnwire.NodeAnnouncement, error)
295

296
        // PrunePersistentPeerConnection is used to remove all internal state
297
        // related to this peer in the server.
298
        PrunePersistentPeerConnection func([33]byte)
299

300
        // FetchLastChanUpdate fetches our latest channel update for a target
301
        // channel.
302
        FetchLastChanUpdate func(lnwire.ShortChannelID) (*lnwire.ChannelUpdate,
303
                error)
304

305
        // FundingManager is an implementation of the funding.Controller interface.
306
        FundingManager funding.Controller
307

308
        // Hodl is used when creating ChannelLinks to specify HodlFlags as
309
        // breakpoints in dev builds.
310
        Hodl *hodl.Config
311

312
        // UnsafeReplay is used when creating ChannelLinks to specify whether or
313
        // not to replay adds on its commitment tx.
314
        UnsafeReplay bool
315

316
        // MaxOutgoingCltvExpiry is used when creating ChannelLinks and is the max
317
        // number of blocks that funds could be locked up for when forwarding
318
        // payments.
319
        MaxOutgoingCltvExpiry uint32
320

321
        // MaxChannelFeeAllocation is used when creating ChannelLinks and is the
322
        // maximum percentage of total funds that can be allocated to a channel's
323
        // commitment fee. This only applies for the initiator of the channel.
324
        MaxChannelFeeAllocation float64
325

326
        // MaxAnchorsCommitFeeRate is the maximum fee rate we'll use as an
327
        // initiator for anchor channel commitments.
328
        MaxAnchorsCommitFeeRate chainfee.SatPerKWeight
329

330
        // CoopCloseTargetConfs is the confirmation target that will be used
331
        // to estimate the fee rate to use during a cooperative channel
332
        // closure initiated by the remote peer.
333
        CoopCloseTargetConfs uint32
334

335
        // ServerPubKey is the serialized, compressed public key of our lnd node.
336
        // It is used to determine which policy (channel edge) to pass to the
337
        // ChannelLink.
338
        ServerPubKey [33]byte
339

340
        // ChannelCommitInterval is the maximum time that is allowed to pass between
341
        // receiving a channel state update and signing the next commitment.
342
        // Setting this to a longer duration allows for more efficient channel
343
        // operations at the cost of latency.
344
        ChannelCommitInterval time.Duration
345

346
        // PendingCommitInterval is the maximum time that is allowed to pass
347
        // while waiting for the remote party to revoke a locally initiated
348
        // commitment state. Setting this to a longer duration if a slow
349
        // response is expected from the remote party or large number of
350
        // payments are attempted at the same time.
351
        PendingCommitInterval time.Duration
352

353
        // ChannelCommitBatchSize is the maximum number of channel state updates
354
        // that is accumulated before signing a new commitment.
355
        ChannelCommitBatchSize uint32
356

357
        // HandleCustomMessage is called whenever a custom message is received
358
        // from the peer.
359
        HandleCustomMessage func(peer [33]byte, msg *lnwire.Custom) error
360

361
        // GetAliases is passed to created links so the Switch and link can be
362
        // aware of the channel's aliases.
363
        GetAliases func(base lnwire.ShortChannelID) []lnwire.ShortChannelID
364

365
        // RequestAlias allows the Brontide struct to request an alias to send
366
        // to the peer.
367
        RequestAlias func() (lnwire.ShortChannelID, error)
368

369
        // AddLocalAlias persists an alias to an underlying alias store.
370
        AddLocalAlias func(alias, base lnwire.ShortChannelID,
371
                gossip bool) error
372

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

379
        // Adds the option to disable forwarding payments in blinded routes
380
        // by failing back any blinding-related payloads as if they were
381
        // invalid.
382
        DisallowRouteBlinding bool
383

384
        // Quit is the server's quit channel. If this is closed, we halt operation.
385
        Quit chan struct{}
386
}
387

388
// Brontide is an active peer on the Lightning Network. This struct is responsible
389
// for managing any channel state related to this peer. To do so, it has
390
// several helper goroutines to handle events such as HTLC timeouts, new
391
// funding workflow, and detecting an uncooperative closure of any active
392
// channels.
393
// TODO(roasbeef): proper reconnection logic.
394
type Brontide struct {
395
        // MUST be used atomically.
396
        started    int32
397
        disconnect int32
398

399
        // MUST be used atomically.
400
        bytesReceived uint64
401
        bytesSent     uint64
402

403
        // isTorConnection is a flag that indicates whether or not we believe
404
        // the remote peer is a tor connection. It is not always possible to
405
        // know this with certainty but we have heuristics we use that should
406
        // catch most cases.
407
        //
408
        // NOTE: We judge the tor-ness of a connection by if the remote peer has
409
        // ".onion" in the address OR if it's connected over localhost.
410
        // This will miss cases where our peer is connected to our clearnet
411
        // address over the tor network (via exit nodes). It will also misjudge
412
        // actual localhost connections as tor. We need to include this because
413
        // inbound connections to our tor address will appear to come from the
414
        // local socks5 proxy. This heuristic is only used to expand the timeout
415
        // window for peers so it is OK to misjudge this. If you use this field
416
        // for any other purpose you should seriously consider whether or not
417
        // this heuristic is good enough for your use case.
418
        isTorConnection bool
419

420
        pingManager *PingManager
421

422
        // lastPingPayload stores an unsafe pointer wrapped as an atomic
423
        // variable which points to the last payload the remote party sent us
424
        // as their ping.
425
        //
426
        // MUST be used atomically.
427
        lastPingPayload atomic.Value
428

429
        cfg Config
430

431
        // activeSignal when closed signals that the peer is now active and
432
        // ready to process messages.
433
        activeSignal chan struct{}
434

435
        // startTime is the time this peer connection was successfully established.
436
        // It will be zero for peers that did not successfully call Start().
437
        startTime time.Time
438

439
        // sendQueue is the channel which is used to queue outgoing messages to be
440
        // written onto the wire. Note that this channel is unbuffered.
441
        sendQueue chan outgoingMsg
442

443
        // outgoingQueue is a buffered channel which allows second/third party
444
        // objects to queue messages to be sent out on the wire.
445
        outgoingQueue chan outgoingMsg
446

447
        // activeChannels is a map which stores the state machines of all
448
        // active channels. Channels are indexed into the map by the txid of
449
        // the funding transaction which opened the channel.
450
        //
451
        // NOTE: On startup, pending channels are stored as nil in this map.
452
        // Confirmed channels have channel data populated in the map. This means
453
        // that accesses to this map should nil-check the LightningChannel to
454
        // see if this is a pending channel or not. The tradeoff here is either
455
        // having two maps everywhere (one for pending, one for confirmed chans)
456
        // or having an extra nil-check per access.
457
        activeChannels *lnutils.SyncMap[
458
                lnwire.ChannelID, *lnwallet.LightningChannel]
459

460
        // addedChannels tracks any new channels opened during this peer's
461
        // lifecycle. We use this to filter out these new channels when the time
462
        // comes to request a reenable for active channels, since they will have
463
        // waited a shorter duration.
464
        addedChannels *lnutils.SyncMap[lnwire.ChannelID, struct{}]
465

466
        // newActiveChannel is used by the fundingManager to send fully opened
467
        // channels to the source peer which handled the funding workflow.
468
        newActiveChannel chan *newChannelMsg
469

470
        // newPendingChannel is used by the fundingManager to send pending open
471
        // channels to the source peer which handled the funding workflow.
472
        newPendingChannel chan *newChannelMsg
473

474
        // removePendingChannel is used by the fundingManager to cancel pending
475
        // open channels to the source peer when the funding flow is failed.
476
        removePendingChannel chan *newChannelMsg
477

478
        // activeMsgStreams is a map from channel id to the channel streams that
479
        // proxy messages to individual, active links.
480
        activeMsgStreams map[lnwire.ChannelID]*msgStream
481

482
        // activeChanCloses is a map that keeps track of all the active
483
        // cooperative channel closures. Any channel closing messages are directed
484
        // to one of these active state machines. Once the channel has been closed,
485
        // the state machine will be deleted from the map.
486
        activeChanCloses map[lnwire.ChannelID]*chancloser.ChanCloser
487

488
        // localCloseChanReqs is a channel in which any local requests to close
489
        // a particular channel are sent over.
490
        localCloseChanReqs chan *htlcswitch.ChanClose
491

492
        // linkFailures receives all reported channel failures from the switch,
493
        // and instructs the channelManager to clean remaining channel state.
494
        linkFailures chan linkFailureReport
495

496
        // chanCloseMsgs is a channel that any message related to channel
497
        // closures are sent over. This includes lnwire.Shutdown message as
498
        // well as lnwire.ClosingSigned messages.
499
        chanCloseMsgs chan *closeMsg
500

501
        // remoteFeatures is the feature vector received from the peer during
502
        // the connection handshake.
503
        remoteFeatures *lnwire.FeatureVector
504

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

511
        // channelEventClient is the channel event subscription client that's
512
        // used to assist retry enabling the channels. This client is only
513
        // created when the reenableTimeout is no greater than 1 minute. Once
514
        // created, it is canceled once the reenabling has been finished.
515
        //
516
        // NOTE: we choose to create the client conditionally to avoid
517
        // potentially holding lots of un-consumed events.
518
        channelEventClient *subscribe.Client
519

520
        startReady chan struct{}
521
        quit       chan struct{}
522
        wg         sync.WaitGroup
523

524
        // log is a peer-specific logging instance.
525
        log btclog.Logger
526
}
527

528
// A compile-time check to ensure that Brontide satisfies the lnpeer.Peer interface.
529
var _ lnpeer.Peer = (*Brontide)(nil)
530

531
// NewBrontide creates a new Brontide from a peer.Config struct.
532
func NewBrontide(cfg Config) *Brontide {
28✔
533
        logPrefix := fmt.Sprintf("Peer(%x):", cfg.PubKeyBytes)
28✔
534

28✔
535
        p := &Brontide{
28✔
536
                cfg:           cfg,
28✔
537
                activeSignal:  make(chan struct{}),
28✔
538
                sendQueue:     make(chan outgoingMsg),
28✔
539
                outgoingQueue: make(chan outgoingMsg),
28✔
540
                addedChannels: &lnutils.SyncMap[lnwire.ChannelID, struct{}]{},
28✔
541
                activeChannels: &lnutils.SyncMap[
28✔
542
                        lnwire.ChannelID, *lnwallet.LightningChannel,
28✔
543
                ]{},
28✔
544
                newActiveChannel:     make(chan *newChannelMsg, 1),
28✔
545
                newPendingChannel:    make(chan *newChannelMsg, 1),
28✔
546
                removePendingChannel: make(chan *newChannelMsg),
28✔
547

28✔
548
                activeMsgStreams:   make(map[lnwire.ChannelID]*msgStream),
28✔
549
                activeChanCloses:   make(map[lnwire.ChannelID]*chancloser.ChanCloser),
28✔
550
                localCloseChanReqs: make(chan *htlcswitch.ChanClose),
28✔
551
                linkFailures:       make(chan linkFailureReport),
28✔
552
                chanCloseMsgs:      make(chan *closeMsg),
28✔
553
                resentChanSyncMsg:  make(map[lnwire.ChannelID]struct{}),
28✔
554
                startReady:         make(chan struct{}),
28✔
555
                quit:               make(chan struct{}),
28✔
556
                log:                build.NewPrefixLog(logPrefix, peerLog),
28✔
557
        }
28✔
558

28✔
559
        if cfg.Conn != nil && cfg.Conn.RemoteAddr() != nil {
32✔
560
                remoteAddr := cfg.Conn.RemoteAddr().String()
4✔
561
                p.isTorConnection = strings.Contains(remoteAddr, ".onion") ||
4✔
562
                        strings.Contains(remoteAddr, "127.0.0.1")
4✔
563
        }
4✔
564

565
        var (
28✔
566
                lastBlockHeader           *wire.BlockHeader
28✔
567
                lastSerializedBlockHeader [wire.MaxBlockHeaderPayload]byte
28✔
568
        )
28✔
569
        newPingPayload := func() []byte {
28✔
570
                // We query the BestBlockHeader from our BestBlockView each time
×
571
                // this is called, and update our serialized block header if
×
572
                // they differ.  Over time, we'll use this to disseminate the
×
573
                // latest block header between all our peers, which can later be
×
574
                // used to cross-check our own view of the network to mitigate
×
575
                // various types of eclipse attacks.
×
576
                header, err := p.cfg.BestBlockView.BestBlockHeader()
×
577
                if err != nil && header == lastBlockHeader {
×
578
                        return lastSerializedBlockHeader[:]
×
579
                }
×
580

581
                buf := bytes.NewBuffer(lastSerializedBlockHeader[0:0])
×
582
                err = header.Serialize(buf)
×
583
                if err == nil {
×
584
                        lastBlockHeader = header
×
585
                } else {
×
586
                        p.log.Warn("unable to serialize current block" +
×
587
                                "header for ping payload generation." +
×
588
                                "This should be impossible and means" +
×
589
                                "there is an implementation bug.")
×
590
                }
×
591

592
                return lastSerializedBlockHeader[:]
×
593
        }
594

595
        // TODO(roasbeef): make dynamic in order to create fake cover traffic.
596
        //
597
        // NOTE(proofofkeags): this was changed to be dynamic to allow better
598
        // pong identification, however, more thought is needed to make this
599
        // actually usable as a traffic decoy.
600
        randPongSize := func() uint16 {
28✔
601
                return uint16(
×
602
                        // We don't need cryptographic randomness here.
×
603
                        /* #nosec */
×
604
                        rand.Intn(pongSizeCeiling) + 1,
×
605
                )
×
606
        }
×
607

608
        p.pingManager = NewPingManager(&PingManagerConfig{
28✔
609
                NewPingPayload:   newPingPayload,
28✔
610
                NewPongSize:      randPongSize,
28✔
611
                IntervalDuration: p.scaleTimeout(pingInterval),
28✔
612
                TimeoutDuration:  p.scaleTimeout(pingTimeout),
28✔
613
                SendPing: func(ping *lnwire.Ping) {
28✔
614
                        p.queueMsg(ping, nil)
×
615
                },
×
616
                OnPongFailure: func(err error) {
×
617
                        eStr := "pong response failure for %s: %v " +
×
618
                                "-- disconnecting"
×
619
                        p.log.Warnf(eStr, p, err)
×
620
                        go p.Disconnect(fmt.Errorf(eStr, p, err))
×
621
                },
×
622
        })
623

624
        return p
28✔
625
}
626

627
// Start starts all helper goroutines the peer needs for normal operations.  In
628
// the case this peer has already been started, then this function is a noop.
629
func (p *Brontide) Start() error {
6✔
630
        if atomic.AddInt32(&p.started, 1) != 1 {
6✔
631
                return nil
×
632
        }
×
633

634
        // Once we've finished starting up the peer, we'll signal to other
635
        // goroutines that the they can move forward to tear down the peer, or
636
        // carry out other relevant changes.
637
        defer close(p.startReady)
6✔
638

6✔
639
        p.log.Tracef("starting with conn[%v->%v]",
6✔
640
                p.cfg.Conn.LocalAddr(), p.cfg.Conn.RemoteAddr())
6✔
641

6✔
642
        // Fetch and then load all the active channels we have with this remote
6✔
643
        // peer from the database.
6✔
644
        activeChans, err := p.cfg.ChannelDB.FetchOpenChannels(
6✔
645
                p.cfg.Addr.IdentityKey,
6✔
646
        )
6✔
647
        if err != nil {
6✔
648
                p.log.Errorf("Unable to fetch active chans "+
×
649
                        "for peer: %v", err)
×
650
                return err
×
651
        }
×
652

653
        if len(activeChans) == 0 {
11✔
654
                go p.cfg.PrunePersistentPeerConnection(p.cfg.PubKeyBytes)
5✔
655
        }
5✔
656

657
        // Quickly check if we have any existing legacy channels with this
658
        // peer.
659
        haveLegacyChan := false
6✔
660
        for _, c := range activeChans {
11✔
661
                if c.ChanType.IsTweakless() {
10✔
662
                        continue
5✔
663
                }
664

665
                haveLegacyChan = true
4✔
666
                break
4✔
667
        }
668

669
        // Exchange local and global features, the init message should be very
670
        // first between two nodes.
671
        if err := p.sendInitMsg(haveLegacyChan); err != nil {
6✔
672
                return fmt.Errorf("unable to send init msg: %w", err)
×
673
        }
×
674

675
        // Before we launch any of the helper goroutines off the peer struct,
676
        // we'll first ensure proper adherence to the p2p protocol. The init
677
        // message MUST be sent before any other message.
678
        readErr := make(chan error, 1)
6✔
679
        msgChan := make(chan lnwire.Message, 1)
6✔
680
        p.wg.Add(1)
6✔
681
        go func() {
12✔
682
                defer p.wg.Done()
6✔
683

6✔
684
                msg, err := p.readNextMessage()
6✔
685
                if err != nil {
7✔
686
                        readErr <- err
1✔
687
                        msgChan <- nil
1✔
688
                        return
1✔
689
                }
1✔
690
                readErr <- nil
6✔
691
                msgChan <- msg
6✔
692
        }()
693

694
        select {
6✔
695
        // In order to avoid blocking indefinitely, we'll give the other peer
696
        // an upper timeout to respond before we bail out early.
697
        case <-time.After(handshakeTimeout):
×
698
                return fmt.Errorf("peer did not complete handshake within %v",
×
699
                        handshakeTimeout)
×
700
        case err := <-readErr:
6✔
701
                if err != nil {
7✔
702
                        return fmt.Errorf("unable to read init msg: %w", err)
1✔
703
                }
1✔
704
        }
705

706
        // Once the init message arrives, we can parse it so we can figure out
707
        // the negotiation of features for this session.
708
        msg := <-msgChan
6✔
709
        if msg, ok := msg.(*lnwire.Init); ok {
12✔
710
                if err := p.handleInitMsg(msg); err != nil {
6✔
711
                        p.storeError(err)
×
712
                        return err
×
713
                }
×
714
        } else {
×
715
                return errors.New("very first message between nodes " +
×
716
                        "must be init message")
×
717
        }
×
718

719
        // Next, load all the active channels we have with this peer,
720
        // registering them with the switch and launching the necessary
721
        // goroutines required to operate them.
722
        p.log.Debugf("Loaded %v active channels from database",
6✔
723
                len(activeChans))
6✔
724

6✔
725
        // Conditionally subscribe to channel events before loading channels so
6✔
726
        // we won't miss events. This subscription is used to listen to active
6✔
727
        // channel event when reenabling channels. Once the reenabling process
6✔
728
        // is finished, this subscription will be canceled.
6✔
729
        //
6✔
730
        // NOTE: ChannelNotifier must be started before subscribing events
6✔
731
        // otherwise we'd panic here.
6✔
732
        if err := p.attachChannelEventSubscription(); err != nil {
6✔
733
                return err
×
734
        }
×
735

736
        msgs, err := p.loadActiveChannels(activeChans)
6✔
737
        if err != nil {
6✔
738
                return fmt.Errorf("unable to load channels: %w", err)
×
739
        }
×
740

741
        p.startTime = time.Now()
6✔
742

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

5✔
750
                // Send the messages directly via writeMessage and bypass the
5✔
751
                // writeHandler goroutine.
5✔
752
                for _, msg := range msgs {
10✔
753
                        if err := p.writeMessage(msg); err != nil {
5✔
754
                                return fmt.Errorf("unable to send "+
×
755
                                        "reestablish msg: %v", err)
×
756
                        }
×
757
                }
758
        }
759

760
        err = p.pingManager.Start()
6✔
761
        if err != nil {
6✔
762
                return fmt.Errorf("could not start ping manager %w", err)
×
763
        }
×
764

765
        p.wg.Add(4)
6✔
766
        go p.queueHandler()
6✔
767
        go p.writeHandler()
6✔
768
        go p.channelManager()
6✔
769
        go p.readHandler()
6✔
770

6✔
771
        // Signal to any external processes that the peer is now active.
6✔
772
        close(p.activeSignal)
6✔
773

6✔
774
        // Node announcements don't propagate very well throughout the network
6✔
775
        // as there isn't a way to efficiently query for them through their
6✔
776
        // timestamp, mostly affecting nodes that were offline during the time
6✔
777
        // of broadcast. We'll resend our node announcement to the remote peer
6✔
778
        // as a best-effort delivery such that it can also propagate to their
6✔
779
        // peers. To ensure they can successfully process it in most cases,
6✔
780
        // we'll only resend it as long as we have at least one confirmed
6✔
781
        // advertised channel with the remote peer.
6✔
782
        //
6✔
783
        // TODO(wilmer): Remove this once we're able to query for node
6✔
784
        // announcements through their timestamps.
6✔
785
        go p.maybeSendNodeAnn(activeChans)
6✔
786

6✔
787
        return nil
6✔
788
}
789

790
// initGossipSync initializes either a gossip syncer or an initial routing
791
// dump, depending on the negotiated synchronization method.
792
func (p *Brontide) initGossipSync() {
6✔
793
        // If the remote peer knows of the new gossip queries feature, then
6✔
794
        // we'll create a new gossipSyncer in the AuthenticatedGossiper for it.
6✔
795
        if p.remoteFeatures.HasFeature(lnwire.GossipQueriesOptional) {
12✔
796
                p.log.Info("Negotiated chan series queries")
6✔
797

6✔
798
                if p.cfg.AuthGossiper == nil {
8✔
799
                        // This should only ever be hit in the unit tests.
2✔
800
                        p.log.Warn("No AuthGossiper configured. Abandoning " +
2✔
801
                                "gossip sync.")
2✔
802
                        return
2✔
803
                }
2✔
804

805
                // Register the peer's gossip syncer with the gossiper.
806
                // This blocks synchronously to ensure the gossip syncer is
807
                // registered with the gossiper before attempting to read
808
                // messages from the remote peer.
809
                //
810
                // TODO(wilmer): Only sync updates from non-channel peers. This
811
                // requires an improved version of the current network
812
                // bootstrapper to ensure we can find and connect to non-channel
813
                // peers.
814
                p.cfg.AuthGossiper.InitSyncState(p)
4✔
815
        }
816
}
817

818
// taprootShutdownAllowed returns true if both parties have negotiated the
819
// shutdown-any-segwit feature.
820
func (p *Brontide) taprootShutdownAllowed() bool {
10✔
821
        return p.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
10✔
822
                p.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
10✔
823
}
10✔
824

825
// QuitSignal is a method that should return a channel which will be sent upon
826
// or closed once the backing peer exits. This allows callers using the
827
// interface to cancel any processing in the event the backing implementation
828
// exits.
829
//
830
// NOTE: Part of the lnpeer.Peer interface.
831
func (p *Brontide) QuitSignal() <-chan struct{} {
4✔
832
        return p.quit
4✔
833
}
4✔
834

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

6✔
842
        // Return a slice of messages to send to the peers in case the channel
6✔
843
        // cannot be loaded normally.
6✔
844
        var msgs []lnwire.Message
6✔
845

6✔
846
        scidAliasNegotiated := p.hasNegotiatedScidAlias()
6✔
847

6✔
848
        for _, dbChan := range chans {
11✔
849
                hasScidFeature := dbChan.ChanType.HasScidAliasFeature()
5✔
850
                if scidAliasNegotiated && !hasScidFeature {
9✔
851
                        // We'll request and store an alias, making sure that a
4✔
852
                        // gossiper mapping is not created for the alias to the
4✔
853
                        // real SCID. This is done because the peer and funding
4✔
854
                        // manager are not aware of each other's states and if
4✔
855
                        // we did not do this, we would accept alias channel
4✔
856
                        // updates after 6 confirmations, which would be buggy.
4✔
857
                        // We'll queue a channel_ready message with the new
4✔
858
                        // alias. This should technically be done *after* the
4✔
859
                        // reestablish, but this behavior is pre-existing since
4✔
860
                        // the funding manager may already queue a
4✔
861
                        // channel_ready before the channel_reestablish.
4✔
862
                        if !dbChan.IsPending {
8✔
863
                                aliasScid, err := p.cfg.RequestAlias()
4✔
864
                                if err != nil {
4✔
865
                                        return nil, err
×
866
                                }
×
867

868
                                err = p.cfg.AddLocalAlias(
4✔
869
                                        aliasScid, dbChan.ShortChanID(), false,
4✔
870
                                )
4✔
871
                                if err != nil {
4✔
872
                                        return nil, err
×
873
                                }
×
874

875
                                chanID := lnwire.NewChanIDFromOutPoint(
4✔
876
                                        dbChan.FundingOutpoint,
4✔
877
                                )
4✔
878

4✔
879
                                // Fetch the second commitment point to send in
4✔
880
                                // the channel_ready message.
4✔
881
                                second, err := dbChan.SecondCommitmentPoint()
4✔
882
                                if err != nil {
4✔
883
                                        return nil, err
×
884
                                }
×
885

886
                                channelReadyMsg := lnwire.NewChannelReady(
4✔
887
                                        chanID, second,
4✔
888
                                )
4✔
889
                                channelReadyMsg.AliasScid = &aliasScid
4✔
890

4✔
891
                                msgs = append(msgs, channelReadyMsg)
4✔
892
                        }
893

894
                        // If we've negotiated the option-scid-alias feature
895
                        // and this channel does not have ScidAliasFeature set
896
                        // to true due to an upgrade where the feature bit was
897
                        // turned on, we'll update the channel's database
898
                        // state.
899
                        err := dbChan.MarkScidAliasNegotiated()
4✔
900
                        if err != nil {
4✔
901
                                return nil, err
×
902
                        }
×
903
                }
904

905
                lnChan, err := lnwallet.NewLightningChannel(
5✔
906
                        p.cfg.Signer, dbChan, p.cfg.SigPool,
5✔
907
                )
5✔
908
                if err != nil {
5✔
909
                        return nil, err
×
910
                }
×
911

912
                chanPoint := dbChan.FundingOutpoint
5✔
913

5✔
914
                chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
5✔
915

5✔
916
                p.log.Infof("Loading ChannelPoint(%v), isPending=%v",
5✔
917
                        chanPoint, lnChan.IsPending())
5✔
918

5✔
919
                // Skip adding any permanently irreconcilable channels to the
5✔
920
                // htlcswitch.
5✔
921
                if !dbChan.HasChanStatus(channeldb.ChanStatusDefault) &&
5✔
922
                        !dbChan.HasChanStatus(channeldb.ChanStatusRestored) {
10✔
923

5✔
924
                        p.log.Warnf("ChannelPoint(%v) has status %v, won't "+
5✔
925
                                "start.", chanPoint, dbChan.ChanStatus())
5✔
926

5✔
927
                        // To help our peer recover from a potential data loss,
5✔
928
                        // we resend our channel reestablish message if the
5✔
929
                        // channel is in a borked state. We won't process any
5✔
930
                        // channel reestablish message sent from the peer, but
5✔
931
                        // that's okay since the assumption is that we did when
5✔
932
                        // marking the channel borked.
5✔
933
                        chanSync, err := dbChan.ChanSyncMsg()
5✔
934
                        if err != nil {
5✔
935
                                p.log.Errorf("Unable to create channel "+
×
936
                                        "reestablish message for channel %v: "+
×
937
                                        "%v", chanPoint, err)
×
938
                                continue
×
939
                        }
940

941
                        msgs = append(msgs, chanSync)
5✔
942

5✔
943
                        // Check if this channel needs to have the cooperative
5✔
944
                        // close process restarted. If so, we'll need to send
5✔
945
                        // the Shutdown message that is returned.
5✔
946
                        if dbChan.HasChanStatus(
5✔
947
                                channeldb.ChanStatusCoopBroadcasted,
5✔
948
                        ) {
5✔
949

×
950
                                shutdownMsg, err := p.restartCoopClose(lnChan)
×
951
                                if err != nil {
×
952
                                        p.log.Errorf("Unable to restart "+
×
953
                                                "coop close for channel: %v",
×
954
                                                err)
×
955
                                        continue
×
956
                                }
957

958
                                if shutdownMsg == nil {
×
959
                                        continue
×
960
                                }
961

962
                                // Append the message to the set of messages to
963
                                // send.
964
                                msgs = append(msgs, shutdownMsg)
×
965
                        }
966

967
                        continue
5✔
968
                }
969

970
                // Before we register this new link with the HTLC Switch, we'll
971
                // need to fetch its current link-layer forwarding policy from
972
                // the database.
973
                graph := p.cfg.ChannelGraph
4✔
974
                info, p1, p2, err := graph.FetchChannelEdgesByOutpoint(
4✔
975
                        &chanPoint,
4✔
976
                )
4✔
977
                if err != nil && !errors.Is(err, channeldb.ErrEdgeNotFound) {
4✔
978
                        return nil, err
×
979
                }
×
980

981
                // We'll filter out our policy from the directional channel
982
                // edges based whom the edge connects to. If it doesn't connect
983
                // to us, then we know that we were the one that advertised the
984
                // policy.
985
                //
986
                // TODO(roasbeef): can add helper method to get policy for
987
                // particular channel.
988
                var selfPolicy *models.ChannelEdgePolicy
4✔
989
                if info != nil && bytes.Equal(info.NodeKey1Bytes[:],
4✔
990
                        p.cfg.ServerPubKey[:]) {
8✔
991

4✔
992
                        selfPolicy = p1
4✔
993
                } else {
8✔
994
                        selfPolicy = p2
4✔
995
                }
4✔
996

997
                // If we don't yet have an advertised routing policy, then
998
                // we'll use the current default, otherwise we'll translate the
999
                // routing policy into a forwarding policy.
1000
                var forwardingPolicy *models.ForwardingPolicy
4✔
1001
                if selfPolicy != nil {
8✔
1002
                        var inboundWireFee lnwire.Fee
4✔
1003
                        _, err := selfPolicy.ExtraOpaqueData.ExtractRecords(
4✔
1004
                                &inboundWireFee,
4✔
1005
                        )
4✔
1006
                        if err != nil {
4✔
1007
                                return nil, err
×
1008
                        }
×
1009

1010
                        inboundFee := models.NewInboundFeeFromWire(
4✔
1011
                                inboundWireFee,
4✔
1012
                        )
4✔
1013

4✔
1014
                        forwardingPolicy = &models.ForwardingPolicy{
4✔
1015
                                MinHTLCOut:    selfPolicy.MinHTLC,
4✔
1016
                                MaxHTLC:       selfPolicy.MaxHTLC,
4✔
1017
                                BaseFee:       selfPolicy.FeeBaseMSat,
4✔
1018
                                FeeRate:       selfPolicy.FeeProportionalMillionths,
4✔
1019
                                TimeLockDelta: uint32(selfPolicy.TimeLockDelta),
4✔
1020

4✔
1021
                                InboundFee: inboundFee,
4✔
1022
                        }
4✔
1023
                } else {
4✔
1024
                        p.log.Warnf("Unable to find our forwarding policy "+
4✔
1025
                                "for channel %v, using default values",
4✔
1026
                                chanPoint)
4✔
1027
                        forwardingPolicy = &p.cfg.RoutingPolicy
4✔
1028
                }
4✔
1029

1030
                p.log.Tracef("Using link policy of: %v",
4✔
1031
                        spew.Sdump(forwardingPolicy))
4✔
1032

4✔
1033
                // If the channel is pending, set the value to nil in the
4✔
1034
                // activeChannels map. This is done to signify that the channel
4✔
1035
                // is pending. We don't add the link to the switch here - it's
4✔
1036
                // the funding manager's responsibility to spin up pending
4✔
1037
                // channels. Adding them here would just be extra work as we'll
4✔
1038
                // tear them down when creating + adding the final link.
4✔
1039
                if lnChan.IsPending() {
8✔
1040
                        p.activeChannels.Store(chanID, nil)
4✔
1041

4✔
1042
                        continue
4✔
1043
                }
1044

1045
                shutdownInfo, err := lnChan.State().ShutdownInfo()
4✔
1046
                if err != nil && !errors.Is(err, channeldb.ErrNoShutdownInfo) {
4✔
1047
                        return nil, err
×
1048
                }
×
1049

1050
                var (
4✔
1051
                        shutdownMsg     fn.Option[lnwire.Shutdown]
4✔
1052
                        shutdownInfoErr error
4✔
1053
                )
4✔
1054
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
8✔
1055
                        // Compute an ideal fee.
4✔
1056
                        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
4✔
1057
                                p.cfg.CoopCloseTargetConfs,
4✔
1058
                        )
4✔
1059
                        if err != nil {
4✔
1060
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1061
                                        "estimate fee: %w", err)
×
1062

×
1063
                                return
×
1064
                        }
×
1065

1066
                        chanCloser, err := p.createChanCloser(
4✔
1067
                                lnChan, info.DeliveryScript.Val, feePerKw, nil,
4✔
1068
                                info.LocalInitiator.Val,
4✔
1069
                        )
4✔
1070
                        if err != nil {
4✔
1071
                                shutdownInfoErr = fmt.Errorf("unable to "+
×
1072
                                        "create chan closer: %w", err)
×
1073

×
1074
                                return
×
1075
                        }
×
1076

1077
                        chanID := lnwire.NewChanIDFromOutPoint(
4✔
1078
                                lnChan.State().FundingOutpoint,
4✔
1079
                        )
4✔
1080

4✔
1081
                        p.activeChanCloses[chanID] = chanCloser
4✔
1082

4✔
1083
                        // Create the Shutdown message.
4✔
1084
                        shutdown, err := chanCloser.ShutdownChan()
4✔
1085
                        if err != nil {
4✔
1086
                                delete(p.activeChanCloses, chanID)
×
1087
                                shutdownInfoErr = err
×
1088

×
1089
                                return
×
1090
                        }
×
1091

1092
                        shutdownMsg = fn.Some(*shutdown)
4✔
1093
                })
1094
                if shutdownInfoErr != nil {
4✔
1095
                        return nil, shutdownInfoErr
×
1096
                }
×
1097

1098
                // Subscribe to the set of on-chain events for this channel.
1099
                chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(
4✔
1100
                        chanPoint,
4✔
1101
                )
4✔
1102
                if err != nil {
4✔
1103
                        return nil, err
×
1104
                }
×
1105

1106
                err = p.addLink(
4✔
1107
                        &chanPoint, lnChan, forwardingPolicy, chainEvents,
4✔
1108
                        true, shutdownMsg,
4✔
1109
                )
4✔
1110
                if err != nil {
4✔
1111
                        return nil, fmt.Errorf("unable to add link %v to "+
×
1112
                                "switch: %v", chanPoint, err)
×
1113
                }
×
1114

1115
                p.activeChannels.Store(chanID, lnChan)
4✔
1116
        }
1117

1118
        return msgs, nil
6✔
1119
}
1120

1121
// addLink creates and adds a new ChannelLink from the specified channel.
1122
func (p *Brontide) addLink(chanPoint *wire.OutPoint,
1123
        lnChan *lnwallet.LightningChannel,
1124
        forwardingPolicy *models.ForwardingPolicy,
1125
        chainEvents *contractcourt.ChainEventSubscription,
1126
        syncStates bool, shutdownMsg fn.Option[lnwire.Shutdown]) error {
4✔
1127

4✔
1128
        // onChannelFailure will be called by the link in case the channel
4✔
1129
        // fails for some reason.
4✔
1130
        onChannelFailure := func(chanID lnwire.ChannelID,
4✔
1131
                shortChanID lnwire.ShortChannelID,
4✔
1132
                linkErr htlcswitch.LinkFailureError) {
8✔
1133

4✔
1134
                failure := linkFailureReport{
4✔
1135
                        chanPoint:   *chanPoint,
4✔
1136
                        chanID:      chanID,
4✔
1137
                        shortChanID: shortChanID,
4✔
1138
                        linkErr:     linkErr,
4✔
1139
                }
4✔
1140

4✔
1141
                select {
4✔
1142
                case p.linkFailures <- failure:
4✔
1143
                case <-p.quit:
×
1144
                case <-p.cfg.Quit:
×
1145
                }
1146
        }
1147

1148
        updateContractSignals := func(signals *contractcourt.ContractSignals) error {
8✔
1149
                return p.cfg.ChainArb.UpdateContractSignals(*chanPoint, signals)
4✔
1150
        }
4✔
1151

1152
        notifyContractUpdate := func(update *contractcourt.ContractUpdate) error {
8✔
1153
                return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update)
4✔
1154
        }
4✔
1155

1156
        //nolint:lll
1157
        linkCfg := htlcswitch.ChannelLinkConfig{
4✔
1158
                Peer:                   p,
4✔
1159
                DecodeHopIterators:     p.cfg.Sphinx.DecodeHopIterators,
4✔
1160
                ExtractErrorEncrypter:  p.cfg.Sphinx.ExtractErrorEncrypter,
4✔
1161
                FetchLastChannelUpdate: p.cfg.FetchLastChanUpdate,
4✔
1162
                HodlMask:               p.cfg.Hodl.Mask(),
4✔
1163
                Registry:               p.cfg.Invoices,
4✔
1164
                BestHeight:             p.cfg.Switch.BestHeight,
4✔
1165
                Circuits:               p.cfg.Switch.CircuitModifier(),
4✔
1166
                ForwardPackets:         p.cfg.InterceptSwitch.ForwardPackets,
4✔
1167
                FwrdingPolicy:          *forwardingPolicy,
4✔
1168
                FeeEstimator:           p.cfg.FeeEstimator,
4✔
1169
                PreimageCache:          p.cfg.WitnessBeacon,
4✔
1170
                ChainEvents:            chainEvents,
4✔
1171
                UpdateContractSignals:  updateContractSignals,
4✔
1172
                NotifyContractUpdate:   notifyContractUpdate,
4✔
1173
                OnChannelFailure:       onChannelFailure,
4✔
1174
                SyncStates:             syncStates,
4✔
1175
                BatchTicker:            ticker.New(p.cfg.ChannelCommitInterval),
4✔
1176
                FwdPkgGCTicker:         ticker.New(time.Hour),
4✔
1177
                PendingCommitTicker: ticker.New(
4✔
1178
                        p.cfg.PendingCommitInterval,
4✔
1179
                ),
4✔
1180
                BatchSize:               p.cfg.ChannelCommitBatchSize,
4✔
1181
                UnsafeReplay:            p.cfg.UnsafeReplay,
4✔
1182
                MinUpdateTimeout:        htlcswitch.DefaultMinLinkFeeUpdateTimeout,
4✔
1183
                MaxUpdateTimeout:        htlcswitch.DefaultMaxLinkFeeUpdateTimeout,
4✔
1184
                OutgoingCltvRejectDelta: p.cfg.OutgoingCltvRejectDelta,
4✔
1185
                TowerClient:             p.cfg.TowerClient,
4✔
1186
                MaxOutgoingCltvExpiry:   p.cfg.MaxOutgoingCltvExpiry,
4✔
1187
                MaxFeeAllocation:        p.cfg.MaxChannelFeeAllocation,
4✔
1188
                MaxAnchorsCommitFeeRate: p.cfg.MaxAnchorsCommitFeeRate,
4✔
1189
                NotifyActiveLink:        p.cfg.ChannelNotifier.NotifyActiveLinkEvent,
4✔
1190
                NotifyActiveChannel:     p.cfg.ChannelNotifier.NotifyActiveChannelEvent,
4✔
1191
                NotifyInactiveChannel:   p.cfg.ChannelNotifier.NotifyInactiveChannelEvent,
4✔
1192
                NotifyInactiveLinkEvent: p.cfg.ChannelNotifier.NotifyInactiveLinkEvent,
4✔
1193
                HtlcNotifier:            p.cfg.HtlcNotifier,
4✔
1194
                GetAliases:              p.cfg.GetAliases,
4✔
1195
                PreviouslySentShutdown:  shutdownMsg,
4✔
1196
                DisallowRouteBlinding:   p.cfg.DisallowRouteBlinding,
4✔
1197
        }
4✔
1198

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

4✔
1206
        // With the channel link created, we'll now notify the htlc switch so
4✔
1207
        // this channel can be used to dispatch local payments and also
4✔
1208
        // passively forward payments.
4✔
1209
        return p.cfg.Switch.CreateAndAddLink(linkCfg, lnChan)
4✔
1210
}
1211

1212
// maybeSendNodeAnn sends our node announcement to the remote peer if at least
1213
// one confirmed public channel exists with them.
1214
func (p *Brontide) maybeSendNodeAnn(channels []*channeldb.OpenChannel) {
6✔
1215
        hasConfirmedPublicChan := false
6✔
1216
        for _, channel := range channels {
11✔
1217
                if channel.IsPending {
9✔
1218
                        continue
4✔
1219
                }
1220
                if channel.ChannelFlags&lnwire.FFAnnounceChannel == 0 {
10✔
1221
                        continue
5✔
1222
                }
1223

1224
                hasConfirmedPublicChan = true
4✔
1225
                break
4✔
1226
        }
1227
        if !hasConfirmedPublicChan {
12✔
1228
                return
6✔
1229
        }
6✔
1230

1231
        ourNodeAnn, err := p.cfg.GenNodeAnnouncement()
4✔
1232
        if err != nil {
4✔
1233
                p.log.Debugf("Unable to retrieve node announcement: %v", err)
×
1234
                return
×
1235
        }
×
1236

1237
        if err := p.SendMessageLazy(false, &ourNodeAnn); err != nil {
4✔
1238
                p.log.Debugf("Unable to resend node announcement: %v", err)
×
1239
        }
×
1240
}
1241

1242
// WaitForDisconnect waits until the peer has disconnected. A peer may be
1243
// disconnected if the local or remote side terminates the connection, or an
1244
// irrecoverable protocol error has been encountered. This method will only
1245
// begin watching the peer's waitgroup after the ready channel or the peer's
1246
// quit channel are signaled. The ready channel should only be signaled if a
1247
// call to Start returns no error. Otherwise, if the peer fails to start,
1248
// calling Disconnect will signal the quit channel and the method will not
1249
// block, since no goroutines were spawned.
1250
func (p *Brontide) WaitForDisconnect(ready chan struct{}) {
4✔
1251
        // Before we try to call the `Wait` goroutine, we'll make sure the main
4✔
1252
        // set of goroutines are already active.
4✔
1253
        select {
4✔
1254
        case <-p.startReady:
4✔
1255
        case <-p.quit:
×
1256
                return
×
1257
        }
1258

1259
        select {
4✔
1260
        case <-ready:
4✔
1261
        case <-p.quit:
1✔
1262
        }
1263

1264
        p.wg.Wait()
4✔
1265
}
1266

1267
// Disconnect terminates the connection with the remote peer. Additionally, a
1268
// signal is sent to the server and htlcSwitch indicating the resources
1269
// allocated to the peer can now be cleaned up.
1270
func (p *Brontide) Disconnect(reason error) {
5✔
1271
        if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
9✔
1272
                return
4✔
1273
        }
4✔
1274

1275
        // Make sure initialization has completed before we try to tear things
1276
        // down.
1277
        select {
5✔
1278
        case <-p.startReady:
4✔
1279
        case <-p.quit:
×
1280
                return
×
1281
        }
1282

1283
        err := fmt.Errorf("disconnecting %s, reason: %v", p, reason)
4✔
1284
        p.storeError(err)
4✔
1285

4✔
1286
        p.log.Infof(err.Error())
4✔
1287

4✔
1288
        // Stop PingManager before closing TCP connection.
4✔
1289
        p.pingManager.Stop()
4✔
1290

4✔
1291
        // Ensure that the TCP connection is properly closed before continuing.
4✔
1292
        p.cfg.Conn.Close()
4✔
1293

4✔
1294
        close(p.quit)
4✔
1295
}
1296

1297
// String returns the string representation of this peer.
1298
func (p *Brontide) String() string {
4✔
1299
        return fmt.Sprintf("%x@%s", p.cfg.PubKeyBytes, p.cfg.Conn.RemoteAddr())
4✔
1300
}
4✔
1301

1302
// readNextMessage reads, and returns the next message on the wire along with
1303
// any additional raw payload.
1304
func (p *Brontide) readNextMessage() (lnwire.Message, error) {
9✔
1305
        noiseConn := p.cfg.Conn
9✔
1306
        err := noiseConn.SetReadDeadline(time.Time{})
9✔
1307
        if err != nil {
9✔
1308
                return nil, err
×
1309
        }
×
1310

1311
        pktLen, err := noiseConn.ReadNextHeader()
9✔
1312
        if err != nil {
13✔
1313
                return nil, fmt.Errorf("read next header: %w", err)
4✔
1314
        }
4✔
1315

1316
        // First we'll read the next _full_ message. We do this rather than
1317
        // reading incrementally from the stream as the Lightning wire protocol
1318
        // is message oriented and allows nodes to pad on additional data to
1319
        // the message stream.
1320
        var (
7✔
1321
                nextMsg lnwire.Message
7✔
1322
                msgLen  uint64
7✔
1323
        )
7✔
1324
        err = p.cfg.ReadPool.Submit(func(buf *buffer.Read) error {
14✔
1325
                // Before reading the body of the message, set the read timeout
7✔
1326
                // accordingly to ensure we don't block other readers using the
7✔
1327
                // pool. We do so only after the task has been scheduled to
7✔
1328
                // ensure the deadline doesn't expire while the message is in
7✔
1329
                // the process of being scheduled.
7✔
1330
                readDeadline := time.Now().Add(
7✔
1331
                        p.scaleTimeout(readMessageTimeout),
7✔
1332
                )
7✔
1333
                readErr := noiseConn.SetReadDeadline(readDeadline)
7✔
1334
                if readErr != nil {
7✔
1335
                        return readErr
×
1336
                }
×
1337

1338
                // The ReadNextBody method will actually end up re-using the
1339
                // buffer, so within this closure, we can continue to use
1340
                // rawMsg as it's just a slice into the buf from the buffer
1341
                // pool.
1342
                rawMsg, readErr := noiseConn.ReadNextBody(buf[:pktLen])
7✔
1343
                if readErr != nil {
7✔
1344
                        return fmt.Errorf("read next body: %w", readErr)
×
1345
                }
×
1346
                msgLen = uint64(len(rawMsg))
7✔
1347

7✔
1348
                // Next, create a new io.Reader implementation from the raw
7✔
1349
                // message, and use this to decode the message directly from.
7✔
1350
                msgReader := bytes.NewReader(rawMsg)
7✔
1351
                nextMsg, err = lnwire.ReadMessage(msgReader, 0)
7✔
1352
                if err != nil {
11✔
1353
                        return err
4✔
1354
                }
4✔
1355

1356
                // At this point, rawMsg and buf will be returned back to the
1357
                // buffer pool for re-use.
1358
                return nil
7✔
1359
        })
1360
        atomic.AddUint64(&p.bytesReceived, msgLen)
7✔
1361
        if err != nil {
11✔
1362
                return nil, err
4✔
1363
        }
4✔
1364

1365
        p.logWireMessage(nextMsg, true)
7✔
1366

7✔
1367
        return nextMsg, nil
7✔
1368
}
1369

1370
// msgStream implements a goroutine-safe, in-order stream of messages to be
1371
// delivered via closure to a receiver. These messages MUST be in order due to
1372
// the nature of the lightning channel commitment and gossiper state machines.
1373
// TODO(conner): use stream handler interface to abstract out stream
1374
// state/logging.
1375
type msgStream struct {
1376
        streamShutdown int32 // To be used atomically.
1377

1378
        peer *Brontide
1379

1380
        apply func(lnwire.Message)
1381

1382
        startMsg string
1383
        stopMsg  string
1384

1385
        msgCond *sync.Cond
1386
        msgs    []lnwire.Message
1387

1388
        mtx sync.Mutex
1389

1390
        producerSema chan struct{}
1391

1392
        wg   sync.WaitGroup
1393
        quit chan struct{}
1394
}
1395

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

6✔
1404
        stream := &msgStream{
6✔
1405
                peer:         p,
6✔
1406
                apply:        apply,
6✔
1407
                startMsg:     startMsg,
6✔
1408
                stopMsg:      stopMsg,
6✔
1409
                producerSema: make(chan struct{}, bufSize),
6✔
1410
                quit:         make(chan struct{}),
6✔
1411
        }
6✔
1412
        stream.msgCond = sync.NewCond(&stream.mtx)
6✔
1413

6✔
1414
        // Before we return the active stream, we'll populate the producer's
6✔
1415
        // semaphore channel. We'll use this to ensure that the producer won't
6✔
1416
        // attempt to allocate memory in the queue for an item until it has
6✔
1417
        // sufficient extra space.
6✔
1418
        for i := uint32(0); i < bufSize; i++ {
2,010✔
1419
                stream.producerSema <- struct{}{}
2,004✔
1420
        }
2,004✔
1421

1422
        return stream
6✔
1423
}
1424

1425
// Start starts the chanMsgStream.
1426
func (ms *msgStream) Start() {
6✔
1427
        ms.wg.Add(1)
6✔
1428
        go ms.msgConsumer()
6✔
1429
}
6✔
1430

1431
// Stop stops the chanMsgStream.
1432
func (ms *msgStream) Stop() {
4✔
1433
        // TODO(roasbeef): signal too?
4✔
1434

4✔
1435
        close(ms.quit)
4✔
1436

4✔
1437
        // Now that we've closed the channel, we'll repeatedly signal the msg
4✔
1438
        // consumer until we've detected that it has exited.
4✔
1439
        for atomic.LoadInt32(&ms.streamShutdown) == 0 {
8✔
1440
                ms.msgCond.Signal()
4✔
1441
                time.Sleep(time.Millisecond * 100)
4✔
1442
        }
4✔
1443

1444
        ms.wg.Wait()
4✔
1445
}
1446

1447
// msgConsumer is the main goroutine that streams messages from the peer's
1448
// readHandler directly to the target channel.
1449
func (ms *msgStream) msgConsumer() {
6✔
1450
        defer ms.wg.Done()
6✔
1451
        defer peerLog.Tracef(ms.stopMsg)
6✔
1452
        defer atomic.StoreInt32(&ms.streamShutdown, 1)
6✔
1453

6✔
1454
        peerLog.Tracef(ms.startMsg)
6✔
1455

6✔
1456
        for {
12✔
1457
                // First, we'll check our condition. If the queue of messages
6✔
1458
                // is empty, then we'll wait until a new item is added.
6✔
1459
                ms.msgCond.L.Lock()
6✔
1460
                for len(ms.msgs) == 0 {
12✔
1461
                        ms.msgCond.Wait()
6✔
1462

6✔
1463
                        // If we woke up in order to exit, then we'll do so.
6✔
1464
                        // Otherwise, we'll check the message queue for any new
6✔
1465
                        // items.
6✔
1466
                        select {
6✔
1467
                        case <-ms.peer.quit:
4✔
1468
                                ms.msgCond.L.Unlock()
4✔
1469
                                return
4✔
1470
                        case <-ms.quit:
4✔
1471
                                ms.msgCond.L.Unlock()
4✔
1472
                                return
4✔
1473
                        default:
4✔
1474
                        }
1475
                }
1476

1477
                // Grab the message off the front of the queue, shifting the
1478
                // slice's reference down one in order to remove the message
1479
                // from the queue.
1480
                msg := ms.msgs[0]
4✔
1481
                ms.msgs[0] = nil // Set to nil to prevent GC leak.
4✔
1482
                ms.msgs = ms.msgs[1:]
4✔
1483

4✔
1484
                ms.msgCond.L.Unlock()
4✔
1485

4✔
1486
                ms.apply(msg)
4✔
1487

4✔
1488
                // We've just successfully processed an item, so we'll signal
4✔
1489
                // to the producer that a new slot in the buffer. We'll use
4✔
1490
                // this to bound the size of the buffer to avoid allowing it to
4✔
1491
                // grow indefinitely.
4✔
1492
                select {
4✔
1493
                case ms.producerSema <- struct{}{}:
4✔
1494
                case <-ms.peer.quit:
4✔
1495
                        return
4✔
1496
                case <-ms.quit:
4✔
1497
                        return
4✔
1498
                }
1499
        }
1500
}
1501

1502
// AddMsg adds a new message to the msgStream. This function is safe for
1503
// concurrent access.
1504
func (ms *msgStream) AddMsg(msg lnwire.Message) {
4✔
1505
        // First, we'll attempt to receive from the producerSema struct. This
4✔
1506
        // acts as a semaphore to prevent us from indefinitely buffering
4✔
1507
        // incoming items from the wire. Either the msg queue isn't full, and
4✔
1508
        // we'll not block, or the queue is full, and we'll block until either
4✔
1509
        // we're signalled to quit, or a slot is freed up.
4✔
1510
        select {
4✔
1511
        case <-ms.producerSema:
4✔
1512
        case <-ms.peer.quit:
×
1513
                return
×
1514
        case <-ms.quit:
×
1515
                return
×
1516
        }
1517

1518
        // Next, we'll lock the condition, and add the message to the end of
1519
        // the message queue.
1520
        ms.msgCond.L.Lock()
4✔
1521
        ms.msgs = append(ms.msgs, msg)
4✔
1522
        ms.msgCond.L.Unlock()
4✔
1523

4✔
1524
        // With the message added, we signal to the msgConsumer that there are
4✔
1525
        // additional messages to consume.
4✔
1526
        ms.msgCond.Signal()
4✔
1527
}
1528

1529
// waitUntilLinkActive waits until the target link is active and returns a
1530
// ChannelLink to pass messages to. It accomplishes this by subscribing to
1531
// an ActiveLinkEvent which is emitted by the link when it first starts up.
1532
func waitUntilLinkActive(p *Brontide,
1533
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
4✔
1534

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

4✔
1537
        // Subscribe to receive channel events.
4✔
1538
        //
4✔
1539
        // NOTE: If the link is already active by SubscribeChannelEvents, then
4✔
1540
        // GetLink will retrieve the link and we can send messages. If the link
4✔
1541
        // becomes active between SubscribeChannelEvents and GetLink, then GetLink
4✔
1542
        // will retrieve the link. If the link becomes active after GetLink, then
4✔
1543
        // we will get an ActiveLinkEvent notification and retrieve the link. If
4✔
1544
        // the call to GetLink is before SubscribeChannelEvents, however, there
4✔
1545
        // will be a race condition.
4✔
1546
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
4✔
1547
        if err != nil {
8✔
1548
                // If we have a non-nil error, then the server is shutting down and we
4✔
1549
                // can exit here and return nil. This means no message will be delivered
4✔
1550
                // to the link.
4✔
1551
                return nil
4✔
1552
        }
4✔
1553
        defer sub.Cancel()
4✔
1554

4✔
1555
        // The link may already be active by this point, and we may have missed the
4✔
1556
        // ActiveLinkEvent. Check if the link exists.
4✔
1557
        link := p.fetchLinkFromKeyAndCid(cid)
4✔
1558
        if link != nil {
8✔
1559
                return link
4✔
1560
        }
4✔
1561

1562
        // If the link is nil, we must wait for it to be active.
1563
        for {
8✔
1564
                select {
4✔
1565
                // A new event has been sent by the ChannelNotifier. We first check
1566
                // whether the event is an ActiveLinkEvent. If it is, we'll check
1567
                // that the event is for this channel. Otherwise, we discard the
1568
                // message.
1569
                case e := <-sub.Updates():
4✔
1570
                        event, ok := e.(channelnotifier.ActiveLinkEvent)
4✔
1571
                        if !ok {
8✔
1572
                                // Ignore this notification.
4✔
1573
                                continue
4✔
1574
                        }
1575

1576
                        chanPoint := event.ChannelPoint
4✔
1577

4✔
1578
                        // Check whether the retrieved chanPoint matches the target
4✔
1579
                        // channel id.
4✔
1580
                        if !cid.IsChanPoint(chanPoint) {
4✔
1581
                                continue
×
1582
                        }
1583

1584
                        // The link shouldn't be nil as we received an
1585
                        // ActiveLinkEvent. If it is nil, we return nil and the
1586
                        // calling function should catch it.
1587
                        return p.fetchLinkFromKeyAndCid(cid)
4✔
1588

1589
                case <-p.quit:
4✔
1590
                        return nil
4✔
1591
                }
1592
        }
1593
}
1594

1595
// newChanMsgStream is used to create a msgStream between the peer and
1596
// particular channel link in the htlcswitch. We utilize additional
1597
// synchronization with the fundingManager to ensure we don't attempt to
1598
// dispatch a message to a channel before it is fully active. A reference to the
1599
// channel this stream forwards to is held in scope to prevent unnecessary
1600
// lookups.
1601
func newChanMsgStream(p *Brontide, cid lnwire.ChannelID) *msgStream {
4✔
1602
        var chanLink htlcswitch.ChannelUpdateHandler
4✔
1603

4✔
1604
        apply := func(msg lnwire.Message) {
8✔
1605
                // This check is fine because if the link no longer exists, it will
4✔
1606
                // be removed from the activeChannels map and subsequent messages
4✔
1607
                // shouldn't reach the chan msg stream.
4✔
1608
                if chanLink == nil {
8✔
1609
                        chanLink = waitUntilLinkActive(p, cid)
4✔
1610

4✔
1611
                        // If the link is still not active and the calling function
4✔
1612
                        // errored out, just return.
4✔
1613
                        if chanLink == nil {
8✔
1614
                                p.log.Warnf("Link=%v is not active")
4✔
1615
                                return
4✔
1616
                        }
4✔
1617
                }
1618

1619
                // In order to avoid unnecessarily delivering message
1620
                // as the peer is exiting, we'll check quickly to see
1621
                // if we need to exit.
1622
                select {
4✔
1623
                case <-p.quit:
×
1624
                        return
×
1625
                default:
4✔
1626
                }
1627

1628
                chanLink.HandleChannelUpdate(msg)
4✔
1629
        }
1630

1631
        return newMsgStream(p,
4✔
1632
                fmt.Sprintf("Update stream for ChannelID(%x) created", cid[:]),
4✔
1633
                fmt.Sprintf("Update stream for ChannelID(%x) exiting", cid[:]),
4✔
1634
                1000,
4✔
1635
                apply,
4✔
1636
        )
4✔
1637
}
1638

1639
// newDiscMsgStream is used to setup a msgStream between the peer and the
1640
// authenticated gossiper. This stream should be used to forward all remote
1641
// channel announcements.
1642
func newDiscMsgStream(p *Brontide) *msgStream {
6✔
1643
        apply := func(msg lnwire.Message) {
10✔
1644
                // TODO(yy): `ProcessRemoteAnnouncement` returns an error chan
4✔
1645
                // and we need to process it.
4✔
1646
                p.cfg.AuthGossiper.ProcessRemoteAnnouncement(msg, p)
4✔
1647
        }
4✔
1648

1649
        return newMsgStream(
6✔
1650
                p,
6✔
1651
                "Update stream for gossiper created",
6✔
1652
                "Update stream for gossiper exited",
6✔
1653
                1000,
6✔
1654
                apply,
6✔
1655
        )
6✔
1656
}
1657

1658
// readHandler is responsible for reading messages off the wire in series, then
1659
// properly dispatching the handling of the message to the proper subsystem.
1660
//
1661
// NOTE: This method MUST be run as a goroutine.
1662
func (p *Brontide) readHandler() {
6✔
1663
        defer p.wg.Done()
6✔
1664

6✔
1665
        // We'll stop the timer after a new messages is received, and also
6✔
1666
        // reset it after we process the next message.
6✔
1667
        idleTimer := time.AfterFunc(idleTimeout, func() {
6✔
1668
                err := fmt.Errorf("peer %s no answer for %s -- disconnecting",
×
1669
                        p, idleTimeout)
×
1670
                p.Disconnect(err)
×
1671
        })
×
1672

1673
        // Initialize our negotiated gossip sync method before reading messages
1674
        // off the wire. When using gossip queries, this ensures a gossip
1675
        // syncer is active by the time query messages arrive.
1676
        //
1677
        // TODO(conner): have peer store gossip syncer directly and bypass
1678
        // gossiper?
1679
        p.initGossipSync()
6✔
1680

6✔
1681
        discStream := newDiscMsgStream(p)
6✔
1682
        discStream.Start()
6✔
1683
        defer discStream.Stop()
6✔
1684
out:
6✔
1685
        for atomic.LoadInt32(&p.disconnect) == 0 {
13✔
1686
                nextMsg, err := p.readNextMessage()
7✔
1687
                if !idleTimer.Stop() {
7✔
1688
                        select {
×
1689
                        case <-idleTimer.C:
×
1690
                        default:
×
1691
                        }
1692
                }
1693
                if err != nil {
9✔
1694
                        p.log.Infof("unable to read message from peer: %v", err)
4✔
1695

4✔
1696
                        // If we could not read our peer's message due to an
4✔
1697
                        // unknown type or invalid alias, we continue processing
4✔
1698
                        // as normal. We store unknown message and address
4✔
1699
                        // types, as they may provide debugging insight.
4✔
1700
                        switch e := err.(type) {
4✔
1701
                        // If this is just a message we don't yet recognize,
1702
                        // we'll continue processing as normal as this allows
1703
                        // us to introduce new messages in a forwards
1704
                        // compatible manner.
1705
                        case *lnwire.UnknownMessage:
4✔
1706
                                p.storeError(e)
4✔
1707
                                idleTimer.Reset(idleTimeout)
4✔
1708
                                continue
4✔
1709

1710
                        // If they sent us an address type that we don't yet
1711
                        // know of, then this isn't a wire error, so we'll
1712
                        // simply continue parsing the remainder of their
1713
                        // messages.
1714
                        case *lnwire.ErrUnknownAddrType:
×
1715
                                p.storeError(e)
×
1716
                                idleTimer.Reset(idleTimeout)
×
1717
                                continue
×
1718

1719
                        // If the NodeAnnouncement has an invalid alias, then
1720
                        // we'll log that error above and continue so we can
1721
                        // continue to read messages from the peer. We do not
1722
                        // store this error because it is of little debugging
1723
                        // value.
1724
                        case *lnwire.ErrInvalidNodeAlias:
×
1725
                                idleTimer.Reset(idleTimeout)
×
1726
                                continue
×
1727

1728
                        // If the error we encountered wasn't just a message we
1729
                        // didn't recognize, then we'll stop all processing as
1730
                        // this is a fatal error.
1731
                        default:
4✔
1732
                                break out
4✔
1733
                        }
1734
                }
1735

1736
                var (
5✔
1737
                        targetChan   lnwire.ChannelID
5✔
1738
                        isLinkUpdate bool
5✔
1739
                )
5✔
1740

5✔
1741
                switch msg := nextMsg.(type) {
5✔
1742
                case *lnwire.Pong:
×
1743
                        // When we receive a Pong message in response to our
×
1744
                        // last ping message, we send it to the pingManager
×
1745
                        p.pingManager.ReceivedPong(msg)
×
1746

1747
                case *lnwire.Ping:
×
1748
                        // First, we'll store their latest ping payload within
×
1749
                        // the relevant atomic variable.
×
1750
                        p.lastPingPayload.Store(msg.PaddingBytes[:])
×
1751

×
1752
                        // Next, we'll send over the amount of specified pong
×
1753
                        // bytes.
×
1754
                        pong := lnwire.NewPong(p.cfg.PongBuf[0:msg.NumPongBytes])
×
1755
                        p.queueMsg(pong, nil)
×
1756

1757
                case *lnwire.OpenChannel,
1758
                        *lnwire.AcceptChannel,
1759
                        *lnwire.FundingCreated,
1760
                        *lnwire.FundingSigned,
1761
                        *lnwire.ChannelReady:
4✔
1762

4✔
1763
                        p.cfg.FundingManager.ProcessFundingMsg(msg, p)
4✔
1764

1765
                case *lnwire.Shutdown:
4✔
1766
                        select {
4✔
1767
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
4✔
1768
                        case <-p.quit:
×
1769
                                break out
×
1770
                        }
1771
                case *lnwire.ClosingSigned:
4✔
1772
                        select {
4✔
1773
                        case p.chanCloseMsgs <- &closeMsg{msg.ChannelID, msg}:
4✔
1774
                        case <-p.quit:
×
1775
                                break out
×
1776
                        }
1777

1778
                case *lnwire.Warning:
×
1779
                        targetChan = msg.ChanID
×
1780
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
×
1781

1782
                case *lnwire.Error:
4✔
1783
                        targetChan = msg.ChanID
4✔
1784
                        isLinkUpdate = p.handleWarningOrError(targetChan, msg)
4✔
1785

1786
                case *lnwire.ChannelReestablish:
4✔
1787
                        targetChan = msg.ChanID
4✔
1788
                        isLinkUpdate = p.hasChannel(targetChan)
4✔
1789

4✔
1790
                        // If we failed to find the link in question, and the
4✔
1791
                        // message received was a channel sync message, then
4✔
1792
                        // this might be a peer trying to resync closed channel.
4✔
1793
                        // In this case we'll try to resend our last channel
4✔
1794
                        // sync message, such that the peer can recover funds
4✔
1795
                        // from the closed channel.
4✔
1796
                        if !isLinkUpdate {
8✔
1797
                                err := p.resendChanSyncMsg(targetChan)
4✔
1798
                                if err != nil {
8✔
1799
                                        // TODO(halseth): send error to peer?
4✔
1800
                                        p.log.Errorf("resend failed: %v",
4✔
1801
                                                err)
4✔
1802
                                }
4✔
1803
                        }
1804

1805
                // For messages that implement the LinkUpdater interface, we
1806
                // will consider them as link updates and send them to
1807
                // chanStream. These messages will be queued inside chanStream
1808
                // if the channel is not active yet.
1809
                case lnwire.LinkUpdater:
4✔
1810
                        targetChan = msg.TargetChanID()
4✔
1811
                        isLinkUpdate = p.hasChannel(targetChan)
4✔
1812

4✔
1813
                        // Log an error if we don't have this channel. This
4✔
1814
                        // means the peer has sent us a message with unknown
4✔
1815
                        // channel ID.
4✔
1816
                        if !isLinkUpdate {
8✔
1817
                                p.log.Errorf("Unknown channel ID: %v found "+
4✔
1818
                                        "in received msg=%s", targetChan,
4✔
1819
                                        nextMsg.MsgType())
4✔
1820
                        }
4✔
1821

1822
                case *lnwire.ChannelUpdate,
1823
                        *lnwire.ChannelAnnouncement,
1824
                        *lnwire.NodeAnnouncement,
1825
                        *lnwire.AnnounceSignatures,
1826
                        *lnwire.GossipTimestampRange,
1827
                        *lnwire.QueryShortChanIDs,
1828
                        *lnwire.QueryChannelRange,
1829
                        *lnwire.ReplyChannelRange,
1830
                        *lnwire.ReplyShortChanIDsEnd:
4✔
1831

4✔
1832
                        discStream.AddMsg(msg)
4✔
1833

1834
                case *lnwire.Custom:
5✔
1835
                        err := p.handleCustomMessage(msg)
5✔
1836
                        if err != nil {
5✔
1837
                                p.storeError(err)
×
1838
                                p.log.Errorf("%v", err)
×
1839
                        }
×
1840

1841
                default:
×
1842
                        // If the message we received is unknown to us, store
×
1843
                        // the type to track the failure.
×
1844
                        err := fmt.Errorf("unknown message type %v received",
×
1845
                                uint16(msg.MsgType()))
×
1846
                        p.storeError(err)
×
1847

×
1848
                        p.log.Errorf("%v", err)
×
1849
                }
1850

1851
                if isLinkUpdate {
9✔
1852
                        // If this is a channel update, then we need to feed it
4✔
1853
                        // into the channel's in-order message stream.
4✔
1854
                        p.sendLinkUpdateMsg(targetChan, nextMsg)
4✔
1855
                }
4✔
1856

1857
                idleTimer.Reset(idleTimeout)
5✔
1858
        }
1859

1860
        p.Disconnect(errors.New("read handler closed"))
4✔
1861

4✔
1862
        p.log.Trace("readHandler for peer done")
4✔
1863
}
1864

1865
// handleCustomMessage handles the given custom message if a handler is
1866
// registered.
1867
func (p *Brontide) handleCustomMessage(msg *lnwire.Custom) error {
5✔
1868
        if p.cfg.HandleCustomMessage == nil {
5✔
1869
                return fmt.Errorf("no custom message handler for "+
×
1870
                        "message type %v", uint16(msg.MsgType()))
×
1871
        }
×
1872

1873
        return p.cfg.HandleCustomMessage(p.PubKey(), msg)
5✔
1874
}
1875

1876
// isLoadedFromDisk returns true if the provided channel ID is loaded from
1877
// disk.
1878
//
1879
// NOTE: only returns true for pending channels.
1880
func (p *Brontide) isLoadedFromDisk(chanID lnwire.ChannelID) bool {
4✔
1881
        // If this is a newly added channel, no need to reestablish.
4✔
1882
        _, added := p.addedChannels.Load(chanID)
4✔
1883
        if added {
8✔
1884
                return false
4✔
1885
        }
4✔
1886

1887
        // Return false if the channel is unknown.
1888
        channel, ok := p.activeChannels.Load(chanID)
4✔
1889
        if !ok {
4✔
1890
                return false
×
1891
        }
×
1892

1893
        // During startup, we will use a nil value to mark a pending channel
1894
        // that's loaded from disk.
1895
        return channel == nil
4✔
1896
}
1897

1898
// isActiveChannel returns true if the provided channel id is active, otherwise
1899
// returns false.
1900
func (p *Brontide) isActiveChannel(chanID lnwire.ChannelID) bool {
12✔
1901
        // The channel would be nil if,
12✔
1902
        // - the channel doesn't exist, or,
12✔
1903
        // - the channel exists, but is pending. In this case, we don't
12✔
1904
        //   consider this channel active.
12✔
1905
        channel, _ := p.activeChannels.Load(chanID)
12✔
1906

12✔
1907
        return channel != nil
12✔
1908
}
12✔
1909

1910
// isPendingChannel returns true if the provided channel ID is pending, and
1911
// returns false if the channel is active or unknown.
1912
func (p *Brontide) isPendingChannel(chanID lnwire.ChannelID) bool {
10✔
1913
        // Return false if the channel is unknown.
10✔
1914
        channel, ok := p.activeChannels.Load(chanID)
10✔
1915
        if !ok {
17✔
1916
                return false
7✔
1917
        }
7✔
1918

1919
        return channel == nil
3✔
1920
}
1921

1922
// hasChannel returns true if the peer has a pending/active channel specified
1923
// by the channel ID.
1924
func (p *Brontide) hasChannel(chanID lnwire.ChannelID) bool {
4✔
1925
        _, ok := p.activeChannels.Load(chanID)
4✔
1926
        return ok
4✔
1927
}
4✔
1928

1929
// storeError stores an error in our peer's buffer of recent errors with the
1930
// current timestamp. Errors are only stored if we have at least one active
1931
// channel with the peer to mitigate a dos vector where a peer costlessly
1932
// connects to us and spams us with errors.
1933
func (p *Brontide) storeError(err error) {
4✔
1934
        var haveChannels bool
4✔
1935

4✔
1936
        p.activeChannels.Range(func(_ lnwire.ChannelID,
4✔
1937
                channel *lnwallet.LightningChannel) bool {
8✔
1938

4✔
1939
                // Pending channels will be nil in the activeChannels map.
4✔
1940
                if channel == nil {
8✔
1941
                        // Return true to continue the iteration.
4✔
1942
                        return true
4✔
1943
                }
4✔
1944

1945
                haveChannels = true
4✔
1946

4✔
1947
                // Return false to break the iteration.
4✔
1948
                return false
4✔
1949
        })
1950

1951
        // If we do not have any active channels with the peer, we do not store
1952
        // errors as a dos mitigation.
1953
        if !haveChannels {
8✔
1954
                p.log.Trace("no channels with peer, not storing err")
4✔
1955
                return
4✔
1956
        }
4✔
1957

1958
        p.cfg.ErrorBuffer.Add(
4✔
1959
                &TimestampedError{Timestamp: time.Now(), Error: err},
4✔
1960
        )
4✔
1961
}
1962

1963
// handleWarningOrError processes a warning or error msg and returns true if
1964
// msg should be forwarded to the associated channel link. False is returned if
1965
// any necessary forwarding of msg was already handled by this method. If msg is
1966
// an error from a peer with an active channel, we'll store it in memory.
1967
//
1968
// NOTE: This method should only be called from within the readHandler.
1969
func (p *Brontide) handleWarningOrError(chanID lnwire.ChannelID,
1970
        msg lnwire.Message) bool {
4✔
1971

4✔
1972
        if errMsg, ok := msg.(*lnwire.Error); ok {
8✔
1973
                p.storeError(errMsg)
4✔
1974
        }
4✔
1975

1976
        switch {
4✔
1977
        // Connection wide messages should be forwarded to all channel links
1978
        // with this peer.
1979
        case chanID == lnwire.ConnectionWideID:
×
1980
                for _, chanStream := range p.activeMsgStreams {
×
1981
                        chanStream.AddMsg(msg)
×
1982
                }
×
1983

1984
                return false
×
1985

1986
        // If the channel ID for the message corresponds to a pending channel,
1987
        // then the funding manager will handle it.
1988
        case p.cfg.FundingManager.IsPendingChannel(chanID, p):
4✔
1989
                p.cfg.FundingManager.ProcessFundingMsg(msg, p)
4✔
1990
                return false
4✔
1991

1992
        // If not we hand the message to the channel link for this channel.
1993
        case p.isActiveChannel(chanID):
4✔
1994
                return true
4✔
1995

1996
        default:
4✔
1997
                return false
4✔
1998
        }
1999
}
2000

2001
// messageSummary returns a human-readable string that summarizes a
2002
// incoming/outgoing message. Not all messages will have a summary, only those
2003
// which have additional data that can be informative at a glance.
2004
func messageSummary(msg lnwire.Message) string {
4✔
2005
        switch msg := msg.(type) {
4✔
2006
        case *lnwire.Init:
4✔
2007
                // No summary.
4✔
2008
                return ""
4✔
2009

2010
        case *lnwire.OpenChannel:
4✔
2011
                return fmt.Sprintf("temp_chan_id=%x, chain=%v, csv=%v, amt=%v, "+
4✔
2012
                        "push_amt=%v, reserve=%v, flags=%v",
4✔
2013
                        msg.PendingChannelID[:], msg.ChainHash,
4✔
2014
                        msg.CsvDelay, msg.FundingAmount, msg.PushAmount,
4✔
2015
                        msg.ChannelReserve, msg.ChannelFlags)
4✔
2016

2017
        case *lnwire.AcceptChannel:
4✔
2018
                return fmt.Sprintf("temp_chan_id=%x, reserve=%v, csv=%v, num_confs=%v",
4✔
2019
                        msg.PendingChannelID[:], msg.ChannelReserve, msg.CsvDelay,
4✔
2020
                        msg.MinAcceptDepth)
4✔
2021

2022
        case *lnwire.FundingCreated:
4✔
2023
                return fmt.Sprintf("temp_chan_id=%x, chan_point=%v",
4✔
2024
                        msg.PendingChannelID[:], msg.FundingPoint)
4✔
2025

2026
        case *lnwire.FundingSigned:
4✔
2027
                return fmt.Sprintf("chan_id=%v", msg.ChanID)
4✔
2028

2029
        case *lnwire.ChannelReady:
4✔
2030
                return fmt.Sprintf("chan_id=%v, next_point=%x",
4✔
2031
                        msg.ChanID, msg.NextPerCommitmentPoint.SerializeCompressed())
4✔
2032

2033
        case *lnwire.Shutdown:
4✔
2034
                return fmt.Sprintf("chan_id=%v, script=%x", msg.ChannelID,
4✔
2035
                        msg.Address[:])
4✔
2036

2037
        case *lnwire.ClosingSigned:
4✔
2038
                return fmt.Sprintf("chan_id=%v, fee_sat=%v", msg.ChannelID,
4✔
2039
                        msg.FeeSatoshis)
4✔
2040

2041
        case *lnwire.UpdateAddHTLC:
4✔
2042
                var blindingPoint []byte
4✔
2043
                msg.BlindingPoint.WhenSome(
4✔
2044
                        func(b tlv.RecordT[lnwire.BlindingPointTlvType,
4✔
2045
                                *btcec.PublicKey]) {
8✔
2046

4✔
2047
                                blindingPoint = b.Val.SerializeCompressed()
4✔
2048
                        },
4✔
2049
                )
2050

2051
                return fmt.Sprintf("chan_id=%v, id=%v, amt=%v, expiry=%v, "+
4✔
2052
                        "hash=%x, blinding_point=%x", msg.ChanID, msg.ID,
4✔
2053
                        msg.Amount, msg.Expiry, msg.PaymentHash[:],
4✔
2054
                        blindingPoint)
4✔
2055

2056
        case *lnwire.UpdateFailHTLC:
4✔
2057
                return fmt.Sprintf("chan_id=%v, id=%v, reason=%x", msg.ChanID,
4✔
2058
                        msg.ID, msg.Reason)
4✔
2059

2060
        case *lnwire.UpdateFulfillHTLC:
4✔
2061
                return fmt.Sprintf("chan_id=%v, id=%v, pre_image=%x",
4✔
2062
                        msg.ChanID, msg.ID, msg.PaymentPreimage[:])
4✔
2063

2064
        case *lnwire.CommitSig:
4✔
2065
                return fmt.Sprintf("chan_id=%v, num_htlcs=%v", msg.ChanID,
4✔
2066
                        len(msg.HtlcSigs))
4✔
2067

2068
        case *lnwire.RevokeAndAck:
4✔
2069
                return fmt.Sprintf("chan_id=%v, rev=%x, next_point=%x",
4✔
2070
                        msg.ChanID, msg.Revocation[:],
4✔
2071
                        msg.NextRevocationKey.SerializeCompressed())
4✔
2072

2073
        case *lnwire.UpdateFailMalformedHTLC:
4✔
2074
                return fmt.Sprintf("chan_id=%v, id=%v, fail_code=%v",
4✔
2075
                        msg.ChanID, msg.ID, msg.FailureCode)
4✔
2076

2077
        case *lnwire.Warning:
×
2078
                return fmt.Sprintf("%v", msg.Warning())
×
2079

2080
        case *lnwire.Error:
4✔
2081
                return fmt.Sprintf("%v", msg.Error())
4✔
2082

2083
        case *lnwire.AnnounceSignatures:
4✔
2084
                return fmt.Sprintf("chan_id=%v, short_chan_id=%v", msg.ChannelID,
4✔
2085
                        msg.ShortChannelID.ToUint64())
4✔
2086

2087
        case *lnwire.ChannelAnnouncement:
4✔
2088
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v",
4✔
2089
                        msg.ChainHash, msg.ShortChannelID.ToUint64())
4✔
2090

2091
        case *lnwire.ChannelUpdate:
4✔
2092
                return fmt.Sprintf("chain_hash=%v, short_chan_id=%v, "+
4✔
2093
                        "mflags=%v, cflags=%v, update_time=%v", msg.ChainHash,
4✔
2094
                        msg.ShortChannelID.ToUint64(), msg.MessageFlags,
4✔
2095
                        msg.ChannelFlags, time.Unix(int64(msg.Timestamp), 0))
4✔
2096

2097
        case *lnwire.NodeAnnouncement:
4✔
2098
                return fmt.Sprintf("node=%x, update_time=%v",
4✔
2099
                        msg.NodeID, time.Unix(int64(msg.Timestamp), 0))
4✔
2100

2101
        case *lnwire.Ping:
×
2102
                return fmt.Sprintf("ping_bytes=%x", msg.PaddingBytes[:])
×
2103

2104
        case *lnwire.Pong:
×
2105
                return fmt.Sprintf("len(pong_bytes)=%d", len(msg.PongBytes[:]))
×
2106

2107
        case *lnwire.UpdateFee:
×
2108
                return fmt.Sprintf("chan_id=%v, fee_update_sat=%v",
×
2109
                        msg.ChanID, int64(msg.FeePerKw))
×
2110

2111
        case *lnwire.ChannelReestablish:
4✔
2112
                return fmt.Sprintf("chan_id=%v, next_local_height=%v, "+
4✔
2113
                        "remote_tail_height=%v", msg.ChanID,
4✔
2114
                        msg.NextLocalCommitHeight, msg.RemoteCommitTailHeight)
4✔
2115

2116
        case *lnwire.ReplyShortChanIDsEnd:
4✔
2117
                return fmt.Sprintf("chain_hash=%v, complete=%v", msg.ChainHash,
4✔
2118
                        msg.Complete)
4✔
2119

2120
        case *lnwire.ReplyChannelRange:
4✔
2121
                return fmt.Sprintf("start_height=%v, end_height=%v, "+
4✔
2122
                        "num_chans=%v, encoding=%v", msg.FirstBlockHeight,
4✔
2123
                        msg.LastBlockHeight(), len(msg.ShortChanIDs),
4✔
2124
                        msg.EncodingType)
4✔
2125

2126
        case *lnwire.QueryShortChanIDs:
4✔
2127
                return fmt.Sprintf("chain_hash=%v, encoding=%v, num_chans=%v",
4✔
2128
                        msg.ChainHash, msg.EncodingType, len(msg.ShortChanIDs))
4✔
2129

2130
        case *lnwire.QueryChannelRange:
4✔
2131
                return fmt.Sprintf("chain_hash=%v, start_height=%v, "+
4✔
2132
                        "end_height=%v", msg.ChainHash, msg.FirstBlockHeight,
4✔
2133
                        msg.LastBlockHeight())
4✔
2134

2135
        case *lnwire.GossipTimestampRange:
4✔
2136
                return fmt.Sprintf("chain_hash=%v, first_stamp=%v, "+
4✔
2137
                        "stamp_range=%v", msg.ChainHash,
4✔
2138
                        time.Unix(int64(msg.FirstTimestamp), 0),
4✔
2139
                        msg.TimestampRange)
4✔
2140

2141
        case *lnwire.Custom:
4✔
2142
                return fmt.Sprintf("type=%d", msg.Type)
4✔
2143
        }
2144

2145
        return fmt.Sprintf("unknown msg type=%T", msg)
×
2146
}
2147

2148
// logWireMessage logs the receipt or sending of particular wire message. This
2149
// function is used rather than just logging the message in order to produce
2150
// less spammy log messages in trace mode by setting the 'Curve" parameter to
2151
// nil. Doing this avoids printing out each of the field elements in the curve
2152
// parameters for secp256k1.
2153
func (p *Brontide) logWireMessage(msg lnwire.Message, read bool) {
16✔
2154
        summaryPrefix := "Received"
16✔
2155
        if !read {
29✔
2156
                summaryPrefix = "Sending"
13✔
2157
        }
13✔
2158

2159
        p.log.Debugf("%v", newLogClosure(func() string {
20✔
2160
                // Debug summary of message.
4✔
2161
                summary := messageSummary(msg)
4✔
2162
                if len(summary) > 0 {
8✔
2163
                        summary = "(" + summary + ")"
4✔
2164
                }
4✔
2165

2166
                preposition := "to"
4✔
2167
                if read {
8✔
2168
                        preposition = "from"
4✔
2169
                }
4✔
2170

2171
                var msgType string
4✔
2172
                if msg.MsgType() < lnwire.CustomTypeStart {
8✔
2173
                        msgType = msg.MsgType().String()
4✔
2174
                } else {
8✔
2175
                        msgType = "custom"
4✔
2176
                }
4✔
2177

2178
                return fmt.Sprintf("%v %v%s %v %s", summaryPrefix,
4✔
2179
                        msgType, summary, preposition, p)
4✔
2180
        }))
2181

2182
        prefix := "readMessage from peer"
16✔
2183
        if !read {
29✔
2184
                prefix = "writeMessage to peer"
13✔
2185
        }
13✔
2186

2187
        p.log.Tracef(prefix+": %v", newLogClosure(func() string {
16✔
2188
                return spew.Sdump(msg)
×
2189
        }))
×
2190
}
2191

2192
// writeMessage writes and flushes the target lnwire.Message to the remote peer.
2193
// If the passed message is nil, this method will only try to flush an existing
2194
// message buffered on the connection. It is safe to call this method again
2195
// with a nil message iff a timeout error is returned. This will continue to
2196
// flush the pending message to the wire.
2197
//
2198
// NOTE:
2199
// Besides its usage in Start, this function should not be used elsewhere
2200
// except in writeHandler. If multiple goroutines call writeMessage at the same
2201
// time, panics can occur because WriteMessage and Flush don't use any locking
2202
// internally.
2203
func (p *Brontide) writeMessage(msg lnwire.Message) error {
13✔
2204
        // Only log the message on the first attempt.
13✔
2205
        if msg != nil {
26✔
2206
                p.logWireMessage(msg, false)
13✔
2207
        }
13✔
2208

2209
        noiseConn := p.cfg.Conn
13✔
2210

13✔
2211
        flushMsg := func() error {
26✔
2212
                // Ensure the write deadline is set before we attempt to send
13✔
2213
                // the message.
13✔
2214
                writeDeadline := time.Now().Add(
13✔
2215
                        p.scaleTimeout(writeMessageTimeout),
13✔
2216
                )
13✔
2217
                err := noiseConn.SetWriteDeadline(writeDeadline)
13✔
2218
                if err != nil {
13✔
2219
                        return err
×
2220
                }
×
2221

2222
                // Flush the pending message to the wire. If an error is
2223
                // encountered, e.g. write timeout, the number of bytes written
2224
                // so far will be returned.
2225
                n, err := noiseConn.Flush()
13✔
2226

13✔
2227
                // Record the number of bytes written on the wire, if any.
13✔
2228
                if n > 0 {
17✔
2229
                        atomic.AddUint64(&p.bytesSent, uint64(n))
4✔
2230
                }
4✔
2231

2232
                return err
13✔
2233
        }
2234

2235
        // If the current message has already been serialized, encrypted, and
2236
        // buffered on the underlying connection we will skip straight to
2237
        // flushing it to the wire.
2238
        if msg == nil {
13✔
2239
                return flushMsg()
×
2240
        }
×
2241

2242
        // Otherwise, this is a new message. We'll acquire a write buffer to
2243
        // serialize the message and buffer the ciphertext on the connection.
2244
        err := p.cfg.WritePool.Submit(func(buf *bytes.Buffer) error {
26✔
2245
                // Using a buffer allocated by the write pool, encode the
13✔
2246
                // message directly into the buffer.
13✔
2247
                _, writeErr := lnwire.WriteMessage(buf, msg, 0)
13✔
2248
                if writeErr != nil {
13✔
2249
                        return writeErr
×
2250
                }
×
2251

2252
                // Finally, write the message itself in a single swoop. This
2253
                // will buffer the ciphertext on the underlying connection. We
2254
                // will defer flushing the message until the write pool has been
2255
                // released.
2256
                return noiseConn.WriteMessage(buf.Bytes())
13✔
2257
        })
2258
        if err != nil {
13✔
2259
                return err
×
2260
        }
×
2261

2262
        return flushMsg()
13✔
2263
}
2264

2265
// writeHandler is a goroutine dedicated to reading messages off of an incoming
2266
// queue, and writing them out to the wire. This goroutine coordinates with the
2267
// queueHandler in order to ensure the incoming message queue is quickly
2268
// drained.
2269
//
2270
// NOTE: This method MUST be run as a goroutine.
2271
func (p *Brontide) writeHandler() {
6✔
2272
        // We'll stop the timer after a new messages is sent, and also reset it
6✔
2273
        // after we process the next message.
6✔
2274
        idleTimer := time.AfterFunc(idleTimeout, func() {
6✔
2275
                err := fmt.Errorf("peer %s no write for %s -- disconnecting",
×
2276
                        p, idleTimeout)
×
2277
                p.Disconnect(err)
×
2278
        })
×
2279

2280
        var exitErr error
6✔
2281

6✔
2282
out:
6✔
2283
        for {
14✔
2284
                select {
8✔
2285
                case outMsg := <-p.sendQueue:
6✔
2286
                        // Record the time at which we first attempt to send the
6✔
2287
                        // message.
6✔
2288
                        startTime := time.Now()
6✔
2289

6✔
2290
                retry:
6✔
2291
                        // Write out the message to the socket. If a timeout
2292
                        // error is encountered, we will catch this and retry
2293
                        // after backing off in case the remote peer is just
2294
                        // slow to process messages from the wire.
2295
                        err := p.writeMessage(outMsg.msg)
6✔
2296
                        if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
6✔
2297
                                p.log.Debugf("Write timeout detected for "+
×
2298
                                        "peer, first write for message "+
×
2299
                                        "attempted %v ago",
×
2300
                                        time.Since(startTime))
×
2301

×
2302
                                // If we received a timeout error, this implies
×
2303
                                // that the message was buffered on the
×
2304
                                // connection successfully and that a flush was
×
2305
                                // attempted. We'll set the message to nil so
×
2306
                                // that on a subsequent pass we only try to
×
2307
                                // flush the buffered message, and forgo
×
2308
                                // reserializing or reencrypting it.
×
2309
                                outMsg.msg = nil
×
2310

×
2311
                                goto retry
×
2312
                        }
2313

2314
                        // The write succeeded, reset the idle timer to prevent
2315
                        // us from disconnecting the peer.
2316
                        if !idleTimer.Stop() {
6✔
2317
                                select {
×
2318
                                case <-idleTimer.C:
×
2319
                                default:
×
2320
                                }
2321
                        }
2322
                        idleTimer.Reset(idleTimeout)
6✔
2323

6✔
2324
                        // If the peer requested a synchronous write, respond
6✔
2325
                        // with the error.
6✔
2326
                        if outMsg.errChan != nil {
11✔
2327
                                outMsg.errChan <- err
5✔
2328
                        }
5✔
2329

2330
                        if err != nil {
6✔
2331
                                exitErr = fmt.Errorf("unable to write "+
×
2332
                                        "message: %v", err)
×
2333
                                break out
×
2334
                        }
2335

2336
                case <-p.quit:
4✔
2337
                        exitErr = lnpeer.ErrPeerExiting
4✔
2338
                        break out
4✔
2339
                }
2340
        }
2341

2342
        // Avoid an exit deadlock by ensuring WaitGroups are decremented before
2343
        // disconnect.
2344
        p.wg.Done()
4✔
2345

4✔
2346
        p.Disconnect(exitErr)
4✔
2347

4✔
2348
        p.log.Trace("writeHandler for peer done")
4✔
2349
}
2350

2351
// queueHandler is responsible for accepting messages from outside subsystems
2352
// to be eventually sent out on the wire by the writeHandler.
2353
//
2354
// NOTE: This method MUST be run as a goroutine.
2355
func (p *Brontide) queueHandler() {
6✔
2356
        defer p.wg.Done()
6✔
2357

6✔
2358
        // priorityMsgs holds an in order list of messages deemed high-priority
6✔
2359
        // to be added to the sendQueue. This predominately includes messages
6✔
2360
        // from the funding manager and htlcswitch.
6✔
2361
        priorityMsgs := list.New()
6✔
2362

6✔
2363
        // lazyMsgs holds an in order list of messages deemed low-priority to be
6✔
2364
        // added to the sendQueue only after all high-priority messages have
6✔
2365
        // been queued. This predominately includes messages from the gossiper.
6✔
2366
        lazyMsgs := list.New()
6✔
2367

6✔
2368
        for {
16✔
2369
                // Examine the front of the priority queue, if it is empty check
10✔
2370
                // the low priority queue.
10✔
2371
                elem := priorityMsgs.Front()
10✔
2372
                if elem == nil {
19✔
2373
                        elem = lazyMsgs.Front()
9✔
2374
                }
9✔
2375

2376
                if elem != nil {
16✔
2377
                        front := elem.Value.(outgoingMsg)
6✔
2378

6✔
2379
                        // There's an element on the queue, try adding
6✔
2380
                        // it to the sendQueue. We also watch for
6✔
2381
                        // messages on the outgoingQueue, in case the
6✔
2382
                        // writeHandler cannot accept messages on the
6✔
2383
                        // sendQueue.
6✔
2384
                        select {
6✔
2385
                        case p.sendQueue <- front:
6✔
2386
                                if front.priority {
11✔
2387
                                        priorityMsgs.Remove(elem)
5✔
2388
                                } else {
10✔
2389
                                        lazyMsgs.Remove(elem)
5✔
2390
                                }
5✔
2391
                        case msg := <-p.outgoingQueue:
4✔
2392
                                if msg.priority {
8✔
2393
                                        priorityMsgs.PushBack(msg)
4✔
2394
                                } else {
8✔
2395
                                        lazyMsgs.PushBack(msg)
4✔
2396
                                }
4✔
2397
                        case <-p.quit:
×
2398
                                return
×
2399
                        }
2400
                } else {
8✔
2401
                        // If there weren't any messages to send to the
8✔
2402
                        // writeHandler, then we'll accept a new message
8✔
2403
                        // into the queue from outside sub-systems.
8✔
2404
                        select {
8✔
2405
                        case msg := <-p.outgoingQueue:
6✔
2406
                                if msg.priority {
11✔
2407
                                        priorityMsgs.PushBack(msg)
5✔
2408
                                } else {
10✔
2409
                                        lazyMsgs.PushBack(msg)
5✔
2410
                                }
5✔
2411
                        case <-p.quit:
4✔
2412
                                return
4✔
2413
                        }
2414
                }
2415
        }
2416
}
2417

2418
// PingTime returns the estimated ping time to the peer in microseconds.
2419
func (p *Brontide) PingTime() int64 {
4✔
2420
        return p.pingManager.GetPingTimeMicroSeconds()
4✔
2421
}
4✔
2422

2423
// queueMsg adds the lnwire.Message to the back of the high priority send queue.
2424
// If the errChan is non-nil, an error is sent back if the msg failed to queue
2425
// or failed to write, and nil otherwise.
2426
func (p *Brontide) queueMsg(msg lnwire.Message, errChan chan error) {
26✔
2427
        p.queue(true, msg, errChan)
26✔
2428
}
26✔
2429

2430
// queueMsgLazy adds the lnwire.Message to the back of the low priority send
2431
// queue. If the errChan is non-nil, an error is sent back if the msg failed to
2432
// queue or failed to write, and nil otherwise.
2433
func (p *Brontide) queueMsgLazy(msg lnwire.Message, errChan chan error) {
5✔
2434
        p.queue(false, msg, errChan)
5✔
2435
}
5✔
2436

2437
// queue sends a given message to the queueHandler using the passed priority. If
2438
// the errChan is non-nil, an error is sent back if the msg failed to queue or
2439
// failed to write, and nil otherwise.
2440
func (p *Brontide) queue(priority bool, msg lnwire.Message,
2441
        errChan chan error) {
27✔
2442

27✔
2443
        select {
27✔
2444
        case p.outgoingQueue <- outgoingMsg{priority, msg, errChan}:
27✔
2445
        case <-p.quit:
4✔
2446
                p.log.Tracef("Peer shutting down, could not enqueue msg: %v.",
4✔
2447
                        spew.Sdump(msg))
4✔
2448
                if errChan != nil {
4✔
2449
                        errChan <- lnpeer.ErrPeerExiting
×
2450
                }
×
2451
        }
2452
}
2453

2454
// ChannelSnapshots returns a slice of channel snapshots detailing all
2455
// currently active channels maintained with the remote peer.
2456
func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
4✔
2457
        snapshots := make(
4✔
2458
                []*channeldb.ChannelSnapshot, 0, p.activeChannels.Len(),
4✔
2459
        )
4✔
2460

4✔
2461
        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
4✔
2462
                activeChan *lnwallet.LightningChannel) error {
8✔
2463

4✔
2464
                // If the activeChan is nil, then we skip it as the channel is
4✔
2465
                // pending.
4✔
2466
                if activeChan == nil {
8✔
2467
                        return nil
4✔
2468
                }
4✔
2469

2470
                // We'll only return a snapshot for channels that are
2471
                // *immediately* available for routing payments over.
2472
                if activeChan.RemoteNextRevocation() == nil {
8✔
2473
                        return nil
4✔
2474
                }
4✔
2475

2476
                snapshot := activeChan.StateSnapshot()
4✔
2477
                snapshots = append(snapshots, snapshot)
4✔
2478

4✔
2479
                return nil
4✔
2480
        })
2481

2482
        return snapshots
4✔
2483
}
2484

2485
// genDeliveryScript returns a new script to be used to send our funds to in
2486
// the case of a cooperative channel close negotiation.
2487
func (p *Brontide) genDeliveryScript() ([]byte, error) {
10✔
2488
        // We'll send a normal p2wkh address unless we've negotiated the
10✔
2489
        // shutdown-any-segwit feature.
10✔
2490
        addrType := lnwallet.WitnessPubKey
10✔
2491
        if p.taprootShutdownAllowed() {
14✔
2492
                addrType = lnwallet.TaprootPubkey
4✔
2493
        }
4✔
2494

2495
        deliveryAddr, err := p.cfg.Wallet.NewAddress(
10✔
2496
                addrType, false, lnwallet.DefaultAccountName,
10✔
2497
        )
10✔
2498
        if err != nil {
10✔
2499
                return nil, err
×
2500
        }
×
2501
        p.log.Infof("Delivery addr for channel close: %v",
10✔
2502
                deliveryAddr)
10✔
2503

10✔
2504
        return txscript.PayToAddrScript(deliveryAddr)
10✔
2505
}
2506

2507
// channelManager is goroutine dedicated to handling all requests/signals
2508
// pertaining to the opening, cooperative closing, and force closing of all
2509
// channels maintained with the remote peer.
2510
//
2511
// NOTE: This method MUST be run as a goroutine.
2512
func (p *Brontide) channelManager() {
19✔
2513
        defer p.wg.Done()
19✔
2514

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

19✔
2520
out:
19✔
2521
        for {
59✔
2522
                select {
40✔
2523
                // A new pending channel has arrived which means we are about
2524
                // to complete a funding workflow and is waiting for the final
2525
                // `ChannelReady` messages to be exchanged. We will add this
2526
                // channel to the `activeChannels` with a nil value to indicate
2527
                // this is a pending channel.
2528
                case req := <-p.newPendingChannel:
5✔
2529
                        p.handleNewPendingChannel(req)
5✔
2530

2531
                // A new channel has arrived which means we've just completed a
2532
                // funding workflow. We'll initialize the necessary local
2533
                // state, and notify the htlc switch of a new link.
2534
                case req := <-p.newActiveChannel:
4✔
2535
                        p.handleNewActiveChannel(req)
4✔
2536

2537
                // The funding flow for a pending channel is failed, we will
2538
                // remove it from Brontide.
2539
                case req := <-p.removePendingChannel:
5✔
2540
                        p.handleRemovePendingChannel(req)
5✔
2541

2542
                // We've just received a local request to close an active
2543
                // channel. It will either kick of a cooperative channel
2544
                // closure negotiation, or be a notification of a breached
2545
                // contract that should be abandoned.
2546
                case req := <-p.localCloseChanReqs:
11✔
2547
                        p.handleLocalCloseReq(req)
11✔
2548

2549
                // We've received a link failure from a link that was added to
2550
                // the switch. This will initiate the teardown of the link, and
2551
                // initiate any on-chain closures if necessary.
2552
                case failure := <-p.linkFailures:
4✔
2553
                        p.handleLinkFailure(failure)
4✔
2554

2555
                // We've received a new cooperative channel closure related
2556
                // message from the remote peer, we'll use this message to
2557
                // advance the chan closer state machine.
2558
                case closeMsg := <-p.chanCloseMsgs:
17✔
2559
                        p.handleCloseMsg(closeMsg)
17✔
2560

2561
                // The channel reannounce delay has elapsed, broadcast the
2562
                // reenabled channel updates to the network. This should only
2563
                // fire once, so we set the reenableTimeout channel to nil to
2564
                // mark it for garbage collection. If the peer is torn down
2565
                // before firing, reenabling will not be attempted.
2566
                // TODO(conner): consolidate reenables timers inside chan status
2567
                // manager
2568
                case <-reenableTimeout:
4✔
2569
                        p.reenableActiveChannels()
4✔
2570

4✔
2571
                        // Since this channel will never fire again during the
4✔
2572
                        // lifecycle of the peer, we nil the channel to mark it
4✔
2573
                        // eligible for garbage collection, and make this
4✔
2574
                        // explicitly ineligible to receive in future calls to
4✔
2575
                        // select. This also shaves a few CPU cycles since the
4✔
2576
                        // select will ignore this case entirely.
4✔
2577
                        reenableTimeout = nil
4✔
2578

4✔
2579
                        // Once the reenabling is attempted, we also cancel the
4✔
2580
                        // channel event subscription to free up the overflow
4✔
2581
                        // queue used in channel notifier.
4✔
2582
                        //
4✔
2583
                        // NOTE: channelEventClient will be nil if the
4✔
2584
                        // reenableTimeout is greater than 1 minute.
4✔
2585
                        if p.channelEventClient != nil {
8✔
2586
                                p.channelEventClient.Cancel()
4✔
2587
                        }
4✔
2588

2589
                case <-p.quit:
4✔
2590
                        // As, we've been signalled to exit, we'll reset all
4✔
2591
                        // our active channel back to their default state.
4✔
2592
                        p.activeChannels.ForEach(func(_ lnwire.ChannelID,
4✔
2593
                                lc *lnwallet.LightningChannel) error {
8✔
2594

4✔
2595
                                // Exit if the channel is nil as it's a pending
4✔
2596
                                // channel.
4✔
2597
                                if lc == nil {
8✔
2598
                                        return nil
4✔
2599
                                }
4✔
2600

2601
                                lc.ResetState()
4✔
2602

4✔
2603
                                return nil
4✔
2604
                        })
2605

2606
                        break out
4✔
2607
                }
2608
        }
2609
}
2610

2611
// reenableActiveChannels searches the index of channels maintained with this
2612
// peer, and reenables each public, non-pending channel. This is done at the
2613
// gossip level by broadcasting a new ChannelUpdate with the disabled bit unset.
2614
// No message will be sent if the channel is already enabled.
2615
func (p *Brontide) reenableActiveChannels() {
4✔
2616
        // First, filter all known channels with this peer for ones that are
4✔
2617
        // both public and not pending.
4✔
2618
        activePublicChans := p.filterChannelsToEnable()
4✔
2619

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

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

4✔
2629
                switch {
4✔
2630
                // No error occurred, continue to request the next channel.
2631
                case err == nil:
4✔
2632
                        continue
4✔
2633

2634
                // Cannot auto enable a manually disabled channel so we do
2635
                // nothing but proceed to the next channel.
2636
                case errors.Is(err, netann.ErrEnableManuallyDisabledChan):
4✔
2637
                        p.log.Debugf("Channel(%v) was manually disabled, "+
4✔
2638
                                "ignoring automatic enable request", chanPoint)
4✔
2639

4✔
2640
                        continue
4✔
2641

2642
                // If the channel is reported as inactive, we will give it
2643
                // another chance. When handling the request, ChanStatusManager
2644
                // will check whether the link is active or not. One of the
2645
                // conditions is whether the link has been marked as
2646
                // reestablished, which happens inside a goroutine(htlcManager)
2647
                // after the link is started. And we may get a false negative
2648
                // saying the link is not active because that goroutine hasn't
2649
                // reached the line to mark the reestablishment. Thus we give
2650
                // it a second chance to send the request.
2651
                case errors.Is(err, netann.ErrEnableInactiveChan):
×
2652
                        // If we don't have a client created, it means we
×
2653
                        // shouldn't retry enabling the channel.
×
2654
                        if p.channelEventClient == nil {
×
2655
                                p.log.Errorf("Channel(%v) request enabling "+
×
2656
                                        "failed due to inactive link",
×
2657
                                        chanPoint)
×
2658

×
2659
                                continue
×
2660
                        }
2661

2662
                        p.log.Warnf("Channel(%v) cannot be enabled as " +
×
2663
                                "ChanStatusManager reported inactive, retrying")
×
2664

×
2665
                        // Add the channel to the retry map.
×
2666
                        retryChans[chanPoint] = struct{}{}
×
2667
                }
2668
        }
2669

2670
        // Retry the channels if we have any.
2671
        if len(retryChans) != 0 {
4✔
2672
                p.retryRequestEnable(retryChans)
×
2673
        }
×
2674
}
2675

2676
// fetchActiveChanCloser attempts to fetch the active chan closer state machine
2677
// for the target channel ID. If the channel isn't active an error is returned.
2678
// Otherwise, either an existing state machine will be returned, or a new one
2679
// will be created.
2680
func (p *Brontide) fetchActiveChanCloser(chanID lnwire.ChannelID) (
2681
        *chancloser.ChanCloser, error) {
17✔
2682

17✔
2683
        chanCloser, found := p.activeChanCloses[chanID]
17✔
2684
        if found {
31✔
2685
                // An entry will only be found if the closer has already been
14✔
2686
                // created for a non-pending channel or for a channel that had
14✔
2687
                // previously started the shutdown process but the connection
14✔
2688
                // was restarted.
14✔
2689
                return chanCloser, nil
14✔
2690
        }
14✔
2691

2692
        // First, we'll ensure that we actually know of the target channel. If
2693
        // not, we'll ignore this message.
2694
        channel, ok := p.activeChannels.Load(chanID)
7✔
2695

7✔
2696
        // If the channel isn't in the map or the channel is nil, return
7✔
2697
        // ErrChannelNotFound as the channel is pending.
7✔
2698
        if !ok || channel == nil {
11✔
2699
                return nil, ErrChannelNotFound
4✔
2700
        }
4✔
2701

2702
        // We'll create a valid closing state machine in order to respond to
2703
        // the initiated cooperative channel closure. First, we set the
2704
        // delivery script that our funds will be paid out to. If an upfront
2705
        // shutdown script was set, we will use it. Otherwise, we get a fresh
2706
        // delivery script.
2707
        //
2708
        // TODO: Expose option to allow upfront shutdown script from watch-only
2709
        // accounts.
2710
        deliveryScript := channel.LocalUpfrontShutdownScript()
7✔
2711
        if len(deliveryScript) == 0 {
14✔
2712
                var err error
7✔
2713
                deliveryScript, err = p.genDeliveryScript()
7✔
2714
                if err != nil {
7✔
2715
                        p.log.Errorf("unable to gen delivery script: %v",
×
2716
                                err)
×
2717
                        return nil, fmt.Errorf("close addr unavailable")
×
2718
                }
×
2719
        }
2720

2721
        // In order to begin fee negotiations, we'll first compute our target
2722
        // ideal fee-per-kw.
2723
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
7✔
2724
                p.cfg.CoopCloseTargetConfs,
7✔
2725
        )
7✔
2726
        if err != nil {
7✔
2727
                p.log.Errorf("unable to query fee estimator: %v", err)
×
2728
                return nil, fmt.Errorf("unable to estimate fee")
×
2729
        }
×
2730

2731
        chanCloser, err = p.createChanCloser(
7✔
2732
                channel, deliveryScript, feePerKw, nil, false,
7✔
2733
        )
7✔
2734
        if err != nil {
7✔
2735
                p.log.Errorf("unable to create chan closer: %v", err)
×
2736
                return nil, fmt.Errorf("unable to create chan closer")
×
2737
        }
×
2738

2739
        p.activeChanCloses[chanID] = chanCloser
7✔
2740

7✔
2741
        return chanCloser, nil
7✔
2742
}
2743

2744
// filterChannelsToEnable filters a list of channels to be enabled upon start.
2745
// The filtered channels are active channels that's neither private nor
2746
// pending.
2747
func (p *Brontide) filterChannelsToEnable() []wire.OutPoint {
4✔
2748
        var activePublicChans []wire.OutPoint
4✔
2749

4✔
2750
        p.activeChannels.Range(func(chanID lnwire.ChannelID,
4✔
2751
                lnChan *lnwallet.LightningChannel) bool {
8✔
2752

4✔
2753
                // If the lnChan is nil, continue as this is a pending channel.
4✔
2754
                if lnChan == nil {
4✔
2755
                        return true
×
2756
                }
×
2757

2758
                dbChan := lnChan.State()
4✔
2759
                isPublic := dbChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
4✔
2760
                if !isPublic || dbChan.IsPending {
4✔
2761
                        return true
×
2762
                }
×
2763

2764
                // We'll also skip any channels added during this peer's
2765
                // lifecycle since they haven't waited out the timeout. Their
2766
                // first announcement will be enabled, and the chan status
2767
                // manager will begin monitoring them passively since they exist
2768
                // in the database.
2769
                if _, ok := p.addedChannels.Load(chanID); ok {
8✔
2770
                        return true
4✔
2771
                }
4✔
2772

2773
                activePublicChans = append(
4✔
2774
                        activePublicChans, dbChan.FundingOutpoint,
4✔
2775
                )
4✔
2776

4✔
2777
                return true
4✔
2778
        })
2779

2780
        return activePublicChans
4✔
2781
}
2782

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

×
2790
        // retryEnable is a helper closure that sends an enable request and
×
2791
        // removes the channel from the map if it's matched.
×
2792
        retryEnable := func(chanPoint wire.OutPoint) error {
×
2793
                // If this is an active channel event, check whether it's in
×
2794
                // our targeted channels map.
×
2795
                _, found := activeChans[chanPoint]
×
2796

×
2797
                // If this channel is irrelevant, return nil so the loop can
×
2798
                // jump to next iteration.
×
2799
                if !found {
×
2800
                        return nil
×
2801
                }
×
2802

2803
                // Otherwise we've just received an active signal for a channel
2804
                // that's previously failed to be enabled, we send the request
2805
                // again.
2806
                //
2807
                // We only give the channel one more shot, so we delete it from
2808
                // our map first to keep it from being attempted again.
2809
                delete(activeChans, chanPoint)
×
2810

×
2811
                // Send the request.
×
2812
                err := p.cfg.ChanStatusMgr.RequestEnable(chanPoint, false)
×
2813
                if err != nil {
×
2814
                        return fmt.Errorf("request enabling channel %v "+
×
2815
                                "failed: %w", chanPoint, err)
×
2816
                }
×
2817

2818
                return nil
×
2819
        }
2820

2821
        for {
×
2822
                // If activeChans is empty, we've done processing all the
×
2823
                // channels.
×
2824
                if len(activeChans) == 0 {
×
2825
                        p.log.Debug("Finished retry enabling channels")
×
2826
                        return
×
2827
                }
×
2828

2829
                select {
×
2830
                // A new event has been sent by the ChannelNotifier. We now
2831
                // check whether it's an active or inactive channel event.
2832
                case e := <-p.channelEventClient.Updates():
×
2833
                        // If this is an active channel event, try enable the
×
2834
                        // channel then jump to the next iteration.
×
2835
                        active, ok := e.(channelnotifier.ActiveChannelEvent)
×
2836
                        if ok {
×
2837
                                chanPoint := *active.ChannelPoint
×
2838

×
2839
                                // If we received an error for this particular
×
2840
                                // channel, we log an error and won't quit as
×
2841
                                // we still want to retry other channels.
×
2842
                                if err := retryEnable(chanPoint); err != nil {
×
2843
                                        p.log.Errorf("Retry failed: %v", err)
×
2844
                                }
×
2845

2846
                                continue
×
2847
                        }
2848

2849
                        // Otherwise check for inactive link event, and jump to
2850
                        // next iteration if it's not.
2851
                        inactive, ok := e.(channelnotifier.InactiveLinkEvent)
×
2852
                        if !ok {
×
2853
                                continue
×
2854
                        }
2855

2856
                        // Found an inactive link event, if this is our
2857
                        // targeted channel, remove it from our map.
2858
                        chanPoint := *inactive.ChannelPoint
×
2859
                        _, found := activeChans[chanPoint]
×
2860
                        if !found {
×
2861
                                continue
×
2862
                        }
2863

2864
                        delete(activeChans, chanPoint)
×
2865
                        p.log.Warnf("Re-enable channel %v failed, received "+
×
2866
                                "inactive link event", chanPoint)
×
2867

2868
                case <-p.quit:
×
2869
                        p.log.Debugf("Peer shutdown during retry enabling")
×
2870
                        return
×
2871
                }
2872
        }
2873
}
2874

2875
// chooseDeliveryScript takes two optionally set shutdown scripts and returns
2876
// a suitable script to close out to. This may be nil if neither script is
2877
// set. If both scripts are set, this function will error if they do not match.
2878
func chooseDeliveryScript(upfront,
2879
        requested lnwire.DeliveryAddress) (lnwire.DeliveryAddress, error) {
16✔
2880

16✔
2881
        // If no upfront shutdown script was provided, return the user
16✔
2882
        // requested address (which may be nil).
16✔
2883
        if len(upfront) == 0 {
26✔
2884
                return requested, nil
10✔
2885
        }
10✔
2886

2887
        // If an upfront shutdown script was provided, and the user did not
2888
        // request a custom shutdown script, return the upfront address.
2889
        if len(requested) == 0 {
16✔
2890
                return upfront, nil
6✔
2891
        }
6✔
2892

2893
        // If both an upfront shutdown script and a custom close script were
2894
        // provided, error if the user provided shutdown script does not match
2895
        // the upfront shutdown script (because closing out to a different
2896
        // script would violate upfront shutdown).
2897
        if !bytes.Equal(upfront, requested) {
6✔
2898
                return nil, chancloser.ErrUpfrontShutdownScriptMismatch
2✔
2899
        }
2✔
2900

2901
        // The user requested script matches the upfront shutdown script, so we
2902
        // can return it without error.
2903
        return upfront, nil
2✔
2904
}
2905

2906
// restartCoopClose checks whether we need to restart the cooperative close
2907
// process for a given channel.
2908
func (p *Brontide) restartCoopClose(lnChan *lnwallet.LightningChannel) (
2909
        *lnwire.Shutdown, error) {
×
2910

×
2911
        // If this channel has status ChanStatusCoopBroadcasted and does not
×
2912
        // have a closing transaction, then the cooperative close process was
×
2913
        // started but never finished. We'll re-create the chanCloser state
×
2914
        // machine and resend Shutdown. BOLT#2 requires that we retransmit
×
2915
        // Shutdown exactly, but doing so would mean persisting the RPC
×
2916
        // provided close script. Instead use the LocalUpfrontShutdownScript
×
2917
        // or generate a script.
×
2918
        c := lnChan.State()
×
2919
        _, err := c.BroadcastedCooperative()
×
2920
        if err != nil && err != channeldb.ErrNoCloseTx {
×
2921
                // An error other than ErrNoCloseTx was encountered.
×
2922
                return nil, err
×
2923
        } else if err == nil {
×
2924
                // This channel has already completed the coop close
×
2925
                // negotiation.
×
2926
                return nil, nil
×
2927
        }
×
2928

2929
        var deliveryScript []byte
×
2930

×
2931
        shutdownInfo, err := c.ShutdownInfo()
×
2932
        switch {
×
2933
        // We have previously stored the delivery script that we need to use
2934
        // in the shutdown message. Re-use this script.
2935
        case err == nil:
×
2936
                shutdownInfo.WhenSome(func(info channeldb.ShutdownInfo) {
×
2937
                        deliveryScript = info.DeliveryScript.Val
×
2938
                })
×
2939

2940
        // An error other than ErrNoShutdownInfo was returned
2941
        case !errors.Is(err, channeldb.ErrNoShutdownInfo):
×
2942
                return nil, err
×
2943

2944
        case errors.Is(err, channeldb.ErrNoShutdownInfo):
×
2945
                deliveryScript = c.LocalShutdownScript
×
2946
                if len(deliveryScript) == 0 {
×
2947
                        var err error
×
2948
                        deliveryScript, err = p.genDeliveryScript()
×
2949
                        if err != nil {
×
2950
                                p.log.Errorf("unable to gen delivery script: "+
×
2951
                                        "%v", err)
×
2952

×
2953
                                return nil, fmt.Errorf("close addr unavailable")
×
2954
                        }
×
2955
                }
2956
        }
2957

2958
        // Compute an ideal fee.
2959
        feePerKw, err := p.cfg.FeeEstimator.EstimateFeePerKW(
×
2960
                p.cfg.CoopCloseTargetConfs,
×
2961
        )
×
2962
        if err != nil {
×
2963
                p.log.Errorf("unable to query fee estimator: %v", err)
×
2964
                return nil, fmt.Errorf("unable to estimate fee")
×
2965
        }
×
2966

2967
        // Determine whether we or the peer are the initiator of the coop
2968
        // close attempt by looking at the channel's status.
2969
        locallyInitiated := c.HasChanStatus(
×
2970
                channeldb.ChanStatusLocalCloseInitiator,
×
2971
        )
×
2972

×
2973
        chanCloser, err := p.createChanCloser(
×
2974
                lnChan, deliveryScript, feePerKw, nil, locallyInitiated,
×
2975
        )
×
2976
        if err != nil {
×
2977
                p.log.Errorf("unable to create chan closer: %v", err)
×
2978
                return nil, fmt.Errorf("unable to create chan closer")
×
2979
        }
×
2980

2981
        // This does not need a mutex even though it is in a different
2982
        // goroutine since this is done before the channelManager goroutine is
2983
        // created.
2984
        chanID := lnwire.NewChanIDFromOutPoint(c.FundingOutpoint)
×
2985
        p.activeChanCloses[chanID] = chanCloser
×
2986

×
2987
        // Create the Shutdown message.
×
2988
        shutdownMsg, err := chanCloser.ShutdownChan()
×
2989
        if err != nil {
×
2990
                p.log.Errorf("unable to create shutdown message: %v", err)
×
2991
                delete(p.activeChanCloses, chanID)
×
2992
                return nil, err
×
2993
        }
×
2994

2995
        return shutdownMsg, nil
×
2996
}
2997

2998
// createChanCloser constructs a ChanCloser from the passed parameters and is
2999
// used to de-duplicate code.
3000
func (p *Brontide) createChanCloser(channel *lnwallet.LightningChannel,
3001
        deliveryScript lnwire.DeliveryAddress, fee chainfee.SatPerKWeight,
3002
        req *htlcswitch.ChanClose,
3003
        locallyInitiated bool) (*chancloser.ChanCloser, error) {
13✔
3004

13✔
3005
        _, startingHeight, err := p.cfg.ChainIO.GetBestBlock()
13✔
3006
        if err != nil {
13✔
3007
                p.log.Errorf("unable to obtain best block: %v", err)
×
3008
                return nil, fmt.Errorf("cannot obtain best block")
×
3009
        }
×
3010

3011
        // The req will only be set if we initiated the co-op closing flow.
3012
        var maxFee chainfee.SatPerKWeight
13✔
3013
        if req != nil {
23✔
3014
                maxFee = req.MaxFee
10✔
3015
        }
10✔
3016

3017
        chanCloser := chancloser.NewChanCloser(
13✔
3018
                chancloser.ChanCloseCfg{
13✔
3019
                        Channel:      channel,
13✔
3020
                        MusigSession: NewMusigChanCloser(channel),
13✔
3021
                        FeeEstimator: &chancloser.SimpleCoopFeeEstimator{},
13✔
3022
                        BroadcastTx:  p.cfg.Wallet.PublishTransaction,
13✔
3023
                        DisableChannel: func(op wire.OutPoint) error {
26✔
3024
                                return p.cfg.ChanStatusMgr.RequestDisable(
13✔
3025
                                        op, false,
13✔
3026
                                )
13✔
3027
                        },
13✔
3028
                        MaxFee: maxFee,
3029
                        Disconnect: func() error {
×
3030
                                return p.cfg.DisconnectPeer(p.IdentityKey())
×
3031
                        },
×
3032
                        ChainParams: &p.cfg.Wallet.Cfg.NetParams,
3033
                        Quit:        p.quit,
3034
                },
3035
                deliveryScript,
3036
                fee,
3037
                uint32(startingHeight),
3038
                req,
3039
                locallyInitiated,
3040
        )
3041

3042
        return chanCloser, nil
13✔
3043
}
3044

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

11✔
3050
        channel, ok := p.activeChannels.Load(chanID)
11✔
3051

11✔
3052
        // Though this function can't be called for pending channels, we still
11✔
3053
        // check whether channel is nil for safety.
11✔
3054
        if !ok || channel == nil {
11✔
3055
                err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
×
3056
                        "unknown", chanID)
×
3057
                p.log.Errorf(err.Error())
×
3058
                req.Err <- err
×
3059
                return
×
3060
        }
×
3061

3062
        switch req.CloseType {
11✔
3063
        // A type of CloseRegular indicates that the user has opted to close
3064
        // out this channel on-chain, so we execute the cooperative channel
3065
        // closure workflow.
3066
        case contractcourt.CloseRegular:
11✔
3067
                // First, we'll choose a delivery address that we'll use to send the
11✔
3068
                // funds to in the case of a successful negotiation.
11✔
3069

11✔
3070
                // An upfront shutdown and user provided script are both optional,
11✔
3071
                // but must be equal if both set  (because we cannot serve a request
11✔
3072
                // to close out to a script which violates upfront shutdown). Get the
11✔
3073
                // appropriate address to close out to (which may be nil if neither
11✔
3074
                // are set) and error if they are both set and do not match.
11✔
3075
                deliveryScript, err := chooseDeliveryScript(
11✔
3076
                        channel.LocalUpfrontShutdownScript(), req.DeliveryScript,
11✔
3077
                )
11✔
3078
                if err != nil {
12✔
3079
                        p.log.Errorf("cannot close channel %v: %v", req.ChanPoint, err)
1✔
3080
                        req.Err <- err
1✔
3081
                        return
1✔
3082
                }
1✔
3083

3084
                // If neither an upfront address or a user set address was
3085
                // provided, generate a fresh script.
3086
                if len(deliveryScript) == 0 {
17✔
3087
                        deliveryScript, err = p.genDeliveryScript()
7✔
3088
                        if err != nil {
7✔
3089
                                p.log.Errorf(err.Error())
×
3090
                                req.Err <- err
×
3091
                                return
×
3092
                        }
×
3093
                }
3094

3095
                chanCloser, err := p.createChanCloser(
10✔
3096
                        channel, deliveryScript, req.TargetFeePerKw, req, true,
10✔
3097
                )
10✔
3098
                if err != nil {
10✔
3099
                        p.log.Errorf(err.Error())
×
3100
                        req.Err <- err
×
3101
                        return
×
3102
                }
×
3103

3104
                p.activeChanCloses[chanID] = chanCloser
10✔
3105

10✔
3106
                // Finally, we'll initiate the channel shutdown within the
10✔
3107
                // chanCloser, and send the shutdown message to the remote
10✔
3108
                // party to kick things off.
10✔
3109
                shutdownMsg, err := chanCloser.ShutdownChan()
10✔
3110
                if err != nil {
10✔
3111
                        p.log.Errorf(err.Error())
×
3112
                        req.Err <- err
×
3113
                        delete(p.activeChanCloses, chanID)
×
3114

×
3115
                        // As we were unable to shutdown the channel, we'll
×
3116
                        // return it back to its normal state.
×
3117
                        channel.ResetState()
×
3118
                        return
×
3119
                }
×
3120

3121
                link := p.fetchLinkFromKeyAndCid(chanID)
10✔
3122
                if link == nil {
10✔
3123
                        // If the link is nil then it means it was already
×
3124
                        // removed from the switch or it never existed in the
×
3125
                        // first place. The latter case is handled at the
×
3126
                        // beginning of this function, so in the case where it
×
3127
                        // has already been removed, we can skip adding the
×
3128
                        // commit hook to queue a Shutdown message.
×
3129
                        p.log.Warnf("link not found during attempted closure: "+
×
3130
                                "%v", chanID)
×
3131
                        return
×
3132
                }
×
3133

3134
                if !link.DisableAdds(htlcswitch.Outgoing) {
10✔
3135
                        p.log.Warnf("Outgoing link adds already "+
×
3136
                                "disabled: %v", link.ChanID())
×
3137
                }
×
3138

3139
                link.OnCommitOnce(htlcswitch.Outgoing, func() {
20✔
3140
                        p.queueMsg(shutdownMsg, nil)
10✔
3141
                })
10✔
3142

3143
        // A type of CloseBreach indicates that the counterparty has breached
3144
        // the channel therefore we need to clean up our local state.
3145
        case contractcourt.CloseBreach:
1✔
3146
                // TODO(roasbeef): no longer need with newer beach logic?
1✔
3147
                p.log.Infof("ChannelPoint(%v) has been breached, wiping "+
1✔
3148
                        "channel", req.ChanPoint)
1✔
3149
                p.WipeChannel(req.ChanPoint)
1✔
3150
        }
3151
}
3152

3153
// linkFailureReport is sent to the channelManager whenever a link reports a
3154
// link failure, and is forced to exit. The report houses the necessary
3155
// information to clean up the channel state, send back the error message, and
3156
// force close if necessary.
3157
type linkFailureReport struct {
3158
        chanPoint   wire.OutPoint
3159
        chanID      lnwire.ChannelID
3160
        shortChanID lnwire.ShortChannelID
3161
        linkErr     htlcswitch.LinkFailureError
3162
}
3163

3164
// handleLinkFailure processes a link failure report when a link in the switch
3165
// fails. It facilitates the removal of all channel state within the peer,
3166
// force closing the channel depending on severity, and sending the error
3167
// message back to the remote party.
3168
func (p *Brontide) handleLinkFailure(failure linkFailureReport) {
4✔
3169
        // Retrieve the channel from the map of active channels. We do this to
4✔
3170
        // have access to it even after WipeChannel remove it from the map.
4✔
3171
        chanID := lnwire.NewChanIDFromOutPoint(failure.chanPoint)
4✔
3172
        lnChan, _ := p.activeChannels.Load(chanID)
4✔
3173

4✔
3174
        // We begin by wiping the link, which will remove it from the switch,
4✔
3175
        // such that it won't be attempted used for any more updates.
4✔
3176
        //
4✔
3177
        // TODO(halseth): should introduce a way to atomically stop/pause the
4✔
3178
        // link and cancel back any adds in its mailboxes such that we can
4✔
3179
        // safely force close without the link being added again and updates
4✔
3180
        // being applied.
4✔
3181
        p.WipeChannel(&failure.chanPoint)
4✔
3182

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

4✔
3188
                closeTx, err := p.cfg.ChainArb.ForceCloseContract(
4✔
3189
                        failure.chanPoint,
4✔
3190
                )
4✔
3191
                if err != nil {
8✔
3192
                        p.log.Errorf("unable to force close "+
4✔
3193
                                "link(%v): %v", failure.shortChanID, err)
4✔
3194
                } else {
8✔
3195
                        p.log.Infof("channel(%v) force "+
4✔
3196
                                "closed with txid %v",
4✔
3197
                                failure.shortChanID, closeTx.TxHash())
4✔
3198
                }
4✔
3199
        }
3200

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

×
3206
                if err := lnChan.State().MarkBorked(); err != nil {
×
3207
                        p.log.Errorf("Unable to mark channel %v borked: %v",
×
3208
                                failure.shortChanID, err)
×
3209
                }
×
3210
        }
3211

3212
        // Send an error to the peer, why we failed the channel.
3213
        if failure.linkErr.ShouldSendToPeer() {
8✔
3214
                // If SendData is set, send it to the peer. If not, we'll use
4✔
3215
                // the standard error messages in the payload. We only include
4✔
3216
                // sendData in the cases where the error data does not contain
4✔
3217
                // sensitive information.
4✔
3218
                data := []byte(failure.linkErr.Error())
4✔
3219
                if failure.linkErr.SendData != nil {
4✔
3220
                        data = failure.linkErr.SendData
×
3221
                }
×
3222

3223
                var networkMsg lnwire.Message
4✔
3224
                if failure.linkErr.Warning {
4✔
3225
                        networkMsg = &lnwire.Warning{
×
3226
                                ChanID: failure.chanID,
×
3227
                                Data:   data,
×
3228
                        }
×
3229
                } else {
4✔
3230
                        networkMsg = &lnwire.Error{
4✔
3231
                                ChanID: failure.chanID,
4✔
3232
                                Data:   data,
4✔
3233
                        }
4✔
3234
                }
4✔
3235

3236
                err := p.SendMessage(true, networkMsg)
4✔
3237
                if err != nil {
4✔
3238
                        p.log.Errorf("unable to send msg to "+
×
3239
                                "remote peer: %v", err)
×
3240
                }
×
3241
        }
3242

3243
        // If the failure action is disconnect, then we'll execute that now. If
3244
        // we had to send an error above, it was a sync call, so we expect the
3245
        // message to be flushed on the wire by now.
3246
        if failure.linkErr.FailureAction == htlcswitch.LinkFailureDisconnect {
4✔
3247
                p.Disconnect(fmt.Errorf("link requested disconnect"))
×
3248
        }
×
3249
}
3250

3251
// fetchLinkFromKeyAndCid fetches a link from the switch via the remote's
3252
// public key and the channel id.
3253
func (p *Brontide) fetchLinkFromKeyAndCid(
3254
        cid lnwire.ChannelID) htlcswitch.ChannelUpdateHandler {
23✔
3255

23✔
3256
        var chanLink htlcswitch.ChannelUpdateHandler
23✔
3257

23✔
3258
        // We don't need to check the error here, and can instead just loop
23✔
3259
        // over the slice and return nil.
23✔
3260
        links, _ := p.cfg.Switch.GetLinksByInterface(p.cfg.PubKeyBytes)
23✔
3261
        for _, link := range links {
45✔
3262
                if link.ChanID() == cid {
44✔
3263
                        chanLink = link
22✔
3264
                        break
22✔
3265
                }
3266
        }
3267

3268
        return chanLink
23✔
3269
}
3270

3271
// finalizeChanClosure performs the final clean up steps once the cooperative
3272
// closure transaction has been fully broadcast. The finalized closing state
3273
// machine should be passed in. Once the transaction has been sufficiently
3274
// confirmed, the channel will be marked as fully closed within the database,
3275
// and any clients will be notified of updates to the closing state.
3276
func (p *Brontide) finalizeChanClosure(chanCloser *chancloser.ChanCloser) {
8✔
3277
        closeReq := chanCloser.CloseRequest()
8✔
3278

8✔
3279
        // First, we'll clear all indexes related to the channel in question.
8✔
3280
        chanPoint := chanCloser.Channel().ChannelPoint()
8✔
3281
        p.WipeChannel(&chanPoint)
8✔
3282

8✔
3283
        // Also clear the activeChanCloses map of this channel.
8✔
3284
        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
8✔
3285
        delete(p.activeChanCloses, cid)
8✔
3286

8✔
3287
        // Next, we'll launch a goroutine which will request to be notified by
8✔
3288
        // the ChainNotifier once the closure transaction obtains a single
8✔
3289
        // confirmation.
8✔
3290
        notifier := p.cfg.ChainNotifier
8✔
3291

8✔
3292
        // If any error happens during waitForChanToClose, forward it to
8✔
3293
        // closeReq. If this channel closure is not locally initiated, closeReq
8✔
3294
        // will be nil, so just ignore the error.
8✔
3295
        errChan := make(chan error, 1)
8✔
3296
        if closeReq != nil {
14✔
3297
                errChan = closeReq.Err
6✔
3298
        }
6✔
3299

3300
        closingTx, err := chanCloser.ClosingTx()
8✔
3301
        if err != nil {
8✔
3302
                if closeReq != nil {
×
3303
                        p.log.Error(err)
×
3304
                        closeReq.Err <- err
×
3305
                }
×
3306
        }
3307

3308
        closingTxid := closingTx.TxHash()
8✔
3309

8✔
3310
        // If this is a locally requested shutdown, update the caller with a
8✔
3311
        // new event detailing the current pending state of this request.
8✔
3312
        if closeReq != nil {
14✔
3313
                closeReq.Updates <- &PendingUpdate{
6✔
3314
                        Txid: closingTxid[:],
6✔
3315
                }
6✔
3316
        }
6✔
3317

3318
        go WaitForChanToClose(chanCloser.NegotiationHeight(), notifier, errChan,
8✔
3319
                &chanPoint, &closingTxid, closingTx.TxOut[0].PkScript, func() {
16✔
3320
                        // Respond to the local subsystem which requested the
8✔
3321
                        // channel closure.
8✔
3322
                        if closeReq != nil {
14✔
3323
                                closeReq.Updates <- &ChannelCloseUpdate{
6✔
3324
                                        ClosingTxid: closingTxid[:],
6✔
3325
                                        Success:     true,
6✔
3326
                                }
6✔
3327
                        }
6✔
3328
                })
3329
}
3330

3331
// WaitForChanToClose uses the passed notifier to wait until the channel has
3332
// been detected as closed on chain and then concludes by executing the
3333
// following actions: the channel point will be sent over the settleChan, and
3334
// finally the callback will be executed. If any error is encountered within
3335
// the function, then it will be sent over the errChan.
3336
func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
3337
        errChan chan error, chanPoint *wire.OutPoint,
3338
        closingTxID *chainhash.Hash, closeScript []byte, cb func()) {
8✔
3339

8✔
3340
        peerLog.Infof("Waiting for confirmation of close of ChannelPoint(%v) "+
8✔
3341
                "with txid: %v", chanPoint, closingTxID)
8✔
3342

8✔
3343
        // TODO(roasbeef): add param for num needed confs
8✔
3344
        confNtfn, err := notifier.RegisterConfirmationsNtfn(
8✔
3345
                closingTxID, closeScript, 1, bestHeight,
8✔
3346
        )
8✔
3347
        if err != nil {
8✔
3348
                if errChan != nil {
×
3349
                        errChan <- err
×
3350
                }
×
3351
                return
×
3352
        }
3353

3354
        // In the case that the ChainNotifier is shutting down, all subscriber
3355
        // notification channels will be closed, generating a nil receive.
3356
        height, ok := <-confNtfn.Confirmed
8✔
3357
        if !ok {
12✔
3358
                return
4✔
3359
        }
4✔
3360

3361
        // The channel has been closed, remove it from any active indexes, and
3362
        // the database state.
3363
        peerLog.Infof("ChannelPoint(%v) is now closed at "+
8✔
3364
                "height %v", chanPoint, height.BlockHeight)
8✔
3365

8✔
3366
        // Finally, execute the closure call back to mark the confirmation of
8✔
3367
        // the transaction closing the contract.
8✔
3368
        cb()
8✔
3369
}
3370

3371
// WipeChannel removes the passed channel point from all indexes associated with
3372
// the peer and the switch.
3373
func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint) {
8✔
3374
        chanID := lnwire.NewChanIDFromOutPoint(*chanPoint)
8✔
3375

8✔
3376
        p.activeChannels.Delete(chanID)
8✔
3377

8✔
3378
        // Instruct the HtlcSwitch to close this link as the channel is no
8✔
3379
        // longer active.
8✔
3380
        p.cfg.Switch.RemoveLink(chanID)
8✔
3381
}
8✔
3382

3383
// handleInitMsg handles the incoming init message which contains global and
3384
// local feature vectors. If feature vectors are incompatible then disconnect.
3385
func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
6✔
3386
        // First, merge any features from the legacy global features field into
6✔
3387
        // those presented in the local features fields.
6✔
3388
        err := msg.Features.Merge(msg.GlobalFeatures)
6✔
3389
        if err != nil {
6✔
3390
                return fmt.Errorf("unable to merge legacy global features: %w",
×
3391
                        err)
×
3392
        }
×
3393

3394
        // Then, finalize the remote feature vector providing the flattened
3395
        // feature bit namespace.
3396
        p.remoteFeatures = lnwire.NewFeatureVector(
6✔
3397
                msg.Features, lnwire.Features,
6✔
3398
        )
6✔
3399

6✔
3400
        // Now that we have their features loaded, we'll ensure that they
6✔
3401
        // didn't set any required bits that we don't know of.
6✔
3402
        err = feature.ValidateRequired(p.remoteFeatures)
6✔
3403
        if err != nil {
6✔
3404
                return fmt.Errorf("invalid remote features: %w", err)
×
3405
        }
×
3406

3407
        // Ensure the remote party's feature vector contains all transitive
3408
        // dependencies. We know ours are correct since they are validated
3409
        // during the feature manager's instantiation.
3410
        err = feature.ValidateDeps(p.remoteFeatures)
6✔
3411
        if err != nil {
6✔
3412
                return fmt.Errorf("invalid remote features: %w", err)
×
3413
        }
×
3414

3415
        // Now that we know we understand their requirements, we'll check to
3416
        // see if they don't support anything that we deem to be mandatory.
3417
        if !p.remoteFeatures.HasFeature(lnwire.DataLossProtectRequired) {
6✔
3418
                return fmt.Errorf("data loss protection required")
×
3419
        }
×
3420

3421
        return nil
6✔
3422
}
3423

3424
// LocalFeatures returns the set of global features that has been advertised by
3425
// the local node. This allows sub-systems that use this interface to gate their
3426
// behavior off the set of negotiated feature bits.
3427
//
3428
// NOTE: Part of the lnpeer.Peer interface.
3429
func (p *Brontide) LocalFeatures() *lnwire.FeatureVector {
4✔
3430
        return p.cfg.Features
4✔
3431
}
4✔
3432

3433
// RemoteFeatures returns the set of global features that has been advertised by
3434
// the remote node. This allows sub-systems that use this interface to gate
3435
// their behavior off the set of negotiated feature bits.
3436
//
3437
// NOTE: Part of the lnpeer.Peer interface.
3438
func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector {
10✔
3439
        return p.remoteFeatures
10✔
3440
}
10✔
3441

3442
// hasNegotiatedScidAlias returns true if we've negotiated the
3443
// option-scid-alias feature bit with the peer.
3444
func (p *Brontide) hasNegotiatedScidAlias() bool {
6✔
3445
        peerHas := p.remoteFeatures.HasFeature(lnwire.ScidAliasOptional)
6✔
3446
        localHas := p.cfg.Features.HasFeature(lnwire.ScidAliasOptional)
6✔
3447
        return peerHas && localHas
6✔
3448
}
6✔
3449

3450
// sendInitMsg sends the Init message to the remote peer. This message contains
3451
// our currently supported local and global features.
3452
func (p *Brontide) sendInitMsg(legacyChan bool) error {
10✔
3453
        features := p.cfg.Features.Clone()
10✔
3454
        legacyFeatures := p.cfg.LegacyFeatures.Clone()
10✔
3455

10✔
3456
        // If we have a legacy channel open with a peer, we downgrade static
10✔
3457
        // remote required to optional in case the peer does not understand the
10✔
3458
        // required feature bit. If we do not do this, the peer will reject our
10✔
3459
        // connection because it does not understand a required feature bit, and
10✔
3460
        // our channel will be unusable.
10✔
3461
        if legacyChan && features.RequiresFeature(lnwire.StaticRemoteKeyRequired) {
11✔
3462
                p.log.Infof("Legacy channel open with peer, " +
1✔
3463
                        "downgrading static remote required feature bit to " +
1✔
3464
                        "optional")
1✔
3465

1✔
3466
                // Unset and set in both the local and global features to
1✔
3467
                // ensure both sets are consistent and merge able by old and
1✔
3468
                // new nodes.
1✔
3469
                features.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3470
                legacyFeatures.Unset(lnwire.StaticRemoteKeyRequired)
1✔
3471

1✔
3472
                features.Set(lnwire.StaticRemoteKeyOptional)
1✔
3473
                legacyFeatures.Set(lnwire.StaticRemoteKeyOptional)
1✔
3474
        }
1✔
3475

3476
        msg := lnwire.NewInitMessage(
10✔
3477
                legacyFeatures.RawFeatureVector,
10✔
3478
                features.RawFeatureVector,
10✔
3479
        )
10✔
3480

10✔
3481
        return p.writeMessage(msg)
10✔
3482
}
3483

3484
// resendChanSyncMsg will attempt to find a channel sync message for the closed
3485
// channel and resend it to our peer.
3486
func (p *Brontide) resendChanSyncMsg(cid lnwire.ChannelID) error {
4✔
3487
        // If we already re-sent the mssage for this channel, we won't do it
4✔
3488
        // again.
4✔
3489
        if _, ok := p.resentChanSyncMsg[cid]; ok {
5✔
3490
                return nil
1✔
3491
        }
1✔
3492

3493
        // Check if we have any channel sync messages stored for this channel.
3494
        c, err := p.cfg.ChannelDB.FetchClosedChannelForID(cid)
4✔
3495
        if err != nil {
8✔
3496
                return fmt.Errorf("unable to fetch channel sync messages for "+
4✔
3497
                        "peer %v: %v", p, err)
4✔
3498
        }
4✔
3499

3500
        if c.LastChanSyncMsg == nil {
4✔
3501
                return fmt.Errorf("no chan sync message stored for channel %v",
×
3502
                        cid)
×
3503
        }
×
3504

3505
        if !c.RemotePub.IsEqual(p.IdentityKey()) {
4✔
3506
                return fmt.Errorf("ignoring channel reestablish from "+
×
3507
                        "peer=%x", p.IdentityKey().SerializeCompressed())
×
3508
        }
×
3509

3510
        p.log.Debugf("Re-sending channel sync message for channel %v to "+
4✔
3511
                "peer", cid)
4✔
3512

4✔
3513
        if err := p.SendMessage(true, c.LastChanSyncMsg); err != nil {
4✔
3514
                return fmt.Errorf("failed resending channel sync "+
×
3515
                        "message to peer %v: %v", p, err)
×
3516
        }
×
3517

3518
        p.log.Debugf("Re-sent channel sync message for channel %v to peer ",
4✔
3519
                cid)
4✔
3520

4✔
3521
        // Note down that we sent the message, so we won't resend it again for
4✔
3522
        // this connection.
4✔
3523
        p.resentChanSyncMsg[cid] = struct{}{}
4✔
3524

4✔
3525
        return nil
4✔
3526
}
3527

3528
// SendMessage sends a variadic number of high-priority messages to the remote
3529
// peer. The first argument denotes if the method should block until the
3530
// messages have been sent to the remote peer or an error is returned,
3531
// otherwise it returns immediately after queuing.
3532
//
3533
// NOTE: Part of the lnpeer.Peer interface.
3534
func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error {
5✔
3535
        return p.sendMessage(sync, true, msgs...)
5✔
3536
}
5✔
3537

3538
// SendMessageLazy sends a variadic number of low-priority messages to the
3539
// remote peer. The first argument denotes if the method should block until
3540
// the messages have been sent to the remote peer or an error is returned,
3541
// otherwise it returns immediately after queueing.
3542
//
3543
// NOTE: Part of the lnpeer.Peer interface.
3544
func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error {
5✔
3545
        return p.sendMessage(sync, false, msgs...)
5✔
3546
}
5✔
3547

3548
// sendMessage queues a variadic number of messages using the passed priority
3549
// to the remote peer. If sync is true, this method will block until the
3550
// messages have been sent to the remote peer or an error is returned, otherwise
3551
// it returns immediately after queueing.
3552
func (p *Brontide) sendMessage(sync, priority bool, msgs ...lnwire.Message) error {
6✔
3553
        // Add all incoming messages to the outgoing queue. A list of error
6✔
3554
        // chans is populated for each message if the caller requested a sync
6✔
3555
        // send.
6✔
3556
        var errChans []chan error
6✔
3557
        if sync {
11✔
3558
                errChans = make([]chan error, 0, len(msgs))
5✔
3559
        }
5✔
3560
        for _, msg := range msgs {
12✔
3561
                // If a sync send was requested, create an error chan to listen
6✔
3562
                // for an ack from the writeHandler.
6✔
3563
                var errChan chan error
6✔
3564
                if sync {
11✔
3565
                        errChan = make(chan error, 1)
5✔
3566
                        errChans = append(errChans, errChan)
5✔
3567
                }
5✔
3568

3569
                if priority {
11✔
3570
                        p.queueMsg(msg, errChan)
5✔
3571
                } else {
10✔
3572
                        p.queueMsgLazy(msg, errChan)
5✔
3573
                }
5✔
3574
        }
3575

3576
        // Wait for all replies from the writeHandler. For async sends, this
3577
        // will be a NOP as the list of error chans is nil.
3578
        for _, errChan := range errChans {
11✔
3579
                select {
5✔
3580
                case err := <-errChan:
5✔
3581
                        return err
5✔
3582
                case <-p.quit:
×
3583
                        return lnpeer.ErrPeerExiting
×
3584
                case <-p.cfg.Quit:
×
3585
                        return lnpeer.ErrPeerExiting
×
3586
                }
3587
        }
3588

3589
        return nil
5✔
3590
}
3591

3592
// PubKey returns the pubkey of the peer in compressed serialized format.
3593
//
3594
// NOTE: Part of the lnpeer.Peer interface.
3595
func (p *Brontide) PubKey() [33]byte {
6✔
3596
        return p.cfg.PubKeyBytes
6✔
3597
}
6✔
3598

3599
// IdentityKey returns the public key of the remote peer.
3600
//
3601
// NOTE: Part of the lnpeer.Peer interface.
3602
func (p *Brontide) IdentityKey() *btcec.PublicKey {
17✔
3603
        return p.cfg.Addr.IdentityKey
17✔
3604
}
17✔
3605

3606
// Address returns the network address of the remote peer.
3607
//
3608
// NOTE: Part of the lnpeer.Peer interface.
3609
func (p *Brontide) Address() net.Addr {
4✔
3610
        return p.cfg.Addr.Address
4✔
3611
}
4✔
3612

3613
// AddNewChannel adds a new channel to the peer. The channel should fail to be
3614
// added if the cancel channel is closed.
3615
//
3616
// NOTE: Part of the lnpeer.Peer interface.
3617
func (p *Brontide) AddNewChannel(newChan *lnpeer.NewChannel,
3618
        cancel <-chan struct{}) error {
4✔
3619

4✔
3620
        errChan := make(chan error, 1)
4✔
3621
        newChanMsg := &newChannelMsg{
4✔
3622
                channel: newChan,
4✔
3623
                err:     errChan,
4✔
3624
        }
4✔
3625

4✔
3626
        select {
4✔
3627
        case p.newActiveChannel <- newChanMsg:
4✔
3628
        case <-cancel:
×
3629
                return errors.New("canceled adding new channel")
×
3630
        case <-p.quit:
×
3631
                return lnpeer.ErrPeerExiting
×
3632
        }
3633

3634
        // We pause here to wait for the peer to recognize the new channel
3635
        // before we close the channel barrier corresponding to the channel.
3636
        select {
4✔
3637
        case err := <-errChan:
4✔
3638
                return err
4✔
3639
        case <-p.quit:
×
3640
                return lnpeer.ErrPeerExiting
×
3641
        }
3642
}
3643

3644
// AddPendingChannel adds a pending open channel to the peer. The channel
3645
// should fail to be added if the cancel channel is closed.
3646
//
3647
// NOTE: Part of the lnpeer.Peer interface.
3648
func (p *Brontide) AddPendingChannel(cid lnwire.ChannelID,
3649
        cancel <-chan struct{}) error {
4✔
3650

4✔
3651
        errChan := make(chan error, 1)
4✔
3652
        newChanMsg := &newChannelMsg{
4✔
3653
                channelID: cid,
4✔
3654
                err:       errChan,
4✔
3655
        }
4✔
3656

4✔
3657
        select {
4✔
3658
        case p.newPendingChannel <- newChanMsg:
4✔
3659

3660
        case <-cancel:
×
3661
                return errors.New("canceled adding pending channel")
×
3662

3663
        case <-p.quit:
×
3664
                return lnpeer.ErrPeerExiting
×
3665
        }
3666

3667
        // We pause here to wait for the peer to recognize the new pending
3668
        // channel before we close the channel barrier corresponding to the
3669
        // channel.
3670
        select {
4✔
3671
        case err := <-errChan:
4✔
3672
                return err
4✔
3673

3674
        case <-cancel:
×
3675
                return errors.New("canceled adding pending channel")
×
3676

3677
        case <-p.quit:
×
3678
                return lnpeer.ErrPeerExiting
×
3679
        }
3680
}
3681

3682
// RemovePendingChannel removes a pending open channel from the peer.
3683
//
3684
// NOTE: Part of the lnpeer.Peer interface.
3685
func (p *Brontide) RemovePendingChannel(cid lnwire.ChannelID) error {
4✔
3686
        errChan := make(chan error, 1)
4✔
3687
        newChanMsg := &newChannelMsg{
4✔
3688
                channelID: cid,
4✔
3689
                err:       errChan,
4✔
3690
        }
4✔
3691

4✔
3692
        select {
4✔
3693
        case p.removePendingChannel <- newChanMsg:
4✔
3694
        case <-p.quit:
×
3695
                return lnpeer.ErrPeerExiting
×
3696
        }
3697

3698
        // We pause here to wait for the peer to respond to the cancellation of
3699
        // the pending channel before we close the channel barrier
3700
        // corresponding to the channel.
3701
        select {
4✔
3702
        case err := <-errChan:
4✔
3703
                return err
4✔
3704

3705
        case <-p.quit:
×
3706
                return lnpeer.ErrPeerExiting
×
3707
        }
3708
}
3709

3710
// StartTime returns the time at which the connection was established if the
3711
// peer started successfully, and zero otherwise.
3712
func (p *Brontide) StartTime() time.Time {
4✔
3713
        return p.startTime
4✔
3714
}
4✔
3715

3716
// handleCloseMsg is called when a new cooperative channel closure related
3717
// message is received from the remote peer. We'll use this message to advance
3718
// the chan closer state machine.
3719
func (p *Brontide) handleCloseMsg(msg *closeMsg) {
17✔
3720
        link := p.fetchLinkFromKeyAndCid(msg.cid)
17✔
3721

17✔
3722
        // We'll now fetch the matching closing state machine in order to continue,
17✔
3723
        // or finalize the channel closure process.
17✔
3724
        chanCloser, err := p.fetchActiveChanCloser(msg.cid)
17✔
3725
        if err != nil {
21✔
3726
                // If the channel is not known to us, we'll simply ignore this message.
4✔
3727
                if err == ErrChannelNotFound {
8✔
3728
                        return
4✔
3729
                }
4✔
3730

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

×
3733
                errMsg := &lnwire.Error{
×
3734
                        ChanID: msg.cid,
×
3735
                        Data:   lnwire.ErrorData(err.Error()),
×
3736
                }
×
3737
                p.queueMsg(errMsg, nil)
×
3738
                return
×
3739
        }
3740

3741
        handleErr := func(err error) {
18✔
3742
                err = fmt.Errorf("unable to process close msg: %w", err)
1✔
3743
                p.log.Error(err)
1✔
3744

1✔
3745
                // As the negotiations failed, we'll reset the channel state machine to
1✔
3746
                // ensure we act to on-chain events as normal.
1✔
3747
                chanCloser.Channel().ResetState()
1✔
3748

1✔
3749
                if chanCloser.CloseRequest() != nil {
1✔
3750
                        chanCloser.CloseRequest().Err <- err
×
3751
                }
×
3752
                delete(p.activeChanCloses, msg.cid)
1✔
3753

1✔
3754
                p.Disconnect(err)
1✔
3755
        }
3756

3757
        // Next, we'll process the next message using the target state machine.
3758
        // We'll either continue negotiation, or halt.
3759
        switch typed := msg.msg.(type) {
17✔
3760
        case *lnwire.Shutdown:
9✔
3761
                // Disable incoming adds immediately.
9✔
3762
                if link != nil && !link.DisableAdds(htlcswitch.Incoming) {
9✔
3763
                        p.log.Warnf("Incoming link adds already disabled: %v",
×
3764
                                link.ChanID())
×
3765
                }
×
3766

3767
                oShutdown, err := chanCloser.ReceiveShutdown(*typed)
9✔
3768
                if err != nil {
9✔
3769
                        handleErr(err)
×
3770
                        return
×
3771
                }
×
3772

3773
                oShutdown.WhenSome(func(msg lnwire.Shutdown) {
16✔
3774
                        // If the link is nil it means we can immediately queue
7✔
3775
                        // the Shutdown message since we don't have to wait for
7✔
3776
                        // commitment transaction synchronization.
7✔
3777
                        if link == nil {
8✔
3778
                                p.queueMsg(&msg, nil)
1✔
3779
                                return
1✔
3780
                        }
1✔
3781

3782
                        // Immediately disallow any new HTLC's from being added
3783
                        // in the outgoing direction.
3784
                        if !link.DisableAdds(htlcswitch.Outgoing) {
6✔
3785
                                p.log.Warnf("Outgoing link adds already "+
×
3786
                                        "disabled: %v", link.ChanID())
×
3787
                        }
×
3788

3789
                        // When we have a Shutdown to send, we defer it till the
3790
                        // next time we send a CommitSig to remain spec
3791
                        // compliant.
3792
                        link.OnCommitOnce(htlcswitch.Outgoing, func() {
12✔
3793
                                p.queueMsg(&msg, nil)
6✔
3794
                        })
6✔
3795
                })
3796

3797
                beginNegotiation := func() {
18✔
3798
                        oClosingSigned, err := chanCloser.BeginNegotiation()
9✔
3799
                        if err != nil {
10✔
3800
                                handleErr(err)
1✔
3801
                                return
1✔
3802
                        }
1✔
3803

3804
                        oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
16✔
3805
                                p.queueMsg(&msg, nil)
8✔
3806
                        })
8✔
3807
                }
3808

3809
                if link == nil {
10✔
3810
                        beginNegotiation()
1✔
3811
                } else {
9✔
3812
                        // Now we register a flush hook to advance the
8✔
3813
                        // ChanCloser and possibly send out a ClosingSigned
8✔
3814
                        // when the link finishes draining.
8✔
3815
                        link.OnFlushedOnce(func() {
16✔
3816
                                // Remove link in goroutine to prevent deadlock.
8✔
3817
                                go p.cfg.Switch.RemoveLink(msg.cid)
8✔
3818
                                beginNegotiation()
8✔
3819
                        })
8✔
3820
                }
3821

3822
        case *lnwire.ClosingSigned:
12✔
3823
                oClosingSigned, err := chanCloser.ReceiveClosingSigned(*typed)
12✔
3824
                if err != nil {
12✔
3825
                        handleErr(err)
×
3826
                        return
×
3827
                }
×
3828

3829
                oClosingSigned.WhenSome(func(msg lnwire.ClosingSigned) {
24✔
3830
                        p.queueMsg(&msg, nil)
12✔
3831
                })
12✔
3832

3833
        default:
×
3834
                panic("impossible closeMsg type")
×
3835
        }
3836

3837
        // If we haven't finished close negotiations, then we'll continue as we
3838
        // can't yet finalize the closure.
3839
        if _, err := chanCloser.ClosingTx(); err != nil {
28✔
3840
                return
12✔
3841
        }
12✔
3842

3843
        // Otherwise, we've agreed on a closing fee! In this case, we'll wrap up
3844
        // the channel closure by notifying relevant sub-systems and launching a
3845
        // goroutine to wait for close tx conf.
3846
        p.finalizeChanClosure(chanCloser)
8✔
3847
}
3848

3849
// HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto
3850
// the channelManager goroutine, which will shut down the link and possibly
3851
// close the channel.
3852
func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose) {
4✔
3853
        select {
4✔
3854
        case p.localCloseChanReqs <- req:
4✔
3855
                p.log.Info("Local close channel request is going to be " +
4✔
3856
                        "delivered to the peer")
4✔
3857
        case <-p.quit:
×
3858
                p.log.Info("Unable to deliver local close channel request " +
×
3859
                        "to peer")
×
3860
        }
3861
}
3862

3863
// NetAddress returns the network of the remote peer as an lnwire.NetAddress.
3864
func (p *Brontide) NetAddress() *lnwire.NetAddress {
4✔
3865
        return p.cfg.Addr
4✔
3866
}
4✔
3867

3868
// Inbound is a getter for the Brontide's Inbound boolean in cfg.
3869
func (p *Brontide) Inbound() bool {
4✔
3870
        return p.cfg.Inbound
4✔
3871
}
4✔
3872

3873
// ConnReq is a getter for the Brontide's connReq in cfg.
3874
func (p *Brontide) ConnReq() *connmgr.ConnReq {
4✔
3875
        return p.cfg.ConnReq
4✔
3876
}
4✔
3877

3878
// ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.
3879
func (p *Brontide) ErrorBuffer() *queue.CircularBuffer {
4✔
3880
        return p.cfg.ErrorBuffer
4✔
3881
}
4✔
3882

3883
// SetAddress sets the remote peer's address given an address.
3884
func (p *Brontide) SetAddress(address net.Addr) {
×
3885
        p.cfg.Addr.Address = address
×
3886
}
×
3887

3888
// ActiveSignal returns the peer's active signal.
3889
func (p *Brontide) ActiveSignal() chan struct{} {
4✔
3890
        return p.activeSignal
4✔
3891
}
4✔
3892

3893
// Conn returns a pointer to the peer's connection struct.
3894
func (p *Brontide) Conn() net.Conn {
4✔
3895
        return p.cfg.Conn
4✔
3896
}
4✔
3897

3898
// BytesReceived returns the number of bytes received from the peer.
3899
func (p *Brontide) BytesReceived() uint64 {
4✔
3900
        return atomic.LoadUint64(&p.bytesReceived)
4✔
3901
}
4✔
3902

3903
// BytesSent returns the number of bytes sent to the peer.
3904
func (p *Brontide) BytesSent() uint64 {
4✔
3905
        return atomic.LoadUint64(&p.bytesSent)
4✔
3906
}
4✔
3907

3908
// LastRemotePingPayload returns the last payload the remote party sent as part
3909
// of their ping.
3910
func (p *Brontide) LastRemotePingPayload() []byte {
4✔
3911
        pingPayload := p.lastPingPayload.Load()
4✔
3912
        if pingPayload == nil {
8✔
3913
                return []byte{}
4✔
3914
        }
4✔
3915

3916
        pingBytes, ok := pingPayload.(lnwire.PingPayload)
×
3917
        if !ok {
×
3918
                return nil
×
3919
        }
×
3920

3921
        return pingBytes
×
3922
}
3923

3924
// attachChannelEventSubscription creates a channel event subscription and
3925
// attaches to client to Brontide if the reenableTimeout is no greater than 1
3926
// minute.
3927
func (p *Brontide) attachChannelEventSubscription() error {
6✔
3928
        // If the timeout is greater than 1 minute, it's unlikely that the link
6✔
3929
        // hasn't yet finished its reestablishment. Return a nil without
6✔
3930
        // creating the client to specify that we don't want to retry.
6✔
3931
        if p.cfg.ChanActiveTimeout > 1*time.Minute {
10✔
3932
                return nil
4✔
3933
        }
4✔
3934

3935
        // When the reenable timeout is less than 1 minute, it's likely the
3936
        // channel link hasn't finished its reestablishment yet. In that case,
3937
        // we'll give it a second chance by subscribing to the channel update
3938
        // events. Upon receiving the `ActiveLinkEvent`, we'll then request
3939
        // enabling the channel again.
3940
        sub, err := p.cfg.ChannelNotifier.SubscribeChannelEvents()
6✔
3941
        if err != nil {
6✔
3942
                return fmt.Errorf("SubscribeChannelEvents failed: %w", err)
×
3943
        }
×
3944

3945
        p.channelEventClient = sub
6✔
3946

6✔
3947
        return nil
6✔
3948
}
3949

3950
// updateNextRevocation updates the existing channel's next revocation if it's
3951
// nil.
3952
func (p *Brontide) updateNextRevocation(c *channeldb.OpenChannel) error {
7✔
3953
        chanPoint := c.FundingOutpoint
7✔
3954
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
7✔
3955

7✔
3956
        // Read the current channel.
7✔
3957
        currentChan, loaded := p.activeChannels.Load(chanID)
7✔
3958

7✔
3959
        // currentChan should exist, but we perform a check anyway to avoid nil
7✔
3960
        // pointer dereference.
7✔
3961
        if !loaded {
8✔
3962
                return fmt.Errorf("missing active channel with chanID=%v",
1✔
3963
                        chanID)
1✔
3964
        }
1✔
3965

3966
        // currentChan should not be nil, but we perform a check anyway to
3967
        // avoid nil pointer dereference.
3968
        if currentChan == nil {
7✔
3969
                return fmt.Errorf("found nil active channel with chanID=%v",
1✔
3970
                        chanID)
1✔
3971
        }
1✔
3972

3973
        // If we're being sent a new channel, and our existing channel doesn't
3974
        // have the next revocation, then we need to update the current
3975
        // existing channel.
3976
        if currentChan.RemoteNextRevocation() != nil {
5✔
3977
                return nil
×
3978
        }
×
3979

3980
        p.log.Infof("Processing retransmitted ChannelReady for "+
5✔
3981
                "ChannelPoint(%v)", chanPoint)
5✔
3982

5✔
3983
        nextRevoke := c.RemoteNextRevocation
5✔
3984

5✔
3985
        err := currentChan.InitNextRevocation(nextRevoke)
5✔
3986
        if err != nil {
5✔
3987
                return fmt.Errorf("unable to init next revocation: %w", err)
×
3988
        }
×
3989

3990
        return nil
5✔
3991
}
3992

3993
// addActiveChannel adds a new active channel to the `activeChannels` map. It
3994
// takes a `channeldb.OpenChannel`, creates a `lnwallet.LightningChannel` from
3995
// it and assembles it with a channel link.
3996
func (p *Brontide) addActiveChannel(c *lnpeer.NewChannel) error {
4✔
3997
        chanPoint := c.FundingOutpoint
4✔
3998
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
3999

4✔
4000
        // If we've reached this point, there are two possible scenarios.  If
4✔
4001
        // the channel was in the active channels map as nil, then it was
4✔
4002
        // loaded from disk and we need to send reestablish. Else, it was not
4✔
4003
        // loaded from disk and we don't need to send reestablish as this is a
4✔
4004
        // fresh channel.
4✔
4005
        shouldReestablish := p.isLoadedFromDisk(chanID)
4✔
4006

4✔
4007
        chanOpts := c.ChanOpts
4✔
4008
        if shouldReestablish {
8✔
4009
                // If we have to do the reestablish dance for this channel,
4✔
4010
                // ensure that we don't try to call InitRemoteMusigNonces twice
4✔
4011
                // by calling SkipNonceInit.
4✔
4012
                chanOpts = append(chanOpts, lnwallet.WithSkipNonceInit())
4✔
4013
        }
4✔
4014

4015
        // If not already active, we'll add this channel to the set of active
4016
        // channels, so we can look it up later easily according to its channel
4017
        // ID.
4018
        lnChan, err := lnwallet.NewLightningChannel(
4✔
4019
                p.cfg.Signer, c.OpenChannel, p.cfg.SigPool, chanOpts...,
4✔
4020
        )
4✔
4021
        if err != nil {
4✔
4022
                return fmt.Errorf("unable to create LightningChannel: %w", err)
×
4023
        }
×
4024

4025
        // Store the channel in the activeChannels map.
4026
        p.activeChannels.Store(chanID, lnChan)
4✔
4027

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

4✔
4030
        // Next, we'll assemble a ChannelLink along with the necessary items it
4✔
4031
        // needs to function.
4✔
4032
        chainEvents, err := p.cfg.ChainArb.SubscribeChannelEvents(chanPoint)
4✔
4033
        if err != nil {
4✔
4034
                return fmt.Errorf("unable to subscribe to chain events: %w",
×
4035
                        err)
×
4036
        }
×
4037

4038
        // We'll query the channel DB for the new channel's initial forwarding
4039
        // policies to determine the policy we start out with.
4040
        initialPolicy, err := p.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
4✔
4041
        if err != nil {
4✔
4042
                return fmt.Errorf("unable to query for initial forwarding "+
×
4043
                        "policy: %v", err)
×
4044
        }
×
4045

4046
        // Create the link and add it to the switch.
4047
        err = p.addLink(
4✔
4048
                &chanPoint, lnChan, initialPolicy, chainEvents,
4✔
4049
                shouldReestablish, fn.None[lnwire.Shutdown](),
4✔
4050
        )
4✔
4051
        if err != nil {
4✔
4052
                return fmt.Errorf("can't register new channel link(%v) with "+
×
4053
                        "peer", chanPoint)
×
4054
        }
×
4055

4056
        return nil
4✔
4057
}
4058

4059
// handleNewActiveChannel handles a `newChannelMsg` request. Depending on we
4060
// know this channel ID or not, we'll either add it to the `activeChannels` map
4061
// or init the next revocation for it.
4062
func (p *Brontide) handleNewActiveChannel(req *newChannelMsg) {
4✔
4063
        newChan := req.channel
4✔
4064
        chanPoint := newChan.FundingOutpoint
4✔
4065
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
4066

4✔
4067
        // Only update RemoteNextRevocation if the channel is in the
4✔
4068
        // activeChannels map and if we added the link to the switch. Only
4✔
4069
        // active channels will be added to the switch.
4✔
4070
        if p.isActiveChannel(chanID) {
8✔
4071
                p.log.Infof("Already have ChannelPoint(%v), ignoring",
4✔
4072
                        chanPoint)
4✔
4073

4✔
4074
                // Handle it and close the err chan on the request.
4✔
4075
                close(req.err)
4✔
4076

4✔
4077
                // Update the next revocation point.
4✔
4078
                err := p.updateNextRevocation(newChan.OpenChannel)
4✔
4079
                if err != nil {
4✔
4080
                        p.log.Errorf(err.Error())
×
4081
                }
×
4082

4083
                return
4✔
4084
        }
4085

4086
        // This is a new channel, we now add it to the map.
4087
        if err := p.addActiveChannel(req.channel); err != nil {
4✔
4088
                // Log and send back the error to the request.
×
4089
                p.log.Errorf(err.Error())
×
4090
                req.err <- err
×
4091

×
4092
                return
×
4093
        }
×
4094

4095
        // Close the err chan if everything went fine.
4096
        close(req.err)
4✔
4097
}
4098

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

8✔
4106
        chanID := req.channelID
8✔
4107

8✔
4108
        // If we already have this channel, something is wrong with the funding
8✔
4109
        // flow as it will only be marked as active after `ChannelReady` is
8✔
4110
        // handled. In this case, we will do nothing but log an error, just in
8✔
4111
        // case this is a legit channel.
8✔
4112
        if p.isActiveChannel(chanID) {
9✔
4113
                p.log.Errorf("Channel(%v) is already active, ignoring "+
1✔
4114
                        "pending channel request", chanID)
1✔
4115

1✔
4116
                return
1✔
4117
        }
1✔
4118

4119
        // The channel has already been added, we will do nothing and return.
4120
        if p.isPendingChannel(chanID) {
8✔
4121
                p.log.Infof("Channel(%v) is already added, ignoring "+
1✔
4122
                        "pending channel request", chanID)
1✔
4123

1✔
4124
                return
1✔
4125
        }
1✔
4126

4127
        // This is a new channel, we now add it to the map `activeChannels`
4128
        // with nil value and mark it as a newly added channel in
4129
        // `addedChannels`.
4130
        p.activeChannels.Store(chanID, nil)
6✔
4131
        p.addedChannels.Store(chanID, struct{}{})
6✔
4132
}
4133

4134
// handleRemovePendingChannel takes a `newChannelMsg` request and removes it
4135
// from `activeChannels` map. The request will be ignored if the channel is
4136
// considered active by Brontide. Noop if the channel ID cannot be found.
4137
func (p *Brontide) handleRemovePendingChannel(req *newChannelMsg) {
8✔
4138
        defer close(req.err)
8✔
4139

8✔
4140
        chanID := req.channelID
8✔
4141

8✔
4142
        // If we already have this channel, something is wrong with the funding
8✔
4143
        // flow as it will only be marked as active after `ChannelReady` is
8✔
4144
        // handled. In this case, we will log an error and exit.
8✔
4145
        if p.isActiveChannel(chanID) {
9✔
4146
                p.log.Errorf("Channel(%v) is active, ignoring remove request",
1✔
4147
                        chanID)
1✔
4148
                return
1✔
4149
        }
1✔
4150

4151
        // The channel has not been added yet, we will log a warning as there
4152
        // is an unexpected call from funding manager.
4153
        if !p.isPendingChannel(chanID) {
12✔
4154
                p.log.Warnf("Channel(%v) not found, removing it anyway", chanID)
5✔
4155
        }
5✔
4156

4157
        // Remove the record of this pending channel.
4158
        p.activeChannels.Delete(chanID)
7✔
4159
        p.addedChannels.Delete(chanID)
7✔
4160
}
4161

4162
// sendLinkUpdateMsg sends a message that updates the channel to the
4163
// channel's message stream.
4164
func (p *Brontide) sendLinkUpdateMsg(cid lnwire.ChannelID, msg lnwire.Message) {
4✔
4165
        p.log.Tracef("Sending link update msg=%v", msg.MsgType())
4✔
4166

4✔
4167
        chanStream, ok := p.activeMsgStreams[cid]
4✔
4168
        if !ok {
8✔
4169
                // If a stream hasn't yet been created, then we'll do so, add
4✔
4170
                // it to the map, and finally start it.
4✔
4171
                chanStream = newChanMsgStream(p, cid)
4✔
4172
                p.activeMsgStreams[cid] = chanStream
4✔
4173
                chanStream.Start()
4✔
4174

4✔
4175
                // Stop the stream when quit.
4✔
4176
                go func() {
8✔
4177
                        <-p.quit
4✔
4178
                        chanStream.Stop()
4✔
4179
                }()
4✔
4180
        }
4181

4182
        // With the stream obtained, add the message to the stream so we can
4183
        // continue processing message.
4184
        chanStream.AddMsg(msg)
4✔
4185
}
4186

4187
// scaleTimeout multiplies the argument duration by a constant factor depending
4188
// on variious heuristics. Currently this is only used to check whether our peer
4189
// appears to be connected over Tor and relaxes the timout deadline. However,
4190
// this is subject to change and should be treated as opaque.
4191
func (p *Brontide) scaleTimeout(timeout time.Duration) time.Duration {
64✔
4192
        if p.isTorConnection {
68✔
4193
                return timeout * time.Duration(torTimeoutMultiplier)
4✔
4194
        }
4✔
4195

4196
        return timeout
60✔
4197
}
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