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

lightningnetwork / lnd / 13725358077

07 Mar 2025 04:51PM UTC coverage: 58.224% (-10.4%) from 68.615%
13725358077

Pull #9458

github

web-flow
Merge bf4c6625f into ab2dc09eb
Pull Request #9458: multi+server.go: add initial permissions for some peers

346 of 549 new or added lines in 10 files covered. (63.02%)

27466 existing lines in 443 files now uncovered.

94609 of 162492 relevant lines covered (58.22%)

1.81 hits per line

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

69.2
/funding/manager.go
1
package funding
2

3
import (
4
        "bytes"
5
        "encoding/binary"
6
        "fmt"
7
        "io"
8
        "sync"
9
        "sync/atomic"
10
        "time"
11

12
        "github.com/btcsuite/btcd/blockchain"
13
        "github.com/btcsuite/btcd/btcec/v2"
14
        "github.com/btcsuite/btcd/btcec/v2/ecdsa"
15
        "github.com/btcsuite/btcd/btcec/v2/schnorr/musig2"
16
        "github.com/btcsuite/btcd/btcutil"
17
        "github.com/btcsuite/btcd/chaincfg/chainhash"
18
        "github.com/btcsuite/btcd/txscript"
19
        "github.com/btcsuite/btcd/wire"
20
        "github.com/davecgh/go-spew/spew"
21
        "github.com/go-errors/errors"
22
        "github.com/lightningnetwork/lnd/chainntnfs"
23
        "github.com/lightningnetwork/lnd/chanacceptor"
24
        "github.com/lightningnetwork/lnd/channeldb"
25
        "github.com/lightningnetwork/lnd/discovery"
26
        "github.com/lightningnetwork/lnd/fn/v2"
27
        "github.com/lightningnetwork/lnd/graph"
28
        "github.com/lightningnetwork/lnd/graph/db/models"
29
        "github.com/lightningnetwork/lnd/input"
30
        "github.com/lightningnetwork/lnd/keychain"
31
        "github.com/lightningnetwork/lnd/labels"
32
        "github.com/lightningnetwork/lnd/lnpeer"
33
        "github.com/lightningnetwork/lnd/lnrpc"
34
        "github.com/lightningnetwork/lnd/lnutils"
35
        "github.com/lightningnetwork/lnd/lnwallet"
36
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
37
        "github.com/lightningnetwork/lnd/lnwallet/chanfunding"
38
        "github.com/lightningnetwork/lnd/lnwire"
39
        "golang.org/x/crypto/salsa20"
40
)
41

42
var (
43
        // byteOrder defines the endian-ness we use for encoding to and from
44
        // buffers.
45
        byteOrder = binary.BigEndian
46

47
        // checkPeerChannelReadyInterval is used when we are waiting for the
48
        // peer to send us ChannelReady. We will check every 1 second to see
49
        // if the message is received.
50
        //
51
        // NOTE: for itest, this value is changed to 10ms.
52
        checkPeerChannelReadyInterval = 1 * time.Second
53

54
        // errNoLocalNonce is returned when a local nonce is not found in the
55
        // expected TLV.
56
        errNoLocalNonce = fmt.Errorf("local nonce not found")
57

58
        // errNoPartialSig is returned when a partial sig is not found in the
59
        // expected TLV.
60
        errNoPartialSig = fmt.Errorf("partial sig not found")
61
)
62

63
// WriteOutpoint writes an outpoint to an io.Writer. This is not the same as
64
// the channeldb variant as this uses WriteVarBytes for the Hash.
65
func WriteOutpoint(w io.Writer, o *wire.OutPoint) error {
3✔
66
        scratch := make([]byte, 4)
3✔
67

3✔
68
        if err := wire.WriteVarBytes(w, 0, o.Hash[:]); err != nil {
3✔
69
                return err
×
70
        }
×
71

72
        byteOrder.PutUint32(scratch, o.Index)
3✔
73
        _, err := w.Write(scratch)
3✔
74
        return err
3✔
75
}
76

77
const (
78
        // MinBtcRemoteDelay is the minimum CSV delay we will require the remote
79
        // to use for its commitment transaction.
80
        MinBtcRemoteDelay uint16 = 144
81

82
        // MaxBtcRemoteDelay is the maximum CSV delay we will require the remote
83
        // to use for its commitment transaction.
84
        MaxBtcRemoteDelay uint16 = 2016
85

86
        // MinChanFundingSize is the smallest channel that we'll allow to be
87
        // created over the RPC interface.
88
        MinChanFundingSize = btcutil.Amount(20000)
89

90
        // MaxBtcFundingAmount is a soft-limit of the maximum channel size
91
        // currently accepted on the Bitcoin chain within the Lightning
92
        // Protocol. This limit is defined in BOLT-0002, and serves as an
93
        // initial precautionary limit while implementations are battle tested
94
        // in the real world.
95
        MaxBtcFundingAmount = btcutil.Amount(1<<24) - 1
96

97
        // MaxBtcFundingAmountWumbo is a soft-limit on the maximum size of wumbo
98
        // channels. This limit is 10 BTC and is the only thing standing between
99
        // you and limitless channel size (apart from 21 million cap).
100
        MaxBtcFundingAmountWumbo = btcutil.Amount(1000000000)
101

102
        msgBufferSize = 50
103

104
        // MaxWaitNumBlocksFundingConf is the maximum number of blocks to wait
105
        // for the funding transaction to be confirmed before forgetting
106
        // channels that aren't initiated by us. 2016 blocks is ~2 weeks.
107
        MaxWaitNumBlocksFundingConf = 2016
108

109
        // pendingChansLimit is the maximum number of pending channels that we
110
        // can have. After this point, pending channel opens will start to be
111
        // rejected.
112
        pendingChansLimit = 50
113
)
114

115
var (
116
        // ErrFundingManagerShuttingDown is an error returned when attempting to
117
        // process a funding request/message but the funding manager has already
118
        // been signaled to shut down.
119
        ErrFundingManagerShuttingDown = errors.New("funding manager shutting " +
120
                "down")
121

122
        // ErrConfirmationTimeout is an error returned when we as a responder
123
        // are waiting for a funding transaction to confirm, but too many
124
        // blocks pass without confirmation.
125
        ErrConfirmationTimeout = errors.New("timeout waiting for funding " +
126
                "confirmation")
127

128
        // errUpfrontShutdownScriptNotSupported is returned if an upfront
129
        // shutdown script is set for a peer that does not support the feature
130
        // bit.
131
        errUpfrontShutdownScriptNotSupported = errors.New("peer does not " +
132
                "support option upfront shutdown script")
133

134
        zeroID [32]byte
135
)
136

137
// reservationWithCtx encapsulates a pending channel reservation. This wrapper
138
// struct is used internally within the funding manager to track and progress
139
// the funding workflow initiated by incoming/outgoing methods from the target
140
// peer. Additionally, this struct houses a response and error channel which is
141
// used to respond to the caller in the case a channel workflow is initiated
142
// via a local signal such as RPC.
143
//
144
// TODO(roasbeef): actually use the context package
145
//   - deadlines, etc.
146
type reservationWithCtx struct {
147
        reservation *lnwallet.ChannelReservation
148
        peer        lnpeer.Peer
149

150
        chanAmt btcutil.Amount
151

152
        // forwardingPolicy is the policy provided by the initFundingMsg.
153
        forwardingPolicy models.ForwardingPolicy
154

155
        // Constraints we require for the remote.
156
        remoteCsvDelay    uint16
157
        remoteMinHtlc     lnwire.MilliSatoshi
158
        remoteMaxValue    lnwire.MilliSatoshi
159
        remoteMaxHtlcs    uint16
160
        remoteChanReserve btcutil.Amount
161

162
        // maxLocalCsv is the maximum csv we will accept from the remote.
163
        maxLocalCsv uint16
164

165
        // channelType is the explicit channel type proposed by the initiator of
166
        // the channel.
167
        channelType *lnwire.ChannelType
168

169
        updateMtx   sync.RWMutex
170
        lastUpdated time.Time
171

172
        updates chan *lnrpc.OpenStatusUpdate
173
        err     chan error
174
}
175

176
// isLocked checks the reservation's timestamp to determine whether it is
177
// locked.
178
func (r *reservationWithCtx) isLocked() bool {
3✔
179
        r.updateMtx.RLock()
3✔
180
        defer r.updateMtx.RUnlock()
3✔
181

3✔
182
        // The time zero value represents a locked reservation.
3✔
183
        return r.lastUpdated.IsZero()
3✔
184
}
3✔
185

186
// updateTimestamp updates the reservation's timestamp with the current time.
187
func (r *reservationWithCtx) updateTimestamp() {
3✔
188
        r.updateMtx.Lock()
3✔
189
        defer r.updateMtx.Unlock()
3✔
190

3✔
191
        r.lastUpdated = time.Now()
3✔
192
}
3✔
193

194
// InitFundingMsg is sent by an outside subsystem to the funding manager in
195
// order to kick off a funding workflow with a specified target peer. The
196
// original request which defines the parameters of the funding workflow are
197
// embedded within this message giving the funding manager full context w.r.t
198
// the workflow.
199
type InitFundingMsg struct {
200
        // Peer is the peer that we want to open a channel to.
201
        Peer lnpeer.Peer
202

203
        // TargetPubkey is the public key of the peer.
204
        TargetPubkey *btcec.PublicKey
205

206
        // ChainHash is the target genesis hash for this channel.
207
        ChainHash chainhash.Hash
208

209
        // SubtractFees set to true means that fees will be subtracted
210
        // from the LocalFundingAmt.
211
        SubtractFees bool
212

213
        // LocalFundingAmt is the size of the channel.
214
        LocalFundingAmt btcutil.Amount
215

216
        // BaseFee is the base fee charged for routing payments regardless of
217
        // the number of milli-satoshis sent.
218
        BaseFee *uint64
219

220
        // FeeRate is the fee rate in ppm (parts per million) that will be
221
        // charged proportionally based on the value of each forwarded HTLC, the
222
        // lowest possible rate is 0 with a granularity of 0.000001
223
        // (millionths).
224
        FeeRate *uint64
225

226
        // PushAmt is the amount pushed to the counterparty.
227
        PushAmt lnwire.MilliSatoshi
228

229
        // FundingFeePerKw is the fee for the funding transaction.
230
        FundingFeePerKw chainfee.SatPerKWeight
231

232
        // Private determines whether or not this channel will be private.
233
        Private bool
234

235
        // MinHtlcIn is the minimum incoming HTLC that we accept.
236
        MinHtlcIn lnwire.MilliSatoshi
237

238
        // RemoteCsvDelay is the CSV delay we require for the remote peer.
239
        RemoteCsvDelay uint16
240

241
        // RemoteChanReserve is the channel reserve we required for the remote
242
        // peer.
243
        RemoteChanReserve btcutil.Amount
244

245
        // MinConfs indicates the minimum number of confirmations that each
246
        // output selected to fund the channel should satisfy.
247
        MinConfs int32
248

249
        // ShutdownScript is an optional upfront shutdown script for the
250
        // channel. This value is optional, so may be nil.
251
        ShutdownScript lnwire.DeliveryAddress
252

253
        // MaxValueInFlight is the maximum amount of coins in MilliSatoshi
254
        // that can be pending within the channel. It only applies to the
255
        // remote party.
256
        MaxValueInFlight lnwire.MilliSatoshi
257

258
        // MaxHtlcs is the maximum number of HTLCs that the remote peer
259
        // can offer us.
260
        MaxHtlcs uint16
261

262
        // MaxLocalCsv is the maximum local csv delay we will accept from our
263
        // peer.
264
        MaxLocalCsv uint16
265

266
        // FundUpToMaxAmt is the maximum amount to try to commit to. If set, the
267
        // MinFundAmt field denotes the acceptable minimum amount to commit to,
268
        // while trying to commit as many coins as possible up to this value.
269
        FundUpToMaxAmt btcutil.Amount
270

271
        // MinFundAmt must be set iff FundUpToMaxAmt is set. It denotes the
272
        // minimum amount to commit to.
273
        MinFundAmt btcutil.Amount
274

275
        // Outpoints is a list of client-selected outpoints that should be used
276
        // for funding a channel. If LocalFundingAmt is specified then this
277
        // amount is allocated from the sum of outpoints towards funding. If
278
        // the FundUpToMaxAmt is specified the entirety of selected funds is
279
        // allocated towards channel funding.
280
        Outpoints []wire.OutPoint
281

282
        // ChanFunder is an optional channel funder that allows the caller to
283
        // control exactly how the channel funding is carried out. If not
284
        // specified, then the default chanfunding.WalletAssembler will be
285
        // used.
286
        ChanFunder chanfunding.Assembler
287

288
        // PendingChanID is not all zeroes (the default value), then this will
289
        // be the pending channel ID used for the funding flow within the wire
290
        // protocol.
291
        PendingChanID PendingChanID
292

293
        // ChannelType allows the caller to use an explicit channel type for the
294
        // funding negotiation. This type will only be observed if BOTH sides
295
        // support explicit channel type negotiation.
296
        ChannelType *lnwire.ChannelType
297

298
        // Memo is any arbitrary information we wish to store locally about the
299
        // channel that will be useful to our future selves.
300
        Memo []byte
301

302
        // Updates is a channel which updates to the opening status of the
303
        // channel are sent on.
304
        Updates chan *lnrpc.OpenStatusUpdate
305

306
        // Err is a channel which errors encountered during the funding flow are
307
        // sent on.
308
        Err chan error
309
}
310

311
// fundingMsg is sent by the ProcessFundingMsg function and packages a
312
// funding-specific lnwire.Message along with the lnpeer.Peer that sent it.
313
type fundingMsg struct {
314
        msg  lnwire.Message
315
        peer lnpeer.Peer
316
}
317

318
// pendingChannels is a map instantiated per-peer which tracks all active
319
// pending single funded channels indexed by their pending channel identifier,
320
// which is a set of 32-bytes generated via a CSPRNG.
321
type pendingChannels map[PendingChanID]*reservationWithCtx
322

323
// serializedPubKey is used within the FundingManager's activeReservations list
324
// to identify the nodes with which the FundingManager is actively working to
325
// initiate new channels.
326
type serializedPubKey [33]byte
327

328
// newSerializedKey creates a new serialized public key from an instance of a
329
// live pubkey object.
330
func newSerializedKey(pubKey *btcec.PublicKey) serializedPubKey {
3✔
331
        var s serializedPubKey
3✔
332
        copy(s[:], pubKey.SerializeCompressed())
3✔
333
        return s
3✔
334
}
3✔
335

336
// DevConfig specifies configs used for integration test only.
337
type DevConfig struct {
338
        // ProcessChannelReadyWait is the duration to sleep before processing
339
        // remote node's channel ready message once the channel as been marked
340
        // as `channelReadySent`.
341
        ProcessChannelReadyWait time.Duration
342
}
343

344
// Config defines the configuration for the FundingManager. All elements
345
// within the configuration MUST be non-nil for the FundingManager to carry out
346
// its duties.
347
type Config struct {
348
        // Dev specifies config values used in integration test. For
349
        // production, this config will always be an empty struct.
350
        Dev *DevConfig
351

352
        // NoWumboChans indicates if we're to reject all incoming wumbo channel
353
        // requests, and also reject all outgoing wumbo channel requests.
354
        NoWumboChans bool
355

356
        // IDKey is the PublicKey that is used to identify this node within the
357
        // Lightning Network.
358
        IDKey *btcec.PublicKey
359

360
        // IDKeyLoc is the locator for the key that is used to identify this
361
        // node within the LightningNetwork.
362
        IDKeyLoc keychain.KeyLocator
363

364
        // Wallet handles the parts of the funding process that involves moving
365
        // funds from on-chain transaction outputs into Lightning channels.
366
        Wallet *lnwallet.LightningWallet
367

368
        // PublishTransaction facilitates the process of broadcasting a
369
        // transaction to the network.
370
        PublishTransaction func(*wire.MsgTx, string) error
371

372
        // UpdateLabel updates the label that a transaction has in our wallet,
373
        // overwriting any existing labels.
374
        UpdateLabel func(chainhash.Hash, string) error
375

376
        // FeeEstimator calculates appropriate fee rates based on historical
377
        // transaction information.
378
        FeeEstimator chainfee.Estimator
379

380
        // Notifier is used by the FundingManager to determine when the
381
        // channel's funding transaction has been confirmed on the blockchain
382
        // so that the channel creation process can be completed.
383
        Notifier chainntnfs.ChainNotifier
384

385
        // ChannelDB is the database that keeps track of all channel state.
386
        ChannelDB *channeldb.ChannelStateDB
387

388
        // SignMessage signs an arbitrary message with a given public key. The
389
        // actual digest signed is the double sha-256 of the message. In the
390
        // case that the private key corresponding to the passed public key
391
        // cannot be located, then an error is returned.
392
        //
393
        // TODO(roasbeef): should instead pass on this responsibility to a
394
        // distinct sub-system?
395
        SignMessage func(keyLoc keychain.KeyLocator,
396
                msg []byte, doubleHash bool) (*ecdsa.Signature, error)
397

398
        // CurrentNodeAnnouncement should return the latest, fully signed node
399
        // announcement from the backing Lightning Network node with a fresh
400
        // timestamp.
401
        CurrentNodeAnnouncement func() (lnwire.NodeAnnouncement, error)
402

403
        // SendAnnouncement is used by the FundingManager to send announcement
404
        // messages to the Gossiper to possibly broadcast to the greater
405
        // network. A set of optional message fields can be provided to populate
406
        // any information within the graph that is not included in the gossip
407
        // message.
408
        SendAnnouncement func(msg lnwire.Message,
409
                optionalFields ...discovery.OptionalMsgField) chan error
410

411
        // NotifyWhenOnline allows the FundingManager to register with a
412
        // subsystem that will notify it when the peer comes online. This is
413
        // used when sending the channelReady message, since it MUST be
414
        // delivered after the funding transaction is confirmed.
415
        //
416
        // NOTE: The peerChan channel must be buffered.
417
        NotifyWhenOnline func(peer [33]byte, peerChan chan<- lnpeer.Peer)
418

419
        // FindChannel queries the database for the channel with the given
420
        // channel ID. Providing the node's public key is an optimization that
421
        // prevents deserializing and scanning through all possible channels.
422
        FindChannel func(node *btcec.PublicKey,
423
                chanID lnwire.ChannelID) (*channeldb.OpenChannel, error)
424

425
        // TempChanIDSeed is a cryptographically random string of bytes that's
426
        // used as a seed to generate pending channel ID's.
427
        TempChanIDSeed [32]byte
428

429
        // DefaultRoutingPolicy is the default routing policy used when
430
        // initially announcing channels.
431
        DefaultRoutingPolicy models.ForwardingPolicy
432

433
        // DefaultMinHtlcIn is the default minimum incoming htlc value that is
434
        // set as a channel parameter.
435
        DefaultMinHtlcIn lnwire.MilliSatoshi
436

437
        // NumRequiredConfs is a function closure that helps the funding
438
        // manager decide how many confirmations it should require for a
439
        // channel extended to it. The function is able to take into account
440
        // the amount of the channel, and any funds we'll be pushed in the
441
        // process to determine how many confirmations we'll require.
442
        NumRequiredConfs func(btcutil.Amount, lnwire.MilliSatoshi) uint16
443

444
        // RequiredRemoteDelay is a function that maps the total amount in a
445
        // proposed channel to the CSV delay that we'll require for the remote
446
        // party. Naturally a larger channel should require a higher CSV delay
447
        // in order to give us more time to claim funds in the case of a
448
        // contract breach.
449
        RequiredRemoteDelay func(btcutil.Amount) uint16
450

451
        // RequiredRemoteChanReserve is a function closure that, given the
452
        // channel capacity and dust limit, will return an appropriate amount
453
        // for the remote peer's required channel reserve that is to be adhered
454
        // to at all times.
455
        RequiredRemoteChanReserve func(capacity,
456
                dustLimit btcutil.Amount) btcutil.Amount
457

458
        // RequiredRemoteMaxValue is a function closure that, given the channel
459
        // capacity, returns the amount of MilliSatoshis that our remote peer
460
        // can have in total outstanding HTLCs with us.
461
        RequiredRemoteMaxValue func(btcutil.Amount) lnwire.MilliSatoshi
462

463
        // RequiredRemoteMaxHTLCs is a function closure that, given the channel
464
        // capacity, returns the number of maximum HTLCs the remote peer can
465
        // offer us.
466
        RequiredRemoteMaxHTLCs func(btcutil.Amount) uint16
467

468
        // WatchNewChannel is to be called once a new channel enters the final
469
        // funding stage: waiting for on-chain confirmation. This method sends
470
        // the channel to the ChainArbitrator so it can watch for any on-chain
471
        // events related to the channel. We also provide the public key of the
472
        // node we're establishing a channel with for reconnection purposes.
473
        WatchNewChannel func(*channeldb.OpenChannel, *btcec.PublicKey) error
474

475
        // ReportShortChanID allows the funding manager to report the confirmed
476
        // short channel ID of a formerly pending zero-conf channel to outside
477
        // sub-systems.
478
        ReportShortChanID func(wire.OutPoint) error
479

480
        // ZombieSweeperInterval is the periodic time interval in which the
481
        // zombie sweeper is run.
482
        ZombieSweeperInterval time.Duration
483

484
        // ReservationTimeout is the length of idle time that must pass before
485
        // a reservation is considered a zombie.
486
        ReservationTimeout time.Duration
487

488
        // MinChanSize is the smallest channel size that we'll accept as an
489
        // inbound channel. We have such a parameter, as otherwise, nodes could
490
        // flood us with very small channels that would never really be usable
491
        // due to fees.
492
        MinChanSize btcutil.Amount
493

494
        // MaxChanSize is the largest channel size that we'll accept as an
495
        // inbound channel. We have such a parameter, so that you may decide how
496
        // WUMBO you would like your channel.
497
        MaxChanSize btcutil.Amount
498

499
        // MaxPendingChannels is the maximum number of pending channels we
500
        // allow for each peer.
501
        MaxPendingChannels int
502

503
        // RejectPush is set true if the fundingmanager should reject any
504
        // incoming channels having a non-zero push amount.
505
        RejectPush bool
506

507
        // MaxLocalCSVDelay is the maximum csv delay we will allow for our
508
        // commit output. Channels that exceed this value will be failed.
509
        MaxLocalCSVDelay uint16
510

511
        // NotifyOpenChannelEvent informs the ChannelNotifier when channels
512
        // transition from pending open to open.
513
        NotifyOpenChannelEvent func(wire.OutPoint, *btcec.PublicKey) error
514

515
        // OpenChannelPredicate is a predicate on the lnwire.OpenChannel message
516
        // and on the requesting node's public key that returns a bool which
517
        // tells the funding manager whether or not to accept the channel.
518
        OpenChannelPredicate chanacceptor.ChannelAcceptor
519

520
        // NotifyPendingOpenChannelEvent informs the ChannelNotifier when
521
        // channels enter a pending state.
522
        NotifyPendingOpenChannelEvent func(wire.OutPoint,
523
                *channeldb.OpenChannel, *btcec.PublicKey) error
524

525
        // NotifyFundingTimeout informs the ChannelNotifier when a pending-open
526
        // channel times out because the funding transaction hasn't confirmed.
527
        // This is only called for the fundee and only if the channel is
528
        // zero-conf.
529
        NotifyFundingTimeout func(wire.OutPoint, *btcec.PublicKey) error
530

531
        // EnableUpfrontShutdown specifies whether the upfront shutdown script
532
        // is enabled.
533
        EnableUpfrontShutdown bool
534

535
        // MaxAnchorsCommitFeeRate is the max commitment fee rate we'll use as
536
        // the initiator for channels of the anchor type.
537
        MaxAnchorsCommitFeeRate chainfee.SatPerKWeight
538

539
        // DeleteAliasEdge allows the Manager to delete an alias channel edge
540
        // from the graph. It also returns our local to-be-deleted policy.
541
        DeleteAliasEdge func(scid lnwire.ShortChannelID) (
542
                *models.ChannelEdgePolicy, error)
543

544
        // AliasManager is an implementation of the aliasHandler interface that
545
        // abstracts away the handling of many alias functions.
546
        AliasManager aliasHandler
547

548
        // IsSweeperOutpoint queries the sweeper store for successfully
549
        // published sweeps. This is useful to decide for the internal wallet
550
        // backed funding flow to not use utxos still being swept by the sweeper
551
        // subsystem.
552
        IsSweeperOutpoint func(wire.OutPoint) bool
553

554
        // AuxLeafStore is an optional store that can be used to store auxiliary
555
        // leaves for certain custom channel types.
556
        AuxLeafStore fn.Option[lnwallet.AuxLeafStore]
557

558
        // AuxFundingController is an optional controller that can be used to
559
        // modify the way we handle certain custom channel types. It's also
560
        // able to automatically handle new custom protocol messages related to
561
        // the funding process.
562
        AuxFundingController fn.Option[AuxFundingController]
563

564
        // AuxSigner is an optional signer that can be used to sign auxiliary
565
        // leaves for certain custom channel types.
566
        AuxSigner fn.Option[lnwallet.AuxSigner]
567

568
        // AuxResolver is an optional interface that can be used to modify the
569
        // way contracts are resolved.
570
        AuxResolver fn.Option[lnwallet.AuxContractResolver]
571
}
572

573
// Manager acts as an orchestrator/bridge between the wallet's
574
// 'ChannelReservation' workflow, and the wire protocol's funding initiation
575
// messages. Any requests to initiate the funding workflow for a channel,
576
// either kicked-off locally or remotely are handled by the funding manager.
577
// Once a channel's funding workflow has been completed, any local callers, the
578
// local peer, and possibly the remote peer are notified of the completion of
579
// the channel workflow. Additionally, any temporary or permanent access
580
// controls between the wallet and remote peers are enforced via the funding
581
// manager.
582
type Manager struct {
583
        started sync.Once
584
        stopped sync.Once
585

586
        // cfg is a copy of the configuration struct that the FundingManager
587
        // was initialized with.
588
        cfg *Config
589

590
        // chanIDKey is a cryptographically random key that's used to generate
591
        // temporary channel ID's.
592
        chanIDKey [32]byte
593

594
        // chanIDNonce is a nonce that's incremented for each new funding
595
        // reservation created.
596
        chanIDNonce atomic.Uint64
597

598
        // nonceMtx is a mutex that guards the pendingMusigNonces.
599
        nonceMtx sync.RWMutex
600

601
        // pendingMusigNonces is used to store the musig2 nonce we generate to
602
        // send funding locked until we receive a funding locked message from
603
        // the remote party. We'll use this to keep track of the nonce we
604
        // generated, so we send the local+remote nonces to the peer state
605
        // machine.
606
        //
607
        // NOTE: This map is protected by the nonceMtx above.
608
        //
609
        // TODO(roasbeef): replace w/ generic concurrent map
610
        pendingMusigNonces map[lnwire.ChannelID]*musig2.Nonces
611

612
        // activeReservations is a map which houses the state of all pending
613
        // funding workflows.
614
        activeReservations map[serializedPubKey]pendingChannels
615

616
        // signedReservations is a utility map that maps the permanent channel
617
        // ID of a funding reservation to its temporary channel ID. This is
618
        // required as mid funding flow, we switch to referencing the channel
619
        // by its full channel ID once the commitment transactions have been
620
        // signed by both parties.
621
        signedReservations map[lnwire.ChannelID]PendingChanID
622

623
        // resMtx guards both of the maps above to ensure that all access is
624
        // goroutine safe.
625
        resMtx sync.RWMutex
626

627
        // fundingMsgs is a channel that relays fundingMsg structs from
628
        // external sub-systems using the ProcessFundingMsg call.
629
        fundingMsgs chan *fundingMsg
630

631
        // fundingRequests is a channel used to receive channel initiation
632
        // requests from a local subsystem within the daemon.
633
        fundingRequests chan *InitFundingMsg
634

635
        localDiscoverySignals *lnutils.SyncMap[lnwire.ChannelID, chan struct{}]
636

637
        handleChannelReadyBarriers *lnutils.SyncMap[lnwire.ChannelID, struct{}]
638

639
        quit chan struct{}
640
        wg   sync.WaitGroup
641
}
642

643
// channelOpeningState represents the different states a channel can be in
644
// between the funding transaction has been confirmed and the channel is
645
// announced to the network and ready to be used.
646
type channelOpeningState uint8
647

648
const (
649
        // markedOpen is the opening state of a channel if the funding
650
        // transaction is confirmed on-chain, but channelReady is not yet
651
        // successfully sent to the other peer.
652
        markedOpen channelOpeningState = iota
653

654
        // channelReadySent is the opening state of a channel if the
655
        // channelReady message has successfully been sent to the other peer,
656
        // but we still haven't announced the channel to the network.
657
        channelReadySent
658

659
        // addedToGraph is the opening state of a channel if the channel has
660
        // been successfully added to the graph immediately after the
661
        // channelReady message has been sent, but we still haven't announced
662
        // the channel to the network.
663
        addedToGraph
664
)
665

666
func (c channelOpeningState) String() string {
3✔
667
        switch c {
3✔
668
        case markedOpen:
3✔
669
                return "markedOpen"
3✔
670
        case channelReadySent:
3✔
671
                return "channelReadySent"
3✔
672
        case addedToGraph:
3✔
673
                return "addedToGraph"
3✔
674
        default:
×
675
                return "unknown"
×
676
        }
677
}
678

679
// NewFundingManager creates and initializes a new instance of the
680
// fundingManager.
681
func NewFundingManager(cfg Config) (*Manager, error) {
3✔
682
        return &Manager{
3✔
683
                cfg:       &cfg,
3✔
684
                chanIDKey: cfg.TempChanIDSeed,
3✔
685
                activeReservations: make(
3✔
686
                        map[serializedPubKey]pendingChannels,
3✔
687
                ),
3✔
688
                signedReservations: make(
3✔
689
                        map[lnwire.ChannelID][32]byte,
3✔
690
                ),
3✔
691
                fundingMsgs: make(
3✔
692
                        chan *fundingMsg, msgBufferSize,
3✔
693
                ),
3✔
694
                fundingRequests: make(
3✔
695
                        chan *InitFundingMsg, msgBufferSize,
3✔
696
                ),
3✔
697
                localDiscoverySignals: &lnutils.SyncMap[
3✔
698
                        lnwire.ChannelID, chan struct{},
3✔
699
                ]{},
3✔
700
                handleChannelReadyBarriers: &lnutils.SyncMap[
3✔
701
                        lnwire.ChannelID, struct{},
3✔
702
                ]{},
3✔
703
                pendingMusigNonces: make(
3✔
704
                        map[lnwire.ChannelID]*musig2.Nonces,
3✔
705
                ),
3✔
706
                quit: make(chan struct{}),
3✔
707
        }, nil
3✔
708
}
3✔
709

710
// Start launches all helper goroutines required for handling requests sent
711
// to the funding manager.
712
func (f *Manager) Start() error {
3✔
713
        var err error
3✔
714
        f.started.Do(func() {
6✔
715
                log.Info("Funding manager starting")
3✔
716
                err = f.start()
3✔
717
        })
3✔
718
        return err
3✔
719
}
720

721
func (f *Manager) start() error {
3✔
722
        // Upon restart, the Funding Manager will check the database to load any
3✔
723
        // channels that were  waiting for their funding transactions to be
3✔
724
        // confirmed on the blockchain at the time when the daemon last went
3✔
725
        // down.
3✔
726
        // TODO(roasbeef): store height that funding finished?
3✔
727
        //  * would then replace call below
3✔
728
        allChannels, err := f.cfg.ChannelDB.FetchAllChannels()
3✔
729
        if err != nil {
3✔
730
                return err
×
731
        }
×
732

733
        for _, channel := range allChannels {
6✔
734
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
3✔
735

3✔
736
                // For any channels that were in a pending state when the
3✔
737
                // daemon was last connected, the Funding Manager will
3✔
738
                // re-initialize the channel barriers, and republish the
3✔
739
                // funding transaction if we're the initiator.
3✔
740
                if channel.IsPending {
6✔
741
                        log.Tracef("Loading pending ChannelPoint(%v), "+
3✔
742
                                "creating chan barrier",
3✔
743
                                channel.FundingOutpoint)
3✔
744

3✔
745
                        f.localDiscoverySignals.Store(
3✔
746
                                chanID, make(chan struct{}),
3✔
747
                        )
3✔
748

3✔
749
                        // Rebroadcast the funding transaction for any pending
3✔
750
                        // channel that we initiated. No error will be returned
3✔
751
                        // if the transaction already has been broadcast.
3✔
752
                        chanType := channel.ChanType
3✔
753
                        if chanType.IsSingleFunder() &&
3✔
754
                                chanType.HasFundingTx() &&
3✔
755
                                channel.IsInitiator {
6✔
756

3✔
757
                                f.rebroadcastFundingTx(channel)
3✔
758
                        }
3✔
759
                } else if channel.ChanType.IsSingleFunder() &&
3✔
760
                        channel.ChanType.HasFundingTx() &&
3✔
761
                        channel.IsZeroConf() && channel.IsInitiator &&
3✔
762
                        !channel.ZeroConfConfirmed() {
3✔
UNCOV
763

×
UNCOV
764
                        // Rebroadcast the funding transaction for unconfirmed
×
UNCOV
765
                        // zero-conf channels if we have the funding tx and are
×
UNCOV
766
                        // also the initiator.
×
UNCOV
767
                        f.rebroadcastFundingTx(channel)
×
UNCOV
768
                }
×
769

770
                // We will restart the funding state machine for all channels,
771
                // which will wait for the channel's funding transaction to be
772
                // confirmed on the blockchain, and transmit the messages
773
                // necessary for the channel to be operational.
774
                f.wg.Add(1)
3✔
775
                go f.advanceFundingState(channel, chanID, nil)
3✔
776
        }
777

778
        f.wg.Add(1) // TODO(roasbeef): tune
3✔
779
        go f.reservationCoordinator()
3✔
780

3✔
781
        return nil
3✔
782
}
783

784
// Stop signals all helper goroutines to execute a graceful shutdown. This
785
// method will block until all goroutines have exited.
786
func (f *Manager) Stop() error {
3✔
787
        f.stopped.Do(func() {
6✔
788
                log.Info("Funding manager shutting down...")
3✔
789
                defer log.Debug("Funding manager shutdown complete")
3✔
790

3✔
791
                close(f.quit)
3✔
792
                f.wg.Wait()
3✔
793
        })
3✔
794

795
        return nil
3✔
796
}
797

798
// rebroadcastFundingTx publishes the funding tx on startup for each
799
// unconfirmed channel.
800
func (f *Manager) rebroadcastFundingTx(c *channeldb.OpenChannel) {
3✔
801
        var fundingTxBuf bytes.Buffer
3✔
802
        err := c.FundingTxn.Serialize(&fundingTxBuf)
3✔
803
        if err != nil {
3✔
804
                log.Errorf("Unable to serialize funding transaction %v: %v",
×
805
                        c.FundingTxn.TxHash(), err)
×
806

×
807
                // Clear the buffer of any bytes that were written before the
×
808
                // serialization error to prevent logging an incomplete
×
809
                // transaction.
×
810
                fundingTxBuf.Reset()
×
811
        } else {
3✔
812
                log.Debugf("Rebroadcasting funding tx for ChannelPoint(%v): "+
3✔
813
                        "%x", c.FundingOutpoint, fundingTxBuf.Bytes())
3✔
814
        }
3✔
815

816
        // Set a nil short channel ID at this stage because we do not know it
817
        // until our funding tx confirms.
818
        label := labels.MakeLabel(labels.LabelTypeChannelOpen, nil)
3✔
819

3✔
820
        err = f.cfg.PublishTransaction(c.FundingTxn, label)
3✔
821
        if err != nil {
3✔
822
                log.Errorf("Unable to rebroadcast funding tx %x for "+
×
823
                        "ChannelPoint(%v): %v", fundingTxBuf.Bytes(),
×
824
                        c.FundingOutpoint, err)
×
825
        }
×
826
}
827

828
// PendingChanID is a type that represents a pending channel ID. This might be
829
// selected by the caller, but if not, will be automatically selected.
830
type PendingChanID = [32]byte
831

832
// nextPendingChanID returns the next free pending channel ID to be used to
833
// identify a particular future channel funding workflow.
834
func (f *Manager) nextPendingChanID() PendingChanID {
3✔
835
        // Obtain a fresh nonce. We do this by encoding the incremented nonce.
3✔
836
        nextNonce := f.chanIDNonce.Add(1)
3✔
837

3✔
838
        var nonceBytes [8]byte
3✔
839
        binary.LittleEndian.PutUint64(nonceBytes[:], nextNonce)
3✔
840

3✔
841
        // We'll generate the next pending channelID by "encrypting" 32-bytes
3✔
842
        // of zeroes which'll extract 32 random bytes from our stream cipher.
3✔
843
        var (
3✔
844
                nextChanID PendingChanID
3✔
845
                zeroes     [32]byte
3✔
846
        )
3✔
847
        salsa20.XORKeyStream(
3✔
848
                nextChanID[:], zeroes[:], nonceBytes[:], &f.chanIDKey,
3✔
849
        )
3✔
850

3✔
851
        return nextChanID
3✔
852
}
3✔
853

854
// CancelPeerReservations cancels all active reservations associated with the
855
// passed node. This will ensure any outputs which have been pre committed,
856
// (and thus locked from coin selection), are properly freed.
857
func (f *Manager) CancelPeerReservations(nodePub [33]byte) {
3✔
858
        log.Debugf("Cancelling all reservations for peer %x", nodePub[:])
3✔
859

3✔
860
        f.resMtx.Lock()
3✔
861
        defer f.resMtx.Unlock()
3✔
862

3✔
863
        // We'll attempt to look up this node in the set of active
3✔
864
        // reservations.  If they don't have any, then there's no further work
3✔
865
        // to be done.
3✔
866
        nodeReservations, ok := f.activeReservations[nodePub]
3✔
867
        if !ok {
6✔
868
                log.Debugf("No active reservations for node: %x", nodePub[:])
3✔
869
                return
3✔
870
        }
3✔
871

872
        // If they do have any active reservations, then we'll cancel all of
873
        // them (which releases any locked UTXO's), and also delete it from the
874
        // reservation map.
875
        for pendingID, resCtx := range nodeReservations {
×
876
                if err := resCtx.reservation.Cancel(); err != nil {
×
877
                        log.Errorf("unable to cancel reservation for "+
×
878
                                "node=%x: %v", nodePub[:], err)
×
879
                }
×
880

881
                resCtx.err <- fmt.Errorf("peer disconnected")
×
882
                delete(nodeReservations, pendingID)
×
883
        }
884

885
        // Finally, we'll delete the node itself from the set of reservations.
886
        delete(f.activeReservations, nodePub)
×
887
}
888

889
// chanIdentifier wraps pending channel ID and channel ID into one struct so
890
// it's easier to identify a specific channel.
891
//
892
// TODO(yy): move to a different package to hide the private fields so direct
893
// access is disabled.
894
type chanIdentifier struct {
895
        // tempChanID is the pending channel ID created by the funder when
896
        // initializing the funding flow. For fundee, it's received from the
897
        // `open_channel` message.
898
        tempChanID lnwire.ChannelID
899

900
        // chanID is the channel ID created by the funder once the
901
        // `accept_channel` message is received. For fundee, it's received from
902
        // the `funding_created` message.
903
        chanID lnwire.ChannelID
904

905
        // chanIDSet is a boolean indicates whether the active channel ID is
906
        // set for this identifier. For zero conf channels, the `chanID` can be
907
        // all-zero, which is the same as the empty value of `ChannelID`. To
908
        // avoid the confusion, we use this boolean to explicitly signal
909
        // whether the `chanID` is set or not.
910
        chanIDSet bool
911
}
912

913
// newChanIdentifier creates a new chanIdentifier.
914
func newChanIdentifier(tempChanID lnwire.ChannelID) *chanIdentifier {
3✔
915
        return &chanIdentifier{
3✔
916
                tempChanID: tempChanID,
3✔
917
        }
3✔
918
}
3✔
919

920
// setChanID updates the `chanIdentifier` with the active channel ID.
921
func (c *chanIdentifier) setChanID(chanID lnwire.ChannelID) {
3✔
922
        c.chanID = chanID
3✔
923
        c.chanIDSet = true
3✔
924
}
3✔
925

926
// hasChanID returns true if the active channel ID has been set.
927
func (c *chanIdentifier) hasChanID() bool {
3✔
928
        return c.chanIDSet
3✔
929
}
3✔
930

931
// failFundingFlow will fail the active funding flow with the target peer,
932
// identified by its unique temporary channel ID. This method will send an
933
// error to the remote peer, and also remove the reservation from our set of
934
// pending reservations.
935
//
936
// TODO(roasbeef): if peer disconnects, and haven't yet broadcast funding
937
// transaction, then all reservations should be cleared.
938
func (f *Manager) failFundingFlow(peer lnpeer.Peer, cid *chanIdentifier,
939
        fundingErr error) {
3✔
940

3✔
941
        log.Debugf("Failing funding flow for pending_id=%v: %v",
3✔
942
                cid.tempChanID, fundingErr)
3✔
943

3✔
944
        // First, notify Brontide to remove the pending channel.
3✔
945
        //
3✔
946
        // NOTE: depending on where we fail the flow, we may not have the
3✔
947
        // active channel ID yet.
3✔
948
        if cid.hasChanID() {
6✔
949
                err := peer.RemovePendingChannel(cid.chanID)
3✔
950
                if err != nil {
3✔
951
                        log.Errorf("Unable to remove channel %v with peer %x: "+
×
952
                                "%v", cid,
×
953
                                peer.IdentityKey().SerializeCompressed(), err)
×
954
                }
×
955
        }
956

957
        ctx, err := f.cancelReservationCtx(
3✔
958
                peer.IdentityKey(), cid.tempChanID, false,
3✔
959
        )
3✔
960
        if err != nil {
6✔
961
                log.Errorf("unable to cancel reservation: %v", err)
3✔
962
        }
3✔
963

964
        // In case the case where the reservation existed, send the funding
965
        // error on the error channel.
966
        if ctx != nil {
6✔
967
                ctx.err <- fundingErr
3✔
968
        }
3✔
969

970
        // We only send the exact error if it is part of out whitelisted set of
971
        // errors (lnwire.FundingError or lnwallet.ReservationError).
972
        var msg lnwire.ErrorData
3✔
973
        switch e := fundingErr.(type) {
3✔
974
        // Let the actual error message be sent to the remote for the
975
        // whitelisted types.
976
        case lnwallet.ReservationError:
3✔
977
                msg = lnwire.ErrorData(e.Error())
3✔
978
        case lnwire.FundingError:
3✔
979
                msg = lnwire.ErrorData(e.Error())
3✔
980
        case chanacceptor.ChanAcceptError:
3✔
981
                msg = lnwire.ErrorData(e.Error())
3✔
982

983
        // For all other error types we just send a generic error.
984
        default:
3✔
985
                msg = lnwire.ErrorData("funding failed due to internal error")
3✔
986
        }
987

988
        errMsg := &lnwire.Error{
3✔
989
                ChanID: cid.tempChanID,
3✔
990
                Data:   msg,
3✔
991
        }
3✔
992

3✔
993
        log.Debugf("Sending funding error to peer (%x): %v",
3✔
994
                peer.IdentityKey().SerializeCompressed(), spew.Sdump(errMsg))
3✔
995
        if err := peer.SendMessage(false, errMsg); err != nil {
3✔
UNCOV
996
                log.Errorf("unable to send error message to peer %v", err)
×
UNCOV
997
        }
×
998
}
999

1000
// sendWarning sends a new warning message to the target peer, targeting the
1001
// specified cid with the passed funding error.
1002
func (f *Manager) sendWarning(peer lnpeer.Peer, cid *chanIdentifier,
1003
        fundingErr error) {
×
1004

×
1005
        msg := fundingErr.Error()
×
1006

×
1007
        errMsg := &lnwire.Warning{
×
1008
                ChanID: cid.tempChanID,
×
1009
                Data:   lnwire.WarningData(msg),
×
1010
        }
×
1011

×
1012
        log.Debugf("Sending funding warning to peer (%x): %v",
×
1013
                peer.IdentityKey().SerializeCompressed(),
×
1014
                spew.Sdump(errMsg),
×
1015
        )
×
1016

×
1017
        if err := peer.SendMessage(false, errMsg); err != nil {
×
1018
                log.Errorf("unable to send error message to peer %v", err)
×
1019
        }
×
1020
}
1021

1022
// reservationCoordinator is the primary goroutine tasked with progressing the
1023
// funding workflow between the wallet, and any outside peers or local callers.
1024
//
1025
// NOTE: This MUST be run as a goroutine.
1026
func (f *Manager) reservationCoordinator() {
3✔
1027
        defer f.wg.Done()
3✔
1028

3✔
1029
        zombieSweepTicker := time.NewTicker(f.cfg.ZombieSweeperInterval)
3✔
1030
        defer zombieSweepTicker.Stop()
3✔
1031

3✔
1032
        for {
6✔
1033
                select {
3✔
1034
                case fmsg := <-f.fundingMsgs:
3✔
1035
                        switch msg := fmsg.msg.(type) {
3✔
1036
                        case *lnwire.OpenChannel:
3✔
1037
                                f.fundeeProcessOpenChannel(fmsg.peer, msg)
3✔
1038

1039
                        case *lnwire.AcceptChannel:
3✔
1040
                                f.funderProcessAcceptChannel(fmsg.peer, msg)
3✔
1041

1042
                        case *lnwire.FundingCreated:
3✔
1043
                                f.fundeeProcessFundingCreated(fmsg.peer, msg)
3✔
1044

1045
                        case *lnwire.FundingSigned:
3✔
1046
                                f.funderProcessFundingSigned(fmsg.peer, msg)
3✔
1047

1048
                        case *lnwire.ChannelReady:
3✔
1049
                                f.wg.Add(1)
3✔
1050
                                go f.handleChannelReady(fmsg.peer, msg)
3✔
1051

UNCOV
1052
                        case *lnwire.Warning:
×
UNCOV
1053
                                f.handleWarningMsg(fmsg.peer, msg)
×
1054

1055
                        case *lnwire.Error:
3✔
1056
                                f.handleErrorMsg(fmsg.peer, msg)
3✔
1057
                        }
1058
                case req := <-f.fundingRequests:
3✔
1059
                        f.handleInitFundingMsg(req)
3✔
1060

1061
                case <-zombieSweepTicker.C:
3✔
1062
                        f.pruneZombieReservations()
3✔
1063

1064
                case <-f.quit:
3✔
1065
                        return
3✔
1066
                }
1067
        }
1068
}
1069

1070
// advanceFundingState will advance the channel through the steps after the
1071
// funding transaction is broadcasted, up until the point where the channel is
1072
// ready for operation. This includes waiting for the funding transaction to
1073
// confirm, sending channel_ready to the peer, adding the channel to the graph,
1074
// and announcing the channel. The updateChan can be set non-nil to get
1075
// OpenStatusUpdates.
1076
//
1077
// NOTE: This MUST be run as a goroutine.
1078
func (f *Manager) advanceFundingState(channel *channeldb.OpenChannel,
1079
        pendingChanID PendingChanID,
1080
        updateChan chan<- *lnrpc.OpenStatusUpdate) {
3✔
1081

3✔
1082
        defer f.wg.Done()
3✔
1083

3✔
1084
        // If the channel is still pending we must wait for the funding
3✔
1085
        // transaction to confirm.
3✔
1086
        if channel.IsPending {
6✔
1087
                err := f.advancePendingChannelState(channel, pendingChanID)
3✔
1088
                if err != nil {
6✔
1089
                        log.Errorf("Unable to advance pending state of "+
3✔
1090
                                "ChannelPoint(%v): %v",
3✔
1091
                                channel.FundingOutpoint, err)
3✔
1092
                        return
3✔
1093
                }
3✔
1094
        }
1095

1096
        var chanOpts []lnwallet.ChannelOpt
3✔
1097
        f.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
3✔
UNCOV
1098
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
UNCOV
1099
        })
×
1100
        f.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
3✔
UNCOV
1101
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
UNCOV
1102
        })
×
1103
        f.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
3✔
1104
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
1105
        })
×
1106

1107
        // We create the state-machine object which wraps the database state.
1108
        lnChannel, err := lnwallet.NewLightningChannel(
3✔
1109
                nil, channel, nil, chanOpts...,
3✔
1110
        )
3✔
1111
        if err != nil {
3✔
1112
                log.Errorf("Unable to create LightningChannel(%v): %v",
×
1113
                        channel.FundingOutpoint, err)
×
1114
                return
×
1115
        }
×
1116

1117
        for {
6✔
1118
                channelState, shortChanID, err := f.getChannelOpeningState(
3✔
1119
                        &channel.FundingOutpoint,
3✔
1120
                )
3✔
1121
                if err == channeldb.ErrChannelNotFound {
6✔
1122
                        // Channel not in fundingManager's opening database,
3✔
1123
                        // meaning it was successfully announced to the
3✔
1124
                        // network.
3✔
1125
                        // TODO(halseth): could do graph consistency check
3✔
1126
                        // here, and re-add the edge if missing.
3✔
1127
                        log.Debugf("ChannelPoint(%v) with chan_id=%x not "+
3✔
1128
                                "found in opening database, assuming already "+
3✔
1129
                                "announced to the network",
3✔
1130
                                channel.FundingOutpoint, pendingChanID)
3✔
1131
                        return
3✔
1132
                } else if err != nil {
6✔
1133
                        log.Errorf("Unable to query database for "+
×
1134
                                "channel opening state(%v): %v",
×
1135
                                channel.FundingOutpoint, err)
×
1136
                        return
×
1137
                }
×
1138

1139
                // If we did find the channel in the opening state database, we
1140
                // have seen the funding transaction being confirmed, but there
1141
                // are still steps left of the setup procedure. We continue the
1142
                // procedure where we left off.
1143
                err = f.stateStep(
3✔
1144
                        channel, lnChannel, shortChanID, pendingChanID,
3✔
1145
                        channelState, updateChan,
3✔
1146
                )
3✔
1147
                if err != nil {
6✔
1148
                        log.Errorf("Unable to advance state(%v): %v",
3✔
1149
                                channel.FundingOutpoint, err)
3✔
1150
                        return
3✔
1151
                }
3✔
1152
        }
1153
}
1154

1155
// stateStep advances the confirmed channel one step in the funding state
1156
// machine. This method is synchronous and the new channel opening state will
1157
// have been written to the database when it successfully returns. The
1158
// updateChan can be set non-nil to get OpenStatusUpdates.
1159
func (f *Manager) stateStep(channel *channeldb.OpenChannel,
1160
        lnChannel *lnwallet.LightningChannel,
1161
        shortChanID *lnwire.ShortChannelID, pendingChanID PendingChanID,
1162
        channelState channelOpeningState,
1163
        updateChan chan<- *lnrpc.OpenStatusUpdate) error {
3✔
1164

3✔
1165
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
3✔
1166
        log.Debugf("Channel(%v) with ShortChanID %v has opening state %v",
3✔
1167
                chanID, shortChanID, channelState)
3✔
1168

3✔
1169
        switch channelState {
3✔
1170
        // The funding transaction was confirmed, but we did not successfully
1171
        // send the channelReady message to the peer, so let's do that now.
1172
        case markedOpen:
3✔
1173
                err := f.sendChannelReady(channel, lnChannel)
3✔
1174
                if err != nil {
3✔
UNCOV
1175
                        return fmt.Errorf("failed sending channelReady: %w",
×
UNCOV
1176
                                err)
×
UNCOV
1177
                }
×
1178

1179
                // As the channelReady message is now sent to the peer, the
1180
                // channel is moved to the next state of the state machine. It
1181
                // will be moved to the last state (actually deleted from the
1182
                // database) after the channel is finally announced.
1183
                err = f.saveChannelOpeningState(
3✔
1184
                        &channel.FundingOutpoint, channelReadySent,
3✔
1185
                        shortChanID,
3✔
1186
                )
3✔
1187
                if err != nil {
3✔
1188
                        return fmt.Errorf("error setting channel state to"+
×
1189
                                " channelReadySent: %w", err)
×
1190
                }
×
1191

1192
                log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
3✔
1193
                        "sent ChannelReady", chanID, shortChanID)
3✔
1194

3✔
1195
                return nil
3✔
1196

1197
        // channelReady was sent to peer, but the channel was not added to the
1198
        // graph and the channel announcement was not sent.
1199
        case channelReadySent:
3✔
1200
                // We must wait until we've received the peer's channel_ready
3✔
1201
                // before sending a channel_update according to BOLT#07.
3✔
1202
                received, err := f.receivedChannelReady(
3✔
1203
                        channel.IdentityPub, chanID,
3✔
1204
                )
3✔
1205
                if err != nil {
3✔
1206
                        return fmt.Errorf("failed to check if channel_ready "+
×
1207
                                "was received: %v", err)
×
1208
                }
×
1209

1210
                if !received {
6✔
1211
                        // We haven't received ChannelReady, so we'll continue
3✔
1212
                        // to the next iteration of the loop after sleeping for
3✔
1213
                        // checkPeerChannelReadyInterval.
3✔
1214
                        select {
3✔
1215
                        case <-time.After(checkPeerChannelReadyInterval):
3✔
UNCOV
1216
                        case <-f.quit:
×
UNCOV
1217
                                return ErrFundingManagerShuttingDown
×
1218
                        }
1219

1220
                        return nil
3✔
1221
                }
1222

1223
                return f.handleChannelReadyReceived(
3✔
1224
                        channel, shortChanID, pendingChanID, updateChan,
3✔
1225
                )
3✔
1226

1227
        // The channel was added to the Router's topology, but the channel
1228
        // announcement was not sent.
1229
        case addedToGraph:
3✔
1230
                if channel.IsZeroConf() {
6✔
1231
                        // If this is a zero-conf channel, then we will wait
3✔
1232
                        // for it to be confirmed before announcing it to the
3✔
1233
                        // greater network.
3✔
1234
                        err := f.waitForZeroConfChannel(channel)
3✔
1235
                        if err != nil {
6✔
1236
                                return fmt.Errorf("failed waiting for zero "+
3✔
1237
                                        "channel: %v", err)
3✔
1238
                        }
3✔
1239

1240
                        // Update the local shortChanID variable such that
1241
                        // annAfterSixConfs uses the confirmed SCID.
1242
                        confirmedScid := channel.ZeroConfRealScid()
3✔
1243
                        shortChanID = &confirmedScid
3✔
1244
                }
1245

1246
                err := f.annAfterSixConfs(channel, shortChanID)
3✔
1247
                if err != nil {
6✔
1248
                        return fmt.Errorf("error sending channel "+
3✔
1249
                                "announcement: %v", err)
3✔
1250
                }
3✔
1251

1252
                // We delete the channel opening state from our internal
1253
                // database as the opening process has succeeded. We can do
1254
                // this because we assume the AuthenticatedGossiper queues the
1255
                // announcement messages, and persists them in case of a daemon
1256
                // shutdown.
1257
                err = f.deleteChannelOpeningState(&channel.FundingOutpoint)
3✔
1258
                if err != nil {
3✔
1259
                        return fmt.Errorf("error deleting channel state: %w",
×
1260
                                err)
×
1261
                }
×
1262

1263
                // After the fee parameters have been stored in the
1264
                // announcement we can delete them from the database. For
1265
                // private channels we do not announce the channel policy to
1266
                // the network but still need to delete them from the database.
1267
                err = f.deleteInitialForwardingPolicy(chanID)
3✔
1268
                if err != nil {
3✔
1269
                        log.Infof("Could not delete initial policy for chanId "+
×
1270
                                "%x", chanID)
×
1271
                }
×
1272

1273
                log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
3✔
1274
                        "announced", chanID, shortChanID)
3✔
1275

3✔
1276
                return nil
3✔
1277
        }
1278

1279
        return fmt.Errorf("undefined channelState: %v", channelState)
×
1280
}
1281

1282
// advancePendingChannelState waits for a pending channel's funding tx to
1283
// confirm, and marks it open in the database when that happens.
1284
func (f *Manager) advancePendingChannelState(channel *channeldb.OpenChannel,
1285
        pendingChanID PendingChanID) error {
3✔
1286

3✔
1287
        if channel.IsZeroConf() {
6✔
1288
                // Persist the alias to the alias database.
3✔
1289
                baseScid := channel.ShortChannelID
3✔
1290
                err := f.cfg.AliasManager.AddLocalAlias(
3✔
1291
                        baseScid, baseScid, true, false,
3✔
1292
                )
3✔
1293
                if err != nil {
3✔
1294
                        return fmt.Errorf("error adding local alias to "+
×
1295
                                "store: %v", err)
×
1296
                }
×
1297

1298
                // We don't wait for zero-conf channels to be confirmed and
1299
                // instead immediately proceed with the rest of the funding
1300
                // flow. The channel opening state is stored under the alias
1301
                // SCID.
1302
                err = f.saveChannelOpeningState(
3✔
1303
                        &channel.FundingOutpoint, markedOpen,
3✔
1304
                        &channel.ShortChannelID,
3✔
1305
                )
3✔
1306
                if err != nil {
3✔
1307
                        return fmt.Errorf("error setting zero-conf channel "+
×
1308
                                "state to markedOpen: %v", err)
×
1309
                }
×
1310

1311
                // The ShortChannelID is already set since it's an alias, but
1312
                // we still need to mark the channel as no longer pending.
1313
                err = channel.MarkAsOpen(channel.ShortChannelID)
3✔
1314
                if err != nil {
3✔
1315
                        return fmt.Errorf("error setting zero-conf channel's "+
×
1316
                                "pending flag to false: %v", err)
×
1317
                }
×
1318

1319
                // Inform the ChannelNotifier that the channel has transitioned
1320
                // from pending open to open.
1321
                if err := f.cfg.NotifyOpenChannelEvent(
3✔
1322
                        channel.FundingOutpoint, channel.IdentityPub,
3✔
1323
                ); err != nil {
3✔
NEW
1324
                        log.Errorf("Unable to notify open channel event for "+
×
NEW
1325
                                "ChannelPoint(%v): %v",
×
NEW
1326
                                channel.FundingOutpoint, err)
×
NEW
1327
                }
×
1328

1329
                // Find and close the discoverySignal for this channel such
1330
                // that ChannelReady messages will be processed.
1331
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
3✔
1332
                discoverySignal, ok := f.localDiscoverySignals.Load(chanID)
3✔
1333
                if ok {
6✔
1334
                        close(discoverySignal)
3✔
1335
                }
3✔
1336

1337
                return nil
3✔
1338
        }
1339

1340
        confChannel, err := f.waitForFundingWithTimeout(channel)
3✔
1341
        if err == ErrConfirmationTimeout {
3✔
UNCOV
1342
                return f.fundingTimeout(channel, pendingChanID)
×
1343
        } else if err != nil {
6✔
1344
                return fmt.Errorf("error waiting for funding "+
3✔
1345
                        "confirmation for ChannelPoint(%v): %v",
3✔
1346
                        channel.FundingOutpoint, err)
3✔
1347
        }
3✔
1348

1349
        if blockchain.IsCoinBaseTx(confChannel.fundingTx) {
3✔
UNCOV
1350
                // If it's a coinbase transaction, we need to wait for it to
×
UNCOV
1351
                // mature. We wait out an additional MinAcceptDepth on top of
×
UNCOV
1352
                // the coinbase maturity as an extra margin of safety.
×
UNCOV
1353
                maturity := f.cfg.Wallet.Cfg.NetParams.CoinbaseMaturity
×
UNCOV
1354
                numCoinbaseConfs := uint32(maturity)
×
UNCOV
1355

×
UNCOV
1356
                if channel.NumConfsRequired > maturity {
×
1357
                        numCoinbaseConfs = uint32(channel.NumConfsRequired)
×
1358
                }
×
1359

UNCOV
1360
                txid := &channel.FundingOutpoint.Hash
×
UNCOV
1361
                fundingScript, err := makeFundingScript(channel)
×
UNCOV
1362
                if err != nil {
×
1363
                        log.Errorf("unable to create funding script for "+
×
1364
                                "ChannelPoint(%v): %v",
×
1365
                                channel.FundingOutpoint, err)
×
1366

×
1367
                        return err
×
1368
                }
×
1369

UNCOV
1370
                confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
×
UNCOV
1371
                        txid, fundingScript, numCoinbaseConfs,
×
UNCOV
1372
                        channel.BroadcastHeight(),
×
UNCOV
1373
                )
×
UNCOV
1374
                if err != nil {
×
1375
                        log.Errorf("Unable to register for confirmation of "+
×
1376
                                "ChannelPoint(%v): %v",
×
1377
                                channel.FundingOutpoint, err)
×
1378

×
1379
                        return err
×
1380
                }
×
1381

UNCOV
1382
                select {
×
UNCOV
1383
                case _, ok := <-confNtfn.Confirmed:
×
UNCOV
1384
                        if !ok {
×
1385
                                return fmt.Errorf("ChainNotifier shutting "+
×
1386
                                        "down, can't complete funding flow "+
×
1387
                                        "for ChannelPoint(%v)",
×
1388
                                        channel.FundingOutpoint)
×
1389
                        }
×
1390

1391
                case <-f.quit:
×
1392
                        return ErrFundingManagerShuttingDown
×
1393
                }
1394
        }
1395

1396
        // Success, funding transaction was confirmed.
1397
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
3✔
1398
        log.Debugf("ChannelID(%v) is now fully confirmed! "+
3✔
1399
                "(shortChanID=%v)", chanID, confChannel.shortChanID)
3✔
1400

3✔
1401
        err = f.handleFundingConfirmation(channel, confChannel)
3✔
1402
        if err != nil {
3✔
1403
                return fmt.Errorf("unable to handle funding "+
×
1404
                        "confirmation for ChannelPoint(%v): %v",
×
1405
                        channel.FundingOutpoint, err)
×
1406
        }
×
1407

1408
        return nil
3✔
1409
}
1410

1411
// ProcessFundingMsg sends a message to the internal fundingManager goroutine,
1412
// allowing it to handle the lnwire.Message.
1413
func (f *Manager) ProcessFundingMsg(msg lnwire.Message, peer lnpeer.Peer) {
3✔
1414
        select {
3✔
1415
        case f.fundingMsgs <- &fundingMsg{msg, peer}:
3✔
1416
        case <-f.quit:
×
1417
                return
×
1418
        }
1419
}
1420

1421
// fundeeProcessOpenChannel creates an initial 'ChannelReservation' within the
1422
// wallet, then responds to the source peer with an accept channel message
1423
// progressing the funding workflow.
1424
//
1425
// TODO(roasbeef): add error chan to all, let channelManager handle
1426
// error+propagate.
1427
//
1428
//nolint:funlen
1429
func (f *Manager) fundeeProcessOpenChannel(peer lnpeer.Peer,
1430
        msg *lnwire.OpenChannel) {
3✔
1431

3✔
1432
        // Check number of pending channels to be smaller than maximum allowed
3✔
1433
        // number and send ErrorGeneric to remote peer if condition is
3✔
1434
        // violated.
3✔
1435
        peerPubKey := peer.IdentityKey()
3✔
1436
        peerIDKey := newSerializedKey(peerPubKey)
3✔
1437

3✔
1438
        amt := msg.FundingAmount
3✔
1439

3✔
1440
        // We get all pending channels for this peer. This is the list of the
3✔
1441
        // active reservations and the channels pending open in the database.
3✔
1442
        f.resMtx.RLock()
3✔
1443
        reservations := f.activeReservations[peerIDKey]
3✔
1444

3✔
1445
        // We don't count reservations that were created from a canned funding
3✔
1446
        // shim. The user has registered the shim and therefore expects this
3✔
1447
        // channel to arrive.
3✔
1448
        numPending := 0
3✔
1449
        for _, res := range reservations {
3✔
UNCOV
1450
                if !res.reservation.IsCannedShim() {
×
UNCOV
1451
                        numPending++
×
UNCOV
1452
                }
×
1453
        }
1454
        f.resMtx.RUnlock()
3✔
1455

3✔
1456
        // Create the channel identifier.
3✔
1457
        cid := newChanIdentifier(msg.PendingChannelID)
3✔
1458

3✔
1459
        // Also count the channels that are already pending. There we don't know
3✔
1460
        // the underlying intent anymore, unfortunately.
3✔
1461
        channels, err := f.cfg.ChannelDB.FetchOpenChannels(peerPubKey)
3✔
1462
        if err != nil {
3✔
1463
                f.failFundingFlow(peer, cid, err)
×
1464
                return
×
1465
        }
×
1466

1467
        for _, c := range channels {
6✔
1468
                // Pending channels that have a non-zero thaw height were also
3✔
1469
                // created through a canned funding shim. Those also don't
3✔
1470
                // count towards the DoS protection limit.
3✔
1471
                //
3✔
1472
                // TODO(guggero): Properly store the funding type (wallet, shim,
3✔
1473
                // PSBT) on the channel so we don't need to use the thaw height.
3✔
1474
                if c.IsPending && c.ThawHeight == 0 {
6✔
1475
                        numPending++
3✔
1476
                }
3✔
1477
        }
1478

1479
        // TODO(roasbeef): modify to only accept a _single_ pending channel per
1480
        // block unless white listed
1481
        if numPending >= f.cfg.MaxPendingChannels {
6✔
1482
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
3✔
1483

3✔
1484
                return
3✔
1485
        }
3✔
1486

1487
        // Ensure that the pendingChansLimit is respected.
1488
        pendingChans, err := f.cfg.ChannelDB.FetchPendingChannels()
3✔
1489
        if err != nil {
3✔
1490
                f.failFundingFlow(peer, cid, err)
×
1491
                return
×
1492
        }
×
1493

1494
        if len(pendingChans) > pendingChansLimit {
3✔
1495
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
×
1496
                return
×
1497
        }
×
1498

1499
        // We'll also reject any requests to create channels until we're fully
1500
        // synced to the network as we won't be able to properly validate the
1501
        // confirmation of the funding transaction.
1502
        isSynced, _, err := f.cfg.Wallet.IsSynced()
3✔
1503
        if err != nil || !isSynced {
3✔
1504
                if err != nil {
×
1505
                        log.Errorf("unable to query wallet: %v", err)
×
1506
                }
×
1507
                err := errors.New("Synchronizing blockchain")
×
1508
                f.failFundingFlow(peer, cid, err)
×
1509
                return
×
1510
        }
1511

1512
        // Ensure that the remote party respects our maximum channel size.
1513
        if amt > f.cfg.MaxChanSize {
6✔
1514
                f.failFundingFlow(
3✔
1515
                        peer, cid,
3✔
1516
                        lnwallet.ErrChanTooLarge(amt, f.cfg.MaxChanSize),
3✔
1517
                )
3✔
1518
                return
3✔
1519
        }
3✔
1520

1521
        // We'll, also ensure that the remote party isn't attempting to propose
1522
        // a channel that's below our current min channel size.
1523
        if amt < f.cfg.MinChanSize {
6✔
1524
                f.failFundingFlow(
3✔
1525
                        peer, cid,
3✔
1526
                        lnwallet.ErrChanTooSmall(amt, f.cfg.MinChanSize),
3✔
1527
                )
3✔
1528
                return
3✔
1529
        }
3✔
1530

1531
        // If request specifies non-zero push amount and 'rejectpush' is set,
1532
        // signal an error.
1533
        if f.cfg.RejectPush && msg.PushAmount > 0 {
3✔
UNCOV
1534
                f.failFundingFlow(peer, cid, lnwallet.ErrNonZeroPushAmount())
×
UNCOV
1535
                return
×
UNCOV
1536
        }
×
1537

1538
        // Send the OpenChannel request to the ChannelAcceptor to determine
1539
        // whether this node will accept the channel.
1540
        chanReq := &chanacceptor.ChannelAcceptRequest{
3✔
1541
                Node:        peer.IdentityKey(),
3✔
1542
                OpenChanMsg: msg,
3✔
1543
        }
3✔
1544

3✔
1545
        // Query our channel acceptor to determine whether we should reject
3✔
1546
        // the channel.
3✔
1547
        acceptorResp := f.cfg.OpenChannelPredicate.Accept(chanReq)
3✔
1548
        if acceptorResp.RejectChannel() {
6✔
1549
                f.failFundingFlow(peer, cid, acceptorResp.ChanAcceptError)
3✔
1550
                return
3✔
1551
        }
3✔
1552

1553
        log.Infof("Recv'd fundingRequest(amt=%v, push=%v, delay=%v, "+
3✔
1554
                "pendingId=%x) from peer(%x)", amt, msg.PushAmount,
3✔
1555
                msg.CsvDelay, msg.PendingChannelID,
3✔
1556
                peer.IdentityKey().SerializeCompressed())
3✔
1557

3✔
1558
        // Attempt to initialize a reservation within the wallet. If the wallet
3✔
1559
        // has insufficient resources to create the channel, then the
3✔
1560
        // reservation attempt may be rejected. Note that since we're on the
3✔
1561
        // responding side of a single funder workflow, we don't commit any
3✔
1562
        // funds to the channel ourselves.
3✔
1563
        //
3✔
1564
        // Before we init the channel, we'll also check to see what commitment
3✔
1565
        // format we can use with this peer. This is dependent on *both* us and
3✔
1566
        // the remote peer are signaling the proper feature bit if we're using
3✔
1567
        // implicit negotiation, and simply the channel type sent over if we're
3✔
1568
        // using explicit negotiation.
3✔
1569
        chanType, commitType, err := negotiateCommitmentType(
3✔
1570
                msg.ChannelType, peer.LocalFeatures(), peer.RemoteFeatures(),
3✔
1571
        )
3✔
1572
        if err != nil {
3✔
1573
                // TODO(roasbeef): should be using soft errors
×
1574
                log.Errorf("channel type negotiation failed: %v", err)
×
1575
                f.failFundingFlow(peer, cid, err)
×
1576
                return
×
1577
        }
×
1578

1579
        var scidFeatureVal bool
3✔
1580
        if hasFeatures(
3✔
1581
                peer.LocalFeatures(), peer.RemoteFeatures(),
3✔
1582
                lnwire.ScidAliasOptional,
3✔
1583
        ) {
6✔
1584

3✔
1585
                scidFeatureVal = true
3✔
1586
        }
3✔
1587

1588
        var (
3✔
1589
                zeroConf bool
3✔
1590
                scid     bool
3✔
1591
        )
3✔
1592

3✔
1593
        // Only echo back a channel type in AcceptChannel if we actually used
3✔
1594
        // explicit negotiation above.
3✔
1595
        if chanType != nil {
6✔
1596
                // Check if the channel type includes the zero-conf or
3✔
1597
                // scid-alias bits.
3✔
1598
                featureVec := lnwire.RawFeatureVector(*chanType)
3✔
1599
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
3✔
1600
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
3✔
1601

3✔
1602
                // If the zero-conf channel type was negotiated, ensure that
3✔
1603
                // the acceptor allows it.
3✔
1604
                if zeroConf && !acceptorResp.ZeroConf {
3✔
1605
                        // Fail the funding flow.
×
1606
                        flowErr := fmt.Errorf("channel acceptor blocked " +
×
1607
                                "zero-conf channel negotiation")
×
1608
                        log.Errorf("Cancelling funding flow for %v based on "+
×
1609
                                "channel acceptor response: %v", cid, flowErr)
×
1610
                        f.failFundingFlow(peer, cid, flowErr)
×
1611
                        return
×
1612
                }
×
1613

1614
                // If the zero-conf channel type wasn't negotiated and the
1615
                // fundee still wants a zero-conf channel, perform more checks.
1616
                // Require that both sides have the scid-alias feature bit set.
1617
                // We don't require anchors here - this is for compatibility
1618
                // with LDK.
1619
                if !zeroConf && acceptorResp.ZeroConf {
3✔
1620
                        if !scidFeatureVal {
×
1621
                                // Fail the funding flow.
×
1622
                                flowErr := fmt.Errorf("scid-alias feature " +
×
1623
                                        "must be negotiated for zero-conf")
×
1624
                                log.Errorf("Cancelling funding flow for "+
×
1625
                                        "zero-conf channel %v: %v", cid,
×
1626
                                        flowErr)
×
1627
                                f.failFundingFlow(peer, cid, flowErr)
×
1628
                                return
×
1629
                        }
×
1630

1631
                        // Set zeroConf to true to enable the zero-conf flow.
1632
                        zeroConf = true
×
1633
                }
1634
        }
1635

1636
        public := msg.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
1637
        switch {
3✔
1638
        // Sending the option-scid-alias channel type for a public channel is
1639
        // disallowed.
1640
        case public && scid:
×
1641
                err = fmt.Errorf("option-scid-alias chantype for public " +
×
1642
                        "channel")
×
1643
                log.Errorf("Cancelling funding flow for public channel %v "+
×
1644
                        "with scid-alias: %v", cid, err)
×
1645
                f.failFundingFlow(peer, cid, err)
×
1646

×
1647
                return
×
1648

1649
        // The current variant of taproot channels can only be used with
1650
        // unadvertised channels for now.
1651
        case commitType.IsTaproot() && public:
×
1652
                err = fmt.Errorf("taproot channel type for public channel")
×
1653
                log.Errorf("Cancelling funding flow for public taproot "+
×
1654
                        "channel %v: %v", cid, err)
×
1655
                f.failFundingFlow(peer, cid, err)
×
1656

×
1657
                return
×
1658
        }
1659

1660
        // At this point, if we have an AuxFundingController active, we'll
1661
        // check to see if we have a special tapscript root to use in our
1662
        // MuSig funding output.
1663
        tapscriptRoot, err := fn.MapOptionZ(
3✔
1664
                f.cfg.AuxFundingController,
3✔
1665
                func(c AuxFundingController) AuxTapscriptResult {
3✔
1666
                        return c.DeriveTapscriptRoot(msg.PendingChannelID)
×
1667
                },
×
1668
        ).Unpack()
1669
        if err != nil {
3✔
1670
                err = fmt.Errorf("error deriving tapscript root: %w", err)
×
1671
                log.Error(err)
×
1672
                f.failFundingFlow(peer, cid, err)
×
1673

×
1674
                return
×
1675
        }
×
1676

1677
        req := &lnwallet.InitFundingReserveMsg{
3✔
1678
                ChainHash:        &msg.ChainHash,
3✔
1679
                PendingChanID:    msg.PendingChannelID,
3✔
1680
                NodeID:           peer.IdentityKey(),
3✔
1681
                NodeAddr:         peer.Address(),
3✔
1682
                LocalFundingAmt:  0,
3✔
1683
                RemoteFundingAmt: amt,
3✔
1684
                CommitFeePerKw:   chainfee.SatPerKWeight(msg.FeePerKiloWeight),
3✔
1685
                FundingFeePerKw:  0,
3✔
1686
                PushMSat:         msg.PushAmount,
3✔
1687
                Flags:            msg.ChannelFlags,
3✔
1688
                MinConfs:         1,
3✔
1689
                CommitType:       commitType,
3✔
1690
                ZeroConf:         zeroConf,
3✔
1691
                OptionScidAlias:  scid,
3✔
1692
                ScidAliasFeature: scidFeatureVal,
3✔
1693
                TapscriptRoot:    tapscriptRoot,
3✔
1694
        }
3✔
1695

3✔
1696
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
3✔
1697
        if err != nil {
3✔
1698
                log.Errorf("Unable to initialize reservation: %v", err)
×
1699
                f.failFundingFlow(peer, cid, err)
×
1700
                return
×
1701
        }
×
1702

1703
        log.Debugf("Initialized channel reservation: zeroConf=%v, psbt=%v, "+
3✔
1704
                "cannedShim=%v", reservation.IsZeroConf(),
3✔
1705
                reservation.IsPsbt(), reservation.IsCannedShim())
3✔
1706

3✔
1707
        if zeroConf {
6✔
1708
                // Store an alias for zero-conf channels. Other option-scid
3✔
1709
                // channels will do this at a later point.
3✔
1710
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
3✔
1711
                if err != nil {
3✔
1712
                        log.Errorf("Unable to request alias: %v", err)
×
1713
                        f.failFundingFlow(peer, cid, err)
×
1714
                        return
×
1715
                }
×
1716

1717
                reservation.AddAlias(aliasScid)
3✔
1718
        }
1719

1720
        // As we're the responder, we get to specify the number of confirmations
1721
        // that we require before both of us consider the channel open. We'll
1722
        // use our mapping to derive the proper number of confirmations based on
1723
        // the amount of the channel, and also if any funds are being pushed to
1724
        // us. If a depth value was set by our channel acceptor, we will use
1725
        // that value instead.
1726
        numConfsReq := f.cfg.NumRequiredConfs(msg.FundingAmount, msg.PushAmount)
3✔
1727
        if acceptorResp.MinAcceptDepth != 0 {
3✔
1728
                numConfsReq = acceptorResp.MinAcceptDepth
×
1729
        }
×
1730

1731
        // We'll ignore the min_depth calculated above if this is a zero-conf
1732
        // channel.
1733
        if zeroConf {
6✔
1734
                numConfsReq = 0
3✔
1735
        }
3✔
1736

1737
        reservation.SetNumConfsRequired(numConfsReq)
3✔
1738

3✔
1739
        // We'll also validate and apply all the constraints the initiating
3✔
1740
        // party is attempting to dictate for our commitment transaction.
3✔
1741
        stateBounds := &channeldb.ChannelStateBounds{
3✔
1742
                ChanReserve:      msg.ChannelReserve,
3✔
1743
                MaxPendingAmount: msg.MaxValueInFlight,
3✔
1744
                MinHTLC:          msg.HtlcMinimum,
3✔
1745
                MaxAcceptedHtlcs: msg.MaxAcceptedHTLCs,
3✔
1746
        }
3✔
1747
        commitParams := &channeldb.CommitmentParams{
3✔
1748
                DustLimit: msg.DustLimit,
3✔
1749
                CsvDelay:  msg.CsvDelay,
3✔
1750
        }
3✔
1751
        err = reservation.CommitConstraints(
3✔
1752
                stateBounds, commitParams, f.cfg.MaxLocalCSVDelay, true,
3✔
1753
        )
3✔
1754
        if err != nil {
3✔
UNCOV
1755
                log.Errorf("Unacceptable channel constraints: %v", err)
×
UNCOV
1756
                f.failFundingFlow(peer, cid, err)
×
UNCOV
1757
                return
×
UNCOV
1758
        }
×
1759

1760
        // Check whether the peer supports upfront shutdown, and get a new
1761
        // wallet address if our node is configured to set shutdown addresses by
1762
        // default. We use the upfront shutdown script provided by our channel
1763
        // acceptor (if any) in lieu of user input.
1764
        shutdown, err := getUpfrontShutdownScript(
3✔
1765
                f.cfg.EnableUpfrontShutdown, peer, acceptorResp.UpfrontShutdown,
3✔
1766
                f.selectShutdownScript,
3✔
1767
        )
3✔
1768
        if err != nil {
3✔
1769
                f.failFundingFlow(
×
1770
                        peer, cid,
×
1771
                        fmt.Errorf("getUpfrontShutdownScript error: %w", err),
×
1772
                )
×
1773
                return
×
1774
        }
×
1775
        reservation.SetOurUpfrontShutdown(shutdown)
3✔
1776

3✔
1777
        // If a script enforced channel lease is being proposed, we'll need to
3✔
1778
        // validate its custom TLV records.
3✔
1779
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
6✔
1780
                if msg.LeaseExpiry == nil {
3✔
1781
                        err := errors.New("missing lease expiry")
×
1782
                        f.failFundingFlow(peer, cid, err)
×
1783
                        return
×
1784
                }
×
1785

1786
                // If we had a shim registered for this channel prior to
1787
                // receiving its corresponding OpenChannel message, then we'll
1788
                // validate the proposed LeaseExpiry against what was registered
1789
                // in our shim.
1790
                if reservation.LeaseExpiry() != 0 {
6✔
1791
                        if uint32(*msg.LeaseExpiry) !=
3✔
1792
                                reservation.LeaseExpiry() {
3✔
1793

×
1794
                                err := errors.New("lease expiry mismatch")
×
1795
                                f.failFundingFlow(peer, cid, err)
×
1796
                                return
×
1797
                        }
×
1798
                }
1799
        }
1800

1801
        log.Infof("Requiring %v confirmations for pendingChan(%x): "+
3✔
1802
                "amt=%v, push_amt=%v, committype=%v, upfrontShutdown=%x",
3✔
1803
                numConfsReq, msg.PendingChannelID, amt, msg.PushAmount,
3✔
1804
                commitType, msg.UpfrontShutdownScript)
3✔
1805

3✔
1806
        // Generate our required constraints for the remote party, using the
3✔
1807
        // values provided by the channel acceptor if they are non-zero.
3✔
1808
        remoteCsvDelay := f.cfg.RequiredRemoteDelay(amt)
3✔
1809
        if acceptorResp.CSVDelay != 0 {
3✔
1810
                remoteCsvDelay = acceptorResp.CSVDelay
×
1811
        }
×
1812

1813
        // If our default dust limit was above their ChannelReserve, we change
1814
        // it to the ChannelReserve. We must make sure the ChannelReserve we
1815
        // send in the AcceptChannel message is above both dust limits.
1816
        // Therefore, take the maximum of msg.DustLimit and our dust limit.
1817
        //
1818
        // NOTE: Even with this bounding, the ChannelAcceptor may return an
1819
        // BOLT#02-invalid ChannelReserve.
1820
        maxDustLimit := reservation.OurContribution().DustLimit
3✔
1821
        if msg.DustLimit > maxDustLimit {
3✔
1822
                maxDustLimit = msg.DustLimit
×
1823
        }
×
1824

1825
        chanReserve := f.cfg.RequiredRemoteChanReserve(amt, maxDustLimit)
3✔
1826
        if acceptorResp.Reserve != 0 {
3✔
1827
                chanReserve = acceptorResp.Reserve
×
1828
        }
×
1829

1830
        remoteMaxValue := f.cfg.RequiredRemoteMaxValue(amt)
3✔
1831
        if acceptorResp.InFlightTotal != 0 {
3✔
1832
                remoteMaxValue = acceptorResp.InFlightTotal
×
1833
        }
×
1834

1835
        maxHtlcs := f.cfg.RequiredRemoteMaxHTLCs(amt)
3✔
1836
        if acceptorResp.HtlcLimit != 0 {
3✔
1837
                maxHtlcs = acceptorResp.HtlcLimit
×
1838
        }
×
1839

1840
        // Default to our default minimum hltc value, replacing it with the
1841
        // channel acceptor's value if it is set.
1842
        minHtlc := f.cfg.DefaultMinHtlcIn
3✔
1843
        if acceptorResp.MinHtlcIn != 0 {
3✔
1844
                minHtlc = acceptorResp.MinHtlcIn
×
1845
        }
×
1846

1847
        // If we are handling a FundingOpen request then we need to specify the
1848
        // default channel fees since they are not provided by the responder
1849
        // interactively.
1850
        ourContribution := reservation.OurContribution()
3✔
1851
        forwardingPolicy := f.defaultForwardingPolicy(
3✔
1852
                ourContribution.ChannelStateBounds,
3✔
1853
        )
3✔
1854

3✔
1855
        // Once the reservation has been created successfully, we add it to
3✔
1856
        // this peer's map of pending reservations to track this particular
3✔
1857
        // reservation until either abort or completion.
3✔
1858
        f.resMtx.Lock()
3✔
1859
        if _, ok := f.activeReservations[peerIDKey]; !ok {
6✔
1860
                f.activeReservations[peerIDKey] = make(pendingChannels)
3✔
1861
        }
3✔
1862
        resCtx := &reservationWithCtx{
3✔
1863
                reservation:       reservation,
3✔
1864
                chanAmt:           amt,
3✔
1865
                forwardingPolicy:  *forwardingPolicy,
3✔
1866
                remoteCsvDelay:    remoteCsvDelay,
3✔
1867
                remoteMinHtlc:     minHtlc,
3✔
1868
                remoteMaxValue:    remoteMaxValue,
3✔
1869
                remoteMaxHtlcs:    maxHtlcs,
3✔
1870
                remoteChanReserve: chanReserve,
3✔
1871
                maxLocalCsv:       f.cfg.MaxLocalCSVDelay,
3✔
1872
                channelType:       chanType,
3✔
1873
                err:               make(chan error, 1),
3✔
1874
                peer:              peer,
3✔
1875
        }
3✔
1876
        f.activeReservations[peerIDKey][msg.PendingChannelID] = resCtx
3✔
1877
        f.resMtx.Unlock()
3✔
1878

3✔
1879
        // Update the timestamp once the fundingOpenMsg has been handled.
3✔
1880
        defer resCtx.updateTimestamp()
3✔
1881

3✔
1882
        cfg := channeldb.ChannelConfig{
3✔
1883
                ChannelStateBounds: channeldb.ChannelStateBounds{
3✔
1884
                        MaxPendingAmount: remoteMaxValue,
3✔
1885
                        ChanReserve:      chanReserve,
3✔
1886
                        MinHTLC:          minHtlc,
3✔
1887
                        MaxAcceptedHtlcs: maxHtlcs,
3✔
1888
                },
3✔
1889
                CommitmentParams: channeldb.CommitmentParams{
3✔
1890
                        DustLimit: msg.DustLimit,
3✔
1891
                        CsvDelay:  remoteCsvDelay,
3✔
1892
                },
3✔
1893
                MultiSigKey: keychain.KeyDescriptor{
3✔
1894
                        PubKey: copyPubKey(msg.FundingKey),
3✔
1895
                },
3✔
1896
                RevocationBasePoint: keychain.KeyDescriptor{
3✔
1897
                        PubKey: copyPubKey(msg.RevocationPoint),
3✔
1898
                },
3✔
1899
                PaymentBasePoint: keychain.KeyDescriptor{
3✔
1900
                        PubKey: copyPubKey(msg.PaymentPoint),
3✔
1901
                },
3✔
1902
                DelayBasePoint: keychain.KeyDescriptor{
3✔
1903
                        PubKey: copyPubKey(msg.DelayedPaymentPoint),
3✔
1904
                },
3✔
1905
                HtlcBasePoint: keychain.KeyDescriptor{
3✔
1906
                        PubKey: copyPubKey(msg.HtlcPoint),
3✔
1907
                },
3✔
1908
        }
3✔
1909

3✔
1910
        // With our parameters set, we'll now process their contribution so we
3✔
1911
        // can move the funding workflow ahead.
3✔
1912
        remoteContribution := &lnwallet.ChannelContribution{
3✔
1913
                FundingAmount:        amt,
3✔
1914
                FirstCommitmentPoint: msg.FirstCommitmentPoint,
3✔
1915
                ChannelConfig:        &cfg,
3✔
1916
                UpfrontShutdown:      msg.UpfrontShutdownScript,
3✔
1917
        }
3✔
1918

3✔
1919
        if resCtx.reservation.IsTaproot() {
6✔
1920
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
3✔
1921
                if err != nil {
3✔
1922
                        log.Error(errNoLocalNonce)
×
1923

×
1924
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
1925

×
1926
                        return
×
1927
                }
×
1928

1929
                remoteContribution.LocalNonce = &musig2.Nonces{
3✔
1930
                        PubNonce: localNonce,
3✔
1931
                }
3✔
1932
        }
1933

1934
        err = reservation.ProcessSingleContribution(remoteContribution)
3✔
1935
        if err != nil {
3✔
UNCOV
1936
                log.Errorf("unable to add contribution reservation: %v", err)
×
UNCOV
1937
                f.failFundingFlow(peer, cid, err)
×
UNCOV
1938
                return
×
UNCOV
1939
        }
×
1940

1941
        log.Infof("Sending fundingResp for pending_id(%x)",
3✔
1942
                msg.PendingChannelID)
3✔
1943
        bounds := remoteContribution.ChannelConfig.ChannelStateBounds
3✔
1944
        log.Debugf("Remote party accepted channel state space bounds: %v",
3✔
1945
                lnutils.SpewLogClosure(bounds))
3✔
1946
        params := remoteContribution.ChannelConfig.CommitmentParams
3✔
1947
        log.Debugf("Remote party accepted commitment rendering params: %v",
3✔
1948
                lnutils.SpewLogClosure(params))
3✔
1949

3✔
1950
        reservation.SetState(lnwallet.SentAcceptChannel)
3✔
1951

3✔
1952
        // With the initiator's contribution recorded, respond with our
3✔
1953
        // contribution in the next message of the workflow.
3✔
1954
        fundingAccept := lnwire.AcceptChannel{
3✔
1955
                PendingChannelID:      msg.PendingChannelID,
3✔
1956
                DustLimit:             ourContribution.DustLimit,
3✔
1957
                MaxValueInFlight:      remoteMaxValue,
3✔
1958
                ChannelReserve:        chanReserve,
3✔
1959
                MinAcceptDepth:        uint32(numConfsReq),
3✔
1960
                HtlcMinimum:           minHtlc,
3✔
1961
                CsvDelay:              remoteCsvDelay,
3✔
1962
                MaxAcceptedHTLCs:      maxHtlcs,
3✔
1963
                FundingKey:            ourContribution.MultiSigKey.PubKey,
3✔
1964
                RevocationPoint:       ourContribution.RevocationBasePoint.PubKey,
3✔
1965
                PaymentPoint:          ourContribution.PaymentBasePoint.PubKey,
3✔
1966
                DelayedPaymentPoint:   ourContribution.DelayBasePoint.PubKey,
3✔
1967
                HtlcPoint:             ourContribution.HtlcBasePoint.PubKey,
3✔
1968
                FirstCommitmentPoint:  ourContribution.FirstCommitmentPoint,
3✔
1969
                UpfrontShutdownScript: ourContribution.UpfrontShutdown,
3✔
1970
                ChannelType:           chanType,
3✔
1971
                LeaseExpiry:           msg.LeaseExpiry,
3✔
1972
        }
3✔
1973

3✔
1974
        if commitType.IsTaproot() {
6✔
1975
                fundingAccept.LocalNonce = lnwire.SomeMusig2Nonce(
3✔
1976
                        ourContribution.LocalNonce.PubNonce,
3✔
1977
                )
3✔
1978
        }
3✔
1979

1980
        if err := peer.SendMessage(true, &fundingAccept); err != nil {
3✔
1981
                log.Errorf("unable to send funding response to peer: %v", err)
×
1982
                f.failFundingFlow(peer, cid, err)
×
1983
                return
×
1984
        }
×
1985
}
1986

1987
// funderProcessAcceptChannel processes a response to the workflow initiation
1988
// sent by the remote peer. This message then queues a message with the funding
1989
// outpoint, and a commitment signature to the remote peer.
1990
//
1991
//nolint:funlen
1992
func (f *Manager) funderProcessAcceptChannel(peer lnpeer.Peer,
1993
        msg *lnwire.AcceptChannel) {
3✔
1994

3✔
1995
        pendingChanID := msg.PendingChannelID
3✔
1996
        peerKey := peer.IdentityKey()
3✔
1997
        var peerKeyBytes []byte
3✔
1998
        if peerKey != nil {
6✔
1999
                peerKeyBytes = peerKey.SerializeCompressed()
3✔
2000
        }
3✔
2001

2002
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
3✔
2003
        if err != nil {
3✔
2004
                log.Warnf("Can't find reservation (peerKey:%x, chan_id:%v)",
×
2005
                        peerKeyBytes, pendingChanID)
×
2006
                return
×
2007
        }
×
2008

2009
        // Update the timestamp once the fundingAcceptMsg has been handled.
2010
        defer resCtx.updateTimestamp()
3✔
2011

3✔
2012
        if resCtx.reservation.State() != lnwallet.SentOpenChannel {
3✔
2013
                return
×
2014
        }
×
2015

2016
        log.Infof("Recv'd fundingResponse for pending_id(%x)",
3✔
2017
                pendingChanID[:])
3✔
2018

3✔
2019
        // Create the channel identifier.
3✔
2020
        cid := newChanIdentifier(msg.PendingChannelID)
3✔
2021

3✔
2022
        // Perform some basic validation of any custom TLV records included.
3✔
2023
        //
3✔
2024
        // TODO: Return errors as funding.Error to give context to remote peer?
3✔
2025
        if resCtx.channelType != nil {
6✔
2026
                // We'll want to quickly check that the ChannelType echoed by
3✔
2027
                // the channel request recipient matches what we proposed.
3✔
2028
                if msg.ChannelType == nil {
3✔
UNCOV
2029
                        err := errors.New("explicit channel type not echoed " +
×
UNCOV
2030
                                "back")
×
UNCOV
2031
                        f.failFundingFlow(peer, cid, err)
×
UNCOV
2032
                        return
×
UNCOV
2033
                }
×
2034
                proposedFeatures := lnwire.RawFeatureVector(*resCtx.channelType)
3✔
2035
                ackedFeatures := lnwire.RawFeatureVector(*msg.ChannelType)
3✔
2036
                if !proposedFeatures.Equals(&ackedFeatures) {
3✔
2037
                        err := errors.New("channel type mismatch")
×
2038
                        f.failFundingFlow(peer, cid, err)
×
2039
                        return
×
2040
                }
×
2041

2042
                // We'll want to do the same with the LeaseExpiry if one should
2043
                // be set.
2044
                if resCtx.reservation.LeaseExpiry() != 0 {
6✔
2045
                        if msg.LeaseExpiry == nil {
3✔
2046
                                err := errors.New("lease expiry not echoed " +
×
2047
                                        "back")
×
2048
                                f.failFundingFlow(peer, cid, err)
×
2049
                                return
×
2050
                        }
×
2051
                        if uint32(*msg.LeaseExpiry) !=
3✔
2052
                                resCtx.reservation.LeaseExpiry() {
3✔
2053

×
2054
                                err := errors.New("lease expiry mismatch")
×
2055
                                f.failFundingFlow(peer, cid, err)
×
2056
                                return
×
2057
                        }
×
2058
                }
UNCOV
2059
        } else if msg.ChannelType != nil {
×
2060
                // The spec isn't too clear about whether it's okay to set the
×
2061
                // channel type in the accept_channel response if we didn't
×
2062
                // explicitly set it in the open_channel message. For now, we
×
2063
                // check that it's the same type we'd have arrived through
×
2064
                // implicit negotiation. If it's another type, we fail the flow.
×
2065
                _, implicitCommitType := implicitNegotiateCommitmentType(
×
2066
                        peer.LocalFeatures(), peer.RemoteFeatures(),
×
2067
                )
×
2068

×
2069
                _, negotiatedCommitType, err := negotiateCommitmentType(
×
2070
                        msg.ChannelType, peer.LocalFeatures(),
×
2071
                        peer.RemoteFeatures(),
×
2072
                )
×
2073
                if err != nil {
×
2074
                        err := errors.New("received unexpected channel type")
×
2075
                        f.failFundingFlow(peer, cid, err)
×
2076
                        return
×
2077
                }
×
2078

2079
                if implicitCommitType != negotiatedCommitType {
×
2080
                        err := errors.New("negotiated unexpected channel type")
×
2081
                        f.failFundingFlow(peer, cid, err)
×
2082
                        return
×
2083
                }
×
2084
        }
2085

2086
        // The required number of confirmations should not be greater than the
2087
        // maximum number of confirmations required by the ChainNotifier to
2088
        // properly dispatch confirmations.
2089
        if msg.MinAcceptDepth > chainntnfs.MaxNumConfs {
3✔
UNCOV
2090
                err := lnwallet.ErrNumConfsTooLarge(
×
UNCOV
2091
                        msg.MinAcceptDepth, chainntnfs.MaxNumConfs,
×
UNCOV
2092
                )
×
UNCOV
2093
                log.Warnf("Unacceptable channel constraints: %v", err)
×
UNCOV
2094
                f.failFundingFlow(peer, cid, err)
×
UNCOV
2095
                return
×
UNCOV
2096
        }
×
2097

2098
        // Check that zero-conf channels have minimum depth set to 0.
2099
        if resCtx.reservation.IsZeroConf() && msg.MinAcceptDepth != 0 {
3✔
2100
                err = fmt.Errorf("zero-conf channel has min_depth non-zero")
×
2101
                log.Warn(err)
×
2102
                f.failFundingFlow(peer, cid, err)
×
2103
                return
×
2104
        }
×
2105

2106
        // If this is not a zero-conf channel but the peer responded with a
2107
        // min-depth of zero, we will use our minimum of 1 instead.
2108
        minDepth := msg.MinAcceptDepth
3✔
2109
        if !resCtx.reservation.IsZeroConf() && minDepth == 0 {
3✔
2110
                log.Infof("Responder to pending_id=%v sent a minimum "+
×
2111
                        "confirmation depth of 0 for non-zero-conf channel. "+
×
2112
                        "We will use a minimum depth of 1 instead.",
×
2113
                        cid.tempChanID)
×
2114

×
2115
                minDepth = 1
×
2116
        }
×
2117

2118
        // We'll also specify the responder's preference for the number of
2119
        // required confirmations, and also the set of channel constraints
2120
        // they've specified for commitment states we can create.
2121
        resCtx.reservation.SetNumConfsRequired(uint16(minDepth))
3✔
2122
        bounds := channeldb.ChannelStateBounds{
3✔
2123
                ChanReserve:      msg.ChannelReserve,
3✔
2124
                MaxPendingAmount: msg.MaxValueInFlight,
3✔
2125
                MinHTLC:          msg.HtlcMinimum,
3✔
2126
                MaxAcceptedHtlcs: msg.MaxAcceptedHTLCs,
3✔
2127
        }
3✔
2128
        commitParams := channeldb.CommitmentParams{
3✔
2129
                DustLimit: msg.DustLimit,
3✔
2130
                CsvDelay:  msg.CsvDelay,
3✔
2131
        }
3✔
2132
        err = resCtx.reservation.CommitConstraints(
3✔
2133
                &bounds, &commitParams, resCtx.maxLocalCsv, false,
3✔
2134
        )
3✔
2135
        if err != nil {
3✔
UNCOV
2136
                log.Warnf("Unacceptable channel constraints: %v", err)
×
UNCOV
2137
                f.failFundingFlow(peer, cid, err)
×
UNCOV
2138
                return
×
UNCOV
2139
        }
×
2140

2141
        cfg := channeldb.ChannelConfig{
3✔
2142
                ChannelStateBounds: channeldb.ChannelStateBounds{
3✔
2143
                        MaxPendingAmount: resCtx.remoteMaxValue,
3✔
2144
                        ChanReserve:      resCtx.remoteChanReserve,
3✔
2145
                        MinHTLC:          resCtx.remoteMinHtlc,
3✔
2146
                        MaxAcceptedHtlcs: resCtx.remoteMaxHtlcs,
3✔
2147
                },
3✔
2148
                CommitmentParams: channeldb.CommitmentParams{
3✔
2149
                        DustLimit: msg.DustLimit,
3✔
2150
                        CsvDelay:  resCtx.remoteCsvDelay,
3✔
2151
                },
3✔
2152
                MultiSigKey: keychain.KeyDescriptor{
3✔
2153
                        PubKey: copyPubKey(msg.FundingKey),
3✔
2154
                },
3✔
2155
                RevocationBasePoint: keychain.KeyDescriptor{
3✔
2156
                        PubKey: copyPubKey(msg.RevocationPoint),
3✔
2157
                },
3✔
2158
                PaymentBasePoint: keychain.KeyDescriptor{
3✔
2159
                        PubKey: copyPubKey(msg.PaymentPoint),
3✔
2160
                },
3✔
2161
                DelayBasePoint: keychain.KeyDescriptor{
3✔
2162
                        PubKey: copyPubKey(msg.DelayedPaymentPoint),
3✔
2163
                },
3✔
2164
                HtlcBasePoint: keychain.KeyDescriptor{
3✔
2165
                        PubKey: copyPubKey(msg.HtlcPoint),
3✔
2166
                },
3✔
2167
        }
3✔
2168

3✔
2169
        // The remote node has responded with their portion of the channel
3✔
2170
        // contribution. At this point, we can process their contribution which
3✔
2171
        // allows us to construct and sign both the commitment transaction, and
3✔
2172
        // the funding transaction.
3✔
2173
        remoteContribution := &lnwallet.ChannelContribution{
3✔
2174
                FirstCommitmentPoint: msg.FirstCommitmentPoint,
3✔
2175
                ChannelConfig:        &cfg,
3✔
2176
                UpfrontShutdown:      msg.UpfrontShutdownScript,
3✔
2177
        }
3✔
2178

3✔
2179
        if resCtx.reservation.IsTaproot() {
6✔
2180
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
3✔
2181
                if err != nil {
3✔
2182
                        log.Error(errNoLocalNonce)
×
2183

×
2184
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
2185

×
2186
                        return
×
2187
                }
×
2188

2189
                remoteContribution.LocalNonce = &musig2.Nonces{
3✔
2190
                        PubNonce: localNonce,
3✔
2191
                }
3✔
2192
        }
2193

2194
        err = resCtx.reservation.ProcessContribution(remoteContribution)
3✔
2195

3✔
2196
        // The wallet has detected that a PSBT funding process was requested by
3✔
2197
        // the user and has halted the funding process after negotiating the
3✔
2198
        // multisig keys. We now have everything that is needed for the user to
3✔
2199
        // start constructing a PSBT that sends to the multisig funding address.
3✔
2200
        var psbtIntent *chanfunding.PsbtIntent
3✔
2201
        if psbtErr, ok := err.(*lnwallet.PsbtFundingRequired); ok {
6✔
2202
                // Return the information that is needed by the user to
3✔
2203
                // construct the PSBT back to the caller.
3✔
2204
                addr, amt, packet, err := psbtErr.Intent.FundingParams()
3✔
2205
                if err != nil {
3✔
2206
                        log.Errorf("Unable to process PSBT funding params "+
×
2207
                                "for contribution from %x: %v", peerKeyBytes,
×
2208
                                err)
×
2209
                        f.failFundingFlow(peer, cid, err)
×
2210
                        return
×
2211
                }
×
2212
                var buf bytes.Buffer
3✔
2213
                err = packet.Serialize(&buf)
3✔
2214
                if err != nil {
3✔
2215
                        log.Errorf("Unable to serialize PSBT for "+
×
2216
                                "contribution from %x: %v", peerKeyBytes, err)
×
2217
                        f.failFundingFlow(peer, cid, err)
×
2218
                        return
×
2219
                }
×
2220
                resCtx.updates <- &lnrpc.OpenStatusUpdate{
3✔
2221
                        PendingChanId: pendingChanID[:],
3✔
2222
                        Update: &lnrpc.OpenStatusUpdate_PsbtFund{
3✔
2223
                                PsbtFund: &lnrpc.ReadyForPsbtFunding{
3✔
2224
                                        FundingAddress: addr.EncodeAddress(),
3✔
2225
                                        FundingAmount:  amt,
3✔
2226
                                        Psbt:           buf.Bytes(),
3✔
2227
                                },
3✔
2228
                        },
3✔
2229
                }
3✔
2230
                psbtIntent = psbtErr.Intent
3✔
2231
        } else if err != nil {
3✔
2232
                log.Errorf("Unable to process contribution from %x: %v",
×
2233
                        peerKeyBytes, err)
×
2234
                f.failFundingFlow(peer, cid, err)
×
2235
                return
×
2236
        }
×
2237

2238
        log.Infof("pendingChan(%x): remote party proposes num_confs=%v, "+
3✔
2239
                "csv_delay=%v", pendingChanID[:], msg.MinAcceptDepth,
3✔
2240
                msg.CsvDelay)
3✔
2241
        bounds = remoteContribution.ChannelConfig.ChannelStateBounds
3✔
2242
        log.Debugf("Remote party accepted channel state space bounds: %v",
3✔
2243
                lnutils.SpewLogClosure(bounds))
3✔
2244
        commitParams = remoteContribution.ChannelConfig.CommitmentParams
3✔
2245
        log.Debugf("Remote party accepted commitment rendering params: %v",
3✔
2246
                lnutils.SpewLogClosure(commitParams))
3✔
2247

3✔
2248
        // If the user requested funding through a PSBT, we cannot directly
3✔
2249
        // continue now and need to wait for the fully funded and signed PSBT
3✔
2250
        // to arrive. To not block any other channels from opening, we wait in
3✔
2251
        // a separate goroutine.
3✔
2252
        if psbtIntent != nil {
6✔
2253
                f.wg.Add(1)
3✔
2254
                go func() {
6✔
2255
                        defer f.wg.Done()
3✔
2256

3✔
2257
                        f.waitForPsbt(psbtIntent, resCtx, cid)
3✔
2258
                }()
3✔
2259

2260
                // With the new goroutine spawned, we can now exit to unblock
2261
                // the main event loop.
2262
                return
3✔
2263
        }
2264

2265
        // In a normal, non-PSBT funding flow, we can jump directly to the next
2266
        // step where we expect our contribution to be finalized.
2267
        f.continueFundingAccept(resCtx, cid)
3✔
2268
}
2269

2270
// waitForPsbt blocks until either a signed PSBT arrives, an error occurs or
2271
// the funding manager shuts down. In the case of a valid PSBT, the funding flow
2272
// is continued.
2273
//
2274
// NOTE: This method must be called as a goroutine.
2275
func (f *Manager) waitForPsbt(intent *chanfunding.PsbtIntent,
2276
        resCtx *reservationWithCtx, cid *chanIdentifier) {
3✔
2277

3✔
2278
        // failFlow is a helper that logs an error message with the current
3✔
2279
        // context and then fails the funding flow.
3✔
2280
        peerKey := resCtx.peer.IdentityKey()
3✔
2281
        failFlow := func(errMsg string, cause error) {
6✔
2282
                log.Errorf("Unable to handle funding accept message "+
3✔
2283
                        "for peer_key=%x, pending_chan_id=%x: %s: %v",
3✔
2284
                        peerKey.SerializeCompressed(), cid.tempChanID, errMsg,
3✔
2285
                        cause)
3✔
2286
                f.failFundingFlow(resCtx.peer, cid, cause)
3✔
2287
        }
3✔
2288

2289
        // We'll now wait until the intent has received the final and complete
2290
        // funding transaction. If the channel is closed without any error being
2291
        // sent, we know everything's going as expected.
2292
        select {
3✔
2293
        case err := <-intent.PsbtReady:
3✔
2294
                switch err {
3✔
2295
                // If the user canceled the funding reservation, we need to
2296
                // inform the other peer about us canceling the reservation.
2297
                case chanfunding.ErrUserCanceled:
3✔
2298
                        failFlow("aborting PSBT flow", err)
3✔
2299
                        return
3✔
2300

2301
                // If the remote canceled the funding reservation, we don't need
2302
                // to send another fail message. But we want to inform the user
2303
                // about what happened.
2304
                case chanfunding.ErrRemoteCanceled:
3✔
2305
                        log.Infof("Remote canceled, aborting PSBT flow "+
3✔
2306
                                "for peer_key=%x, pending_chan_id=%x",
3✔
2307
                                peerKey.SerializeCompressed(), cid.tempChanID)
3✔
2308
                        return
3✔
2309

2310
                // Nil error means the flow continues normally now.
2311
                case nil:
3✔
2312

2313
                // For any other error, we'll fail the funding flow.
2314
                default:
×
2315
                        failFlow("error waiting for PSBT flow", err)
×
2316
                        return
×
2317
                }
2318

2319
                // At this point, we'll see if there's an AuxFundingDesc we
2320
                // need to deliver so the funding process can continue
2321
                // properly.
2322
                auxFundingDesc, err := fn.MapOptionZ(
3✔
2323
                        f.cfg.AuxFundingController,
3✔
2324
                        func(c AuxFundingController) AuxFundingDescResult {
3✔
2325
                                return c.DescFromPendingChanID(
×
2326
                                        cid.tempChanID,
×
2327
                                        lnwallet.NewAuxChanState(
×
2328
                                                resCtx.reservation.ChanState(),
×
2329
                                        ),
×
2330
                                        resCtx.reservation.CommitmentKeyRings(),
×
2331
                                        true,
×
2332
                                )
×
2333
                        },
×
2334
                ).Unpack()
2335
                if err != nil {
3✔
2336
                        failFlow("error continuing PSBT flow", err)
×
2337
                        return
×
2338
                }
×
2339

2340
                // A non-nil error means we can continue the funding flow.
2341
                // Notify the wallet so it can prepare everything we need to
2342
                // continue.
2343
                //
2344
                // We'll also pass along the aux funding controller as well,
2345
                // which may be used to help process the finalized PSBT.
2346
                err = resCtx.reservation.ProcessPsbt(auxFundingDesc)
3✔
2347
                if err != nil {
3✔
2348
                        failFlow("error continuing PSBT flow", err)
×
2349
                        return
×
2350
                }
×
2351

2352
                // We are now ready to continue the funding flow.
2353
                f.continueFundingAccept(resCtx, cid)
3✔
2354

2355
        // Handle a server shutdown as well because the reservation won't
2356
        // survive a restart as it's in memory only.
2357
        case <-f.quit:
×
2358
                log.Errorf("Unable to handle funding accept message "+
×
2359
                        "for peer_key=%x, pending_chan_id=%x: funding manager "+
×
2360
                        "shutting down", peerKey.SerializeCompressed(),
×
2361
                        cid.tempChanID)
×
2362
                return
×
2363
        }
2364
}
2365

2366
// continueFundingAccept continues the channel funding flow once our
2367
// contribution is finalized, the channel output is known and the funding
2368
// transaction is signed.
2369
func (f *Manager) continueFundingAccept(resCtx *reservationWithCtx,
2370
        cid *chanIdentifier) {
3✔
2371

3✔
2372
        // Now that we have their contribution, we can extract, then send over
3✔
2373
        // both the funding out point and our signature for their version of
3✔
2374
        // the commitment transaction to the remote peer.
3✔
2375
        outPoint := resCtx.reservation.FundingOutpoint()
3✔
2376
        _, sig := resCtx.reservation.OurSignatures()
3✔
2377

3✔
2378
        // A new channel has almost finished the funding process. In order to
3✔
2379
        // properly synchronize with the writeHandler goroutine, we add a new
3✔
2380
        // channel to the barriers map which will be closed once the channel is
3✔
2381
        // fully open.
3✔
2382
        channelID := lnwire.NewChanIDFromOutPoint(*outPoint)
3✔
2383
        log.Debugf("Creating chan barrier for ChanID(%v)", channelID)
3✔
2384

3✔
2385
        // The next message that advances the funding flow will reference the
3✔
2386
        // channel via its permanent channel ID, so we'll set up this mapping
3✔
2387
        // so we can retrieve the reservation context once we get the
3✔
2388
        // FundingSigned message.
3✔
2389
        f.resMtx.Lock()
3✔
2390
        f.signedReservations[channelID] = cid.tempChanID
3✔
2391
        f.resMtx.Unlock()
3✔
2392

3✔
2393
        log.Infof("Generated ChannelPoint(%v) for pending_id(%x)", outPoint,
3✔
2394
                cid.tempChanID[:])
3✔
2395

3✔
2396
        // Before sending FundingCreated sent, we notify Brontide to keep track
3✔
2397
        // of this pending open channel.
3✔
2398
        err := resCtx.peer.AddPendingChannel(channelID, f.quit)
3✔
2399
        if err != nil {
3✔
2400
                pubKey := resCtx.peer.IdentityKey().SerializeCompressed()
×
2401
                log.Errorf("Unable to add pending channel %v with peer %x: %v",
×
2402
                        channelID, pubKey, err)
×
2403
        }
×
2404

2405
        // Once Brontide is aware of this channel, we need to set it in
2406
        // chanIdentifier so this channel will be removed from Brontide if the
2407
        // funding flow fails.
2408
        cid.setChanID(channelID)
3✔
2409

3✔
2410
        // Send the FundingCreated msg.
3✔
2411
        fundingCreated := &lnwire.FundingCreated{
3✔
2412
                PendingChannelID: cid.tempChanID,
3✔
2413
                FundingPoint:     *outPoint,
3✔
2414
        }
3✔
2415

3✔
2416
        // If this is a taproot channel, then we'll need to populate the musig2
3✔
2417
        // partial sig field instead of the regular commit sig field.
3✔
2418
        if resCtx.reservation.IsTaproot() {
6✔
2419
                partialSig, ok := sig.(*lnwallet.MusigPartialSig)
3✔
2420
                if !ok {
3✔
2421
                        err := fmt.Errorf("expected musig partial sig, got %T",
×
2422
                                sig)
×
2423
                        log.Error(err)
×
2424
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2425

×
2426
                        return
×
2427
                }
×
2428

2429
                fundingCreated.PartialSig = lnwire.MaybePartialSigWithNonce(
3✔
2430
                        partialSig.ToWireSig(),
3✔
2431
                )
3✔
2432
        } else {
3✔
2433
                fundingCreated.CommitSig, err = lnwire.NewSigFromSignature(sig)
3✔
2434
                if err != nil {
3✔
2435
                        log.Errorf("Unable to parse signature: %v", err)
×
2436
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2437
                        return
×
2438
                }
×
2439
        }
2440

2441
        resCtx.reservation.SetState(lnwallet.SentFundingCreated)
3✔
2442

3✔
2443
        if err := resCtx.peer.SendMessage(true, fundingCreated); err != nil {
3✔
2444
                log.Errorf("Unable to send funding complete message: %v", err)
×
2445
                f.failFundingFlow(resCtx.peer, cid, err)
×
2446
                return
×
2447
        }
×
2448
}
2449

2450
// fundeeProcessFundingCreated progresses the funding workflow when the daemon
2451
// is on the responding side of a single funder workflow. Once this message has
2452
// been processed, a signature is sent to the remote peer allowing it to
2453
// broadcast the funding transaction, progressing the workflow into the final
2454
// stage.
2455
//
2456
//nolint:funlen
2457
func (f *Manager) fundeeProcessFundingCreated(peer lnpeer.Peer,
2458
        msg *lnwire.FundingCreated) {
3✔
2459

3✔
2460
        peerKey := peer.IdentityKey()
3✔
2461
        pendingChanID := msg.PendingChannelID
3✔
2462

3✔
2463
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
3✔
2464
        if err != nil {
3✔
2465
                log.Warnf("can't find reservation (peer_id:%v, chan_id:%x)",
×
2466
                        peerKey, pendingChanID[:])
×
2467
                return
×
2468
        }
×
2469

2470
        // The channel initiator has responded with the funding outpoint of the
2471
        // final funding transaction, as well as a signature for our version of
2472
        // the commitment transaction. So at this point, we can validate the
2473
        // initiator's commitment transaction, then send our own if it's valid.
2474
        fundingOut := msg.FundingPoint
3✔
2475
        log.Infof("completing pending_id(%x) with ChannelPoint(%v)",
3✔
2476
                pendingChanID[:], fundingOut)
3✔
2477

3✔
2478
        if resCtx.reservation.State() != lnwallet.SentAcceptChannel {
3✔
2479
                return
×
2480
        }
×
2481

2482
        // Create the channel identifier without setting the active channel ID.
2483
        cid := newChanIdentifier(pendingChanID)
3✔
2484

3✔
2485
        // For taproot channels, the commit signature is actually the partial
3✔
2486
        // signature. Otherwise, we can convert the ECDSA commit signature into
3✔
2487
        // our internal input.Signature type.
3✔
2488
        var commitSig input.Signature
3✔
2489
        if resCtx.reservation.IsTaproot() {
6✔
2490
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
3✔
2491
                if err != nil {
3✔
2492
                        f.failFundingFlow(peer, cid, err)
×
2493

×
2494
                        return
×
2495
                }
×
2496

2497
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
3✔
2498
                        &partialSig,
3✔
2499
                )
3✔
2500
        } else {
3✔
2501
                commitSig, err = msg.CommitSig.ToSignature()
3✔
2502
                if err != nil {
3✔
2503
                        log.Errorf("unable to parse signature: %v", err)
×
2504
                        f.failFundingFlow(peer, cid, err)
×
2505
                        return
×
2506
                }
×
2507
        }
2508

2509
        // At this point, we'll see if there's an AuxFundingDesc we need to
2510
        // deliver so the funding process can continue properly.
2511
        auxFundingDesc, err := fn.MapOptionZ(
3✔
2512
                f.cfg.AuxFundingController,
3✔
2513
                func(c AuxFundingController) AuxFundingDescResult {
3✔
2514
                        return c.DescFromPendingChanID(
×
2515
                                cid.tempChanID, lnwallet.NewAuxChanState(
×
2516
                                        resCtx.reservation.ChanState(),
×
2517
                                ), resCtx.reservation.CommitmentKeyRings(),
×
2518
                                true,
×
2519
                        )
×
2520
                },
×
2521
        ).Unpack()
2522
        if err != nil {
3✔
2523
                log.Errorf("error continuing PSBT flow: %v", err)
×
2524
                f.failFundingFlow(peer, cid, err)
×
2525
                return
×
2526
        }
×
2527

2528
        // With all the necessary data available, attempt to advance the
2529
        // funding workflow to the next stage. If this succeeds then the
2530
        // funding transaction will broadcast after our next message.
2531
        // CompleteReservationSingle will also mark the channel as 'IsPending'
2532
        // in the database.
2533
        //
2534
        // We'll also directly pass in the AuxFunding controller as well,
2535
        // which may be used by the reservation system to finalize funding our
2536
        // side.
2537
        completeChan, err := resCtx.reservation.CompleteReservationSingle(
3✔
2538
                &fundingOut, commitSig, auxFundingDesc,
3✔
2539
        )
3✔
2540
        if err != nil {
3✔
2541
                log.Errorf("unable to complete single reservation: %v", err)
×
2542
                f.failFundingFlow(peer, cid, err)
×
2543
                return
×
2544
        }
×
2545

2546
        // Get forwarding policy before deleting the reservation context.
2547
        forwardingPolicy := resCtx.forwardingPolicy
3✔
2548

3✔
2549
        // The channel is marked IsPending in the database, and can be removed
3✔
2550
        // from the set of active reservations.
3✔
2551
        f.deleteReservationCtx(peerKey, cid.tempChanID)
3✔
2552

3✔
2553
        // If something goes wrong before the funding transaction is confirmed,
3✔
2554
        // we use this convenience method to delete the pending OpenChannel
3✔
2555
        // from the database.
3✔
2556
        deleteFromDatabase := func() {
3✔
2557
                localBalance := completeChan.LocalCommitment.LocalBalance.ToSatoshis()
×
2558
                closeInfo := &channeldb.ChannelCloseSummary{
×
2559
                        ChanPoint:               completeChan.FundingOutpoint,
×
2560
                        ChainHash:               completeChan.ChainHash,
×
2561
                        RemotePub:               completeChan.IdentityPub,
×
2562
                        CloseType:               channeldb.FundingCanceled,
×
2563
                        Capacity:                completeChan.Capacity,
×
2564
                        SettledBalance:          localBalance,
×
2565
                        RemoteCurrentRevocation: completeChan.RemoteCurrentRevocation,
×
2566
                        RemoteNextRevocation:    completeChan.RemoteNextRevocation,
×
2567
                        LocalChanConfig:         completeChan.LocalChanCfg,
×
2568
                }
×
2569

×
2570
                // Close the channel with us as the initiator because we are
×
2571
                // deciding to exit the funding flow due to an internal error.
×
2572
                if err := completeChan.CloseChannel(
×
2573
                        closeInfo, channeldb.ChanStatusLocalCloseInitiator,
×
2574
                ); err != nil {
×
2575
                        log.Errorf("Failed closing channel %v: %v",
×
2576
                                completeChan.FundingOutpoint, err)
×
2577
                }
×
2578
        }
2579

2580
        // A new channel has almost finished the funding process. In order to
2581
        // properly synchronize with the writeHandler goroutine, we add a new
2582
        // channel to the barriers map which will be closed once the channel is
2583
        // fully open.
2584
        channelID := lnwire.NewChanIDFromOutPoint(fundingOut)
3✔
2585
        log.Debugf("Creating chan barrier for ChanID(%v)", channelID)
3✔
2586

3✔
2587
        fundingSigned := &lnwire.FundingSigned{}
3✔
2588

3✔
2589
        // For taproot channels, we'll need to send over a partial signature
3✔
2590
        // that includes the nonce along side the signature.
3✔
2591
        _, sig := resCtx.reservation.OurSignatures()
3✔
2592
        if resCtx.reservation.IsTaproot() {
6✔
2593
                partialSig, ok := sig.(*lnwallet.MusigPartialSig)
3✔
2594
                if !ok {
3✔
2595
                        err := fmt.Errorf("expected musig partial sig, got %T",
×
2596
                                sig)
×
2597
                        log.Error(err)
×
2598
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2599
                        deleteFromDatabase()
×
2600

×
2601
                        return
×
2602
                }
×
2603

2604
                fundingSigned.PartialSig = lnwire.MaybePartialSigWithNonce(
3✔
2605
                        partialSig.ToWireSig(),
3✔
2606
                )
3✔
2607
        } else {
3✔
2608
                fundingSigned.CommitSig, err = lnwire.NewSigFromSignature(sig)
3✔
2609
                if err != nil {
3✔
2610
                        log.Errorf("unable to parse signature: %v", err)
×
2611
                        f.failFundingFlow(peer, cid, err)
×
2612
                        deleteFromDatabase()
×
2613

×
2614
                        return
×
2615
                }
×
2616
        }
2617

2618
        // Before sending FundingSigned, we notify Brontide first to keep track
2619
        // of this pending open channel.
2620
        if err := peer.AddPendingChannel(channelID, f.quit); err != nil {
3✔
2621
                pubKey := peer.IdentityKey().SerializeCompressed()
×
2622
                log.Errorf("Unable to add pending channel %v with peer %x: %v",
×
2623
                        cid.chanID, pubKey, err)
×
2624
        }
×
2625

2626
        // Once Brontide is aware of this channel, we need to set it in
2627
        // chanIdentifier so this channel will be removed from Brontide if the
2628
        // funding flow fails.
2629
        cid.setChanID(channelID)
3✔
2630

3✔
2631
        fundingSigned.ChanID = cid.chanID
3✔
2632

3✔
2633
        log.Infof("sending FundingSigned for pending_id(%x) over "+
3✔
2634
                "ChannelPoint(%v)", pendingChanID[:], fundingOut)
3✔
2635

3✔
2636
        // With their signature for our version of the commitment transaction
3✔
2637
        // verified, we can now send over our signature to the remote peer.
3✔
2638
        if err := peer.SendMessage(true, fundingSigned); err != nil {
3✔
2639
                log.Errorf("unable to send FundingSigned message: %v", err)
×
2640
                f.failFundingFlow(peer, cid, err)
×
2641
                deleteFromDatabase()
×
2642
                return
×
2643
        }
×
2644

2645
        // With a permanent channel id established we can save the respective
2646
        // forwarding policy in the database. In the channel announcement phase
2647
        // this forwarding policy is retrieved and applied.
2648
        err = f.saveInitialForwardingPolicy(cid.chanID, &forwardingPolicy)
3✔
2649
        if err != nil {
3✔
2650
                log.Errorf("Unable to store the forwarding policy: %v", err)
×
2651
        }
×
2652

2653
        // Now that we've sent over our final signature for this channel, we'll
2654
        // send it to the ChainArbitrator so it can watch for any on-chain
2655
        // actions during this final confirmation stage.
2656
        if err := f.cfg.WatchNewChannel(completeChan, peerKey); err != nil {
3✔
2657
                log.Errorf("Unable to send new ChannelPoint(%v) for "+
×
2658
                        "arbitration: %v", fundingOut, err)
×
2659
        }
×
2660

2661
        // Create an entry in the local discovery map so we can ensure that we
2662
        // process the channel confirmation fully before we receive a
2663
        // channel_ready message.
2664
        f.localDiscoverySignals.Store(cid.chanID, make(chan struct{}))
3✔
2665

3✔
2666
        // Inform the ChannelNotifier that the channel has entered
3✔
2667
        // pending open state.
3✔
2668
        if err := f.cfg.NotifyPendingOpenChannelEvent(
3✔
2669
                fundingOut, completeChan, completeChan.IdentityPub,
3✔
2670
        ); err != nil {
3✔
NEW
2671
                log.Errorf("Unable to send pending-open channel event for "+
×
NEW
2672
                        "ChannelPoint(%v) %v", fundingOut, err)
×
NEW
2673
        }
×
2674

2675
        // At this point we have sent our last funding message to the
2676
        // initiating peer before the funding transaction will be broadcast.
2677
        // With this last message, our job as the responder is now complete.
2678
        // We'll wait for the funding transaction to reach the specified number
2679
        // of confirmations, then start normal operations.
2680
        //
2681
        // When we get to this point we have sent the signComplete message to
2682
        // the channel funder, and BOLT#2 specifies that we MUST remember the
2683
        // channel for reconnection. The channel is already marked
2684
        // as pending in the database, so in case of a disconnect or restart,
2685
        // we will continue waiting for the confirmation the next time we start
2686
        // the funding manager. In case the funding transaction never appears
2687
        // on the blockchain, we must forget this channel. We therefore
2688
        // completely forget about this channel if we haven't seen the funding
2689
        // transaction in 288 blocks (~ 48 hrs), by canceling the reservation
2690
        // and canceling the wait for the funding confirmation.
2691
        f.wg.Add(1)
3✔
2692
        go f.advanceFundingState(completeChan, pendingChanID, nil)
3✔
2693
}
2694

2695
// funderProcessFundingSigned processes the final message received in a single
2696
// funder workflow. Once this message is processed, the funding transaction is
2697
// broadcast. Once the funding transaction reaches a sufficient number of
2698
// confirmations, a message is sent to the responding peer along with a compact
2699
// encoding of the location of the channel within the blockchain.
2700
func (f *Manager) funderProcessFundingSigned(peer lnpeer.Peer,
2701
        msg *lnwire.FundingSigned) {
3✔
2702

3✔
2703
        // As the funding signed message will reference the reservation by its
3✔
2704
        // permanent channel ID, we'll need to perform an intermediate look up
3✔
2705
        // before we can obtain the reservation.
3✔
2706
        f.resMtx.Lock()
3✔
2707
        pendingChanID, ok := f.signedReservations[msg.ChanID]
3✔
2708
        delete(f.signedReservations, msg.ChanID)
3✔
2709
        f.resMtx.Unlock()
3✔
2710

3✔
2711
        // Create the channel identifier and set the channel ID.
3✔
2712
        //
3✔
2713
        // NOTE: we may get an empty pending channel ID here if the key cannot
3✔
2714
        // be found, which means when we cancel the reservation context in
3✔
2715
        // `failFundingFlow`, we will get an error. In this case, we will send
3✔
2716
        // an error msg to our peer using the active channel ID.
3✔
2717
        //
3✔
2718
        // TODO(yy): refactor the funding flow to fix this case.
3✔
2719
        cid := newChanIdentifier(pendingChanID)
3✔
2720
        cid.setChanID(msg.ChanID)
3✔
2721

3✔
2722
        // If the pending channel ID is not found, fail the funding flow.
3✔
2723
        if !ok {
3✔
2724
                // NOTE: we directly overwrite the pending channel ID here for
×
2725
                // this rare case since we don't have a valid pending channel
×
2726
                // ID.
×
2727
                cid.tempChanID = msg.ChanID
×
2728

×
2729
                err := fmt.Errorf("unable to find signed reservation for "+
×
2730
                        "chan_id=%x", msg.ChanID)
×
2731
                log.Warnf(err.Error())
×
2732
                f.failFundingFlow(peer, cid, err)
×
2733
                return
×
2734
        }
×
2735

2736
        peerKey := peer.IdentityKey()
3✔
2737
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
3✔
2738
        if err != nil {
3✔
2739
                log.Warnf("Unable to find reservation (peer_id:%v, "+
×
2740
                        "chan_id:%x)", peerKey, pendingChanID[:])
×
2741
                // TODO: add ErrChanNotFound?
×
2742
                f.failFundingFlow(peer, cid, err)
×
2743
                return
×
2744
        }
×
2745

2746
        if resCtx.reservation.State() != lnwallet.SentFundingCreated {
3✔
2747
                err := fmt.Errorf("unable to find reservation for chan_id=%x",
×
2748
                        msg.ChanID)
×
2749
                f.failFundingFlow(peer, cid, err)
×
2750

×
2751
                return
×
2752
        }
×
2753

2754
        // Create an entry in the local discovery map so we can ensure that we
2755
        // process the channel confirmation fully before we receive a
2756
        // channel_ready message.
2757
        fundingPoint := resCtx.reservation.FundingOutpoint()
3✔
2758
        permChanID := lnwire.NewChanIDFromOutPoint(*fundingPoint)
3✔
2759
        f.localDiscoverySignals.Store(permChanID, make(chan struct{}))
3✔
2760

3✔
2761
        // We have to store the forwardingPolicy before the reservation context
3✔
2762
        // is deleted. The policy will then be read and applied in
3✔
2763
        // newChanAnnouncement.
3✔
2764
        err = f.saveInitialForwardingPolicy(
3✔
2765
                permChanID, &resCtx.forwardingPolicy,
3✔
2766
        )
3✔
2767
        if err != nil {
3✔
2768
                log.Errorf("Unable to store the forwarding policy: %v", err)
×
2769
        }
×
2770

2771
        // For taproot channels, the commit signature is actually the partial
2772
        // signature. Otherwise, we can convert the ECDSA commit signature into
2773
        // our internal input.Signature type.
2774
        var commitSig input.Signature
3✔
2775
        if resCtx.reservation.IsTaproot() {
6✔
2776
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
3✔
2777
                if err != nil {
3✔
2778
                        f.failFundingFlow(peer, cid, err)
×
2779

×
2780
                        return
×
2781
                }
×
2782

2783
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
3✔
2784
                        &partialSig,
3✔
2785
                )
3✔
2786
        } else {
3✔
2787
                commitSig, err = msg.CommitSig.ToSignature()
3✔
2788
                if err != nil {
3✔
2789
                        log.Errorf("unable to parse signature: %v", err)
×
2790
                        f.failFundingFlow(peer, cid, err)
×
2791
                        return
×
2792
                }
×
2793
        }
2794

2795
        completeChan, err := resCtx.reservation.CompleteReservation(
3✔
2796
                nil, commitSig,
3✔
2797
        )
3✔
2798
        if err != nil {
3✔
2799
                log.Errorf("Unable to complete reservation sign "+
×
2800
                        "complete: %v", err)
×
2801
                f.failFundingFlow(peer, cid, err)
×
2802
                return
×
2803
        }
×
2804

2805
        // The channel is now marked IsPending in the database, and we can
2806
        // delete it from our set of active reservations.
2807
        f.deleteReservationCtx(peerKey, pendingChanID)
3✔
2808

3✔
2809
        // Broadcast the finalized funding transaction to the network, but only
3✔
2810
        // if we actually have the funding transaction.
3✔
2811
        if completeChan.ChanType.HasFundingTx() {
6✔
2812
                fundingTx := completeChan.FundingTxn
3✔
2813
                var fundingTxBuf bytes.Buffer
3✔
2814
                if err := fundingTx.Serialize(&fundingTxBuf); err != nil {
3✔
2815
                        log.Errorf("Unable to serialize funding "+
×
2816
                                "transaction %v: %v", fundingTx.TxHash(), err)
×
2817

×
2818
                        // Clear the buffer of any bytes that were written
×
2819
                        // before the serialization error to prevent logging an
×
2820
                        // incomplete transaction.
×
2821
                        fundingTxBuf.Reset()
×
2822
                }
×
2823

2824
                log.Infof("Broadcasting funding tx for ChannelPoint(%v): %x",
3✔
2825
                        completeChan.FundingOutpoint, fundingTxBuf.Bytes())
3✔
2826

3✔
2827
                // Set a nil short channel ID at this stage because we do not
3✔
2828
                // know it until our funding tx confirms.
3✔
2829
                label := labels.MakeLabel(
3✔
2830
                        labels.LabelTypeChannelOpen, nil,
3✔
2831
                )
3✔
2832

3✔
2833
                err = f.cfg.PublishTransaction(fundingTx, label)
3✔
2834
                if err != nil {
3✔
2835
                        log.Errorf("Unable to broadcast funding tx %x for "+
×
2836
                                "ChannelPoint(%v): %v", fundingTxBuf.Bytes(),
×
2837
                                completeChan.FundingOutpoint, err)
×
2838

×
2839
                        // We failed to broadcast the funding transaction, but
×
2840
                        // watch the channel regardless, in case the
×
2841
                        // transaction made it to the network. We will retry
×
2842
                        // broadcast at startup.
×
2843
                        //
×
2844
                        // TODO(halseth): retry more often? Handle with CPFP?
×
2845
                        // Just delete from the DB?
×
2846
                }
×
2847
        }
2848

2849
        // Before we proceed, if we have a funding hook that wants a
2850
        // notification that it's safe to broadcast the funding transaction,
2851
        // then we'll send that now.
2852
        err = fn.MapOptionZ(
3✔
2853
                f.cfg.AuxFundingController,
3✔
2854
                func(controller AuxFundingController) error {
3✔
2855
                        return controller.ChannelFinalized(cid.tempChanID)
×
2856
                },
×
2857
        )
2858
        if err != nil {
3✔
2859
                log.Errorf("Failed to inform aux funding controller about "+
×
2860
                        "ChannelPoint(%v) being finalized: %v", fundingPoint,
×
2861
                        err)
×
2862
        }
×
2863

2864
        // Now that we have a finalized reservation for this funding flow,
2865
        // we'll send the to be active channel to the ChainArbitrator so it can
2866
        // watch for any on-chain actions before the channel has fully
2867
        // confirmed.
2868
        if err := f.cfg.WatchNewChannel(completeChan, peerKey); err != nil {
3✔
2869
                log.Errorf("Unable to send new ChannelPoint(%v) for "+
×
2870
                        "arbitration: %v", fundingPoint, err)
×
2871
        }
×
2872

2873
        log.Infof("Finalizing pending_id(%x) over ChannelPoint(%v), "+
3✔
2874
                "waiting for channel open on-chain", pendingChanID[:],
3✔
2875
                fundingPoint)
3✔
2876

3✔
2877
        // Send an update to the upstream client that the negotiation process
3✔
2878
        // is over.
3✔
2879
        upd := &lnrpc.OpenStatusUpdate{
3✔
2880
                Update: &lnrpc.OpenStatusUpdate_ChanPending{
3✔
2881
                        ChanPending: &lnrpc.PendingUpdate{
3✔
2882
                                Txid:        fundingPoint.Hash[:],
3✔
2883
                                OutputIndex: fundingPoint.Index,
3✔
2884
                        },
3✔
2885
                },
3✔
2886
                PendingChanId: pendingChanID[:],
3✔
2887
        }
3✔
2888

3✔
2889
        select {
3✔
2890
        case resCtx.updates <- upd:
3✔
2891
                // Inform the ChannelNotifier that the channel has entered
3✔
2892
                // pending open state.
3✔
2893
                if err := f.cfg.NotifyPendingOpenChannelEvent(
3✔
2894
                        *fundingPoint, completeChan, completeChan.IdentityPub,
3✔
2895
                ); err != nil {
3✔
NEW
2896
                        log.Errorf("Unable to send pending-open channel "+
×
NEW
2897
                                "event for ChannelPoint(%v) %v", fundingPoint,
×
NEW
2898
                                err)
×
NEW
2899
                }
×
2900

2901
        case <-f.quit:
×
2902
                return
×
2903
        }
2904

2905
        // At this point we have broadcast the funding transaction and done all
2906
        // necessary processing.
2907
        f.wg.Add(1)
3✔
2908
        go f.advanceFundingState(completeChan, pendingChanID, resCtx.updates)
3✔
2909
}
2910

2911
// confirmedChannel wraps a confirmed funding transaction, as well as the short
2912
// channel ID which identifies that channel into a single struct. We'll use
2913
// this to pass around the final state of a channel after it has been
2914
// confirmed.
2915
type confirmedChannel struct {
2916
        // shortChanID expresses where in the block the funding transaction was
2917
        // located.
2918
        shortChanID lnwire.ShortChannelID
2919

2920
        // fundingTx is the funding transaction that created the channel.
2921
        fundingTx *wire.MsgTx
2922
}
2923

2924
// fundingTimeout is called when callers of waitForFundingWithTimeout receive
2925
// an ErrConfirmationTimeout. It is used to clean-up channel state and mark the
2926
// channel as closed. The error is only returned for the responder of the
2927
// channel flow.
2928
func (f *Manager) fundingTimeout(c *channeldb.OpenChannel,
UNCOV
2929
        pendingID PendingChanID) error {
×
UNCOV
2930

×
UNCOV
2931
        // We'll get a timeout if the number of blocks mined since the channel
×
UNCOV
2932
        // was initiated reaches MaxWaitNumBlocksFundingConf and we are not the
×
UNCOV
2933
        // channel initiator.
×
UNCOV
2934
        localBalance := c.LocalCommitment.LocalBalance.ToSatoshis()
×
UNCOV
2935
        closeInfo := &channeldb.ChannelCloseSummary{
×
UNCOV
2936
                ChainHash:               c.ChainHash,
×
UNCOV
2937
                ChanPoint:               c.FundingOutpoint,
×
UNCOV
2938
                RemotePub:               c.IdentityPub,
×
UNCOV
2939
                Capacity:                c.Capacity,
×
UNCOV
2940
                SettledBalance:          localBalance,
×
UNCOV
2941
                CloseType:               channeldb.FundingCanceled,
×
UNCOV
2942
                RemoteCurrentRevocation: c.RemoteCurrentRevocation,
×
UNCOV
2943
                RemoteNextRevocation:    c.RemoteNextRevocation,
×
UNCOV
2944
                LocalChanConfig:         c.LocalChanCfg,
×
UNCOV
2945
        }
×
UNCOV
2946

×
UNCOV
2947
        // Close the channel with us as the initiator because we are timing the
×
UNCOV
2948
        // channel out.
×
UNCOV
2949
        if err := c.CloseChannel(
×
UNCOV
2950
                closeInfo, channeldb.ChanStatusLocalCloseInitiator,
×
UNCOV
2951
        ); err != nil {
×
2952
                return fmt.Errorf("failed closing channel %v: %w",
×
2953
                        c.FundingOutpoint, err)
×
2954
        }
×
2955

2956
        // Notify other subsystems about the funding timeout.
NEW
2957
        err := f.cfg.NotifyFundingTimeout(c.FundingOutpoint, c.IdentityPub)
×
NEW
2958
        if err != nil {
×
NEW
2959
                log.Errorf("failed to notify of funding timeout for "+
×
NEW
2960
                        "ChanPoint(%v): %v", c.FundingOutpoint, err)
×
NEW
2961
        }
×
2962

UNCOV
2963
        timeoutErr := fmt.Errorf("timeout waiting for funding tx (%v) to "+
×
UNCOV
2964
                "confirm", c.FundingOutpoint)
×
UNCOV
2965

×
UNCOV
2966
        // When the peer comes online, we'll notify it that we are now
×
UNCOV
2967
        // considering the channel flow canceled.
×
UNCOV
2968
        f.wg.Add(1)
×
UNCOV
2969
        go func() {
×
UNCOV
2970
                defer f.wg.Done()
×
UNCOV
2971

×
UNCOV
2972
                peer, err := f.waitForPeerOnline(c.IdentityPub)
×
UNCOV
2973
                switch err {
×
2974
                // We're already shutting down, so we can just return.
2975
                case ErrFundingManagerShuttingDown:
×
2976
                        return
×
2977

2978
                // nil error means we continue on.
UNCOV
2979
                case nil:
×
2980

2981
                // For unexpected errors, we print the error and still try to
2982
                // fail the funding flow.
2983
                default:
×
2984
                        log.Errorf("Unexpected error while waiting for peer "+
×
2985
                                "to come online: %v", err)
×
2986
                }
2987

2988
                // Create channel identifier and set the channel ID.
UNCOV
2989
                cid := newChanIdentifier(pendingID)
×
UNCOV
2990
                cid.setChanID(lnwire.NewChanIDFromOutPoint(c.FundingOutpoint))
×
UNCOV
2991

×
UNCOV
2992
                // TODO(halseth): should this send be made
×
UNCOV
2993
                // reliable?
×
UNCOV
2994

×
UNCOV
2995
                // The reservation won't exist at this point, but we'll send an
×
UNCOV
2996
                // Error message over anyways with ChanID set to pendingID.
×
UNCOV
2997
                f.failFundingFlow(peer, cid, timeoutErr)
×
2998
        }()
2999

UNCOV
3000
        return timeoutErr
×
3001
}
3002

3003
// waitForFundingWithTimeout is a wrapper around waitForFundingConfirmation and
3004
// waitForTimeout that will return ErrConfirmationTimeout if we are not the
3005
// channel initiator and the MaxWaitNumBlocksFundingConf has passed from the
3006
// funding broadcast height. In case of confirmation, the short channel ID of
3007
// the channel and the funding transaction will be returned.
3008
func (f *Manager) waitForFundingWithTimeout(
3009
        ch *channeldb.OpenChannel) (*confirmedChannel, error) {
3✔
3010

3✔
3011
        confChan := make(chan *confirmedChannel)
3✔
3012
        timeoutChan := make(chan error, 1)
3✔
3013
        cancelChan := make(chan struct{})
3✔
3014

3✔
3015
        f.wg.Add(1)
3✔
3016
        go f.waitForFundingConfirmation(ch, cancelChan, confChan)
3✔
3017

3✔
3018
        // If we are not the initiator, we have no money at stake and will
3✔
3019
        // timeout waiting for the funding transaction to confirm after a
3✔
3020
        // while.
3✔
3021
        if !ch.IsInitiator && !ch.IsZeroConf() {
6✔
3022
                f.wg.Add(1)
3✔
3023
                go f.waitForTimeout(ch, cancelChan, timeoutChan)
3✔
3024
        }
3✔
3025
        defer close(cancelChan)
3✔
3026

3✔
3027
        select {
3✔
UNCOV
3028
        case err := <-timeoutChan:
×
UNCOV
3029
                if err != nil {
×
3030
                        return nil, err
×
3031
                }
×
UNCOV
3032
                return nil, ErrConfirmationTimeout
×
3033

3034
        case <-f.quit:
3✔
3035
                // The fundingManager is shutting down, and will resume wait on
3✔
3036
                // startup.
3✔
3037
                return nil, ErrFundingManagerShuttingDown
3✔
3038

3039
        case confirmedChannel, ok := <-confChan:
3✔
3040
                if !ok {
3✔
3041
                        return nil, fmt.Errorf("waiting for funding" +
×
3042
                                "confirmation failed")
×
3043
                }
×
3044
                return confirmedChannel, nil
3✔
3045
        }
3046
}
3047

3048
// makeFundingScript re-creates the funding script for the funding transaction
3049
// of the target channel.
3050
func makeFundingScript(channel *channeldb.OpenChannel) ([]byte, error) {
3✔
3051
        localKey := channel.LocalChanCfg.MultiSigKey.PubKey
3✔
3052
        remoteKey := channel.RemoteChanCfg.MultiSigKey.PubKey
3✔
3053

3✔
3054
        if channel.ChanType.IsTaproot() {
6✔
3055
                pkScript, _, err := input.GenTaprootFundingScript(
3✔
3056
                        localKey, remoteKey, int64(channel.Capacity),
3✔
3057
                        channel.TapscriptRoot,
3✔
3058
                )
3✔
3059
                if err != nil {
3✔
3060
                        return nil, err
×
3061
                }
×
3062

3063
                return pkScript, nil
3✔
3064
        }
3065

3066
        multiSigScript, err := input.GenMultiSigScript(
3✔
3067
                localKey.SerializeCompressed(),
3✔
3068
                remoteKey.SerializeCompressed(),
3✔
3069
        )
3✔
3070
        if err != nil {
3✔
3071
                return nil, err
×
3072
        }
×
3073

3074
        return input.WitnessScriptHash(multiSigScript)
3✔
3075
}
3076

3077
// waitForFundingConfirmation handles the final stages of the channel funding
3078
// process once the funding transaction has been broadcast. The primary
3079
// function of waitForFundingConfirmation is to wait for blockchain
3080
// confirmation, and then to notify the other systems that must be notified
3081
// when a channel has become active for lightning transactions.
3082
// The wait can be canceled by closing the cancelChan. In case of success,
3083
// a *lnwire.ShortChannelID will be passed to confChan.
3084
//
3085
// NOTE: This MUST be run as a goroutine.
3086
func (f *Manager) waitForFundingConfirmation(
3087
        completeChan *channeldb.OpenChannel, cancelChan <-chan struct{},
3088
        confChan chan<- *confirmedChannel) {
3✔
3089

3✔
3090
        defer f.wg.Done()
3✔
3091
        defer close(confChan)
3✔
3092

3✔
3093
        // Register with the ChainNotifier for a notification once the funding
3✔
3094
        // transaction reaches `numConfs` confirmations.
3✔
3095
        txid := completeChan.FundingOutpoint.Hash
3✔
3096
        fundingScript, err := makeFundingScript(completeChan)
3✔
3097
        if err != nil {
3✔
3098
                log.Errorf("unable to create funding script for "+
×
3099
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3100
                        err)
×
3101
                return
×
3102
        }
×
3103
        numConfs := uint32(completeChan.NumConfsRequired)
3✔
3104

3✔
3105
        // If the underlying channel is a zero-conf channel, we'll set numConfs
3✔
3106
        // to 6, since it will be zero here.
3✔
3107
        if completeChan.IsZeroConf() {
6✔
3108
                numConfs = 6
3✔
3109
        }
3✔
3110

3111
        confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
3✔
3112
                &txid, fundingScript, numConfs,
3✔
3113
                completeChan.BroadcastHeight(),
3✔
3114
        )
3✔
3115
        if err != nil {
3✔
3116
                log.Errorf("Unable to register for confirmation of "+
×
3117
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3118
                        err)
×
3119
                return
×
3120
        }
×
3121

3122
        log.Infof("Waiting for funding tx (%v) to reach %v confirmations",
3✔
3123
                txid, numConfs)
3✔
3124

3✔
3125
        var confDetails *chainntnfs.TxConfirmation
3✔
3126
        var ok bool
3✔
3127

3✔
3128
        // Wait until the specified number of confirmations has been reached,
3✔
3129
        // we get a cancel signal, or the wallet signals a shutdown.
3✔
3130
        select {
3✔
3131
        case confDetails, ok = <-confNtfn.Confirmed:
3✔
3132
                // fallthrough
3133

UNCOV
3134
        case <-cancelChan:
×
UNCOV
3135
                log.Warnf("canceled waiting for funding confirmation, "+
×
UNCOV
3136
                        "stopping funding flow for ChannelPoint(%v)",
×
UNCOV
3137
                        completeChan.FundingOutpoint)
×
UNCOV
3138
                return
×
3139

3140
        case <-f.quit:
3✔
3141
                log.Warnf("fundingManager shutting down, stopping funding "+
3✔
3142
                        "flow for ChannelPoint(%v)",
3✔
3143
                        completeChan.FundingOutpoint)
3✔
3144
                return
3✔
3145
        }
3146

3147
        if !ok {
3✔
3148
                log.Warnf("ChainNotifier shutting down, cannot complete "+
×
3149
                        "funding flow for ChannelPoint(%v)",
×
3150
                        completeChan.FundingOutpoint)
×
3151
                return
×
3152
        }
×
3153

3154
        fundingPoint := completeChan.FundingOutpoint
3✔
3155
        log.Infof("ChannelPoint(%v) is now active: ChannelID(%v)",
3✔
3156
                fundingPoint, lnwire.NewChanIDFromOutPoint(fundingPoint))
3✔
3157

3✔
3158
        // With the block height and the transaction index known, we can
3✔
3159
        // construct the compact chanID which is used on the network to unique
3✔
3160
        // identify channels.
3✔
3161
        shortChanID := lnwire.ShortChannelID{
3✔
3162
                BlockHeight: confDetails.BlockHeight,
3✔
3163
                TxIndex:     confDetails.TxIndex,
3✔
3164
                TxPosition:  uint16(fundingPoint.Index),
3✔
3165
        }
3✔
3166

3✔
3167
        select {
3✔
3168
        case confChan <- &confirmedChannel{
3169
                shortChanID: shortChanID,
3170
                fundingTx:   confDetails.Tx,
3171
        }:
3✔
3172
        case <-f.quit:
×
3173
                return
×
3174
        }
3175
}
3176

3177
// waitForTimeout will close the timeout channel if MaxWaitNumBlocksFundingConf
3178
// has passed from the broadcast height of the given channel. In case of error,
3179
// the error is sent on timeoutChan. The wait can be canceled by closing the
3180
// cancelChan.
3181
//
3182
// NOTE: timeoutChan MUST be buffered.
3183
// NOTE: This MUST be run as a goroutine.
3184
func (f *Manager) waitForTimeout(completeChan *channeldb.OpenChannel,
3185
        cancelChan <-chan struct{}, timeoutChan chan<- error) {
3✔
3186

3✔
3187
        defer f.wg.Done()
3✔
3188

3✔
3189
        epochClient, err := f.cfg.Notifier.RegisterBlockEpochNtfn(nil)
3✔
3190
        if err != nil {
3✔
3191
                timeoutChan <- fmt.Errorf("unable to register for epoch "+
×
3192
                        "notification: %v", err)
×
3193
                return
×
3194
        }
×
3195

3196
        defer epochClient.Cancel()
3✔
3197

3✔
3198
        // On block maxHeight we will cancel the funding confirmation wait.
3✔
3199
        broadcastHeight := completeChan.BroadcastHeight()
3✔
3200
        maxHeight := broadcastHeight + MaxWaitNumBlocksFundingConf
3✔
3201
        for {
6✔
3202
                select {
3✔
3203
                case epoch, ok := <-epochClient.Epochs:
3✔
3204
                        if !ok {
3✔
3205
                                timeoutChan <- fmt.Errorf("epoch client " +
×
3206
                                        "shutting down")
×
3207
                                return
×
3208
                        }
×
3209

3210
                        // Close the timeout channel and exit if the block is
3211
                        // above the max height.
3212
                        if uint32(epoch.Height) >= maxHeight {
3✔
UNCOV
3213
                                log.Warnf("Waited for %v blocks without "+
×
UNCOV
3214
                                        "seeing funding transaction confirmed,"+
×
UNCOV
3215
                                        " cancelling.",
×
UNCOV
3216
                                        MaxWaitNumBlocksFundingConf)
×
UNCOV
3217

×
UNCOV
3218
                                // Notify the caller of the timeout.
×
UNCOV
3219
                                close(timeoutChan)
×
UNCOV
3220
                                return
×
UNCOV
3221
                        }
×
3222

3223
                        // TODO: If we are the channel initiator implement
3224
                        // a method for recovering the funds from the funding
3225
                        // transaction
3226

3227
                case <-cancelChan:
3✔
3228
                        return
3✔
3229

3230
                case <-f.quit:
3✔
3231
                        // The fundingManager is shutting down, will resume
3✔
3232
                        // waiting for the funding transaction on startup.
3✔
3233
                        return
3✔
3234
                }
3235
        }
3236
}
3237

3238
// makeLabelForTx updates the label for the confirmed funding transaction. If
3239
// we opened the channel, and lnd's wallet published our funding tx (which is
3240
// not the case for some channels) then we update our transaction label with
3241
// our short channel ID, which is known now that our funding transaction has
3242
// confirmed. We do not label transactions we did not publish, because our
3243
// wallet has no knowledge of them.
3244
func (f *Manager) makeLabelForTx(c *channeldb.OpenChannel) {
3✔
3245
        if c.IsInitiator && c.ChanType.HasFundingTx() {
6✔
3246
                shortChanID := c.ShortChanID()
3✔
3247

3✔
3248
                // For zero-conf channels, we'll use the actually-confirmed
3✔
3249
                // short channel id.
3✔
3250
                if c.IsZeroConf() {
6✔
3251
                        shortChanID = c.ZeroConfRealScid()
3✔
3252
                }
3✔
3253

3254
                label := labels.MakeLabel(
3✔
3255
                        labels.LabelTypeChannelOpen, &shortChanID,
3✔
3256
                )
3✔
3257

3✔
3258
                err := f.cfg.UpdateLabel(c.FundingOutpoint.Hash, label)
3✔
3259
                if err != nil {
3✔
3260
                        log.Errorf("unable to update label: %v", err)
×
3261
                }
×
3262
        }
3263
}
3264

3265
// handleFundingConfirmation marks a channel as open in the database, and set
3266
// the channelOpeningState markedOpen. In addition it will report the now
3267
// decided short channel ID to the switch, and close the local discovery signal
3268
// for this channel.
3269
func (f *Manager) handleFundingConfirmation(
3270
        completeChan *channeldb.OpenChannel,
3271
        confChannel *confirmedChannel) error {
3✔
3272

3✔
3273
        fundingPoint := completeChan.FundingOutpoint
3✔
3274
        chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
3✔
3275

3✔
3276
        // TODO(roasbeef): ideally persistent state update for chan above
3✔
3277
        // should be abstracted
3✔
3278

3✔
3279
        // Now that that the channel has been fully confirmed, we'll request
3✔
3280
        // that the wallet fully verify this channel to ensure that it can be
3✔
3281
        // used.
3✔
3282
        err := f.cfg.Wallet.ValidateChannel(completeChan, confChannel.fundingTx)
3✔
3283
        if err != nil {
3✔
3284
                // TODO(roasbeef): delete chan state?
×
3285
                return fmt.Errorf("unable to validate channel: %w", err)
×
3286
        }
×
3287

3288
        // Now that the channel has been validated, we'll persist an alias for
3289
        // this channel if the option-scid-alias feature-bit was negotiated.
3290
        if completeChan.NegotiatedAliasFeature() {
6✔
3291
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
3✔
3292
                if err != nil {
3✔
3293
                        return fmt.Errorf("unable to request alias: %w", err)
×
3294
                }
×
3295

3296
                err = f.cfg.AliasManager.AddLocalAlias(
3✔
3297
                        aliasScid, confChannel.shortChanID, true, false,
3✔
3298
                )
3✔
3299
                if err != nil {
3✔
3300
                        return fmt.Errorf("unable to request alias: %w", err)
×
3301
                }
×
3302
        }
3303

3304
        // The funding transaction now being confirmed, we add this channel to
3305
        // the fundingManager's internal persistent state machine that we use
3306
        // to track the remaining process of the channel opening. This is
3307
        // useful to resume the opening process in case of restarts. We set the
3308
        // opening state before we mark the channel opened in the database,
3309
        // such that we can receover from one of the db writes failing.
3310
        err = f.saveChannelOpeningState(
3✔
3311
                &fundingPoint, markedOpen, &confChannel.shortChanID,
3✔
3312
        )
3✔
3313
        if err != nil {
3✔
3314
                return fmt.Errorf("error setting channel state to "+
×
3315
                        "markedOpen: %v", err)
×
3316
        }
×
3317

3318
        // Now that the channel has been fully confirmed and we successfully
3319
        // saved the opening state, we'll mark it as open within the database.
3320
        err = completeChan.MarkAsOpen(confChannel.shortChanID)
3✔
3321
        if err != nil {
3✔
3322
                return fmt.Errorf("error setting channel pending flag to "+
×
3323
                        "false:        %v", err)
×
3324
        }
×
3325

3326
        // Update the confirmed funding transaction label.
3327
        f.makeLabelForTx(completeChan)
3✔
3328

3✔
3329
        // Inform the ChannelNotifier that the channel has transitioned from
3✔
3330
        // pending open to open.
3✔
3331
        if err := f.cfg.NotifyOpenChannelEvent(
3✔
3332
                completeChan.FundingOutpoint, completeChan.IdentityPub,
3✔
3333
        ); err != nil {
6✔
3334
                log.Errorf("Unable to notify open channel event for "+
3✔
3335
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
3✔
3336
                        err)
3✔
3337
        }
3✔
3338

3339
        // Close the discoverySignal channel, indicating to a separate
3340
        // goroutine that the channel now is marked as open in the database
3341
        // and that it is acceptable to process channel_ready messages
3342
        // from the peer.
3343
        if discoverySignal, ok := f.localDiscoverySignals.Load(chanID); ok {
6✔
3344
                close(discoverySignal)
3✔
3345
        }
3✔
3346

3347
        return nil
3✔
3348
}
3349

3350
// sendChannelReady creates and sends the channelReady message.
3351
// This should be called after the funding transaction has been confirmed,
3352
// and the channelState is 'markedOpen'.
3353
func (f *Manager) sendChannelReady(completeChan *channeldb.OpenChannel,
3354
        channel *lnwallet.LightningChannel) error {
3✔
3355

3✔
3356
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
3✔
3357

3✔
3358
        var peerKey [33]byte
3✔
3359
        copy(peerKey[:], completeChan.IdentityPub.SerializeCompressed())
3✔
3360

3✔
3361
        // Next, we'll send over the channel_ready message which marks that we
3✔
3362
        // consider the channel open by presenting the remote party with our
3✔
3363
        // next revocation key. Without the revocation key, the remote party
3✔
3364
        // will be unable to propose state transitions.
3✔
3365
        nextRevocation, err := channel.NextRevocationKey()
3✔
3366
        if err != nil {
3✔
3367
                return fmt.Errorf("unable to create next revocation: %w", err)
×
3368
        }
×
3369
        channelReadyMsg := lnwire.NewChannelReady(chanID, nextRevocation)
3✔
3370

3✔
3371
        // If this is a taproot channel, then we also need to send along our
3✔
3372
        // set of musig2 nonces as well.
3✔
3373
        if completeChan.ChanType.IsTaproot() {
6✔
3374
                log.Infof("ChanID(%v): generating musig2 nonces...",
3✔
3375
                        chanID)
3✔
3376

3✔
3377
                f.nonceMtx.Lock()
3✔
3378
                localNonce, ok := f.pendingMusigNonces[chanID]
3✔
3379
                if !ok {
6✔
3380
                        // If we don't have any nonces generated yet for this
3✔
3381
                        // first state, then we'll generate them now and stow
3✔
3382
                        // them away.  When we receive the funding locked
3✔
3383
                        // message, we'll then pass along this same set of
3✔
3384
                        // nonces.
3✔
3385
                        newNonce, err := channel.GenMusigNonces()
3✔
3386
                        if err != nil {
3✔
3387
                                f.nonceMtx.Unlock()
×
3388
                                return err
×
3389
                        }
×
3390

3391
                        // Now that we've generated the nonce for this channel,
3392
                        // we'll store it in the set of pending nonces.
3393
                        localNonce = newNonce
3✔
3394
                        f.pendingMusigNonces[chanID] = localNonce
3✔
3395
                }
3396
                f.nonceMtx.Unlock()
3✔
3397

3✔
3398
                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
3✔
3399
                        localNonce.PubNonce,
3✔
3400
                )
3✔
3401
        }
3402

3403
        // If the channel negotiated the option-scid-alias feature bit, we'll
3404
        // send a TLV segment that includes an alias the peer can use in their
3405
        // invoice hop hints. We'll send the first alias we find for the
3406
        // channel since it does not matter which alias we send. We'll error
3407
        // out in the odd case that no aliases are found.
3408
        if completeChan.NegotiatedAliasFeature() {
6✔
3409
                aliases := f.cfg.AliasManager.GetAliases(
3✔
3410
                        completeChan.ShortChanID(),
3✔
3411
                )
3✔
3412
                if len(aliases) == 0 {
3✔
3413
                        return fmt.Errorf("no aliases found")
×
3414
                }
×
3415

3416
                // We can use a pointer to aliases since GetAliases returns a
3417
                // copy of the alias slice.
3418
                channelReadyMsg.AliasScid = &aliases[0]
3✔
3419
        }
3420

3421
        // If the peer has disconnected before we reach this point, we will need
3422
        // to wait for him to come back online before sending the channelReady
3423
        // message. This is special for channelReady, since failing to send any
3424
        // of the previous messages in the funding flow just cancels the flow.
3425
        // But now the funding transaction is confirmed, the channel is open
3426
        // and we have to make sure the peer gets the channelReady message when
3427
        // it comes back online. This is also crucial during restart of lnd,
3428
        // where we might try to resend the channelReady message before the
3429
        // server has had the time to connect to the peer. We keep trying to
3430
        // send channelReady until we succeed, or the fundingManager is shut
3431
        // down.
3432
        for {
6✔
3433
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
3✔
3434
                if err != nil {
3✔
UNCOV
3435
                        return err
×
UNCOV
3436
                }
×
3437

3438
                localAlias := peer.LocalFeatures().HasFeature(
3✔
3439
                        lnwire.ScidAliasOptional,
3✔
3440
                )
3✔
3441
                remoteAlias := peer.RemoteFeatures().HasFeature(
3✔
3442
                        lnwire.ScidAliasOptional,
3✔
3443
                )
3✔
3444

3✔
3445
                // We could also refresh the channel state instead of checking
3✔
3446
                // whether the feature was negotiated, but this saves us a
3✔
3447
                // database read.
3✔
3448
                if channelReadyMsg.AliasScid == nil && localAlias &&
3✔
3449
                        remoteAlias {
3✔
3450

×
3451
                        // If an alias was not assigned above and the scid
×
3452
                        // alias feature was negotiated, check if we already
×
3453
                        // have an alias stored in case handleChannelReady was
×
3454
                        // called before this. If an alias exists, use that in
×
3455
                        // channel_ready. Otherwise, request and store an
×
3456
                        // alias and use that.
×
3457
                        aliases := f.cfg.AliasManager.GetAliases(
×
3458
                                completeChan.ShortChannelID,
×
3459
                        )
×
3460
                        if len(aliases) == 0 {
×
3461
                                // No aliases were found.
×
3462
                                alias, err := f.cfg.AliasManager.RequestAlias()
×
3463
                                if err != nil {
×
3464
                                        return err
×
3465
                                }
×
3466

3467
                                err = f.cfg.AliasManager.AddLocalAlias(
×
3468
                                        alias, completeChan.ShortChannelID,
×
3469
                                        false, false,
×
3470
                                )
×
3471
                                if err != nil {
×
3472
                                        return err
×
3473
                                }
×
3474

3475
                                channelReadyMsg.AliasScid = &alias
×
3476
                        } else {
×
3477
                                channelReadyMsg.AliasScid = &aliases[0]
×
3478
                        }
×
3479
                }
3480

3481
                log.Infof("Peer(%x) is online, sending ChannelReady "+
3✔
3482
                        "for ChannelID(%v)", peerKey, chanID)
3✔
3483

3✔
3484
                if err := peer.SendMessage(true, channelReadyMsg); err == nil {
6✔
3485
                        // Sending succeeded, we can break out and continue the
3✔
3486
                        // funding flow.
3✔
3487
                        break
3✔
3488
                }
3489

3490
                log.Warnf("Unable to send channelReady to peer %x: %v. "+
×
3491
                        "Will retry when online", peerKey, err)
×
3492
        }
3493

3494
        return nil
3✔
3495
}
3496

3497
// receivedChannelReady checks whether or not we've received a ChannelReady
3498
// from the remote peer. If we have, RemoteNextRevocation will be set.
3499
func (f *Manager) receivedChannelReady(node *btcec.PublicKey,
3500
        chanID lnwire.ChannelID) (bool, error) {
3✔
3501

3✔
3502
        // If the funding manager has exited, return an error to stop looping.
3✔
3503
        // Note that the peer may appear as online while the funding manager
3✔
3504
        // has stopped due to the shutdown order in the server.
3✔
3505
        select {
3✔
3506
        case <-f.quit:
×
3507
                return false, ErrFundingManagerShuttingDown
×
3508
        default:
3✔
3509
        }
3510

3511
        // Avoid a tight loop if peer is offline.
3512
        if _, err := f.waitForPeerOnline(node); err != nil {
3✔
3513
                log.Errorf("Wait for peer online failed: %v", err)
×
3514
                return false, err
×
3515
        }
×
3516

3517
        // If we cannot find the channel, then we haven't processed the
3518
        // remote's channelReady message.
3519
        channel, err := f.cfg.FindChannel(node, chanID)
3✔
3520
        if err != nil {
3✔
3521
                log.Errorf("Unable to locate ChannelID(%v) to determine if "+
×
3522
                        "ChannelReady was received", chanID)
×
3523
                return false, err
×
3524
        }
×
3525

3526
        // If we haven't insert the next revocation point, we haven't finished
3527
        // processing the channel ready message.
3528
        if channel.RemoteNextRevocation == nil {
6✔
3529
                return false, nil
3✔
3530
        }
3✔
3531

3532
        // Finally, the barrier signal is removed once we finish
3533
        // `handleChannelReady`. If we can still find the signal, we haven't
3534
        // finished processing it yet.
3535
        _, loaded := f.handleChannelReadyBarriers.Load(chanID)
3✔
3536

3✔
3537
        return !loaded, nil
3✔
3538
}
3539

3540
// extractAnnounceParams extracts the various channel announcement and update
3541
// parameters that will be needed to construct a ChannelAnnouncement and a
3542
// ChannelUpdate.
3543
func (f *Manager) extractAnnounceParams(c *channeldb.OpenChannel) (
3544
        lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
3✔
3545

3✔
3546
        // We'll obtain the min HTLC value we can forward in our direction, as
3✔
3547
        // we'll use this value within our ChannelUpdate. This constraint is
3✔
3548
        // originally set by the remote node, as it will be the one that will
3✔
3549
        // need to determine the smallest HTLC it deems economically relevant.
3✔
3550
        fwdMinHTLC := c.LocalChanCfg.MinHTLC
3✔
3551

3✔
3552
        // We don't necessarily want to go as low as the remote party allows.
3✔
3553
        // Check it against our default forwarding policy.
3✔
3554
        if fwdMinHTLC < f.cfg.DefaultRoutingPolicy.MinHTLCOut {
6✔
3555
                fwdMinHTLC = f.cfg.DefaultRoutingPolicy.MinHTLCOut
3✔
3556
        }
3✔
3557

3558
        // We'll obtain the max HTLC value we can forward in our direction, as
3559
        // we'll use this value within our ChannelUpdate. This value must be <=
3560
        // channel capacity and <= the maximum in-flight msats set by the peer.
3561
        fwdMaxHTLC := c.LocalChanCfg.MaxPendingAmount
3✔
3562
        capacityMSat := lnwire.NewMSatFromSatoshis(c.Capacity)
3✔
3563
        if fwdMaxHTLC > capacityMSat {
3✔
3564
                fwdMaxHTLC = capacityMSat
×
3565
        }
×
3566

3567
        return fwdMinHTLC, fwdMaxHTLC
3✔
3568
}
3569

3570
// addToGraph sends a ChannelAnnouncement and a ChannelUpdate to the
3571
// gossiper so that the channel is added to the graph builder's internal graph.
3572
// These announcement messages are NOT broadcasted to the greater network,
3573
// only to the channel counter party. The proofs required to announce the
3574
// channel to the greater network will be created and sent in annAfterSixConfs.
3575
// The peerAlias is used for zero-conf channels to give the counter-party a
3576
// ChannelUpdate they understand. ourPolicy may be set for various
3577
// option-scid-alias channels to re-use the same policy.
3578
func (f *Manager) addToGraph(completeChan *channeldb.OpenChannel,
3579
        shortChanID *lnwire.ShortChannelID,
3580
        peerAlias *lnwire.ShortChannelID,
3581
        ourPolicy *models.ChannelEdgePolicy) error {
3✔
3582

3✔
3583
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
3✔
3584

3✔
3585
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
3✔
3586

3✔
3587
        ann, err := f.newChanAnnouncement(
3✔
3588
                f.cfg.IDKey, completeChan.IdentityPub,
3✔
3589
                &completeChan.LocalChanCfg.MultiSigKey,
3✔
3590
                completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
3✔
3591
                chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
3✔
3592
                completeChan.ChanType,
3✔
3593
        )
3✔
3594
        if err != nil {
3✔
3595
                return fmt.Errorf("error generating channel "+
×
3596
                        "announcement: %v", err)
×
3597
        }
×
3598

3599
        // Send ChannelAnnouncement and ChannelUpdate to the gossiper to add
3600
        // to the Router's topology.
3601
        errChan := f.cfg.SendAnnouncement(
3✔
3602
                ann.chanAnn, discovery.ChannelCapacity(completeChan.Capacity),
3✔
3603
                discovery.ChannelPoint(completeChan.FundingOutpoint),
3✔
3604
                discovery.TapscriptRoot(completeChan.TapscriptRoot),
3✔
3605
        )
3✔
3606
        select {
3✔
3607
        case err := <-errChan:
3✔
3608
                if err != nil {
3✔
3609
                        if graph.IsError(err, graph.ErrOutdated,
×
3610
                                graph.ErrIgnored) {
×
3611

×
3612
                                log.Debugf("Graph rejected "+
×
3613
                                        "ChannelAnnouncement: %v", err)
×
3614
                        } else {
×
3615
                                return fmt.Errorf("error sending channel "+
×
3616
                                        "announcement: %v", err)
×
3617
                        }
×
3618
                }
3619
        case <-f.quit:
×
3620
                return ErrFundingManagerShuttingDown
×
3621
        }
3622

3623
        errChan = f.cfg.SendAnnouncement(
3✔
3624
                ann.chanUpdateAnn, discovery.RemoteAlias(peerAlias),
3✔
3625
        )
3✔
3626
        select {
3✔
3627
        case err := <-errChan:
3✔
3628
                if err != nil {
3✔
3629
                        if graph.IsError(err, graph.ErrOutdated,
×
3630
                                graph.ErrIgnored) {
×
3631

×
3632
                                log.Debugf("Graph rejected "+
×
3633
                                        "ChannelUpdate: %v", err)
×
3634
                        } else {
×
3635
                                return fmt.Errorf("error sending channel "+
×
3636
                                        "update: %v", err)
×
3637
                        }
×
3638
                }
3639
        case <-f.quit:
×
3640
                return ErrFundingManagerShuttingDown
×
3641
        }
3642

3643
        return nil
3✔
3644
}
3645

3646
// annAfterSixConfs broadcasts the necessary channel announcement messages to
3647
// the network after 6 confs. Should be called after the channelReady message
3648
// is sent and the channel is added to the graph (channelState is
3649
// 'addedToGraph') and the channel is ready to be used. This is the last
3650
// step in the channel opening process, and the opening state will be deleted
3651
// from the database if successful.
3652
func (f *Manager) annAfterSixConfs(completeChan *channeldb.OpenChannel,
3653
        shortChanID *lnwire.ShortChannelID) error {
3✔
3654

3✔
3655
        // If this channel is not meant to be announced to the greater network,
3✔
3656
        // we'll only send our NodeAnnouncement to our counterparty to ensure we
3✔
3657
        // don't leak any of our information.
3✔
3658
        announceChan := completeChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
3659
        if !announceChan {
6✔
3660
                log.Debugf("Will not announce private channel %v.",
3✔
3661
                        shortChanID.ToUint64())
3✔
3662

3✔
3663
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
3✔
3664
                if err != nil {
3✔
3665
                        return err
×
3666
                }
×
3667

3668
                nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
3✔
3669
                if err != nil {
3✔
3670
                        return fmt.Errorf("unable to retrieve current node "+
×
3671
                                "announcement: %v", err)
×
3672
                }
×
3673

3674
                chanID := lnwire.NewChanIDFromOutPoint(
3✔
3675
                        completeChan.FundingOutpoint,
3✔
3676
                )
3✔
3677
                pubKey := peer.PubKey()
3✔
3678
                log.Debugf("Sending our NodeAnnouncement for "+
3✔
3679
                        "ChannelID(%v) to %x", chanID, pubKey)
3✔
3680

3✔
3681
                // TODO(halseth): make reliable. If the peer is not online this
3✔
3682
                // will fail, and the opening process will stop. Should instead
3✔
3683
                // block here, waiting for the peer to come online.
3✔
3684
                if err := peer.SendMessage(true, &nodeAnn); err != nil {
3✔
3685
                        return fmt.Errorf("unable to send node announcement "+
×
3686
                                "to peer %x: %v", pubKey, err)
×
3687
                }
×
3688
        } else {
3✔
3689
                // Otherwise, we'll wait until the funding transaction has
3✔
3690
                // reached 6 confirmations before announcing it.
3✔
3691
                numConfs := uint32(completeChan.NumConfsRequired)
3✔
3692
                if numConfs < 6 {
6✔
3693
                        numConfs = 6
3✔
3694
                }
3✔
3695
                txid := completeChan.FundingOutpoint.Hash
3✔
3696
                log.Debugf("Will announce channel %v after ChannelPoint"+
3✔
3697
                        "(%v) has gotten %d confirmations",
3✔
3698
                        shortChanID.ToUint64(), completeChan.FundingOutpoint,
3✔
3699
                        numConfs)
3✔
3700

3✔
3701
                fundingScript, err := makeFundingScript(completeChan)
3✔
3702
                if err != nil {
3✔
3703
                        return fmt.Errorf("unable to create funding script "+
×
3704
                                "for ChannelPoint(%v): %v",
×
3705
                                completeChan.FundingOutpoint, err)
×
3706
                }
×
3707

3708
                // Register with the ChainNotifier for a notification once the
3709
                // funding transaction reaches at least 6 confirmations.
3710
                confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
3✔
3711
                        &txid, fundingScript, numConfs,
3✔
3712
                        completeChan.BroadcastHeight(),
3✔
3713
                )
3✔
3714
                if err != nil {
3✔
3715
                        return fmt.Errorf("unable to register for "+
×
3716
                                "confirmation of ChannelPoint(%v): %v",
×
3717
                                completeChan.FundingOutpoint, err)
×
3718
                }
×
3719

3720
                // Wait until 6 confirmations has been reached or the wallet
3721
                // signals a shutdown.
3722
                select {
3✔
3723
                case _, ok := <-confNtfn.Confirmed:
3✔
3724
                        if !ok {
3✔
3725
                                return fmt.Errorf("ChainNotifier shutting "+
×
3726
                                        "down, cannot complete funding flow "+
×
3727
                                        "for ChannelPoint(%v)",
×
3728
                                        completeChan.FundingOutpoint)
×
3729
                        }
×
3730
                        // Fallthrough.
3731

3732
                case <-f.quit:
3✔
3733
                        return fmt.Errorf("%v, stopping funding flow for "+
3✔
3734
                                "ChannelPoint(%v)",
3✔
3735
                                ErrFundingManagerShuttingDown,
3✔
3736
                                completeChan.FundingOutpoint)
3✔
3737
                }
3738

3739
                fundingPoint := completeChan.FundingOutpoint
3✔
3740
                chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
3✔
3741

3✔
3742
                log.Infof("Announcing ChannelPoint(%v), short_chan_id=%v",
3✔
3743
                        &fundingPoint, shortChanID)
3✔
3744

3✔
3745
                // If this is a non-zero-conf option-scid-alias channel, we'll
3✔
3746
                // delete the mappings the gossiper uses so that ChannelUpdates
3✔
3747
                // with aliases won't be accepted. This is done elsewhere for
3✔
3748
                // zero-conf channels.
3✔
3749
                isScidFeature := completeChan.NegotiatedAliasFeature()
3✔
3750
                isZeroConf := completeChan.IsZeroConf()
3✔
3751
                if isScidFeature && !isZeroConf {
6✔
3752
                        baseScid := completeChan.ShortChanID()
3✔
3753
                        err := f.cfg.AliasManager.DeleteSixConfs(baseScid)
3✔
3754
                        if err != nil {
3✔
3755
                                return fmt.Errorf("failed deleting six confs "+
×
3756
                                        "maps: %v", err)
×
3757
                        }
×
3758

3759
                        // We'll delete the edge and add it again via
3760
                        // addToGraph. This is because the peer may have
3761
                        // sent us a ChannelUpdate with an alias and we don't
3762
                        // want to relay this.
3763
                        ourPolicy, err := f.cfg.DeleteAliasEdge(baseScid)
3✔
3764
                        if err != nil {
3✔
3765
                                return fmt.Errorf("failed deleting real edge "+
×
3766
                                        "for alias channel from graph: %v",
×
3767
                                        err)
×
3768
                        }
×
3769

3770
                        err = f.addToGraph(
3✔
3771
                                completeChan, &baseScid, nil, ourPolicy,
3✔
3772
                        )
3✔
3773
                        if err != nil {
3✔
3774
                                return fmt.Errorf("failed to re-add to "+
×
3775
                                        "graph: %v", err)
×
3776
                        }
×
3777
                }
3778

3779
                // Create and broadcast the proofs required to make this channel
3780
                // public and usable for other nodes for routing.
3781
                err = f.announceChannel(
3✔
3782
                        f.cfg.IDKey, completeChan.IdentityPub,
3✔
3783
                        &completeChan.LocalChanCfg.MultiSigKey,
3✔
3784
                        completeChan.RemoteChanCfg.MultiSigKey.PubKey,
3✔
3785
                        *shortChanID, chanID, completeChan.ChanType,
3✔
3786
                )
3✔
3787
                if err != nil {
6✔
3788
                        return fmt.Errorf("channel announcement failed: %w",
3✔
3789
                                err)
3✔
3790
                }
3✔
3791

3792
                log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+
3✔
3793
                        "sent to gossiper", &fundingPoint, shortChanID)
3✔
3794
        }
3795

3796
        return nil
3✔
3797
}
3798

3799
// waitForZeroConfChannel is called when the state is addedToGraph with
3800
// a zero-conf channel. This will wait for the real confirmation, add the
3801
// confirmed SCID to the router graph, and then announce after six confs.
3802
func (f *Manager) waitForZeroConfChannel(c *channeldb.OpenChannel) error {
3✔
3803
        // First we'll check whether the channel is confirmed on-chain. If it
3✔
3804
        // is already confirmed, the chainntnfs subsystem will return with the
3✔
3805
        // confirmed tx. Otherwise, we'll wait here until confirmation occurs.
3✔
3806
        confChan, err := f.waitForFundingWithTimeout(c)
3✔
3807
        if err != nil {
6✔
3808
                return fmt.Errorf("error waiting for zero-conf funding "+
3✔
3809
                        "confirmation for ChannelPoint(%v): %v",
3✔
3810
                        c.FundingOutpoint, err)
3✔
3811
        }
3✔
3812

3813
        // We'll need to refresh the channel state so that things are properly
3814
        // populated when validating the channel state. Otherwise, a panic may
3815
        // occur due to inconsistency in the OpenChannel struct.
3816
        err = c.Refresh()
3✔
3817
        if err != nil {
6✔
3818
                return fmt.Errorf("unable to refresh channel state: %w", err)
3✔
3819
        }
3✔
3820

3821
        // Now that we have the confirmed transaction and the proper SCID,
3822
        // we'll call ValidateChannel to ensure the confirmed tx is properly
3823
        // formatted.
3824
        err = f.cfg.Wallet.ValidateChannel(c, confChan.fundingTx)
3✔
3825
        if err != nil {
3✔
3826
                return fmt.Errorf("unable to validate zero-conf channel: "+
×
3827
                        "%v", err)
×
3828
        }
×
3829

3830
        // Once we know the confirmed ShortChannelID, we'll need to save it to
3831
        // the database and refresh the OpenChannel struct with it.
3832
        err = c.MarkRealScid(confChan.shortChanID)
3✔
3833
        if err != nil {
3✔
3834
                return fmt.Errorf("unable to set confirmed SCID for zero "+
×
3835
                        "channel: %v", err)
×
3836
        }
×
3837

3838
        // Six confirmations have been reached. If this channel is public,
3839
        // we'll delete some of the alias mappings the gossiper uses.
3840
        isPublic := c.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
3841
        if isPublic {
6✔
3842
                err = f.cfg.AliasManager.DeleteSixConfs(c.ShortChannelID)
3✔
3843
                if err != nil {
3✔
3844
                        return fmt.Errorf("unable to delete base alias after "+
×
3845
                                "six confirmations: %v", err)
×
3846
                }
×
3847

3848
                // TODO: Make this atomic!
3849
                ourPolicy, err := f.cfg.DeleteAliasEdge(c.ShortChanID())
3✔
3850
                if err != nil {
3✔
3851
                        return fmt.Errorf("unable to delete alias edge from "+
×
3852
                                "graph: %v", err)
×
3853
                }
×
3854

3855
                // We'll need to update the graph with the new ShortChannelID
3856
                // via an addToGraph call. We don't pass in the peer's
3857
                // alias since we'll be using the confirmed SCID from now on
3858
                // regardless if it's public or not.
3859
                err = f.addToGraph(
3✔
3860
                        c, &confChan.shortChanID, nil, ourPolicy,
3✔
3861
                )
3✔
3862
                if err != nil {
3✔
3863
                        return fmt.Errorf("failed adding confirmed zero-conf "+
×
3864
                                "SCID to graph: %v", err)
×
3865
                }
×
3866
        }
3867

3868
        // Since we have now marked down the confirmed SCID, we'll also need to
3869
        // tell the Switch to refresh the relevant ChannelLink so that forwards
3870
        // under the confirmed SCID are possible if this is a public channel.
3871
        err = f.cfg.ReportShortChanID(c.FundingOutpoint)
3✔
3872
        if err != nil {
3✔
3873
                // This should only fail if the link is not found in the
×
3874
                // Switch's linkIndex map. If this is the case, then the peer
×
3875
                // has gone offline and the next time the link is loaded, it
×
3876
                // will have a refreshed state. Just log an error here.
×
3877
                log.Errorf("unable to report scid for zero-conf channel "+
×
3878
                        "channel: %v", err)
×
3879
        }
×
3880

3881
        // Update the confirmed transaction's label.
3882
        f.makeLabelForTx(c)
3✔
3883

3✔
3884
        return nil
3✔
3885
}
3886

3887
// genFirstStateMusigNonce generates a nonces for the "first" local state. This
3888
// is the verification nonce for the state created for us after the initial
3889
// commitment transaction signed as part of the funding flow.
3890
func genFirstStateMusigNonce(channel *channeldb.OpenChannel,
3891
) (*musig2.Nonces, error) {
3✔
3892

3✔
3893
        musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
3✔
3894
                channel.RevocationProducer,
3✔
3895
        )
3✔
3896
        if err != nil {
3✔
3897
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3898
                        "nonces: %v", err)
×
3899
        }
×
3900

3901
        // We use the _next_ commitment height here as we need to generate the
3902
        // nonce for the next state the remote party will sign for us.
3903
        verNonce, err := channeldb.NewMusigVerificationNonce(
3✔
3904
                channel.LocalChanCfg.MultiSigKey.PubKey,
3✔
3905
                channel.LocalCommitment.CommitHeight+1,
3✔
3906
                musig2ShaChain,
3✔
3907
        )
3✔
3908
        if err != nil {
3✔
3909
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3910
                        "nonces: %v", err)
×
3911
        }
×
3912

3913
        return verNonce, nil
3✔
3914
}
3915

3916
// handleChannelReady finalizes the channel funding process and enables the
3917
// channel to enter normal operating mode.
3918
func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen
3919
        msg *lnwire.ChannelReady) {
3✔
3920

3✔
3921
        defer f.wg.Done()
3✔
3922

3✔
3923
        // If we are in development mode, we'll wait for specified duration
3✔
3924
        // before processing the channel ready message.
3✔
3925
        if f.cfg.Dev != nil {
6✔
3926
                duration := f.cfg.Dev.ProcessChannelReadyWait
3✔
3927
                log.Warnf("Channel(%v): sleeping %v before processing "+
3✔
3928
                        "channel_ready", msg.ChanID, duration)
3✔
3929

3✔
3930
                select {
3✔
3931
                case <-time.After(duration):
3✔
3932
                        log.Warnf("Channel(%v): slept %v before processing "+
3✔
3933
                                "channel_ready", msg.ChanID, duration)
3✔
3934
                case <-f.quit:
×
3935
                        log.Warnf("Channel(%v): quit sleeping", msg.ChanID)
×
3936
                        return
×
3937
                }
3938
        }
3939

3940
        log.Debugf("Received ChannelReady for ChannelID(%v) from "+
3✔
3941
                "peer %x", msg.ChanID,
3✔
3942
                peer.IdentityKey().SerializeCompressed())
3✔
3943

3✔
3944
        // We now load or create a new channel barrier for this channel.
3✔
3945
        _, loaded := f.handleChannelReadyBarriers.LoadOrStore(
3✔
3946
                msg.ChanID, struct{}{},
3✔
3947
        )
3✔
3948

3✔
3949
        // If we are currently in the process of handling a channel_ready
3✔
3950
        // message for this channel, ignore.
3✔
3951
        if loaded {
6✔
3952
                log.Infof("Already handling channelReady for "+
3✔
3953
                        "ChannelID(%v), ignoring.", msg.ChanID)
3✔
3954
                return
3✔
3955
        }
3✔
3956

3957
        // If not already handling channelReady for this channel, then the
3958
        // `LoadOrStore` has set up a barrier, and it will be removed once this
3959
        // function exits.
3960
        defer f.handleChannelReadyBarriers.Delete(msg.ChanID)
3✔
3961

3✔
3962
        localDiscoverySignal, ok := f.localDiscoverySignals.Load(msg.ChanID)
3✔
3963
        if ok {
6✔
3964
                // Before we proceed with processing the channel_ready
3✔
3965
                // message, we'll wait for the local waitForFundingConfirmation
3✔
3966
                // goroutine to signal that it has the necessary state in
3✔
3967
                // place. Otherwise, we may be missing critical information
3✔
3968
                // required to handle forwarded HTLC's.
3✔
3969
                select {
3✔
3970
                case <-localDiscoverySignal:
3✔
3971
                        // Fallthrough
3972
                case <-f.quit:
×
3973
                        return
×
3974
                }
3975

3976
                // With the signal received, we can now safely delete the entry
3977
                // from the map.
3978
                f.localDiscoverySignals.Delete(msg.ChanID)
3✔
3979
        }
3980

3981
        // First, we'll attempt to locate the channel whose funding workflow is
3982
        // being finalized by this message. We go to the database rather than
3983
        // our reservation map as we may have restarted, mid funding flow. Also
3984
        // provide the node's public key to make the search faster.
3985
        chanID := msg.ChanID
3✔
3986
        channel, err := f.cfg.FindChannel(peer.IdentityKey(), chanID)
3✔
3987
        if err != nil {
3✔
3988
                log.Errorf("Unable to locate ChannelID(%v), cannot complete "+
×
3989
                        "funding", chanID)
×
3990
                return
×
3991
        }
×
3992

3993
        // If this is a taproot channel, then we can generate the set of nonces
3994
        // the remote party needs to send the next remote commitment here.
3995
        var firstVerNonce *musig2.Nonces
3✔
3996
        if channel.ChanType.IsTaproot() {
6✔
3997
                firstVerNonce, err = genFirstStateMusigNonce(channel)
3✔
3998
                if err != nil {
3✔
3999
                        log.Error(err)
×
4000
                        return
×
4001
                }
×
4002
        }
4003

4004
        // We'll need to store the received TLV alias if the option_scid_alias
4005
        // feature was negotiated. This will be used to provide route hints
4006
        // during invoice creation. In the zero-conf case, it is also used to
4007
        // provide a ChannelUpdate to the remote peer. This is done before the
4008
        // call to InsertNextRevocation in case the call to PutPeerAlias fails.
4009
        // If it were to fail on the first call to handleChannelReady, we
4010
        // wouldn't want the channel to be usable yet.
4011
        if channel.NegotiatedAliasFeature() {
6✔
4012
                // If the AliasScid field is nil, we must fail out. We will
3✔
4013
                // most likely not be able to route through the peer.
3✔
4014
                if msg.AliasScid == nil {
3✔
4015
                        log.Debugf("Consider closing ChannelID(%v), peer "+
×
4016
                                "does not implement the option-scid-alias "+
×
4017
                                "feature properly", chanID)
×
4018
                        return
×
4019
                }
×
4020

4021
                // We'll store the AliasScid so that invoice creation can use
4022
                // it.
4023
                err = f.cfg.AliasManager.PutPeerAlias(chanID, *msg.AliasScid)
3✔
4024
                if err != nil {
3✔
4025
                        log.Errorf("unable to store peer's alias: %v", err)
×
4026
                        return
×
4027
                }
×
4028

4029
                // If we do not have an alias stored, we'll create one now.
4030
                // This is only used in the upgrade case where a user toggles
4031
                // the option-scid-alias feature-bit to on. We'll also send the
4032
                // channel_ready message here in case the link is created
4033
                // before sendChannelReady is called.
4034
                aliases := f.cfg.AliasManager.GetAliases(
3✔
4035
                        channel.ShortChannelID,
3✔
4036
                )
3✔
4037
                if len(aliases) == 0 {
3✔
4038
                        // No aliases were found so we'll request and store an
×
4039
                        // alias and use it in the channel_ready message.
×
4040
                        alias, err := f.cfg.AliasManager.RequestAlias()
×
4041
                        if err != nil {
×
4042
                                log.Errorf("unable to request alias: %v", err)
×
4043
                                return
×
4044
                        }
×
4045

4046
                        err = f.cfg.AliasManager.AddLocalAlias(
×
4047
                                alias, channel.ShortChannelID, false, false,
×
4048
                        )
×
4049
                        if err != nil {
×
4050
                                log.Errorf("unable to add local alias: %v",
×
4051
                                        err)
×
4052
                                return
×
4053
                        }
×
4054

4055
                        secondPoint, err := channel.SecondCommitmentPoint()
×
4056
                        if err != nil {
×
4057
                                log.Errorf("unable to fetch second "+
×
4058
                                        "commitment point: %v", err)
×
4059
                                return
×
4060
                        }
×
4061

4062
                        channelReadyMsg := lnwire.NewChannelReady(
×
4063
                                chanID, secondPoint,
×
4064
                        )
×
4065
                        channelReadyMsg.AliasScid = &alias
×
4066

×
4067
                        if firstVerNonce != nil {
×
4068
                                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:ll
×
4069
                                        firstVerNonce.PubNonce,
×
4070
                                )
×
4071
                        }
×
4072

4073
                        err = peer.SendMessage(true, channelReadyMsg)
×
4074
                        if err != nil {
×
4075
                                log.Errorf("unable to send channel_ready: %v",
×
4076
                                        err)
×
4077
                                return
×
4078
                        }
×
4079
                }
4080
        }
4081

4082
        // If the RemoteNextRevocation is non-nil, it means that we have
4083
        // already processed channelReady for this channel, so ignore. This
4084
        // check is after the alias logic so we store the peer's most recent
4085
        // alias. The spec requires us to validate that subsequent
4086
        // channel_ready messages use the same per commitment point (the
4087
        // second), but it is not actually necessary since we'll just end up
4088
        // ignoring it. We are, however, required to *send* the same per
4089
        // commitment point, since another pedantic implementation might
4090
        // verify it.
4091
        if channel.RemoteNextRevocation != nil {
6✔
4092
                log.Infof("Received duplicate channelReady for "+
3✔
4093
                        "ChannelID(%v), ignoring.", chanID)
3✔
4094
                return
3✔
4095
        }
3✔
4096

4097
        // If this is a taproot channel, then we'll need to map the received
4098
        // nonces to a nonce pair, and also fetch our pending nonces, which are
4099
        // required in order to make the channel whole.
4100
        var chanOpts []lnwallet.ChannelOpt
3✔
4101
        if channel.ChanType.IsTaproot() {
6✔
4102
                f.nonceMtx.Lock()
3✔
4103
                localNonce, ok := f.pendingMusigNonces[chanID]
3✔
4104
                if !ok {
6✔
4105
                        // If there's no pending nonce for this channel ID,
3✔
4106
                        // we'll use the one generated above.
3✔
4107
                        localNonce = firstVerNonce
3✔
4108
                        f.pendingMusigNonces[chanID] = firstVerNonce
3✔
4109
                }
3✔
4110
                f.nonceMtx.Unlock()
3✔
4111

3✔
4112
                log.Infof("ChanID(%v): applying local+remote musig2 nonces",
3✔
4113
                        chanID)
3✔
4114

3✔
4115
                remoteNonce, err := msg.NextLocalNonce.UnwrapOrErrV(
3✔
4116
                        errNoLocalNonce,
3✔
4117
                )
3✔
4118
                if err != nil {
3✔
4119
                        cid := newChanIdentifier(msg.ChanID)
×
4120
                        f.sendWarning(peer, cid, err)
×
4121

×
4122
                        return
×
4123
                }
×
4124

4125
                chanOpts = append(
3✔
4126
                        chanOpts,
3✔
4127
                        lnwallet.WithLocalMusigNonces(localNonce),
3✔
4128
                        lnwallet.WithRemoteMusigNonces(&musig2.Nonces{
3✔
4129
                                PubNonce: remoteNonce,
3✔
4130
                        }),
3✔
4131
                )
3✔
4132

3✔
4133
                // Inform the aux funding controller that the liquidity in the
3✔
4134
                // custom channel is now ready to be advertised. We potentially
3✔
4135
                // haven't sent our own channel ready message yet, but other
3✔
4136
                // than that the channel is ready to count toward available
3✔
4137
                // liquidity.
3✔
4138
                err = fn.MapOptionZ(
3✔
4139
                        f.cfg.AuxFundingController,
3✔
4140
                        func(controller AuxFundingController) error {
3✔
4141
                                return controller.ChannelReady(
×
4142
                                        lnwallet.NewAuxChanState(channel),
×
4143
                                )
×
4144
                        },
×
4145
                )
4146
                if err != nil {
3✔
4147
                        cid := newChanIdentifier(msg.ChanID)
×
4148
                        f.sendWarning(peer, cid, err)
×
4149

×
4150
                        return
×
4151
                }
×
4152
        }
4153

4154
        // The channel_ready message contains the next commitment point we'll
4155
        // need to create the next commitment state for the remote party. So
4156
        // we'll insert that into the channel now before passing it along to
4157
        // other sub-systems.
4158
        err = channel.InsertNextRevocation(msg.NextPerCommitmentPoint)
3✔
4159
        if err != nil {
3✔
4160
                log.Errorf("unable to insert next commitment point: %v", err)
×
4161
                return
×
4162
        }
×
4163

4164
        // Before we can add the channel to the peer, we'll need to ensure that
4165
        // we have an initial forwarding policy set.
4166
        if err := f.ensureInitialForwardingPolicy(chanID, channel); err != nil {
3✔
4167
                log.Errorf("Unable to ensure initial forwarding policy: %v",
×
4168
                        err)
×
4169
        }
×
4170

4171
        err = peer.AddNewChannel(&lnpeer.NewChannel{
3✔
4172
                OpenChannel: channel,
3✔
4173
                ChanOpts:    chanOpts,
3✔
4174
        }, f.quit)
3✔
4175
        if err != nil {
3✔
4176
                log.Errorf("Unable to add new channel %v with peer %x: %v",
×
4177
                        channel.FundingOutpoint,
×
4178
                        peer.IdentityKey().SerializeCompressed(), err,
×
4179
                )
×
4180
        }
×
4181
}
4182

4183
// handleChannelReadyReceived is called once the remote's channelReady message
4184
// is received and processed. At this stage, we must have sent out our
4185
// channelReady message, once the remote's channelReady is processed, the
4186
// channel is now active, thus we change its state to `addedToGraph` to
4187
// let the channel start handling routing.
4188
func (f *Manager) handleChannelReadyReceived(channel *channeldb.OpenChannel,
4189
        scid *lnwire.ShortChannelID, pendingChanID PendingChanID,
4190
        updateChan chan<- *lnrpc.OpenStatusUpdate) error {
3✔
4191

3✔
4192
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
3✔
4193

3✔
4194
        // Since we've sent+received funding locked at this point, we
3✔
4195
        // can clean up the pending musig2 nonce state.
3✔
4196
        f.nonceMtx.Lock()
3✔
4197
        delete(f.pendingMusigNonces, chanID)
3✔
4198
        f.nonceMtx.Unlock()
3✔
4199

3✔
4200
        var peerAlias *lnwire.ShortChannelID
3✔
4201
        if channel.IsZeroConf() {
6✔
4202
                // We'll need to wait until channel_ready has been received and
3✔
4203
                // the peer lets us know the alias they want to use for the
3✔
4204
                // channel. With this information, we can then construct a
3✔
4205
                // ChannelUpdate for them.  If an alias does not yet exist,
3✔
4206
                // we'll just return, letting the next iteration of the loop
3✔
4207
                // check again.
3✔
4208
                var defaultAlias lnwire.ShortChannelID
3✔
4209
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
3✔
4210
                foundAlias, _ := f.cfg.AliasManager.GetPeerAlias(chanID)
3✔
4211
                if foundAlias == defaultAlias {
3✔
4212
                        return nil
×
4213
                }
×
4214

4215
                peerAlias = &foundAlias
3✔
4216
        }
4217

4218
        err := f.addToGraph(channel, scid, peerAlias, nil)
3✔
4219
        if err != nil {
3✔
4220
                return fmt.Errorf("failed adding to graph: %w", err)
×
4221
        }
×
4222

4223
        // As the channel is now added to the ChannelRouter's topology, the
4224
        // channel is moved to the next state of the state machine. It will be
4225
        // moved to the last state (actually deleted from the database) after
4226
        // the channel is finally announced.
4227
        err = f.saveChannelOpeningState(
3✔
4228
                &channel.FundingOutpoint, addedToGraph, scid,
3✔
4229
        )
3✔
4230
        if err != nil {
3✔
4231
                return fmt.Errorf("error setting channel state to"+
×
4232
                        " addedToGraph: %w", err)
×
4233
        }
×
4234

4235
        log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
3✔
4236
                "added to graph", chanID, scid)
3✔
4237

3✔
4238
        err = fn.MapOptionZ(
3✔
4239
                f.cfg.AuxFundingController,
3✔
4240
                func(controller AuxFundingController) error {
3✔
4241
                        return controller.ChannelReady(
×
4242
                                lnwallet.NewAuxChanState(channel),
×
4243
                        )
×
4244
                },
×
4245
        )
4246
        if err != nil {
3✔
4247
                return fmt.Errorf("failed notifying aux funding controller "+
×
4248
                        "about channel ready: %w", err)
×
4249
        }
×
4250

4251
        // Give the caller a final update notifying them that the channel is
4252
        fundingPoint := channel.FundingOutpoint
3✔
4253
        cp := &lnrpc.ChannelPoint{
3✔
4254
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
3✔
4255
                        FundingTxidBytes: fundingPoint.Hash[:],
3✔
4256
                },
3✔
4257
                OutputIndex: fundingPoint.Index,
3✔
4258
        }
3✔
4259

3✔
4260
        if updateChan != nil {
6✔
4261
                upd := &lnrpc.OpenStatusUpdate{
3✔
4262
                        Update: &lnrpc.OpenStatusUpdate_ChanOpen{
3✔
4263
                                ChanOpen: &lnrpc.ChannelOpenUpdate{
3✔
4264
                                        ChannelPoint: cp,
3✔
4265
                                },
3✔
4266
                        },
3✔
4267
                        PendingChanId: pendingChanID[:],
3✔
4268
                }
3✔
4269

3✔
4270
                select {
3✔
4271
                case updateChan <- upd:
3✔
4272
                case <-f.quit:
×
4273
                        return ErrFundingManagerShuttingDown
×
4274
                }
4275
        }
4276

4277
        return nil
3✔
4278
}
4279

4280
// ensureInitialForwardingPolicy ensures that we have an initial forwarding
4281
// policy set for the given channel. If we don't, we'll fall back to the default
4282
// values.
4283
func (f *Manager) ensureInitialForwardingPolicy(chanID lnwire.ChannelID,
4284
        channel *channeldb.OpenChannel) error {
3✔
4285

3✔
4286
        // Before we can add the channel to the peer, we'll need to ensure that
3✔
4287
        // we have an initial forwarding policy set. This should always be the
3✔
4288
        // case except for a channel that was created with lnd <= 0.15.5 and
3✔
4289
        // is still pending while updating to this version.
3✔
4290
        var needDBUpdate bool
3✔
4291
        forwardingPolicy, err := f.getInitialForwardingPolicy(chanID)
3✔
4292
        if err != nil {
3✔
4293
                log.Errorf("Unable to fetch initial forwarding policy, "+
×
4294
                        "falling back to default values: %v", err)
×
4295

×
4296
                forwardingPolicy = f.defaultForwardingPolicy(
×
4297
                        channel.LocalChanCfg.ChannelStateBounds,
×
4298
                )
×
4299
                needDBUpdate = true
×
4300
        }
×
4301

4302
        // We only started storing the actual values for MinHTLCOut and MaxHTLC
4303
        // after 0.16.x, so if a channel was opened with such a version and is
4304
        // still pending while updating to this version, we'll need to set the
4305
        // values to the default values.
4306
        if forwardingPolicy.MinHTLCOut == 0 {
6✔
4307
                forwardingPolicy.MinHTLCOut = channel.LocalChanCfg.MinHTLC
3✔
4308
                needDBUpdate = true
3✔
4309
        }
3✔
4310
        if forwardingPolicy.MaxHTLC == 0 {
6✔
4311
                forwardingPolicy.MaxHTLC = channel.LocalChanCfg.MaxPendingAmount
3✔
4312
                needDBUpdate = true
3✔
4313
        }
3✔
4314

4315
        // And finally, if we found that the values currently stored aren't
4316
        // sufficient for the link, we'll update the database.
4317
        if needDBUpdate {
6✔
4318
                err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
3✔
4319
                if err != nil {
3✔
4320
                        return fmt.Errorf("unable to update initial "+
×
4321
                                "forwarding policy: %v", err)
×
4322
                }
×
4323
        }
4324

4325
        return nil
3✔
4326
}
4327

4328
// chanAnnouncement encapsulates the two authenticated announcements that we
4329
// send out to the network after a new channel has been created locally.
4330
type chanAnnouncement struct {
4331
        chanAnn       *lnwire.ChannelAnnouncement1
4332
        chanUpdateAnn *lnwire.ChannelUpdate1
4333
        chanProof     *lnwire.AnnounceSignatures1
4334
}
4335

4336
// newChanAnnouncement creates the authenticated channel announcement messages
4337
// required to broadcast a newly created channel to the network. The
4338
// announcement is two part: the first part authenticates the existence of the
4339
// channel and contains four signatures binding the funding pub keys and
4340
// identity pub keys of both parties to the channel, and the second segment is
4341
// authenticated only by us and contains our directional routing policy for the
4342
// channel. ourPolicy may be set in order to re-use an existing, non-default
4343
// policy.
4344
func (f *Manager) newChanAnnouncement(localPubKey,
4345
        remotePubKey *btcec.PublicKey, localFundingKey *keychain.KeyDescriptor,
4346
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4347
        chanID lnwire.ChannelID, fwdMinHTLC, fwdMaxHTLC lnwire.MilliSatoshi,
4348
        ourPolicy *models.ChannelEdgePolicy,
4349
        chanType channeldb.ChannelType) (*chanAnnouncement, error) {
3✔
4350

3✔
4351
        chainHash := *f.cfg.Wallet.Cfg.NetParams.GenesisHash
3✔
4352

3✔
4353
        // The unconditional section of the announcement is the ShortChannelID
3✔
4354
        // itself which compactly encodes the location of the funding output
3✔
4355
        // within the blockchain.
3✔
4356
        chanAnn := &lnwire.ChannelAnnouncement1{
3✔
4357
                ShortChannelID: shortChanID,
3✔
4358
                Features:       lnwire.NewRawFeatureVector(),
3✔
4359
                ChainHash:      chainHash,
3✔
4360
        }
3✔
4361

3✔
4362
        // If this is a taproot channel, then we'll set a special bit in the
3✔
4363
        // feature vector to indicate to the routing layer that this needs a
3✔
4364
        // slightly different type of validation.
3✔
4365
        //
3✔
4366
        // TODO(roasbeef): temp, remove after gossip 1.5
3✔
4367
        if chanType.IsTaproot() {
6✔
4368
                log.Debugf("Applying taproot feature bit to "+
3✔
4369
                        "ChannelAnnouncement for %v", chanID)
3✔
4370

3✔
4371
                chanAnn.Features.Set(
3✔
4372
                        lnwire.SimpleTaprootChannelsRequiredStaging,
3✔
4373
                )
3✔
4374
        }
3✔
4375

4376
        // The chanFlags field indicates which directed edge of the channel is
4377
        // being updated within the ChannelUpdateAnnouncement announcement
4378
        // below. A value of zero means it's the edge of the "first" node and 1
4379
        // being the other node.
4380
        var chanFlags lnwire.ChanUpdateChanFlags
3✔
4381

3✔
4382
        // The lexicographical ordering of the two identity public keys of the
3✔
4383
        // nodes indicates which of the nodes is "first". If our serialized
3✔
4384
        // identity key is lower than theirs then we're the "first" node and
3✔
4385
        // second otherwise.
3✔
4386
        selfBytes := localPubKey.SerializeCompressed()
3✔
4387
        remoteBytes := remotePubKey.SerializeCompressed()
3✔
4388
        if bytes.Compare(selfBytes, remoteBytes) == -1 {
6✔
4389
                copy(chanAnn.NodeID1[:], localPubKey.SerializeCompressed())
3✔
4390
                copy(chanAnn.NodeID2[:], remotePubKey.SerializeCompressed())
3✔
4391
                copy(
3✔
4392
                        chanAnn.BitcoinKey1[:],
3✔
4393
                        localFundingKey.PubKey.SerializeCompressed(),
3✔
4394
                )
3✔
4395
                copy(
3✔
4396
                        chanAnn.BitcoinKey2[:],
3✔
4397
                        remoteFundingKey.SerializeCompressed(),
3✔
4398
                )
3✔
4399

3✔
4400
                // If we're the first node then update the chanFlags to
3✔
4401
                // indicate the "direction" of the update.
3✔
4402
                chanFlags = 0
3✔
4403
        } else {
6✔
4404
                copy(chanAnn.NodeID1[:], remotePubKey.SerializeCompressed())
3✔
4405
                copy(chanAnn.NodeID2[:], localPubKey.SerializeCompressed())
3✔
4406
                copy(
3✔
4407
                        chanAnn.BitcoinKey1[:],
3✔
4408
                        remoteFundingKey.SerializeCompressed(),
3✔
4409
                )
3✔
4410
                copy(
3✔
4411
                        chanAnn.BitcoinKey2[:],
3✔
4412
                        localFundingKey.PubKey.SerializeCompressed(),
3✔
4413
                )
3✔
4414

3✔
4415
                // If we're the second node then update the chanFlags to
3✔
4416
                // indicate the "direction" of the update.
3✔
4417
                chanFlags = 1
3✔
4418
        }
3✔
4419

4420
        // Our channel update message flags will signal that we support the
4421
        // max_htlc field.
4422
        msgFlags := lnwire.ChanUpdateRequiredMaxHtlc
3✔
4423

3✔
4424
        // We announce the channel with the default values. Some of
3✔
4425
        // these values can later be changed by crafting a new ChannelUpdate.
3✔
4426
        chanUpdateAnn := &lnwire.ChannelUpdate1{
3✔
4427
                ShortChannelID: shortChanID,
3✔
4428
                ChainHash:      chainHash,
3✔
4429
                Timestamp:      uint32(time.Now().Unix()),
3✔
4430
                MessageFlags:   msgFlags,
3✔
4431
                ChannelFlags:   chanFlags,
3✔
4432
                TimeLockDelta: uint16(
3✔
4433
                        f.cfg.DefaultRoutingPolicy.TimeLockDelta,
3✔
4434
                ),
3✔
4435
                HtlcMinimumMsat: fwdMinHTLC,
3✔
4436
                HtlcMaximumMsat: fwdMaxHTLC,
3✔
4437
        }
3✔
4438

3✔
4439
        // The caller of newChanAnnouncement is expected to provide the initial
3✔
4440
        // forwarding policy to be announced. If no persisted initial policy
3✔
4441
        // values are found, then we will use the default policy values in the
3✔
4442
        // channel announcement.
3✔
4443
        storedFwdingPolicy, err := f.getInitialForwardingPolicy(chanID)
3✔
4444
        if err != nil && !errors.Is(err, channeldb.ErrChannelNotFound) {
3✔
4445
                return nil, errors.Errorf("unable to generate channel "+
×
4446
                        "update announcement: %v", err)
×
4447
        }
×
4448

4449
        switch {
3✔
4450
        case ourPolicy != nil:
3✔
4451
                // If ourPolicy is non-nil, modify the default parameters of the
3✔
4452
                // ChannelUpdate.
3✔
4453
                chanUpdateAnn.MessageFlags = ourPolicy.MessageFlags
3✔
4454
                chanUpdateAnn.ChannelFlags = ourPolicy.ChannelFlags
3✔
4455
                chanUpdateAnn.TimeLockDelta = ourPolicy.TimeLockDelta
3✔
4456
                chanUpdateAnn.HtlcMinimumMsat = ourPolicy.MinHTLC
3✔
4457
                chanUpdateAnn.HtlcMaximumMsat = ourPolicy.MaxHTLC
3✔
4458
                chanUpdateAnn.BaseFee = uint32(ourPolicy.FeeBaseMSat)
3✔
4459
                chanUpdateAnn.FeeRate = uint32(
3✔
4460
                        ourPolicy.FeeProportionalMillionths,
3✔
4461
                )
3✔
4462

4463
        case storedFwdingPolicy != nil:
3✔
4464
                chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
3✔
4465
                chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
3✔
4466

4467
        default:
×
4468
                log.Infof("No channel forwarding policy specified for channel "+
×
4469
                        "announcement of ChannelID(%v). "+
×
4470
                        "Assuming default fee parameters.", chanID)
×
4471
                chanUpdateAnn.BaseFee = uint32(
×
4472
                        f.cfg.DefaultRoutingPolicy.BaseFee,
×
4473
                )
×
4474
                chanUpdateAnn.FeeRate = uint32(
×
4475
                        f.cfg.DefaultRoutingPolicy.FeeRate,
×
4476
                )
×
4477
        }
4478

4479
        // With the channel update announcement constructed, we'll generate a
4480
        // signature that signs a double-sha digest of the announcement.
4481
        // This'll serve to authenticate this announcement and any other future
4482
        // updates we may send.
4483
        chanUpdateMsg, err := chanUpdateAnn.DataToSign()
3✔
4484
        if err != nil {
3✔
4485
                return nil, err
×
4486
        }
×
4487
        sig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanUpdateMsg, true)
3✔
4488
        if err != nil {
3✔
4489
                return nil, errors.Errorf("unable to generate channel "+
×
4490
                        "update announcement signature: %v", err)
×
4491
        }
×
4492
        chanUpdateAnn.Signature, err = lnwire.NewSigFromSignature(sig)
3✔
4493
        if err != nil {
3✔
4494
                return nil, errors.Errorf("unable to generate channel "+
×
4495
                        "update announcement signature: %v", err)
×
4496
        }
×
4497

4498
        // The channel existence proofs itself is currently announced in
4499
        // distinct message. In order to properly authenticate this message, we
4500
        // need two signatures: one under the identity public key used which
4501
        // signs the message itself and another signature of the identity
4502
        // public key under the funding key itself.
4503
        //
4504
        // TODO(roasbeef): use SignAnnouncement here instead?
4505
        chanAnnMsg, err := chanAnn.DataToSign()
3✔
4506
        if err != nil {
3✔
4507
                return nil, err
×
4508
        }
×
4509
        nodeSig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanAnnMsg, true)
3✔
4510
        if err != nil {
3✔
4511
                return nil, errors.Errorf("unable to generate node "+
×
4512
                        "signature for channel announcement: %v", err)
×
4513
        }
×
4514
        bitcoinSig, err := f.cfg.SignMessage(
3✔
4515
                localFundingKey.KeyLocator, chanAnnMsg, true,
3✔
4516
        )
3✔
4517
        if err != nil {
3✔
4518
                return nil, errors.Errorf("unable to generate bitcoin "+
×
4519
                        "signature for node public key: %v", err)
×
4520
        }
×
4521

4522
        // Finally, we'll generate the announcement proof which we'll use to
4523
        // provide the other side with the necessary signatures required to
4524
        // allow them to reconstruct the full channel announcement.
4525
        proof := &lnwire.AnnounceSignatures1{
3✔
4526
                ChannelID:      chanID,
3✔
4527
                ShortChannelID: shortChanID,
3✔
4528
        }
3✔
4529
        proof.NodeSignature, err = lnwire.NewSigFromSignature(nodeSig)
3✔
4530
        if err != nil {
3✔
4531
                return nil, err
×
4532
        }
×
4533
        proof.BitcoinSignature, err = lnwire.NewSigFromSignature(bitcoinSig)
3✔
4534
        if err != nil {
3✔
4535
                return nil, err
×
4536
        }
×
4537

4538
        return &chanAnnouncement{
3✔
4539
                chanAnn:       chanAnn,
3✔
4540
                chanUpdateAnn: chanUpdateAnn,
3✔
4541
                chanProof:     proof,
3✔
4542
        }, nil
3✔
4543
}
4544

4545
// announceChannel announces a newly created channel to the rest of the network
4546
// by crafting the two authenticated announcements required for the peers on
4547
// the network to recognize the legitimacy of the channel. The crafted
4548
// announcements are then sent to the channel router to handle broadcasting to
4549
// the network during its next trickle.
4550
// This method is synchronous and will return when all the network requests
4551
// finish, either successfully or with an error.
4552
func (f *Manager) announceChannel(localIDKey, remoteIDKey *btcec.PublicKey,
4553
        localFundingKey *keychain.KeyDescriptor,
4554
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4555
        chanID lnwire.ChannelID, chanType channeldb.ChannelType) error {
3✔
4556

3✔
4557
        // First, we'll create the batch of announcements to be sent upon
3✔
4558
        // initial channel creation. This includes the channel announcement
3✔
4559
        // itself, the channel update announcement, and our half of the channel
3✔
4560
        // proof needed to fully authenticate the channel.
3✔
4561
        //
3✔
4562
        // We can pass in zeroes for the min and max htlc policy, because we
3✔
4563
        // only use the channel announcement message from the returned struct.
3✔
4564
        ann, err := f.newChanAnnouncement(
3✔
4565
                localIDKey, remoteIDKey, localFundingKey, remoteFundingKey,
3✔
4566
                shortChanID, chanID, 0, 0, nil, chanType,
3✔
4567
        )
3✔
4568
        if err != nil {
3✔
4569
                log.Errorf("can't generate channel announcement: %v", err)
×
4570
                return err
×
4571
        }
×
4572

4573
        // We only send the channel proof announcement and the node announcement
4574
        // because addToGraph previously sent the ChannelAnnouncement and
4575
        // the ChannelUpdate announcement messages. The channel proof and node
4576
        // announcements are broadcast to the greater network.
4577
        errChan := f.cfg.SendAnnouncement(ann.chanProof)
3✔
4578
        select {
3✔
4579
        case err := <-errChan:
3✔
4580
                if err != nil {
6✔
4581
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4582
                                graph.ErrIgnored) {
3✔
4583

×
4584
                                log.Debugf("Graph rejected "+
×
4585
                                        "AnnounceSignatures: %v", err)
×
4586
                        } else {
3✔
4587
                                log.Errorf("Unable to send channel "+
3✔
4588
                                        "proof: %v", err)
3✔
4589
                                return err
3✔
4590
                        }
3✔
4591
                }
4592

4593
        case <-f.quit:
×
4594
                return ErrFundingManagerShuttingDown
×
4595
        }
4596

4597
        // Now that the channel is announced to the network, we will also
4598
        // obtain and send a node announcement. This is done since a node
4599
        // announcement is only accepted after a channel is known for that
4600
        // particular node, and this might be our first channel.
4601
        nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
3✔
4602
        if err != nil {
3✔
4603
                log.Errorf("can't generate node announcement: %v", err)
×
4604
                return err
×
4605
        }
×
4606

4607
        errChan = f.cfg.SendAnnouncement(&nodeAnn)
3✔
4608
        select {
3✔
4609
        case err := <-errChan:
3✔
4610
                if err != nil {
6✔
4611
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4612
                                graph.ErrIgnored) {
6✔
4613

3✔
4614
                                log.Debugf("Graph rejected "+
3✔
4615
                                        "NodeAnnouncement: %v", err)
3✔
4616
                        } else {
3✔
4617
                                log.Errorf("Unable to send node "+
×
4618
                                        "announcement: %v", err)
×
4619
                                return err
×
4620
                        }
×
4621
                }
4622

4623
        case <-f.quit:
×
4624
                return ErrFundingManagerShuttingDown
×
4625
        }
4626

4627
        return nil
3✔
4628
}
4629

4630
// InitFundingWorkflow sends a message to the funding manager instructing it
4631
// to initiate a single funder workflow with the source peer.
4632
func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg) {
3✔
4633
        f.fundingRequests <- msg
3✔
4634
}
3✔
4635

4636
// getUpfrontShutdownScript takes a user provided script and a getScript
4637
// function which can be used to generate an upfront shutdown script. If our
4638
// peer does not support the feature, this function will error if a non-zero
4639
// script was provided by the user, and return an empty script otherwise. If
4640
// our peer does support the feature, we will return the user provided script
4641
// if non-zero, or a freshly generated script if our node is configured to set
4642
// upfront shutdown scripts automatically.
4643
func getUpfrontShutdownScript(enableUpfrontShutdown bool, peer lnpeer.Peer,
4644
        script lnwire.DeliveryAddress,
4645
        getScript func(bool) (lnwire.DeliveryAddress, error)) (lnwire.DeliveryAddress,
4646
        error) {
3✔
4647

3✔
4648
        // Check whether the remote peer supports upfront shutdown scripts.
3✔
4649
        remoteUpfrontShutdown := peer.RemoteFeatures().HasFeature(
3✔
4650
                lnwire.UpfrontShutdownScriptOptional,
3✔
4651
        )
3✔
4652

3✔
4653
        // If the peer does not support upfront shutdown scripts, and one has been
3✔
4654
        // provided, return an error because the feature is not supported.
3✔
4655
        if !remoteUpfrontShutdown && len(script) != 0 {
3✔
UNCOV
4656
                return nil, errUpfrontShutdownScriptNotSupported
×
UNCOV
4657
        }
×
4658

4659
        // If the peer does not support upfront shutdown, return an empty address.
4660
        if !remoteUpfrontShutdown {
3✔
UNCOV
4661
                return nil, nil
×
UNCOV
4662
        }
×
4663

4664
        // If the user has provided an script and the peer supports the feature,
4665
        // return it. Note that user set scripts override the enable upfront
4666
        // shutdown flag.
4667
        if len(script) > 0 {
6✔
4668
                return script, nil
3✔
4669
        }
3✔
4670

4671
        // If we do not have setting of upfront shutdown script enabled, return
4672
        // an empty script.
4673
        if !enableUpfrontShutdown {
6✔
4674
                return nil, nil
3✔
4675
        }
3✔
4676

4677
        // We can safely send a taproot address iff, both sides have negotiated
4678
        // the shutdown-any-segwit feature.
UNCOV
4679
        taprootOK := peer.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
×
UNCOV
4680
                peer.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
×
UNCOV
4681

×
UNCOV
4682
        return getScript(taprootOK)
×
4683
}
4684

4685
// handleInitFundingMsg creates a channel reservation within the daemon's
4686
// wallet, then sends a funding request to the remote peer kicking off the
4687
// funding workflow.
4688
func (f *Manager) handleInitFundingMsg(msg *InitFundingMsg) {
3✔
4689
        var (
3✔
4690
                peerKey        = msg.Peer.IdentityKey()
3✔
4691
                localAmt       = msg.LocalFundingAmt
3✔
4692
                baseFee        = msg.BaseFee
3✔
4693
                feeRate        = msg.FeeRate
3✔
4694
                minHtlcIn      = msg.MinHtlcIn
3✔
4695
                remoteCsvDelay = msg.RemoteCsvDelay
3✔
4696
                maxValue       = msg.MaxValueInFlight
3✔
4697
                maxHtlcs       = msg.MaxHtlcs
3✔
4698
                maxCSV         = msg.MaxLocalCsv
3✔
4699
                chanReserve    = msg.RemoteChanReserve
3✔
4700
                outpoints      = msg.Outpoints
3✔
4701
        )
3✔
4702

3✔
4703
        // If no maximum CSV delay was set for this channel, we use our default
3✔
4704
        // value.
3✔
4705
        if maxCSV == 0 {
6✔
4706
                maxCSV = f.cfg.MaxLocalCSVDelay
3✔
4707
        }
3✔
4708

4709
        log.Infof("Initiating fundingRequest(local_amt=%v "+
3✔
4710
                "(subtract_fees=%v), push_amt=%v, chain_hash=%v, peer=%x, "+
3✔
4711
                "min_confs=%v)", localAmt, msg.SubtractFees, msg.PushAmt,
3✔
4712
                msg.ChainHash, peerKey.SerializeCompressed(), msg.MinConfs)
3✔
4713

3✔
4714
        // We set the channel flags to indicate whether we want this channel to
3✔
4715
        // be announced to the network.
3✔
4716
        var channelFlags lnwire.FundingFlag
3✔
4717
        if !msg.Private {
6✔
4718
                // This channel will be announced.
3✔
4719
                channelFlags = lnwire.FFAnnounceChannel
3✔
4720
        }
3✔
4721

4722
        // If the caller specified their own channel ID, then we'll use that.
4723
        // Otherwise we'll generate a fresh one as normal.  This will be used
4724
        // to track this reservation throughout its lifetime.
4725
        var chanID PendingChanID
3✔
4726
        if msg.PendingChanID == zeroID {
6✔
4727
                chanID = f.nextPendingChanID()
3✔
4728
        } else {
6✔
4729
                // If the user specified their own pending channel ID, then
3✔
4730
                // we'll ensure it doesn't collide with any existing pending
3✔
4731
                // channel ID.
3✔
4732
                chanID = msg.PendingChanID
3✔
4733
                if _, err := f.getReservationCtx(peerKey, chanID); err == nil {
3✔
4734
                        msg.Err <- fmt.Errorf("pendingChannelID(%x) "+
×
4735
                                "already present", chanID[:])
×
4736
                        return
×
4737
                }
×
4738
        }
4739

4740
        // Check whether the peer supports upfront shutdown, and get an address
4741
        // which should be used (either a user specified address or a new
4742
        // address from the wallet if our node is configured to set shutdown
4743
        // address by default).
4744
        shutdown, err := getUpfrontShutdownScript(
3✔
4745
                f.cfg.EnableUpfrontShutdown, msg.Peer, msg.ShutdownScript,
3✔
4746
                f.selectShutdownScript,
3✔
4747
        )
3✔
4748
        if err != nil {
3✔
4749
                msg.Err <- err
×
4750
                return
×
4751
        }
×
4752

4753
        // Initialize a funding reservation with the local wallet. If the
4754
        // wallet doesn't have enough funds to commit to this channel, then the
4755
        // request will fail, and be aborted.
4756
        //
4757
        // Before we init the channel, we'll also check to see what commitment
4758
        // format we can use with this peer. This is dependent on *both* us and
4759
        // the remote peer are signaling the proper feature bit.
4760
        chanType, commitType, err := negotiateCommitmentType(
3✔
4761
                msg.ChannelType, msg.Peer.LocalFeatures(),
3✔
4762
                msg.Peer.RemoteFeatures(),
3✔
4763
        )
3✔
4764
        if err != nil {
6✔
4765
                log.Errorf("channel type negotiation failed: %v", err)
3✔
4766
                msg.Err <- err
3✔
4767
                return
3✔
4768
        }
3✔
4769

4770
        var (
3✔
4771
                zeroConf bool
3✔
4772
                scid     bool
3✔
4773
        )
3✔
4774

3✔
4775
        if chanType != nil {
6✔
4776
                // Check if the returned chanType includes either the zero-conf
3✔
4777
                // or scid-alias bits.
3✔
4778
                featureVec := lnwire.RawFeatureVector(*chanType)
3✔
4779
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
3✔
4780
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
3✔
4781

3✔
4782
                // The option-scid-alias channel type for a public channel is
3✔
4783
                // disallowed.
3✔
4784
                if scid && !msg.Private {
3✔
4785
                        err = fmt.Errorf("option-scid-alias chantype for " +
×
4786
                                "public channel")
×
4787
                        log.Error(err)
×
4788
                        msg.Err <- err
×
4789

×
4790
                        return
×
4791
                }
×
4792
        }
4793

4794
        // First, we'll query the fee estimator for a fee that should get the
4795
        // commitment transaction confirmed by the next few blocks (conf target
4796
        // of 3). We target the near blocks here to ensure that we'll be able
4797
        // to execute a timely unilateral channel closure if needed.
4798
        commitFeePerKw, err := f.cfg.FeeEstimator.EstimateFeePerKW(3)
3✔
4799
        if err != nil {
3✔
4800
                msg.Err <- err
×
4801
                return
×
4802
        }
×
4803

4804
        // For anchor channels cap the initial commit fee rate at our defined
4805
        // maximum.
4806
        if commitType.HasAnchors() &&
3✔
4807
                commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
6✔
4808

3✔
4809
                commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate
3✔
4810
        }
3✔
4811

4812
        var scidFeatureVal bool
3✔
4813
        if hasFeatures(
3✔
4814
                msg.Peer.LocalFeatures(), msg.Peer.RemoteFeatures(),
3✔
4815
                lnwire.ScidAliasOptional,
3✔
4816
        ) {
6✔
4817

3✔
4818
                scidFeatureVal = true
3✔
4819
        }
3✔
4820

4821
        // At this point, if we have an AuxFundingController active, we'll check
4822
        // to see if we have a special tapscript root to use in our MuSig2
4823
        // funding output.
4824
        tapscriptRoot, err := fn.MapOptionZ(
3✔
4825
                f.cfg.AuxFundingController,
3✔
4826
                func(c AuxFundingController) AuxTapscriptResult {
3✔
4827
                        return c.DeriveTapscriptRoot(chanID)
×
4828
                },
×
4829
        ).Unpack()
4830
        if err != nil {
3✔
4831
                err = fmt.Errorf("error deriving tapscript root: %w", err)
×
4832
                log.Error(err)
×
4833
                msg.Err <- err
×
4834

×
4835
                return
×
4836
        }
×
4837

4838
        req := &lnwallet.InitFundingReserveMsg{
3✔
4839
                ChainHash:         &msg.ChainHash,
3✔
4840
                PendingChanID:     chanID,
3✔
4841
                NodeID:            peerKey,
3✔
4842
                NodeAddr:          msg.Peer.Address(),
3✔
4843
                SubtractFees:      msg.SubtractFees,
3✔
4844
                LocalFundingAmt:   localAmt,
3✔
4845
                RemoteFundingAmt:  0,
3✔
4846
                FundUpToMaxAmt:    msg.FundUpToMaxAmt,
3✔
4847
                MinFundAmt:        msg.MinFundAmt,
3✔
4848
                RemoteChanReserve: chanReserve,
3✔
4849
                Outpoints:         outpoints,
3✔
4850
                CommitFeePerKw:    commitFeePerKw,
3✔
4851
                FundingFeePerKw:   msg.FundingFeePerKw,
3✔
4852
                PushMSat:          msg.PushAmt,
3✔
4853
                Flags:             channelFlags,
3✔
4854
                MinConfs:          msg.MinConfs,
3✔
4855
                CommitType:        commitType,
3✔
4856
                ChanFunder:        msg.ChanFunder,
3✔
4857
                // Unconfirmed Utxos which are marked by the sweeper subsystem
3✔
4858
                // are excluded from the coin selection because they are not
3✔
4859
                // final and can be RBFed by the sweeper subsystem.
3✔
4860
                AllowUtxoForFunding: func(u lnwallet.Utxo) bool {
6✔
4861
                        // Utxos with at least 1 confirmation are safe to use
3✔
4862
                        // for channel openings because they don't bare the risk
3✔
4863
                        // of being replaced (BIP 125 RBF).
3✔
4864
                        if u.Confirmations > 0 {
6✔
4865
                                return true
3✔
4866
                        }
3✔
4867

4868
                        // Query the sweeper storage to make sure we don't use
4869
                        // an unconfirmed utxo still in use by the sweeper
4870
                        // subsystem.
4871
                        return !f.cfg.IsSweeperOutpoint(u.OutPoint)
3✔
4872
                },
4873
                ZeroConf:         zeroConf,
4874
                OptionScidAlias:  scid,
4875
                ScidAliasFeature: scidFeatureVal,
4876
                Memo:             msg.Memo,
4877
                TapscriptRoot:    tapscriptRoot,
4878
        }
4879

4880
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
3✔
4881
        if err != nil {
6✔
4882
                msg.Err <- err
3✔
4883
                return
3✔
4884
        }
3✔
4885

4886
        if zeroConf {
6✔
4887
                // Store the alias for zero-conf channels in the underlying
3✔
4888
                // partial channel state.
3✔
4889
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
3✔
4890
                if err != nil {
3✔
4891
                        msg.Err <- err
×
4892
                        return
×
4893
                }
×
4894

4895
                reservation.AddAlias(aliasScid)
3✔
4896
        }
4897

4898
        // Set our upfront shutdown address in the existing reservation.
4899
        reservation.SetOurUpfrontShutdown(shutdown)
3✔
4900

3✔
4901
        // Now that we have successfully reserved funds for this channel in the
3✔
4902
        // wallet, we can fetch the final channel capacity. This is done at
3✔
4903
        // this point since the final capacity might change in case of
3✔
4904
        // SubtractFees=true.
3✔
4905
        capacity := reservation.Capacity()
3✔
4906

3✔
4907
        log.Infof("Target commit tx sat/kw for pendingID(%x): %v", chanID,
3✔
4908
                int64(commitFeePerKw))
3✔
4909

3✔
4910
        // If the remote CSV delay was not set in the open channel request,
3✔
4911
        // we'll use the RequiredRemoteDelay closure to compute the delay we
3✔
4912
        // require given the total amount of funds within the channel.
3✔
4913
        if remoteCsvDelay == 0 {
6✔
4914
                remoteCsvDelay = f.cfg.RequiredRemoteDelay(capacity)
3✔
4915
        }
3✔
4916

4917
        // If no minimum HTLC value was specified, use the default one.
4918
        if minHtlcIn == 0 {
6✔
4919
                minHtlcIn = f.cfg.DefaultMinHtlcIn
3✔
4920
        }
3✔
4921

4922
        // If no max value was specified, use the default one.
4923
        if maxValue == 0 {
6✔
4924
                maxValue = f.cfg.RequiredRemoteMaxValue(capacity)
3✔
4925
        }
3✔
4926

4927
        if maxHtlcs == 0 {
6✔
4928
                maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
3✔
4929
        }
3✔
4930

4931
        // Once the reservation has been created, and indexed, queue a funding
4932
        // request to the remote peer, kicking off the funding workflow.
4933
        ourContribution := reservation.OurContribution()
3✔
4934

3✔
4935
        // Prepare the optional channel fee values from the initFundingMsg. If
3✔
4936
        // useBaseFee or useFeeRate are false the client did not provide fee
3✔
4937
        // values hence we assume default fee settings from the config.
3✔
4938
        forwardingPolicy := f.defaultForwardingPolicy(
3✔
4939
                ourContribution.ChannelStateBounds,
3✔
4940
        )
3✔
4941
        if baseFee != nil {
6✔
4942
                forwardingPolicy.BaseFee = lnwire.MilliSatoshi(*baseFee)
3✔
4943
        }
3✔
4944

4945
        if feeRate != nil {
6✔
4946
                forwardingPolicy.FeeRate = lnwire.MilliSatoshi(*feeRate)
3✔
4947
        }
3✔
4948

4949
        // Fetch our dust limit which is part of the default channel
4950
        // constraints, and log it.
4951
        ourDustLimit := ourContribution.DustLimit
3✔
4952

3✔
4953
        log.Infof("Dust limit for pendingID(%x): %v", chanID, ourDustLimit)
3✔
4954

3✔
4955
        // If the channel reserve is not specified, then we calculate an
3✔
4956
        // appropriate amount here.
3✔
4957
        if chanReserve == 0 {
6✔
4958
                chanReserve = f.cfg.RequiredRemoteChanReserve(
3✔
4959
                        capacity, ourDustLimit,
3✔
4960
                )
3✔
4961
        }
3✔
4962

4963
        // If a pending channel map for this peer isn't already created, then
4964
        // we create one, ultimately allowing us to track this pending
4965
        // reservation within the target peer.
4966
        peerIDKey := newSerializedKey(peerKey)
3✔
4967
        f.resMtx.Lock()
3✔
4968
        if _, ok := f.activeReservations[peerIDKey]; !ok {
6✔
4969
                f.activeReservations[peerIDKey] = make(pendingChannels)
3✔
4970
        }
3✔
4971

4972
        resCtx := &reservationWithCtx{
3✔
4973
                chanAmt:           capacity,
3✔
4974
                forwardingPolicy:  *forwardingPolicy,
3✔
4975
                remoteCsvDelay:    remoteCsvDelay,
3✔
4976
                remoteMinHtlc:     minHtlcIn,
3✔
4977
                remoteMaxValue:    maxValue,
3✔
4978
                remoteMaxHtlcs:    maxHtlcs,
3✔
4979
                remoteChanReserve: chanReserve,
3✔
4980
                maxLocalCsv:       maxCSV,
3✔
4981
                channelType:       chanType,
3✔
4982
                reservation:       reservation,
3✔
4983
                peer:              msg.Peer,
3✔
4984
                updates:           msg.Updates,
3✔
4985
                err:               msg.Err,
3✔
4986
        }
3✔
4987
        f.activeReservations[peerIDKey][chanID] = resCtx
3✔
4988
        f.resMtx.Unlock()
3✔
4989

3✔
4990
        // Update the timestamp once the InitFundingMsg has been handled.
3✔
4991
        defer resCtx.updateTimestamp()
3✔
4992

3✔
4993
        // Check the sanity of the selected channel constraints.
3✔
4994
        bounds := &channeldb.ChannelStateBounds{
3✔
4995
                ChanReserve:      chanReserve,
3✔
4996
                MaxPendingAmount: maxValue,
3✔
4997
                MinHTLC:          minHtlcIn,
3✔
4998
                MaxAcceptedHtlcs: maxHtlcs,
3✔
4999
        }
3✔
5000
        commitParams := &channeldb.CommitmentParams{
3✔
5001
                DustLimit: ourDustLimit,
3✔
5002
                CsvDelay:  remoteCsvDelay,
3✔
5003
        }
3✔
5004
        err = lnwallet.VerifyConstraints(
3✔
5005
                bounds, commitParams, resCtx.maxLocalCsv, capacity,
3✔
5006
        )
3✔
5007
        if err != nil {
3✔
UNCOV
5008
                _, reserveErr := f.cancelReservationCtx(peerKey, chanID, false)
×
UNCOV
5009
                if reserveErr != nil {
×
5010
                        log.Errorf("unable to cancel reservation: %v",
×
5011
                                reserveErr)
×
5012
                }
×
5013

UNCOV
5014
                msg.Err <- err
×
UNCOV
5015
                return
×
5016
        }
5017

5018
        // When opening a script enforced channel lease, include the required
5019
        // expiry TLV record in our proposal.
5020
        var leaseExpiry *lnwire.LeaseExpiry
3✔
5021
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
6✔
5022
                leaseExpiry = new(lnwire.LeaseExpiry)
3✔
5023
                *leaseExpiry = lnwire.LeaseExpiry(reservation.LeaseExpiry())
3✔
5024
        }
3✔
5025

5026
        log.Infof("Starting funding workflow with %v for pending_id(%x), "+
3✔
5027
                "committype=%v", msg.Peer.Address(), chanID, commitType)
3✔
5028

3✔
5029
        reservation.SetState(lnwallet.SentOpenChannel)
3✔
5030

3✔
5031
        fundingOpen := lnwire.OpenChannel{
3✔
5032
                ChainHash:             *f.cfg.Wallet.Cfg.NetParams.GenesisHash,
3✔
5033
                PendingChannelID:      chanID,
3✔
5034
                FundingAmount:         capacity,
3✔
5035
                PushAmount:            msg.PushAmt,
3✔
5036
                DustLimit:             ourDustLimit,
3✔
5037
                MaxValueInFlight:      maxValue,
3✔
5038
                ChannelReserve:        chanReserve,
3✔
5039
                HtlcMinimum:           minHtlcIn,
3✔
5040
                FeePerKiloWeight:      uint32(commitFeePerKw),
3✔
5041
                CsvDelay:              remoteCsvDelay,
3✔
5042
                MaxAcceptedHTLCs:      maxHtlcs,
3✔
5043
                FundingKey:            ourContribution.MultiSigKey.PubKey,
3✔
5044
                RevocationPoint:       ourContribution.RevocationBasePoint.PubKey,
3✔
5045
                PaymentPoint:          ourContribution.PaymentBasePoint.PubKey,
3✔
5046
                HtlcPoint:             ourContribution.HtlcBasePoint.PubKey,
3✔
5047
                DelayedPaymentPoint:   ourContribution.DelayBasePoint.PubKey,
3✔
5048
                FirstCommitmentPoint:  ourContribution.FirstCommitmentPoint,
3✔
5049
                ChannelFlags:          channelFlags,
3✔
5050
                UpfrontShutdownScript: shutdown,
3✔
5051
                ChannelType:           chanType,
3✔
5052
                LeaseExpiry:           leaseExpiry,
3✔
5053
        }
3✔
5054

3✔
5055
        if commitType.IsTaproot() {
6✔
5056
                fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
3✔
5057
                        ourContribution.LocalNonce.PubNonce,
3✔
5058
                )
3✔
5059
        }
3✔
5060

5061
        if err := msg.Peer.SendMessage(true, &fundingOpen); err != nil {
3✔
5062
                e := fmt.Errorf("unable to send funding request message: %w",
×
5063
                        err)
×
5064
                log.Errorf(e.Error())
×
5065

×
5066
                // Since we were unable to send the initial message to the peer
×
5067
                // and start the funding flow, we'll cancel this reservation.
×
5068
                _, err := f.cancelReservationCtx(peerKey, chanID, false)
×
5069
                if err != nil {
×
5070
                        log.Errorf("unable to cancel reservation: %v", err)
×
5071
                }
×
5072

5073
                msg.Err <- e
×
5074
                return
×
5075
        }
5076
}
5077

5078
// handleWarningMsg processes the warning which was received from remote peer.
UNCOV
5079
func (f *Manager) handleWarningMsg(peer lnpeer.Peer, msg *lnwire.Warning) {
×
UNCOV
5080
        log.Warnf("received warning message from peer %x: %v",
×
UNCOV
5081
                peer.IdentityKey().SerializeCompressed(), msg.Warning())
×
UNCOV
5082
}
×
5083

5084
// handleErrorMsg processes the error which was received from remote peer,
5085
// depending on the type of error we should do different clean up steps and
5086
// inform the user about it.
5087
func (f *Manager) handleErrorMsg(peer lnpeer.Peer, msg *lnwire.Error) {
3✔
5088
        chanID := msg.ChanID
3✔
5089
        peerKey := peer.IdentityKey()
3✔
5090

3✔
5091
        // First, we'll attempt to retrieve and cancel the funding workflow
3✔
5092
        // that this error was tied to. If we're unable to do so, then we'll
3✔
5093
        // exit early as this was an unwarranted error.
3✔
5094
        resCtx, err := f.cancelReservationCtx(peerKey, chanID, true)
3✔
5095
        if err != nil {
3✔
5096
                log.Warnf("Received error for non-existent funding "+
×
5097
                        "flow: %v (%v)", err, msg.Error())
×
5098
                return
×
5099
        }
×
5100

5101
        // If we did indeed find the funding workflow, then we'll return the
5102
        // error back to the caller (if any), and cancel the workflow itself.
5103
        fundingErr := fmt.Errorf("received funding error from %x: %v",
3✔
5104
                peerKey.SerializeCompressed(), msg.Error(),
3✔
5105
        )
3✔
5106
        log.Errorf(fundingErr.Error())
3✔
5107

3✔
5108
        // If this was a PSBT funding flow, the remote likely timed out because
3✔
5109
        // we waited too long. Return a nice error message to the user in that
3✔
5110
        // case so the user knows what's the problem.
3✔
5111
        if resCtx.reservation.IsPsbt() {
6✔
5112
                fundingErr = fmt.Errorf("%w: %v", chanfunding.ErrRemoteCanceled,
3✔
5113
                        fundingErr)
3✔
5114
        }
3✔
5115

5116
        resCtx.err <- fundingErr
3✔
5117
}
5118

5119
// pruneZombieReservations loops through all pending reservations and fails the
5120
// funding flow for any reservations that have not been updated since the
5121
// ReservationTimeout and are not locked waiting for the funding transaction.
5122
func (f *Manager) pruneZombieReservations() {
3✔
5123
        zombieReservations := make(pendingChannels)
3✔
5124

3✔
5125
        f.resMtx.RLock()
3✔
5126
        for _, pendingReservations := range f.activeReservations {
6✔
5127
                for pendingChanID, resCtx := range pendingReservations {
6✔
5128
                        if resCtx.isLocked() {
3✔
5129
                                continue
×
5130
                        }
5131

5132
                        // We don't want to expire PSBT funding reservations.
5133
                        // These reservations are always initiated by us and the
5134
                        // remote peer is likely going to cancel them after some
5135
                        // idle time anyway. So no need for us to also prune
5136
                        // them.
5137
                        sinceLastUpdate := time.Since(resCtx.lastUpdated)
3✔
5138
                        isExpired := sinceLastUpdate > f.cfg.ReservationTimeout
3✔
5139
                        if !resCtx.reservation.IsPsbt() && isExpired {
6✔
5140
                                zombieReservations[pendingChanID] = resCtx
3✔
5141
                        }
3✔
5142
                }
5143
        }
5144
        f.resMtx.RUnlock()
3✔
5145

3✔
5146
        for pendingChanID, resCtx := range zombieReservations {
6✔
5147
                err := fmt.Errorf("reservation timed out waiting for peer "+
3✔
5148
                        "(peer_id:%x, chan_id:%x)",
3✔
5149
                        resCtx.peer.IdentityKey().SerializeCompressed(),
3✔
5150
                        pendingChanID[:])
3✔
5151
                log.Warnf(err.Error())
3✔
5152

3✔
5153
                chanID := lnwire.NewChanIDFromOutPoint(
3✔
5154
                        *resCtx.reservation.FundingOutpoint(),
3✔
5155
                )
3✔
5156

3✔
5157
                // Create channel identifier and set the channel ID.
3✔
5158
                cid := newChanIdentifier(pendingChanID)
3✔
5159
                cid.setChanID(chanID)
3✔
5160

3✔
5161
                f.failFundingFlow(resCtx.peer, cid, err)
3✔
5162
        }
3✔
5163
}
5164

5165
// cancelReservationCtx does all needed work in order to securely cancel the
5166
// reservation.
5167
func (f *Manager) cancelReservationCtx(peerKey *btcec.PublicKey,
5168
        pendingChanID PendingChanID,
5169
        byRemote bool) (*reservationWithCtx, error) {
3✔
5170

3✔
5171
        log.Infof("Cancelling funding reservation for node_key=%x, "+
3✔
5172
                "chan_id=%x", peerKey.SerializeCompressed(), pendingChanID[:])
3✔
5173

3✔
5174
        peerIDKey := newSerializedKey(peerKey)
3✔
5175
        f.resMtx.Lock()
3✔
5176
        defer f.resMtx.Unlock()
3✔
5177

3✔
5178
        nodeReservations, ok := f.activeReservations[peerIDKey]
3✔
5179
        if !ok {
6✔
5180
                // No reservations for this node.
3✔
5181
                return nil, errors.Errorf("no active reservations for peer(%x)",
3✔
5182
                        peerIDKey[:])
3✔
5183
        }
3✔
5184

5185
        ctx, ok := nodeReservations[pendingChanID]
3✔
5186
        if !ok {
3✔
UNCOV
5187
                return nil, errors.Errorf("unknown channel (id: %x) for "+
×
UNCOV
5188
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
×
UNCOV
5189
        }
×
5190

5191
        // If the reservation was a PSBT funding flow and it was canceled by the
5192
        // remote peer, then we need to thread through a different error message
5193
        // to the subroutine that's waiting for the user input so it can return
5194
        // a nice error message to the user.
5195
        if ctx.reservation.IsPsbt() && byRemote {
6✔
5196
                ctx.reservation.RemoteCanceled()
3✔
5197
        }
3✔
5198

5199
        if err := ctx.reservation.Cancel(); err != nil {
3✔
5200
                return nil, errors.Errorf("unable to cancel reservation: %v",
×
5201
                        err)
×
5202
        }
×
5203

5204
        delete(nodeReservations, pendingChanID)
3✔
5205

3✔
5206
        // If this was the last active reservation for this peer, delete the
3✔
5207
        // peer's entry altogether.
3✔
5208
        if len(nodeReservations) == 0 {
6✔
5209
                delete(f.activeReservations, peerIDKey)
3✔
5210
        }
3✔
5211
        return ctx, nil
3✔
5212
}
5213

5214
// deleteReservationCtx deletes the reservation uniquely identified by the
5215
// target public key of the peer, and the specified pending channel ID.
5216
func (f *Manager) deleteReservationCtx(peerKey *btcec.PublicKey,
5217
        pendingChanID PendingChanID) {
3✔
5218

3✔
5219
        peerIDKey := newSerializedKey(peerKey)
3✔
5220
        f.resMtx.Lock()
3✔
5221
        defer f.resMtx.Unlock()
3✔
5222

3✔
5223
        nodeReservations, ok := f.activeReservations[peerIDKey]
3✔
5224
        if !ok {
3✔
5225
                // No reservations for this node.
×
5226
                return
×
5227
        }
×
5228
        delete(nodeReservations, pendingChanID)
3✔
5229

3✔
5230
        // If this was the last active reservation for this peer, delete the
3✔
5231
        // peer's entry altogether.
3✔
5232
        if len(nodeReservations) == 0 {
6✔
5233
                delete(f.activeReservations, peerIDKey)
3✔
5234
        }
3✔
5235
}
5236

5237
// getReservationCtx returns the reservation context for a particular pending
5238
// channel ID for a target peer.
5239
func (f *Manager) getReservationCtx(peerKey *btcec.PublicKey,
5240
        pendingChanID PendingChanID) (*reservationWithCtx, error) {
3✔
5241

3✔
5242
        peerIDKey := newSerializedKey(peerKey)
3✔
5243
        f.resMtx.RLock()
3✔
5244
        resCtx, ok := f.activeReservations[peerIDKey][pendingChanID]
3✔
5245
        f.resMtx.RUnlock()
3✔
5246

3✔
5247
        if !ok {
6✔
5248
                return nil, errors.Errorf("unknown channel (id: %x) for "+
3✔
5249
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
3✔
5250
        }
3✔
5251

5252
        return resCtx, nil
3✔
5253
}
5254

5255
// IsPendingChannel returns a boolean indicating whether the channel identified
5256
// by the pendingChanID and given peer is pending, meaning it is in the process
5257
// of being funded. After the funding transaction has been confirmed, the
5258
// channel will receive a new, permanent channel ID, and will no longer be
5259
// considered pending.
5260
func (f *Manager) IsPendingChannel(pendingChanID PendingChanID,
5261
        peer lnpeer.Peer) bool {
3✔
5262

3✔
5263
        peerIDKey := newSerializedKey(peer.IdentityKey())
3✔
5264
        f.resMtx.RLock()
3✔
5265
        _, ok := f.activeReservations[peerIDKey][pendingChanID]
3✔
5266
        f.resMtx.RUnlock()
3✔
5267

3✔
5268
        return ok
3✔
5269
}
3✔
5270

5271
func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
3✔
5272
        var tmp btcec.JacobianPoint
3✔
5273
        pub.AsJacobian(&tmp)
3✔
5274
        tmp.ToAffine()
3✔
5275
        return btcec.NewPublicKey(&tmp.X, &tmp.Y)
3✔
5276
}
3✔
5277

5278
// defaultForwardingPolicy returns the default forwarding policy based on the
5279
// default routing policy and our local channel constraints.
5280
func (f *Manager) defaultForwardingPolicy(
5281
        bounds channeldb.ChannelStateBounds) *models.ForwardingPolicy {
3✔
5282

3✔
5283
        return &models.ForwardingPolicy{
3✔
5284
                MinHTLCOut:    bounds.MinHTLC,
3✔
5285
                MaxHTLC:       bounds.MaxPendingAmount,
3✔
5286
                BaseFee:       f.cfg.DefaultRoutingPolicy.BaseFee,
3✔
5287
                FeeRate:       f.cfg.DefaultRoutingPolicy.FeeRate,
3✔
5288
                TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
3✔
5289
        }
3✔
5290
}
3✔
5291

5292
// saveInitialForwardingPolicy saves the forwarding policy for the provided
5293
// chanPoint in the channelOpeningStateBucket.
5294
func (f *Manager) saveInitialForwardingPolicy(chanID lnwire.ChannelID,
5295
        forwardingPolicy *models.ForwardingPolicy) error {
3✔
5296

3✔
5297
        return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
3✔
5298
                chanID, forwardingPolicy,
3✔
5299
        )
3✔
5300
}
3✔
5301

5302
// getInitialForwardingPolicy fetches the initial forwarding policy for a given
5303
// channel id from the database which will be applied during the channel
5304
// announcement phase.
5305
func (f *Manager) getInitialForwardingPolicy(
5306
        chanID lnwire.ChannelID) (*models.ForwardingPolicy, error) {
3✔
5307

3✔
5308
        return f.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
3✔
5309
}
3✔
5310

5311
// deleteInitialForwardingPolicy removes channel fees for this chanID from
5312
// the database.
5313
func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
3✔
5314
        return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
3✔
5315
}
3✔
5316

5317
// saveChannelOpeningState saves the channelOpeningState for the provided
5318
// chanPoint to the channelOpeningStateBucket.
5319
func (f *Manager) saveChannelOpeningState(chanPoint *wire.OutPoint,
5320
        state channelOpeningState, shortChanID *lnwire.ShortChannelID) error {
3✔
5321

3✔
5322
        var outpointBytes bytes.Buffer
3✔
5323
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
3✔
5324
                return err
×
5325
        }
×
5326

5327
        // Save state and the uint64 representation of the shortChanID
5328
        // for later use.
5329
        scratch := make([]byte, 10)
3✔
5330
        byteOrder.PutUint16(scratch[:2], uint16(state))
3✔
5331
        byteOrder.PutUint64(scratch[2:], shortChanID.ToUint64())
3✔
5332

3✔
5333
        return f.cfg.ChannelDB.SaveChannelOpeningState(
3✔
5334
                outpointBytes.Bytes(), scratch,
3✔
5335
        )
3✔
5336
}
5337

5338
// getChannelOpeningState fetches the channelOpeningState for the provided
5339
// chanPoint from the database, or returns ErrChannelNotFound if the channel
5340
// is not found.
5341
func (f *Manager) getChannelOpeningState(chanPoint *wire.OutPoint) (
5342
        channelOpeningState, *lnwire.ShortChannelID, error) {
3✔
5343

3✔
5344
        var outpointBytes bytes.Buffer
3✔
5345
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
3✔
5346
                return 0, nil, err
×
5347
        }
×
5348

5349
        value, err := f.cfg.ChannelDB.GetChannelOpeningState(
3✔
5350
                outpointBytes.Bytes(),
3✔
5351
        )
3✔
5352
        if err != nil {
6✔
5353
                return 0, nil, err
3✔
5354
        }
3✔
5355

5356
        state := channelOpeningState(byteOrder.Uint16(value[:2]))
3✔
5357
        shortChanID := lnwire.NewShortChanIDFromInt(byteOrder.Uint64(value[2:]))
3✔
5358
        return state, &shortChanID, nil
3✔
5359
}
5360

5361
// deleteChannelOpeningState removes any state for chanPoint from the database.
5362
func (f *Manager) deleteChannelOpeningState(chanPoint *wire.OutPoint) error {
3✔
5363
        var outpointBytes bytes.Buffer
3✔
5364
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
3✔
5365
                return err
×
5366
        }
×
5367

5368
        return f.cfg.ChannelDB.DeleteChannelOpeningState(
3✔
5369
                outpointBytes.Bytes(),
3✔
5370
        )
3✔
5371
}
5372

5373
// selectShutdownScript selects the shutdown script we should send to the peer.
5374
// If we can use taproot, then we prefer that, otherwise we'll use a p2wkh
5375
// script.
5376
func (f *Manager) selectShutdownScript(taprootOK bool,
5377
) (lnwire.DeliveryAddress, error) {
×
5378

×
5379
        addrType := lnwallet.WitnessPubKey
×
5380
        if taprootOK {
×
5381
                addrType = lnwallet.TaprootPubkey
×
5382
        }
×
5383

5384
        addr, err := f.cfg.Wallet.NewAddress(
×
5385
                addrType, false, lnwallet.DefaultAccountName,
×
5386
        )
×
5387
        if err != nil {
×
5388
                return nil, err
×
5389
        }
×
5390

5391
        return txscript.PayToAddrScript(addr)
×
5392
}
5393

5394
// waitForPeerOnline blocks until the peer specified by peerPubkey comes online
5395
// and then returns the online peer.
5396
func (f *Manager) waitForPeerOnline(peerPubkey *btcec.PublicKey) (lnpeer.Peer,
5397
        error) {
3✔
5398

3✔
5399
        peerChan := make(chan lnpeer.Peer, 1)
3✔
5400

3✔
5401
        var peerKey [33]byte
3✔
5402
        copy(peerKey[:], peerPubkey.SerializeCompressed())
3✔
5403

3✔
5404
        f.cfg.NotifyWhenOnline(peerKey, peerChan)
3✔
5405

3✔
5406
        var peer lnpeer.Peer
3✔
5407
        select {
3✔
5408
        case peer = <-peerChan:
3✔
UNCOV
5409
        case <-f.quit:
×
UNCOV
5410
                return peer, ErrFundingManagerShuttingDown
×
5411
        }
5412
        return peer, nil
3✔
5413
}
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