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

lightningnetwork / lnd / 13315153898

13 Feb 2025 07:04PM UTC coverage: 58.791% (+9.4%) from 49.357%
13315153898

Pull #9458

github

Crypt-iQ
release-notes: update for 0.19.0
Pull Request #9458: multi+server.go: add initial permissions for some peers

332 of 551 new or added lines in 9 files covered. (60.25%)

25 existing lines in 8 files now uncovered.

136364 of 231946 relevant lines covered (58.79%)

19200.47 hits per line

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

73.57
/funding/manager.go
1
package funding
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

103
        msgBufferSize = 50
104

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

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

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

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

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

135
        zeroID [32]byte
136
)
137

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

151
        chanAmt btcutil.Amount
152

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

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

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

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

170
        updateMtx   sync.RWMutex
171
        lastUpdated time.Time
172

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

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

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

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

137✔
192
        r.lastUpdated = time.Now()
137✔
193
}
137✔
194

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

512
        // NotifyOpenChannelEvent informs the ChannelNotifier when channels
513
        // transition from pending open to open.
514
        NotifyOpenChannelEvent func(wire.OutPoint, string) error
515

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

734
        for _, channel := range allChannels {
122✔
735
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
12✔
736

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

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

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

4✔
758
                                f.rebroadcastFundingTx(channel)
4✔
759
                        }
4✔
760
                } else if channel.ChanType.IsSingleFunder() &&
11✔
761
                        channel.ChanType.HasFundingTx() &&
11✔
762
                        channel.IsZeroConf() && channel.IsInitiator &&
11✔
763
                        !channel.ZeroConfConfirmed() {
13✔
764

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

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

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

110✔
782
        return nil
110✔
783
}
784

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

106✔
792
                close(f.quit)
106✔
793
                f.wg.Wait()
106✔
794
        })
106✔
795

796
        return nil
107✔
797
}
798

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

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

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

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

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

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

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

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

59✔
852
        return nextChanID
59✔
853
}
59✔
854

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

110✔
1033
        for {
485✔
1034
                select {
375✔
1035
                case fmsg := <-f.fundingMsgs:
212✔
1036
                        switch msg := fmsg.msg.(type) {
212✔
1037
                        case *lnwire.OpenChannel:
56✔
1038
                                f.fundeeProcessOpenChannel(fmsg.peer, msg)
56✔
1039

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

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

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

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

1053
                        case *lnwire.Warning:
42✔
1054
                                f.handleWarningMsg(fmsg.peer, msg)
42✔
1055

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

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

1065
                case <-f.quit:
106✔
1066
                        return
106✔
1067
                }
1068
        }
1069
}
1070

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

66✔
1083
        defer f.wg.Done()
66✔
1084

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

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

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

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

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

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

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

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

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

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

37✔
1196
                return nil
37✔
1197

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

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

1221
                        return nil
27✔
1222
                }
1223

1224
                return f.handleChannelReadyReceived(
27✔
1225
                        channel, shortChanID, pendingChanID, updateChan,
27✔
1226
                )
27✔
1227

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

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

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

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

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

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

27✔
1277
                return nil
27✔
1278
        }
1279

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

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

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

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

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

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

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

1339
                return nil
7✔
1340
        }
1341

1342
        confChannel, err := f.waitForFundingWithTimeout(channel)
54✔
1343
        if err == ErrConfirmationTimeout {
56✔
1344
                return f.fundingTimeout(channel, pendingChanID)
2✔
1345
        } else if err != nil {
76✔
1346
                return fmt.Errorf("error waiting for funding "+
22✔
1347
                        "confirmation for ChannelPoint(%v): %v",
22✔
1348
                        channel.FundingOutpoint, err)
22✔
1349
        }
22✔
1350

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

2✔
1358
                if channel.NumConfsRequired > maturity {
2✔
1359
                        numCoinbaseConfs = uint32(channel.NumConfsRequired)
×
1360
                }
×
1361

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

×
1369
                        return err
×
1370
                }
×
1371

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

×
1381
                        return err
×
1382
                }
×
1383

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

1393
                case <-f.quit:
×
1394
                        return ErrFundingManagerShuttingDown
×
1395
                }
1396
        }
1397

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

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

1410
        return nil
33✔
1411
}
1412

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

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

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

56✔
1440
        amt := msg.FundingAmount
56✔
1441

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

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

56✔
1458
        // Create the channel identifier.
56✔
1459
        cid := newChanIdentifier(msg.PendingChannelID)
56✔
1460

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

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

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

7✔
1486
                return
7✔
1487
        }
7✔
1488

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

1496
        if len(pendingChans) > pendingChansLimit {
52✔
1497
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
×
1498
                return
×
1499
        }
×
1500

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

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

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

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

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

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

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

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

1581
        var scidFeatureVal bool
49✔
1582
        if hasFeatures(
49✔
1583
                peer.LocalFeatures(), peer.RemoteFeatures(),
49✔
1584
                lnwire.ScidAliasOptional,
49✔
1585
        ) {
55✔
1586

6✔
1587
                scidFeatureVal = true
6✔
1588
        }
6✔
1589

1590
        var (
49✔
1591
                zeroConf bool
49✔
1592
                scid     bool
49✔
1593
        )
49✔
1594

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

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

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

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

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

×
1649
                return
×
1650

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

×
1659
                return
×
1660
        }
1661

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

×
1676
                return
×
1677
        }
×
1678

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

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

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

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

1719
                reservation.AddAlias(aliasScid)
5✔
1720
        }
1721

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

1733
        // We'll ignore the min_depth calculated above if this is a zero-conf
1734
        // channel.
1735
        if zeroConf {
54✔
1736
                numConfsReq = 0
5✔
1737
        }
5✔
1738

1739
        reservation.SetNumConfsRequired(numConfsReq)
49✔
1740

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

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

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

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

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

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

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

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

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

1832
        remoteMaxValue := f.cfg.RequiredRemoteMaxValue(amt)
49✔
1833
        if acceptorResp.InFlightTotal != 0 {
49✔
1834
                remoteMaxValue = acceptorResp.InFlightTotal
×
1835
        }
×
1836

1837
        maxHtlcs := f.cfg.RequiredRemoteMaxHTLCs(amt)
49✔
1838
        if acceptorResp.HtlcLimit != 0 {
49✔
1839
                maxHtlcs = acceptorResp.HtlcLimit
×
1840
        }
×
1841

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

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

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

49✔
1881
        // Update the timestamp once the fundingOpenMsg has been handled.
49✔
1882
        defer resCtx.updateTimestamp()
49✔
1883

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

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

49✔
1921
        if resCtx.reservation.IsTaproot() {
54✔
1922
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
5✔
1923
                if err != nil {
5✔
1924
                        log.Error(errNoLocalNonce)
×
1925

×
1926
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
1927

×
1928
                        return
×
1929
                }
×
1930

1931
                remoteContribution.LocalNonce = &musig2.Nonces{
5✔
1932
                        PubNonce: localNonce,
5✔
1933
                }
5✔
1934
        }
1935

1936
        err = reservation.ProcessSingleContribution(remoteContribution)
49✔
1937
        if err != nil {
55✔
1938
                log.Errorf("unable to add contribution reservation: %v", err)
6✔
1939
                f.failFundingFlow(peer, cid, err)
6✔
1940
                return
6✔
1941
        }
6✔
1942

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

43✔
1952
        reservation.SetState(lnwallet.SentAcceptChannel)
43✔
1953

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

43✔
1976
        if commitType.IsTaproot() {
48✔
1977
                fundingAccept.LocalNonce = lnwire.SomeMusig2Nonce(
5✔
1978
                        ourContribution.LocalNonce.PubNonce,
5✔
1979
                )
5✔
1980
        }
5✔
1981

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

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

35✔
1997
        pendingChanID := msg.PendingChannelID
35✔
1998
        peerKey := peer.IdentityKey()
35✔
1999
        var peerKeyBytes []byte
35✔
2000
        if peerKey != nil {
70✔
2001
                peerKeyBytes = peerKey.SerializeCompressed()
35✔
2002
        }
35✔
2003

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

2011
        // Update the timestamp once the fundingAcceptMsg has been handled.
2012
        defer resCtx.updateTimestamp()
35✔
2013

35✔
2014
        if resCtx.reservation.State() != lnwallet.SentOpenChannel {
35✔
2015
                return
×
2016
        }
×
2017

2018
        log.Infof("Recv'd fundingResponse for pending_id(%x)",
35✔
2019
                pendingChanID[:])
35✔
2020

35✔
2021
        // Create the channel identifier.
35✔
2022
        cid := newChanIdentifier(msg.PendingChannelID)
35✔
2023

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

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

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

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

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

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

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

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

×
2117
                minDepth = 1
×
2118
        }
×
2119

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

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

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

32✔
2181
        if resCtx.reservation.IsTaproot() {
37✔
2182
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
5✔
2183
                if err != nil {
5✔
2184
                        log.Error(errNoLocalNonce)
×
2185

×
2186
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
2187

×
2188
                        return
×
2189
                }
×
2190

2191
                remoteContribution.LocalNonce = &musig2.Nonces{
5✔
2192
                        PubNonce: localNonce,
5✔
2193
                }
5✔
2194
        }
2195

2196
        err = resCtx.reservation.ProcessContribution(remoteContribution)
32✔
2197

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

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

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

3✔
2259
                        f.waitForPsbt(psbtIntent, resCtx, cid)
3✔
2260
                }()
3✔
2261

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

32✔
2395
        log.Infof("Generated ChannelPoint(%v) for pending_id(%x)", outPoint,
32✔
2396
                cid.tempChanID[:])
32✔
2397

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

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

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

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

×
2428
                        return
×
2429
                }
×
2430

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

2443
        resCtx.reservation.SetState(lnwallet.SentFundingCreated)
32✔
2444

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

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

30✔
2462
        peerKey := peer.IdentityKey()
30✔
2463
        pendingChanID := msg.PendingChannelID
30✔
2464

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

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

30✔
2480
        if resCtx.reservation.State() != lnwallet.SentAcceptChannel {
30✔
2481
                return
×
2482
        }
×
2483

2484
        // Create the channel identifier without setting the active channel ID.
2485
        cid := newChanIdentifier(pendingChanID)
30✔
2486

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

×
2496
                        return
×
2497
                }
×
2498

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

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

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

2548
        // Get forwarding policy before deleting the reservation context.
2549
        forwardingPolicy := resCtx.forwardingPolicy
30✔
2550

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

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

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

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

30✔
2589
        fundingSigned := &lnwire.FundingSigned{}
30✔
2590

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

×
2603
                        return
×
2604
                }
×
2605

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

×
2616
                        return
×
2617
                }
×
2618
        }
2619

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

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

30✔
2633
        fundingSigned.ChanID = cid.chanID
30✔
2634

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2754
                return
×
2755
        }
×
2756

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

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

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

×
2783
                        return
×
2784
                }
×
2785

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

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

2808
        // The channel is now marked IsPending in the database, and we can
2809
        // delete it from our set of active reservations.
2810
        f.deleteReservationCtx(peerKey, pendingChanID)
30✔
2811

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

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

2827
                log.Infof("Broadcasting funding tx for ChannelPoint(%v): %x",
29✔
2828
                        completeChan.FundingOutpoint, fundingTxBuf.Bytes())
29✔
2829

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

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

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

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

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

2876
        log.Infof("Finalizing pending_id(%x) over ChannelPoint(%v), "+
30✔
2877
                "waiting for channel open on-chain", pendingChanID[:],
30✔
2878
                fundingPoint)
30✔
2879

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

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

2905
        case <-f.quit:
×
2906
                return
×
2907
        }
2908

2909
        // At this point we have broadcast the funding transaction and done all
2910
        // necessary processing.
2911
        f.wg.Add(1)
30✔
2912
        go f.advanceFundingState(completeChan, pendingChanID, resCtx.updates)
30✔
2913
}
2914

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

2924
        // fundingTx is the funding transaction that created the channel.
2925
        fundingTx *wire.MsgTx
2926
}
2927

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

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

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

2960
        // Notify other subsystems about the funding timeout.
2961
        remoteHex := remotePubHex(c.IdentityPub)
2✔
2962
        err := f.cfg.NotifyFundingTimeout(c.FundingOutpoint, remoteHex)
2✔
2963
        if err != nil {
2✔
NEW
2964
                log.Errorf("failed to notify of funding timeout for "+
×
NEW
2965
                        "ChanPoint(%v): %v", c.FundingOutpoint, err)
×
NEW
2966
        }
×
2967

2968
        timeoutErr := fmt.Errorf("timeout waiting for funding tx (%v) to "+
2✔
2969
                "confirm", c.FundingOutpoint)
2✔
2970

2✔
2971
        // When the peer comes online, we'll notify it that we are now
2✔
2972
        // considering the channel flow canceled.
2✔
2973
        f.wg.Add(1)
2✔
2974
        go func() {
4✔
2975
                defer f.wg.Done()
2✔
2976

2✔
2977
                peer, err := f.waitForPeerOnline(c.IdentityPub)
2✔
2978
                switch err {
2✔
2979
                // We're already shutting down, so we can just return.
2980
                case ErrFundingManagerShuttingDown:
×
2981
                        return
×
2982

2983
                // nil error means we continue on.
2984
                case nil:
2✔
2985

2986
                // For unexpected errors, we print the error and still try to
2987
                // fail the funding flow.
2988
                default:
×
2989
                        log.Errorf("Unexpected error while waiting for peer "+
×
2990
                                "to come online: %v", err)
×
2991
                }
2992

2993
                // Create channel identifier and set the channel ID.
2994
                cid := newChanIdentifier(pendingID)
2✔
2995
                cid.setChanID(lnwire.NewChanIDFromOutPoint(c.FundingOutpoint))
2✔
2996

2✔
2997
                // TODO(halseth): should this send be made
2✔
2998
                // reliable?
2✔
2999

2✔
3000
                // The reservation won't exist at this point, but we'll send an
2✔
3001
                // Error message over anyways with ChanID set to pendingID.
2✔
3002
                f.failFundingFlow(peer, cid, timeoutErr)
2✔
3003
        }()
3004

3005
        return timeoutErr
2✔
3006
}
3007

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

60✔
3016
        confChan := make(chan *confirmedChannel)
60✔
3017
        timeoutChan := make(chan error, 1)
60✔
3018
        cancelChan := make(chan struct{})
60✔
3019

60✔
3020
        f.wg.Add(1)
60✔
3021
        go f.waitForFundingConfirmation(ch, cancelChan, confChan)
60✔
3022

60✔
3023
        // If we are not the initiator, we have no money at stake and will
60✔
3024
        // timeout waiting for the funding transaction to confirm after a
60✔
3025
        // while.
60✔
3026
        if !ch.IsInitiator && !ch.IsZeroConf() {
88✔
3027
                f.wg.Add(1)
28✔
3028
                go f.waitForTimeout(ch, cancelChan, timeoutChan)
28✔
3029
        }
28✔
3030
        defer close(cancelChan)
60✔
3031

60✔
3032
        select {
60✔
3033
        case err := <-timeoutChan:
2✔
3034
                if err != nil {
2✔
3035
                        return nil, err
×
3036
                }
×
3037
                return nil, ErrConfirmationTimeout
2✔
3038

3039
        case <-f.quit:
24✔
3040
                // The fundingManager is shutting down, and will resume wait on
24✔
3041
                // startup.
24✔
3042
                return nil, ErrFundingManagerShuttingDown
24✔
3043

3044
        case confirmedChannel, ok := <-confChan:
37✔
3045
                if !ok {
37✔
3046
                        return nil, fmt.Errorf("waiting for funding" +
×
3047
                                "confirmation failed")
×
3048
                }
×
3049
                return confirmedChannel, nil
37✔
3050
        }
3051
}
3052

3053
// makeFundingScript re-creates the funding script for the funding transaction
3054
// of the target channel.
3055
func makeFundingScript(channel *channeldb.OpenChannel) ([]byte, error) {
80✔
3056
        localKey := channel.LocalChanCfg.MultiSigKey.PubKey
80✔
3057
        remoteKey := channel.RemoteChanCfg.MultiSigKey.PubKey
80✔
3058

80✔
3059
        if channel.ChanType.IsTaproot() {
88✔
3060
                pkScript, _, err := input.GenTaprootFundingScript(
8✔
3061
                        localKey, remoteKey, int64(channel.Capacity),
8✔
3062
                        channel.TapscriptRoot,
8✔
3063
                )
8✔
3064
                if err != nil {
8✔
3065
                        return nil, err
×
3066
                }
×
3067

3068
                return pkScript, nil
8✔
3069
        }
3070

3071
        multiSigScript, err := input.GenMultiSigScript(
75✔
3072
                localKey.SerializeCompressed(),
75✔
3073
                remoteKey.SerializeCompressed(),
75✔
3074
        )
75✔
3075
        if err != nil {
75✔
3076
                return nil, err
×
3077
        }
×
3078

3079
        return input.WitnessScriptHash(multiSigScript)
75✔
3080
}
3081

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

60✔
3095
        defer f.wg.Done()
60✔
3096
        defer close(confChan)
60✔
3097

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

60✔
3110
        // If the underlying channel is a zero-conf channel, we'll set numConfs
60✔
3111
        // to 6, since it will be zero here.
60✔
3112
        if completeChan.IsZeroConf() {
69✔
3113
                numConfs = 6
9✔
3114
        }
9✔
3115

3116
        confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
60✔
3117
                &txid, fundingScript, numConfs,
60✔
3118
                completeChan.BroadcastHeight(),
60✔
3119
        )
60✔
3120
        if err != nil {
60✔
3121
                log.Errorf("Unable to register for confirmation of "+
×
3122
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3123
                        err)
×
3124
                return
×
3125
        }
×
3126

3127
        log.Infof("Waiting for funding tx (%v) to reach %v confirmations",
60✔
3128
                txid, numConfs)
60✔
3129

60✔
3130
        var confDetails *chainntnfs.TxConfirmation
60✔
3131
        var ok bool
60✔
3132

60✔
3133
        // Wait until the specified number of confirmations has been reached,
60✔
3134
        // we get a cancel signal, or the wallet signals a shutdown.
60✔
3135
        select {
60✔
3136
        case confDetails, ok = <-confNtfn.Confirmed:
37✔
3137
                // fallthrough
3138

3139
        case <-cancelChan:
4✔
3140
                log.Warnf("canceled waiting for funding confirmation, "+
4✔
3141
                        "stopping funding flow for ChannelPoint(%v)",
4✔
3142
                        completeChan.FundingOutpoint)
4✔
3143
                return
4✔
3144

3145
        case <-f.quit:
22✔
3146
                log.Warnf("fundingManager shutting down, stopping funding "+
22✔
3147
                        "flow for ChannelPoint(%v)",
22✔
3148
                        completeChan.FundingOutpoint)
22✔
3149
                return
22✔
3150
        }
3151

3152
        if !ok {
37✔
3153
                log.Warnf("ChainNotifier shutting down, cannot complete "+
×
3154
                        "funding flow for ChannelPoint(%v)",
×
3155
                        completeChan.FundingOutpoint)
×
3156
                return
×
3157
        }
×
3158

3159
        fundingPoint := completeChan.FundingOutpoint
37✔
3160
        log.Infof("ChannelPoint(%v) is now active: ChannelID(%v)",
37✔
3161
                fundingPoint, lnwire.NewChanIDFromOutPoint(fundingPoint))
37✔
3162

37✔
3163
        // With the block height and the transaction index known, we can
37✔
3164
        // construct the compact chanID which is used on the network to unique
37✔
3165
        // identify channels.
37✔
3166
        shortChanID := lnwire.ShortChannelID{
37✔
3167
                BlockHeight: confDetails.BlockHeight,
37✔
3168
                TxIndex:     confDetails.TxIndex,
37✔
3169
                TxPosition:  uint16(fundingPoint.Index),
37✔
3170
        }
37✔
3171

37✔
3172
        select {
37✔
3173
        case confChan <- &confirmedChannel{
3174
                shortChanID: shortChanID,
3175
                fundingTx:   confDetails.Tx,
3176
        }:
37✔
3177
        case <-f.quit:
×
3178
                return
×
3179
        }
3180
}
3181

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

28✔
3192
        defer f.wg.Done()
28✔
3193

28✔
3194
        epochClient, err := f.cfg.Notifier.RegisterBlockEpochNtfn(nil)
28✔
3195
        if err != nil {
28✔
3196
                timeoutChan <- fmt.Errorf("unable to register for epoch "+
×
3197
                        "notification: %v", err)
×
3198
                return
×
3199
        }
×
3200

3201
        defer epochClient.Cancel()
28✔
3202

28✔
3203
        // On block maxHeight we will cancel the funding confirmation wait.
28✔
3204
        broadcastHeight := completeChan.BroadcastHeight()
28✔
3205
        maxHeight := broadcastHeight + MaxWaitNumBlocksFundingConf
28✔
3206
        for {
58✔
3207
                select {
30✔
3208
                case epoch, ok := <-epochClient.Epochs:
7✔
3209
                        if !ok {
7✔
3210
                                timeoutChan <- fmt.Errorf("epoch client " +
×
3211
                                        "shutting down")
×
3212
                                return
×
3213
                        }
×
3214

3215
                        // Close the timeout channel and exit if the block is
3216
                        // above the max height.
3217
                        if uint32(epoch.Height) >= maxHeight {
9✔
3218
                                log.Warnf("Waited for %v blocks without "+
2✔
3219
                                        "seeing funding transaction confirmed,"+
2✔
3220
                                        " cancelling.",
2✔
3221
                                        MaxWaitNumBlocksFundingConf)
2✔
3222

2✔
3223
                                // Notify the caller of the timeout.
2✔
3224
                                close(timeoutChan)
2✔
3225
                                return
2✔
3226
                        }
2✔
3227

3228
                        // TODO: If we are the channel initiator implement
3229
                        // a method for recovering the funds from the funding
3230
                        // transaction
3231

3232
                case <-cancelChan:
18✔
3233
                        return
18✔
3234

3235
                case <-f.quit:
11✔
3236
                        // The fundingManager is shutting down, will resume
11✔
3237
                        // waiting for the funding transaction on startup.
11✔
3238
                        return
11✔
3239
                }
3240
        }
3241
}
3242

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

19✔
3253
                // For zero-conf channels, we'll use the actually-confirmed
19✔
3254
                // short channel id.
19✔
3255
                if c.IsZeroConf() {
24✔
3256
                        shortChanID = c.ZeroConfRealScid()
5✔
3257
                }
5✔
3258

3259
                label := labels.MakeLabel(
19✔
3260
                        labels.LabelTypeChannelOpen, &shortChanID,
19✔
3261
                )
19✔
3262

19✔
3263
                err := f.cfg.UpdateLabel(c.FundingOutpoint.Hash, label)
19✔
3264
                if err != nil {
19✔
3265
                        log.Errorf("unable to update label: %v", err)
×
3266
                }
×
3267
        }
3268
}
3269

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

33✔
3278
        fundingPoint := completeChan.FundingOutpoint
33✔
3279
        chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
33✔
3280

33✔
3281
        // TODO(roasbeef): ideally persistent state update for chan above
33✔
3282
        // should be abstracted
33✔
3283

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

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

3301
                err = f.cfg.AliasManager.AddLocalAlias(
5✔
3302
                        aliasScid, confChannel.shortChanID, true, false,
5✔
3303
                )
5✔
3304
                if err != nil {
5✔
3305
                        return fmt.Errorf("unable to request alias: %w", err)
×
3306
                }
×
3307
        }
3308

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

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

3331
        // Update the confirmed funding transaction label.
3332
        f.makeLabelForTx(completeChan)
33✔
3333

33✔
3334
        // Inform the ChannelNotifier that the channel has transitioned from
33✔
3335
        // pending open to open.
33✔
3336
        remoteHex := remotePubHex(completeChan.IdentityPub)
33✔
3337
        if err := f.cfg.NotifyOpenChannelEvent(
33✔
3338
                completeChan.FundingOutpoint, remoteHex,
33✔
3339
        ); err != nil {
36✔
3340
                log.Errorf("Unable to notify open channel event for "+
3✔
3341
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
3✔
3342
                        err)
3✔
3343
        }
3✔
3344

3345
        // Close the discoverySignal channel, indicating to a separate
3346
        // goroutine that the channel now is marked as open in the database
3347
        // and that it is acceptable to process channel_ready messages
3348
        // from the peer.
3349
        if discoverySignal, ok := f.localDiscoverySignals.Load(chanID); ok {
66✔
3350
                close(discoverySignal)
33✔
3351
        }
33✔
3352

3353
        return nil
33✔
3354
}
3355

3356
// sendChannelReady creates and sends the channelReady message.
3357
// This should be called after the funding transaction has been confirmed,
3358
// and the channelState is 'markedOpen'.
3359
func (f *Manager) sendChannelReady(completeChan *channeldb.OpenChannel,
3360
        channel *lnwallet.LightningChannel) error {
38✔
3361

38✔
3362
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
38✔
3363

38✔
3364
        var peerKey [33]byte
38✔
3365
        copy(peerKey[:], completeChan.IdentityPub.SerializeCompressed())
38✔
3366

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

38✔
3377
        // If this is a taproot channel, then we also need to send along our
38✔
3378
        // set of musig2 nonces as well.
38✔
3379
        if completeChan.ChanType.IsTaproot() {
45✔
3380
                log.Infof("ChanID(%v): generating musig2 nonces...",
7✔
3381
                        chanID)
7✔
3382

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

3397
                        // Now that we've generated the nonce for this channel,
3398
                        // we'll store it in the set of pending nonces.
3399
                        localNonce = newNonce
7✔
3400
                        f.pendingMusigNonces[chanID] = localNonce
7✔
3401
                }
3402
                f.nonceMtx.Unlock()
7✔
3403

7✔
3404
                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
7✔
3405
                        localNonce.PubNonce,
7✔
3406
                )
7✔
3407
        }
3408

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

3422
                // We can use a pointer to aliases since GetAliases returns a
3423
                // copy of the alias slice.
3424
                channelReadyMsg.AliasScid = &aliases[0]
9✔
3425
        }
3426

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

3444
                localAlias := peer.LocalFeatures().HasFeature(
37✔
3445
                        lnwire.ScidAliasOptional,
37✔
3446
                )
37✔
3447
                remoteAlias := peer.RemoteFeatures().HasFeature(
37✔
3448
                        lnwire.ScidAliasOptional,
37✔
3449
                )
37✔
3450

37✔
3451
                // We could also refresh the channel state instead of checking
37✔
3452
                // whether the feature was negotiated, but this saves us a
37✔
3453
                // database read.
37✔
3454
                if channelReadyMsg.AliasScid == nil && localAlias &&
37✔
3455
                        remoteAlias {
37✔
3456

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

3473
                                err = f.cfg.AliasManager.AddLocalAlias(
×
3474
                                        alias, completeChan.ShortChannelID,
×
3475
                                        false, false,
×
3476
                                )
×
3477
                                if err != nil {
×
3478
                                        return err
×
3479
                                }
×
3480

3481
                                channelReadyMsg.AliasScid = &alias
×
3482
                        } else {
×
3483
                                channelReadyMsg.AliasScid = &aliases[0]
×
3484
                        }
×
3485
                }
3486

3487
                log.Infof("Peer(%x) is online, sending ChannelReady "+
37✔
3488
                        "for ChannelID(%v)", peerKey, chanID)
37✔
3489

37✔
3490
                if err := peer.SendMessage(true, channelReadyMsg); err == nil {
74✔
3491
                        // Sending succeeded, we can break out and continue the
37✔
3492
                        // funding flow.
37✔
3493
                        break
37✔
3494
                }
3495

3496
                log.Warnf("Unable to send channelReady to peer %x: %v. "+
×
3497
                        "Will retry when online", peerKey, err)
×
3498
        }
3499

3500
        return nil
37✔
3501
}
3502

3503
// receivedChannelReady checks whether or not we've received a ChannelReady
3504
// from the remote peer. If we have, RemoteNextRevocation will be set.
3505
func (f *Manager) receivedChannelReady(node *btcec.PublicKey,
3506
        chanID lnwire.ChannelID) (bool, error) {
63✔
3507

63✔
3508
        // If the funding manager has exited, return an error to stop looping.
63✔
3509
        // Note that the peer may appear as online while the funding manager
63✔
3510
        // has stopped due to the shutdown order in the server.
63✔
3511
        select {
63✔
3512
        case <-f.quit:
×
3513
                return false, ErrFundingManagerShuttingDown
×
3514
        default:
63✔
3515
        }
3516

3517
        // Avoid a tight loop if peer is offline.
3518
        if _, err := f.waitForPeerOnline(node); err != nil {
63✔
3519
                log.Errorf("Wait for peer online failed: %v", err)
×
3520
                return false, err
×
3521
        }
×
3522

3523
        // If we cannot find the channel, then we haven't processed the
3524
        // remote's channelReady message.
3525
        channel, err := f.cfg.FindChannel(node, chanID)
63✔
3526
        if err != nil {
63✔
3527
                log.Errorf("Unable to locate ChannelID(%v) to determine if "+
×
3528
                        "ChannelReady was received", chanID)
×
3529
                return false, err
×
3530
        }
×
3531

3532
        // If we haven't insert the next revocation point, we haven't finished
3533
        // processing the channel ready message.
3534
        if channel.RemoteNextRevocation == nil {
102✔
3535
                return false, nil
39✔
3536
        }
39✔
3537

3538
        // Finally, the barrier signal is removed once we finish
3539
        // `handleChannelReady`. If we can still find the signal, we haven't
3540
        // finished processing it yet.
3541
        _, loaded := f.handleChannelReadyBarriers.Load(chanID)
27✔
3542

27✔
3543
        return !loaded, nil
27✔
3544
}
3545

3546
// extractAnnounceParams extracts the various channel announcement and update
3547
// parameters that will be needed to construct a ChannelAnnouncement and a
3548
// ChannelUpdate.
3549
func (f *Manager) extractAnnounceParams(c *channeldb.OpenChannel) (
3550
        lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
29✔
3551

29✔
3552
        // We'll obtain the min HTLC value we can forward in our direction, as
29✔
3553
        // we'll use this value within our ChannelUpdate. This constraint is
29✔
3554
        // originally set by the remote node, as it will be the one that will
29✔
3555
        // need to determine the smallest HTLC it deems economically relevant.
29✔
3556
        fwdMinHTLC := c.LocalChanCfg.MinHTLC
29✔
3557

29✔
3558
        // We don't necessarily want to go as low as the remote party allows.
29✔
3559
        // Check it against our default forwarding policy.
29✔
3560
        if fwdMinHTLC < f.cfg.DefaultRoutingPolicy.MinHTLCOut {
32✔
3561
                fwdMinHTLC = f.cfg.DefaultRoutingPolicy.MinHTLCOut
3✔
3562
        }
3✔
3563

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

3573
        return fwdMinHTLC, fwdMaxHTLC
29✔
3574
}
3575

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

29✔
3589
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
29✔
3590

29✔
3591
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
29✔
3592

29✔
3593
        ann, err := f.newChanAnnouncement(
29✔
3594
                f.cfg.IDKey, completeChan.IdentityPub,
29✔
3595
                &completeChan.LocalChanCfg.MultiSigKey,
29✔
3596
                completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
29✔
3597
                chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
29✔
3598
                completeChan.ChanType,
29✔
3599
        )
29✔
3600
        if err != nil {
29✔
3601
                return fmt.Errorf("error generating channel "+
×
3602
                        "announcement: %v", err)
×
3603
        }
×
3604

3605
        // Send ChannelAnnouncement and ChannelUpdate to the gossiper to add
3606
        // to the Router's topology.
3607
        errChan := f.cfg.SendAnnouncement(
29✔
3608
                ann.chanAnn, discovery.ChannelCapacity(completeChan.Capacity),
29✔
3609
                discovery.ChannelPoint(completeChan.FundingOutpoint),
29✔
3610
                discovery.TapscriptRoot(completeChan.TapscriptRoot),
29✔
3611
        )
29✔
3612
        select {
29✔
3613
        case err := <-errChan:
29✔
3614
                if err != nil {
29✔
3615
                        if graph.IsError(err, graph.ErrOutdated,
×
3616
                                graph.ErrIgnored) {
×
3617

×
3618
                                log.Debugf("Graph rejected "+
×
3619
                                        "ChannelAnnouncement: %v", err)
×
3620
                        } else {
×
3621
                                return fmt.Errorf("error sending channel "+
×
3622
                                        "announcement: %v", err)
×
3623
                        }
×
3624
                }
3625
        case <-f.quit:
×
3626
                return ErrFundingManagerShuttingDown
×
3627
        }
3628

3629
        errChan = f.cfg.SendAnnouncement(
29✔
3630
                ann.chanUpdateAnn, discovery.RemoteAlias(peerAlias),
29✔
3631
        )
29✔
3632
        select {
29✔
3633
        case err := <-errChan:
29✔
3634
                if err != nil {
29✔
3635
                        if graph.IsError(err, graph.ErrOutdated,
×
3636
                                graph.ErrIgnored) {
×
3637

×
3638
                                log.Debugf("Graph rejected "+
×
3639
                                        "ChannelUpdate: %v", err)
×
3640
                        } else {
×
3641
                                return fmt.Errorf("error sending channel "+
×
3642
                                        "update: %v", err)
×
3643
                        }
×
3644
                }
3645
        case <-f.quit:
×
3646
                return ErrFundingManagerShuttingDown
×
3647
        }
3648

3649
        return nil
29✔
3650
}
3651

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

29✔
3661
        // If this channel is not meant to be announced to the greater network,
29✔
3662
        // we'll only send our NodeAnnouncement to our counterparty to ensure we
29✔
3663
        // don't leak any of our information.
29✔
3664
        announceChan := completeChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
29✔
3665
        if !announceChan {
40✔
3666
                log.Debugf("Will not announce private channel %v.",
11✔
3667
                        shortChanID.ToUint64())
11✔
3668

11✔
3669
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
11✔
3670
                if err != nil {
11✔
3671
                        return err
×
3672
                }
×
3673

3674
                nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
11✔
3675
                if err != nil {
11✔
3676
                        return fmt.Errorf("unable to retrieve current node "+
×
3677
                                "announcement: %v", err)
×
3678
                }
×
3679

3680
                chanID := lnwire.NewChanIDFromOutPoint(
11✔
3681
                        completeChan.FundingOutpoint,
11✔
3682
                )
11✔
3683
                pubKey := peer.PubKey()
11✔
3684
                log.Debugf("Sending our NodeAnnouncement for "+
11✔
3685
                        "ChannelID(%v) to %x", chanID, pubKey)
11✔
3686

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

21✔
3707
                fundingScript, err := makeFundingScript(completeChan)
21✔
3708
                if err != nil {
21✔
3709
                        return fmt.Errorf("unable to create funding script "+
×
3710
                                "for ChannelPoint(%v): %v",
×
3711
                                completeChan.FundingOutpoint, err)
×
3712
                }
×
3713

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

3726
                // Wait until 6 confirmations has been reached or the wallet
3727
                // signals a shutdown.
3728
                select {
21✔
3729
                case _, ok := <-confNtfn.Confirmed:
19✔
3730
                        if !ok {
19✔
3731
                                return fmt.Errorf("ChainNotifier shutting "+
×
3732
                                        "down, cannot complete funding flow "+
×
3733
                                        "for ChannelPoint(%v)",
×
3734
                                        completeChan.FundingOutpoint)
×
3735
                        }
×
3736
                        // Fallthrough.
3737

3738
                case <-f.quit:
5✔
3739
                        return fmt.Errorf("%v, stopping funding flow for "+
5✔
3740
                                "ChannelPoint(%v)",
5✔
3741
                                ErrFundingManagerShuttingDown,
5✔
3742
                                completeChan.FundingOutpoint)
5✔
3743
                }
3744

3745
                fundingPoint := completeChan.FundingOutpoint
19✔
3746
                chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
19✔
3747

19✔
3748
                log.Infof("Announcing ChannelPoint(%v), short_chan_id=%v",
19✔
3749
                        &fundingPoint, shortChanID)
19✔
3750

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

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

3776
                        err = f.addToGraph(
3✔
3777
                                completeChan, &baseScid, nil, ourPolicy,
3✔
3778
                        )
3✔
3779
                        if err != nil {
3✔
3780
                                return fmt.Errorf("failed to re-add to "+
×
3781
                                        "graph: %v", err)
×
3782
                        }
×
3783
                }
3784

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

3798
                log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+
19✔
3799
                        "sent to gossiper", &fundingPoint, shortChanID)
19✔
3800
        }
3801

3802
        return nil
27✔
3803
}
3804

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

3819
        // We'll need to refresh the channel state so that things are properly
3820
        // populated when validating the channel state. Otherwise, a panic may
3821
        // occur due to inconsistency in the OpenChannel struct.
3822
        err = c.Refresh()
7✔
3823
        if err != nil {
10✔
3824
                return fmt.Errorf("unable to refresh channel state: %w", err)
3✔
3825
        }
3✔
3826

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

3836
        // Once we know the confirmed ShortChannelID, we'll need to save it to
3837
        // the database and refresh the OpenChannel struct with it.
3838
        err = c.MarkRealScid(confChan.shortChanID)
7✔
3839
        if err != nil {
7✔
3840
                return fmt.Errorf("unable to set confirmed SCID for zero "+
×
3841
                        "channel: %v", err)
×
3842
        }
×
3843

3844
        // Six confirmations have been reached. If this channel is public,
3845
        // we'll delete some of the alias mappings the gossiper uses.
3846
        isPublic := c.ChannelFlags&lnwire.FFAnnounceChannel != 0
7✔
3847
        if isPublic {
12✔
3848
                err = f.cfg.AliasManager.DeleteSixConfs(c.ShortChannelID)
5✔
3849
                if err != nil {
5✔
3850
                        return fmt.Errorf("unable to delete base alias after "+
×
3851
                                "six confirmations: %v", err)
×
3852
                }
×
3853

3854
                // TODO: Make this atomic!
3855
                ourPolicy, err := f.cfg.DeleteAliasEdge(c.ShortChanID())
5✔
3856
                if err != nil {
5✔
3857
                        return fmt.Errorf("unable to delete alias edge from "+
×
3858
                                "graph: %v", err)
×
3859
                }
×
3860

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

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

3887
        // Update the confirmed transaction's label.
3888
        f.makeLabelForTx(c)
7✔
3889

7✔
3890
        return nil
7✔
3891
}
3892

3893
// genFirstStateMusigNonce generates a nonces for the "first" local state. This
3894
// is the verification nonce for the state created for us after the initial
3895
// commitment transaction signed as part of the funding flow.
3896
func genFirstStateMusigNonce(channel *channeldb.OpenChannel,
3897
) (*musig2.Nonces, error) {
7✔
3898

7✔
3899
        musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
7✔
3900
                channel.RevocationProducer,
7✔
3901
        )
7✔
3902
        if err != nil {
7✔
3903
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3904
                        "nonces: %v", err)
×
3905
        }
×
3906

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

3919
        return verNonce, nil
7✔
3920
}
3921

3922
// handleChannelReady finalizes the channel funding process and enables the
3923
// channel to enter normal operating mode.
3924
func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen
3925
        msg *lnwire.ChannelReady) {
31✔
3926

31✔
3927
        defer f.wg.Done()
31✔
3928

31✔
3929
        // If we are in development mode, we'll wait for specified duration
31✔
3930
        // before processing the channel ready message.
31✔
3931
        if f.cfg.Dev != nil {
34✔
3932
                duration := f.cfg.Dev.ProcessChannelReadyWait
3✔
3933
                log.Warnf("Channel(%v): sleeping %v before processing "+
3✔
3934
                        "channel_ready", msg.ChanID, duration)
3✔
3935

3✔
3936
                select {
3✔
3937
                case <-time.After(duration):
3✔
3938
                        log.Warnf("Channel(%v): slept %v before processing "+
3✔
3939
                                "channel_ready", msg.ChanID, duration)
3✔
3940
                case <-f.quit:
×
3941
                        log.Warnf("Channel(%v): quit sleeping", msg.ChanID)
×
3942
                        return
×
3943
                }
3944
        }
3945

3946
        log.Debugf("Received ChannelReady for ChannelID(%v) from "+
31✔
3947
                "peer %x", msg.ChanID,
31✔
3948
                peer.IdentityKey().SerializeCompressed())
31✔
3949

31✔
3950
        // We now load or create a new channel barrier for this channel.
31✔
3951
        _, loaded := f.handleChannelReadyBarriers.LoadOrStore(
31✔
3952
                msg.ChanID, struct{}{},
31✔
3953
        )
31✔
3954

31✔
3955
        // If we are currently in the process of handling a channel_ready
31✔
3956
        // message for this channel, ignore.
31✔
3957
        if loaded {
35✔
3958
                log.Infof("Already handling channelReady for "+
4✔
3959
                        "ChannelID(%v), ignoring.", msg.ChanID)
4✔
3960
                return
4✔
3961
        }
4✔
3962

3963
        // If not already handling channelReady for this channel, then the
3964
        // `LoadOrStore` has set up a barrier, and it will be removed once this
3965
        // function exits.
3966
        defer f.handleChannelReadyBarriers.Delete(msg.ChanID)
30✔
3967

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

3982
                // With the signal received, we can now safely delete the entry
3983
                // from the map.
3984
                f.localDiscoverySignals.Delete(msg.ChanID)
28✔
3985
        }
3986

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

3999
        // If this is a taproot channel, then we can generate the set of nonces
4000
        // the remote party needs to send the next remote commitment here.
4001
        var firstVerNonce *musig2.Nonces
30✔
4002
        if channel.ChanType.IsTaproot() {
37✔
4003
                firstVerNonce, err = genFirstStateMusigNonce(channel)
7✔
4004
                if err != nil {
7✔
4005
                        log.Error(err)
×
4006
                        return
×
4007
                }
×
4008
        }
4009

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

4027
                // We'll store the AliasScid so that invoice creation can use
4028
                // it.
4029
                err = f.cfg.AliasManager.PutPeerAlias(chanID, *msg.AliasScid)
9✔
4030
                if err != nil {
9✔
4031
                        log.Errorf("unable to store peer's alias: %v", err)
×
4032
                        return
×
4033
                }
×
4034

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

4052
                        err = f.cfg.AliasManager.AddLocalAlias(
×
4053
                                alias, channel.ShortChannelID, false, false,
×
4054
                        )
×
4055
                        if err != nil {
×
4056
                                log.Errorf("unable to add local alias: %v",
×
4057
                                        err)
×
4058
                                return
×
4059
                        }
×
4060

4061
                        secondPoint, err := channel.SecondCommitmentPoint()
×
4062
                        if err != nil {
×
4063
                                log.Errorf("unable to fetch second "+
×
4064
                                        "commitment point: %v", err)
×
4065
                                return
×
4066
                        }
×
4067

4068
                        channelReadyMsg := lnwire.NewChannelReady(
×
4069
                                chanID, secondPoint,
×
4070
                        )
×
4071
                        channelReadyMsg.AliasScid = &alias
×
4072

×
4073
                        if firstVerNonce != nil {
×
4074
                                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:ll
×
4075
                                        firstVerNonce.PubNonce,
×
4076
                                )
×
4077
                        }
×
4078

4079
                        err = peer.SendMessage(true, channelReadyMsg)
×
4080
                        if err != nil {
×
4081
                                log.Errorf("unable to send channel_ready: %v",
×
4082
                                        err)
×
4083
                                return
×
4084
                        }
×
4085
                }
4086
        }
4087

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

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

7✔
4118
                log.Infof("ChanID(%v): applying local+remote musig2 nonces",
7✔
4119
                        chanID)
7✔
4120

7✔
4121
                remoteNonce, err := msg.NextLocalNonce.UnwrapOrErrV(
7✔
4122
                        errNoLocalNonce,
7✔
4123
                )
7✔
4124
                if err != nil {
7✔
4125
                        cid := newChanIdentifier(msg.ChanID)
×
4126
                        f.sendWarning(peer, cid, err)
×
4127

×
4128
                        return
×
4129
                }
×
4130

4131
                chanOpts = append(
7✔
4132
                        chanOpts,
7✔
4133
                        lnwallet.WithLocalMusigNonces(localNonce),
7✔
4134
                        lnwallet.WithRemoteMusigNonces(&musig2.Nonces{
7✔
4135
                                PubNonce: remoteNonce,
7✔
4136
                        }),
7✔
4137
                )
7✔
4138

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

×
4156
                        return
×
4157
                }
×
4158
        }
4159

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

4170
        // Before we can add the channel to the peer, we'll need to ensure that
4171
        // we have an initial forwarding policy set.
4172
        if err := f.ensureInitialForwardingPolicy(chanID, channel); err != nil {
29✔
4173
                log.Errorf("Unable to ensure initial forwarding policy: %v",
×
4174
                        err)
×
4175
        }
×
4176

4177
        err = peer.AddNewChannel(&lnpeer.NewChannel{
29✔
4178
                OpenChannel: channel,
29✔
4179
                ChanOpts:    chanOpts,
29✔
4180
        }, f.quit)
29✔
4181
        if err != nil {
29✔
4182
                log.Errorf("Unable to add new channel %v with peer %x: %v",
×
4183
                        channel.FundingOutpoint,
×
4184
                        peer.IdentityKey().SerializeCompressed(), err,
×
4185
                )
×
4186
        }
×
4187
}
4188

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

27✔
4198
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
27✔
4199

27✔
4200
        // Since we've sent+received funding locked at this point, we
27✔
4201
        // can clean up the pending musig2 nonce state.
27✔
4202
        f.nonceMtx.Lock()
27✔
4203
        delete(f.pendingMusigNonces, chanID)
27✔
4204
        f.nonceMtx.Unlock()
27✔
4205

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

4221
                peerAlias = &foundAlias
7✔
4222
        }
4223

4224
        err := f.addToGraph(channel, scid, peerAlias, nil)
27✔
4225
        if err != nil {
27✔
4226
                return fmt.Errorf("failed adding to graph: %w", err)
×
4227
        }
×
4228

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

4241
        log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
27✔
4242
                "added to graph", chanID, scid)
27✔
4243

27✔
4244
        err = fn.MapOptionZ(
27✔
4245
                f.cfg.AuxFundingController,
27✔
4246
                func(controller AuxFundingController) error {
27✔
4247
                        return controller.ChannelReady(
×
4248
                                lnwallet.NewAuxChanState(channel),
×
4249
                        )
×
4250
                },
×
4251
        )
4252
        if err != nil {
27✔
4253
                return fmt.Errorf("failed notifying aux funding controller "+
×
4254
                        "about channel ready: %w", err)
×
4255
        }
×
4256

4257
        // Give the caller a final update notifying them that the channel is
4258
        fundingPoint := channel.FundingOutpoint
27✔
4259
        cp := &lnrpc.ChannelPoint{
27✔
4260
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
27✔
4261
                        FundingTxidBytes: fundingPoint.Hash[:],
27✔
4262
                },
27✔
4263
                OutputIndex: fundingPoint.Index,
27✔
4264
        }
27✔
4265

27✔
4266
        if updateChan != nil {
40✔
4267
                upd := &lnrpc.OpenStatusUpdate{
13✔
4268
                        Update: &lnrpc.OpenStatusUpdate_ChanOpen{
13✔
4269
                                ChanOpen: &lnrpc.ChannelOpenUpdate{
13✔
4270
                                        ChannelPoint: cp,
13✔
4271
                                },
13✔
4272
                        },
13✔
4273
                        PendingChanId: pendingChanID[:],
13✔
4274
                }
13✔
4275

13✔
4276
                select {
13✔
4277
                case updateChan <- upd:
13✔
4278
                case <-f.quit:
×
4279
                        return ErrFundingManagerShuttingDown
×
4280
                }
4281
        }
4282

4283
        return nil
27✔
4284
}
4285

4286
// ensureInitialForwardingPolicy ensures that we have an initial forwarding
4287
// policy set for the given channel. If we don't, we'll fall back to the default
4288
// values.
4289
func (f *Manager) ensureInitialForwardingPolicy(chanID lnwire.ChannelID,
4290
        channel *channeldb.OpenChannel) error {
29✔
4291

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

×
4302
                forwardingPolicy = f.defaultForwardingPolicy(
×
4303
                        channel.LocalChanCfg.ChannelStateBounds,
×
4304
                )
×
4305
                needDBUpdate = true
×
4306
        }
×
4307

4308
        // We only started storing the actual values for MinHTLCOut and MaxHTLC
4309
        // after 0.16.x, so if a channel was opened with such a version and is
4310
        // still pending while updating to this version, we'll need to set the
4311
        // values to the default values.
4312
        if forwardingPolicy.MinHTLCOut == 0 {
45✔
4313
                forwardingPolicy.MinHTLCOut = channel.LocalChanCfg.MinHTLC
16✔
4314
                needDBUpdate = true
16✔
4315
        }
16✔
4316
        if forwardingPolicy.MaxHTLC == 0 {
45✔
4317
                forwardingPolicy.MaxHTLC = channel.LocalChanCfg.MaxPendingAmount
16✔
4318
                needDBUpdate = true
16✔
4319
        }
16✔
4320

4321
        // And finally, if we found that the values currently stored aren't
4322
        // sufficient for the link, we'll update the database.
4323
        if needDBUpdate {
45✔
4324
                err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
16✔
4325
                if err != nil {
16✔
4326
                        return fmt.Errorf("unable to update initial "+
×
4327
                                "forwarding policy: %v", err)
×
4328
                }
×
4329
        }
4330

4331
        return nil
29✔
4332
}
4333

4334
// chanAnnouncement encapsulates the two authenticated announcements that we
4335
// send out to the network after a new channel has been created locally.
4336
type chanAnnouncement struct {
4337
        chanAnn       *lnwire.ChannelAnnouncement1
4338
        chanUpdateAnn *lnwire.ChannelUpdate1
4339
        chanProof     *lnwire.AnnounceSignatures1
4340
}
4341

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

45✔
4357
        chainHash := *f.cfg.Wallet.Cfg.NetParams.GenesisHash
45✔
4358

45✔
4359
        // The unconditional section of the announcement is the ShortChannelID
45✔
4360
        // itself which compactly encodes the location of the funding output
45✔
4361
        // within the blockchain.
45✔
4362
        chanAnn := &lnwire.ChannelAnnouncement1{
45✔
4363
                ShortChannelID: shortChanID,
45✔
4364
                Features:       lnwire.NewRawFeatureVector(),
45✔
4365
                ChainHash:      chainHash,
45✔
4366
        }
45✔
4367

45✔
4368
        // If this is a taproot channel, then we'll set a special bit in the
45✔
4369
        // feature vector to indicate to the routing layer that this needs a
45✔
4370
        // slightly different type of validation.
45✔
4371
        //
45✔
4372
        // TODO(roasbeef): temp, remove after gossip 1.5
45✔
4373
        if chanType.IsTaproot() {
52✔
4374
                log.Debugf("Applying taproot feature bit to "+
7✔
4375
                        "ChannelAnnouncement for %v", chanID)
7✔
4376

7✔
4377
                chanAnn.Features.Set(
7✔
4378
                        lnwire.SimpleTaprootChannelsRequiredStaging,
7✔
4379
                )
7✔
4380
        }
7✔
4381

4382
        // The chanFlags field indicates which directed edge of the channel is
4383
        // being updated within the ChannelUpdateAnnouncement announcement
4384
        // below. A value of zero means it's the edge of the "first" node and 1
4385
        // being the other node.
4386
        var chanFlags lnwire.ChanUpdateChanFlags
45✔
4387

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

24✔
4406
                // If we're the first node then update the chanFlags to
24✔
4407
                // indicate the "direction" of the update.
24✔
4408
                chanFlags = 0
24✔
4409
        } else {
48✔
4410
                copy(chanAnn.NodeID1[:], remotePubKey.SerializeCompressed())
24✔
4411
                copy(chanAnn.NodeID2[:], localPubKey.SerializeCompressed())
24✔
4412
                copy(
24✔
4413
                        chanAnn.BitcoinKey1[:],
24✔
4414
                        remoteFundingKey.SerializeCompressed(),
24✔
4415
                )
24✔
4416
                copy(
24✔
4417
                        chanAnn.BitcoinKey2[:],
24✔
4418
                        localFundingKey.PubKey.SerializeCompressed(),
24✔
4419
                )
24✔
4420

24✔
4421
                // If we're the second node then update the chanFlags to
24✔
4422
                // indicate the "direction" of the update.
24✔
4423
                chanFlags = 1
24✔
4424
        }
24✔
4425

4426
        // Our channel update message flags will signal that we support the
4427
        // max_htlc field.
4428
        msgFlags := lnwire.ChanUpdateRequiredMaxHtlc
45✔
4429

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

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

4455
        switch {
45✔
4456
        case ourPolicy != nil:
3✔
4457
                // If ourPolicy is non-nil, modify the default parameters of the
3✔
4458
                // ChannelUpdate.
3✔
4459
                chanUpdateAnn.MessageFlags = ourPolicy.MessageFlags
3✔
4460
                chanUpdateAnn.ChannelFlags = ourPolicy.ChannelFlags
3✔
4461
                chanUpdateAnn.TimeLockDelta = ourPolicy.TimeLockDelta
3✔
4462
                chanUpdateAnn.HtlcMinimumMsat = ourPolicy.MinHTLC
3✔
4463
                chanUpdateAnn.HtlcMaximumMsat = ourPolicy.MaxHTLC
3✔
4464
                chanUpdateAnn.BaseFee = uint32(ourPolicy.FeeBaseMSat)
3✔
4465
                chanUpdateAnn.FeeRate = uint32(
3✔
4466
                        ourPolicy.FeeProportionalMillionths,
3✔
4467
                )
3✔
4468

4469
        case storedFwdingPolicy != nil:
45✔
4470
                chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
45✔
4471
                chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
45✔
4472

4473
        default:
×
4474
                log.Infof("No channel forwarding policy specified for channel "+
×
4475
                        "announcement of ChannelID(%v). "+
×
4476
                        "Assuming default fee parameters.", chanID)
×
4477
                chanUpdateAnn.BaseFee = uint32(
×
4478
                        f.cfg.DefaultRoutingPolicy.BaseFee,
×
4479
                )
×
4480
                chanUpdateAnn.FeeRate = uint32(
×
4481
                        f.cfg.DefaultRoutingPolicy.FeeRate,
×
4482
                )
×
4483
        }
4484

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

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

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

4544
        return &chanAnnouncement{
45✔
4545
                chanAnn:       chanAnn,
45✔
4546
                chanUpdateAnn: chanUpdateAnn,
45✔
4547
                chanProof:     proof,
45✔
4548
        }, nil
45✔
4549
}
4550

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

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

4579
        // We only send the channel proof announcement and the node announcement
4580
        // because addToGraph previously sent the ChannelAnnouncement and
4581
        // the ChannelUpdate announcement messages. The channel proof and node
4582
        // announcements are broadcast to the greater network.
4583
        errChan := f.cfg.SendAnnouncement(ann.chanProof)
19✔
4584
        select {
19✔
4585
        case err := <-errChan:
19✔
4586
                if err != nil {
22✔
4587
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4588
                                graph.ErrIgnored) {
3✔
4589

×
4590
                                log.Debugf("Graph rejected "+
×
4591
                                        "AnnounceSignatures: %v", err)
×
4592
                        } else {
3✔
4593
                                log.Errorf("Unable to send channel "+
3✔
4594
                                        "proof: %v", err)
3✔
4595
                                return err
3✔
4596
                        }
3✔
4597
                }
4598

4599
        case <-f.quit:
×
4600
                return ErrFundingManagerShuttingDown
×
4601
        }
4602

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

4613
        errChan = f.cfg.SendAnnouncement(&nodeAnn)
19✔
4614
        select {
19✔
4615
        case err := <-errChan:
19✔
4616
                if err != nil {
22✔
4617
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4618
                                graph.ErrIgnored) {
6✔
4619

3✔
4620
                                log.Debugf("Graph rejected "+
3✔
4621
                                        "NodeAnnouncement: %v", err)
3✔
4622
                        } else {
3✔
4623
                                log.Errorf("Unable to send node "+
×
4624
                                        "announcement: %v", err)
×
4625
                                return err
×
4626
                        }
×
4627
                }
4628

4629
        case <-f.quit:
×
4630
                return ErrFundingManagerShuttingDown
×
4631
        }
4632

4633
        return nil
19✔
4634
}
4635

4636
// InitFundingWorkflow sends a message to the funding manager instructing it
4637
// to initiate a single funder workflow with the source peer.
4638
func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg) {
59✔
4639
        f.fundingRequests <- msg
59✔
4640
}
59✔
4641

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

111✔
4654
        // Check whether the remote peer supports upfront shutdown scripts.
111✔
4655
        remoteUpfrontShutdown := peer.RemoteFeatures().HasFeature(
111✔
4656
                lnwire.UpfrontShutdownScriptOptional,
111✔
4657
        )
111✔
4658

111✔
4659
        // If the peer does not support upfront shutdown scripts, and one has been
111✔
4660
        // provided, return an error because the feature is not supported.
111✔
4661
        if !remoteUpfrontShutdown && len(script) != 0 {
112✔
4662
                return nil, errUpfrontShutdownScriptNotSupported
1✔
4663
        }
1✔
4664

4665
        // If the peer does not support upfront shutdown, return an empty address.
4666
        if !remoteUpfrontShutdown {
213✔
4667
                return nil, nil
103✔
4668
        }
103✔
4669

4670
        // If the user has provided an script and the peer supports the feature,
4671
        // return it. Note that user set scripts override the enable upfront
4672
        // shutdown flag.
4673
        if len(script) > 0 {
12✔
4674
                return script, nil
5✔
4675
        }
5✔
4676

4677
        // If we do not have setting of upfront shutdown script enabled, return
4678
        // an empty script.
4679
        if !enableUpfrontShutdown {
9✔
4680
                return nil, nil
4✔
4681
        }
4✔
4682

4683
        // We can safely send a taproot address iff, both sides have negotiated
4684
        // the shutdown-any-segwit feature.
4685
        taprootOK := peer.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
1✔
4686
                peer.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
1✔
4687

1✔
4688
        return getScript(taprootOK)
1✔
4689
}
4690

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

59✔
4709
        // If no maximum CSV delay was set for this channel, we use our default
59✔
4710
        // value.
59✔
4711
        if maxCSV == 0 {
118✔
4712
                maxCSV = f.cfg.MaxLocalCSVDelay
59✔
4713
        }
59✔
4714

4715
        log.Infof("Initiating fundingRequest(local_amt=%v "+
59✔
4716
                "(subtract_fees=%v), push_amt=%v, chain_hash=%v, peer=%x, "+
59✔
4717
                "min_confs=%v)", localAmt, msg.SubtractFees, msg.PushAmt,
59✔
4718
                msg.ChainHash, peerKey.SerializeCompressed(), msg.MinConfs)
59✔
4719

59✔
4720
        // We set the channel flags to indicate whether we want this channel to
59✔
4721
        // be announced to the network.
59✔
4722
        var channelFlags lnwire.FundingFlag
59✔
4723
        if !msg.Private {
113✔
4724
                // This channel will be announced.
54✔
4725
                channelFlags = lnwire.FFAnnounceChannel
54✔
4726
        }
54✔
4727

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

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

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

4776
        var (
59✔
4777
                zeroConf bool
59✔
4778
                scid     bool
59✔
4779
        )
59✔
4780

59✔
4781
        if chanType != nil {
66✔
4782
                // Check if the returned chanType includes either the zero-conf
7✔
4783
                // or scid-alias bits.
7✔
4784
                featureVec := lnwire.RawFeatureVector(*chanType)
7✔
4785
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
7✔
4786
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
7✔
4787

7✔
4788
                // The option-scid-alias channel type for a public channel is
7✔
4789
                // disallowed.
7✔
4790
                if scid && !msg.Private {
7✔
4791
                        err = fmt.Errorf("option-scid-alias chantype for " +
×
4792
                                "public channel")
×
4793
                        log.Error(err)
×
4794
                        msg.Err <- err
×
4795

×
4796
                        return
×
4797
                }
×
4798
        }
4799

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

4810
        // For anchor channels cap the initial commit fee rate at our defined
4811
        // maximum.
4812
        if commitType.HasAnchors() &&
59✔
4813
                commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
66✔
4814

7✔
4815
                commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate
7✔
4816
        }
7✔
4817

4818
        var scidFeatureVal bool
59✔
4819
        if hasFeatures(
59✔
4820
                msg.Peer.LocalFeatures(), msg.Peer.RemoteFeatures(),
59✔
4821
                lnwire.ScidAliasOptional,
59✔
4822
        ) {
65✔
4823

6✔
4824
                scidFeatureVal = true
6✔
4825
        }
6✔
4826

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

×
4841
                return
×
4842
        }
×
4843

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

4874
                        // Query the sweeper storage to make sure we don't use
4875
                        // an unconfirmed utxo still in use by the sweeper
4876
                        // subsystem.
4877
                        return !f.cfg.IsSweeperOutpoint(u.OutPoint)
60✔
4878
                },
4879
                ZeroConf:         zeroConf,
4880
                OptionScidAlias:  scid,
4881
                ScidAliasFeature: scidFeatureVal,
4882
                Memo:             msg.Memo,
4883
                TapscriptRoot:    tapscriptRoot,
4884
        }
4885

4886
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
59✔
4887
        if err != nil {
62✔
4888
                msg.Err <- err
3✔
4889
                return
3✔
4890
        }
3✔
4891

4892
        if zeroConf {
64✔
4893
                // Store the alias for zero-conf channels in the underlying
5✔
4894
                // partial channel state.
5✔
4895
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
5✔
4896
                if err != nil {
5✔
4897
                        msg.Err <- err
×
4898
                        return
×
4899
                }
×
4900

4901
                reservation.AddAlias(aliasScid)
5✔
4902
        }
4903

4904
        // Set our upfront shutdown address in the existing reservation.
4905
        reservation.SetOurUpfrontShutdown(shutdown)
59✔
4906

59✔
4907
        // Now that we have successfully reserved funds for this channel in the
59✔
4908
        // wallet, we can fetch the final channel capacity. This is done at
59✔
4909
        // this point since the final capacity might change in case of
59✔
4910
        // SubtractFees=true.
59✔
4911
        capacity := reservation.Capacity()
59✔
4912

59✔
4913
        log.Infof("Target commit tx sat/kw for pendingID(%x): %v", chanID,
59✔
4914
                int64(commitFeePerKw))
59✔
4915

59✔
4916
        // If the remote CSV delay was not set in the open channel request,
59✔
4917
        // we'll use the RequiredRemoteDelay closure to compute the delay we
59✔
4918
        // require given the total amount of funds within the channel.
59✔
4919
        if remoteCsvDelay == 0 {
117✔
4920
                remoteCsvDelay = f.cfg.RequiredRemoteDelay(capacity)
58✔
4921
        }
58✔
4922

4923
        // If no minimum HTLC value was specified, use the default one.
4924
        if minHtlcIn == 0 {
117✔
4925
                minHtlcIn = f.cfg.DefaultMinHtlcIn
58✔
4926
        }
58✔
4927

4928
        // If no max value was specified, use the default one.
4929
        if maxValue == 0 {
117✔
4930
                maxValue = f.cfg.RequiredRemoteMaxValue(capacity)
58✔
4931
        }
58✔
4932

4933
        if maxHtlcs == 0 {
118✔
4934
                maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
59✔
4935
        }
59✔
4936

4937
        // Once the reservation has been created, and indexed, queue a funding
4938
        // request to the remote peer, kicking off the funding workflow.
4939
        ourContribution := reservation.OurContribution()
59✔
4940

59✔
4941
        // Prepare the optional channel fee values from the initFundingMsg. If
59✔
4942
        // useBaseFee or useFeeRate are false the client did not provide fee
59✔
4943
        // values hence we assume default fee settings from the config.
59✔
4944
        forwardingPolicy := f.defaultForwardingPolicy(
59✔
4945
                ourContribution.ChannelStateBounds,
59✔
4946
        )
59✔
4947
        if baseFee != nil {
63✔
4948
                forwardingPolicy.BaseFee = lnwire.MilliSatoshi(*baseFee)
4✔
4949
        }
4✔
4950

4951
        if feeRate != nil {
63✔
4952
                forwardingPolicy.FeeRate = lnwire.MilliSatoshi(*feeRate)
4✔
4953
        }
4✔
4954

4955
        // Fetch our dust limit which is part of the default channel
4956
        // constraints, and log it.
4957
        ourDustLimit := ourContribution.DustLimit
59✔
4958

59✔
4959
        log.Infof("Dust limit for pendingID(%x): %v", chanID, ourDustLimit)
59✔
4960

59✔
4961
        // If the channel reserve is not specified, then we calculate an
59✔
4962
        // appropriate amount here.
59✔
4963
        if chanReserve == 0 {
114✔
4964
                chanReserve = f.cfg.RequiredRemoteChanReserve(
55✔
4965
                        capacity, ourDustLimit,
55✔
4966
                )
55✔
4967
        }
55✔
4968

4969
        // If a pending channel map for this peer isn't already created, then
4970
        // we create one, ultimately allowing us to track this pending
4971
        // reservation within the target peer.
4972
        peerIDKey := newSerializedKey(peerKey)
59✔
4973
        f.resMtx.Lock()
59✔
4974
        if _, ok := f.activeReservations[peerIDKey]; !ok {
111✔
4975
                f.activeReservations[peerIDKey] = make(pendingChannels)
52✔
4976
        }
52✔
4977

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

59✔
4996
        // Update the timestamp once the InitFundingMsg has been handled.
59✔
4997
        defer resCtx.updateTimestamp()
59✔
4998

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

5020
                msg.Err <- err
2✔
5021
                return
2✔
5022
        }
5023

5024
        // When opening a script enforced channel lease, include the required
5025
        // expiry TLV record in our proposal.
5026
        var leaseExpiry *lnwire.LeaseExpiry
57✔
5027
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
60✔
5028
                leaseExpiry = new(lnwire.LeaseExpiry)
3✔
5029
                *leaseExpiry = lnwire.LeaseExpiry(reservation.LeaseExpiry())
3✔
5030
        }
3✔
5031

5032
        log.Infof("Starting funding workflow with %v for pending_id(%x), "+
57✔
5033
                "committype=%v", msg.Peer.Address(), chanID, commitType)
57✔
5034

57✔
5035
        reservation.SetState(lnwallet.SentOpenChannel)
57✔
5036

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

57✔
5061
        if commitType.IsTaproot() {
62✔
5062
                fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
5✔
5063
                        ourContribution.LocalNonce.PubNonce,
5✔
5064
                )
5✔
5065
        }
5✔
5066

5067
        if err := msg.Peer.SendMessage(true, &fundingOpen); err != nil {
57✔
5068
                e := fmt.Errorf("unable to send funding request message: %w",
×
5069
                        err)
×
5070
                log.Errorf(e.Error())
×
5071

×
5072
                // Since we were unable to send the initial message to the peer
×
5073
                // and start the funding flow, we'll cancel this reservation.
×
5074
                _, err := f.cancelReservationCtx(peerKey, chanID, false)
×
5075
                if err != nil {
×
5076
                        log.Errorf("unable to cancel reservation: %v", err)
×
5077
                }
×
5078

5079
                msg.Err <- e
×
5080
                return
×
5081
        }
5082
}
5083

5084
// handleWarningMsg processes the warning which was received from remote peer.
5085
func (f *Manager) handleWarningMsg(peer lnpeer.Peer, msg *lnwire.Warning) {
42✔
5086
        log.Warnf("received warning message from peer %x: %v",
42✔
5087
                peer.IdentityKey().SerializeCompressed(), msg.Warning())
42✔
5088
}
42✔
5089

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

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

5107
        // If we did indeed find the funding workflow, then we'll return the
5108
        // error back to the caller (if any), and cancel the workflow itself.
5109
        fundingErr := fmt.Errorf("received funding error from %x: %v",
3✔
5110
                peerKey.SerializeCompressed(), msg.Error(),
3✔
5111
        )
3✔
5112
        log.Errorf(fundingErr.Error())
3✔
5113

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

5122
        resCtx.err <- fundingErr
3✔
5123
}
5124

5125
// pruneZombieReservations loops through all pending reservations and fails the
5126
// funding flow for any reservations that have not been updated since the
5127
// ReservationTimeout and are not locked waiting for the funding transaction.
5128
func (f *Manager) pruneZombieReservations() {
6✔
5129
        zombieReservations := make(pendingChannels)
6✔
5130

6✔
5131
        f.resMtx.RLock()
6✔
5132
        for _, pendingReservations := range f.activeReservations {
12✔
5133
                for pendingChanID, resCtx := range pendingReservations {
12✔
5134
                        if resCtx.isLocked() {
6✔
5135
                                continue
×
5136
                        }
5137

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

6✔
5152
        for pendingChanID, resCtx := range zombieReservations {
12✔
5153
                err := fmt.Errorf("reservation timed out waiting for peer "+
6✔
5154
                        "(peer_id:%x, chan_id:%x)",
6✔
5155
                        resCtx.peer.IdentityKey().SerializeCompressed(),
6✔
5156
                        pendingChanID[:])
6✔
5157
                log.Warnf(err.Error())
6✔
5158

6✔
5159
                chanID := lnwire.NewChanIDFromOutPoint(
6✔
5160
                        *resCtx.reservation.FundingOutpoint(),
6✔
5161
                )
6✔
5162

6✔
5163
                // Create channel identifier and set the channel ID.
6✔
5164
                cid := newChanIdentifier(pendingChanID)
6✔
5165
                cid.setChanID(chanID)
6✔
5166

6✔
5167
                f.failFundingFlow(resCtx.peer, cid, err)
6✔
5168
        }
6✔
5169
}
5170

5171
// cancelReservationCtx does all needed work in order to securely cancel the
5172
// reservation.
5173
func (f *Manager) cancelReservationCtx(peerKey *btcec.PublicKey,
5174
        pendingChanID PendingChanID,
5175
        byRemote bool) (*reservationWithCtx, error) {
26✔
5176

26✔
5177
        log.Infof("Cancelling funding reservation for node_key=%x, "+
26✔
5178
                "chan_id=%x", peerKey.SerializeCompressed(), pendingChanID[:])
26✔
5179

26✔
5180
        peerIDKey := newSerializedKey(peerKey)
26✔
5181
        f.resMtx.Lock()
26✔
5182
        defer f.resMtx.Unlock()
26✔
5183

26✔
5184
        nodeReservations, ok := f.activeReservations[peerIDKey]
26✔
5185
        if !ok {
36✔
5186
                // No reservations for this node.
10✔
5187
                return nil, errors.Errorf("no active reservations for peer(%x)",
10✔
5188
                        peerIDKey[:])
10✔
5189
        }
10✔
5190

5191
        ctx, ok := nodeReservations[pendingChanID]
19✔
5192
        if !ok {
21✔
5193
                return nil, errors.Errorf("unknown channel (id: %x) for "+
2✔
5194
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
2✔
5195
        }
2✔
5196

5197
        // If the reservation was a PSBT funding flow and it was canceled by the
5198
        // remote peer, then we need to thread through a different error message
5199
        // to the subroutine that's waiting for the user input so it can return
5200
        // a nice error message to the user.
5201
        if ctx.reservation.IsPsbt() && byRemote {
20✔
5202
                ctx.reservation.RemoteCanceled()
3✔
5203
        }
3✔
5204

5205
        if err := ctx.reservation.Cancel(); err != nil {
17✔
5206
                return nil, errors.Errorf("unable to cancel reservation: %v",
×
5207
                        err)
×
5208
        }
×
5209

5210
        delete(nodeReservations, pendingChanID)
17✔
5211

17✔
5212
        // If this was the last active reservation for this peer, delete the
17✔
5213
        // peer's entry altogether.
17✔
5214
        if len(nodeReservations) == 0 {
34✔
5215
                delete(f.activeReservations, peerIDKey)
17✔
5216
        }
17✔
5217
        return ctx, nil
17✔
5218
}
5219

5220
// deleteReservationCtx deletes the reservation uniquely identified by the
5221
// target public key of the peer, and the specified pending channel ID.
5222
func (f *Manager) deleteReservationCtx(peerKey *btcec.PublicKey,
5223
        pendingChanID PendingChanID) {
57✔
5224

57✔
5225
        peerIDKey := newSerializedKey(peerKey)
57✔
5226
        f.resMtx.Lock()
57✔
5227
        defer f.resMtx.Unlock()
57✔
5228

57✔
5229
        nodeReservations, ok := f.activeReservations[peerIDKey]
57✔
5230
        if !ok {
57✔
5231
                // No reservations for this node.
×
5232
                return
×
5233
        }
×
5234
        delete(nodeReservations, pendingChanID)
57✔
5235

57✔
5236
        // If this was the last active reservation for this peer, delete the
57✔
5237
        // peer's entry altogether.
57✔
5238
        if len(nodeReservations) == 0 {
107✔
5239
                delete(f.activeReservations, peerIDKey)
50✔
5240
        }
50✔
5241
}
5242

5243
// getReservationCtx returns the reservation context for a particular pending
5244
// channel ID for a target peer.
5245
func (f *Manager) getReservationCtx(peerKey *btcec.PublicKey,
5246
        pendingChanID PendingChanID) (*reservationWithCtx, error) {
91✔
5247

91✔
5248
        peerIDKey := newSerializedKey(peerKey)
91✔
5249
        f.resMtx.RLock()
91✔
5250
        resCtx, ok := f.activeReservations[peerIDKey][pendingChanID]
91✔
5251
        f.resMtx.RUnlock()
91✔
5252

91✔
5253
        if !ok {
94✔
5254
                return nil, errors.Errorf("unknown channel (id: %x) for "+
3✔
5255
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
3✔
5256
        }
3✔
5257

5258
        return resCtx, nil
91✔
5259
}
5260

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

3✔
5269
        peerIDKey := newSerializedKey(peer.IdentityKey())
3✔
5270
        f.resMtx.RLock()
3✔
5271
        _, ok := f.activeReservations[peerIDKey][pendingChanID]
3✔
5272
        f.resMtx.RUnlock()
3✔
5273

3✔
5274
        return ok
3✔
5275
}
3✔
5276

5277
func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
378✔
5278
        var tmp btcec.JacobianPoint
378✔
5279
        pub.AsJacobian(&tmp)
378✔
5280
        tmp.ToAffine()
378✔
5281
        return btcec.NewPublicKey(&tmp.X, &tmp.Y)
378✔
5282
}
378✔
5283

5284
// defaultForwardingPolicy returns the default forwarding policy based on the
5285
// default routing policy and our local channel constraints.
5286
func (f *Manager) defaultForwardingPolicy(
5287
        bounds channeldb.ChannelStateBounds) *models.ForwardingPolicy {
105✔
5288

105✔
5289
        return &models.ForwardingPolicy{
105✔
5290
                MinHTLCOut:    bounds.MinHTLC,
105✔
5291
                MaxHTLC:       bounds.MaxPendingAmount,
105✔
5292
                BaseFee:       f.cfg.DefaultRoutingPolicy.BaseFee,
105✔
5293
                FeeRate:       f.cfg.DefaultRoutingPolicy.FeeRate,
105✔
5294
                TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
105✔
5295
        }
105✔
5296
}
105✔
5297

5298
// saveInitialForwardingPolicy saves the forwarding policy for the provided
5299
// chanPoint in the channelOpeningStateBucket.
5300
func (f *Manager) saveInitialForwardingPolicy(chanID lnwire.ChannelID,
5301
        forwardingPolicy *models.ForwardingPolicy) error {
70✔
5302

70✔
5303
        return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
70✔
5304
                chanID, forwardingPolicy,
70✔
5305
        )
70✔
5306
}
70✔
5307

5308
// getInitialForwardingPolicy fetches the initial forwarding policy for a given
5309
// channel id from the database which will be applied during the channel
5310
// announcement phase.
5311
func (f *Manager) getInitialForwardingPolicy(
5312
        chanID lnwire.ChannelID) (*models.ForwardingPolicy, error) {
97✔
5313

97✔
5314
        return f.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
97✔
5315
}
97✔
5316

5317
// deleteInitialForwardingPolicy removes channel fees for this chanID from
5318
// the database.
5319
func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
27✔
5320
        return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
27✔
5321
}
27✔
5322

5323
// saveChannelOpeningState saves the channelOpeningState for the provided
5324
// chanPoint to the channelOpeningStateBucket.
5325
func (f *Manager) saveChannelOpeningState(chanPoint *wire.OutPoint,
5326
        state channelOpeningState, shortChanID *lnwire.ShortChannelID) error {
95✔
5327

95✔
5328
        var outpointBytes bytes.Buffer
95✔
5329
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
95✔
5330
                return err
×
5331
        }
×
5332

5333
        // Save state and the uint64 representation of the shortChanID
5334
        // for later use.
5335
        scratch := make([]byte, 10)
95✔
5336
        byteOrder.PutUint16(scratch[:2], uint16(state))
95✔
5337
        byteOrder.PutUint64(scratch[2:], shortChanID.ToUint64())
95✔
5338

95✔
5339
        return f.cfg.ChannelDB.SaveChannelOpeningState(
95✔
5340
                outpointBytes.Bytes(), scratch,
95✔
5341
        )
95✔
5342
}
5343

5344
// getChannelOpeningState fetches the channelOpeningState for the provided
5345
// chanPoint from the database, or returns ErrChannelNotFound if the channel
5346
// is not found.
5347
func (f *Manager) getChannelOpeningState(chanPoint *wire.OutPoint) (
5348
        channelOpeningState, *lnwire.ShortChannelID, error) {
254✔
5349

254✔
5350
        var outpointBytes bytes.Buffer
254✔
5351
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
254✔
5352
                return 0, nil, err
×
5353
        }
×
5354

5355
        value, err := f.cfg.ChannelDB.GetChannelOpeningState(
254✔
5356
                outpointBytes.Bytes(),
254✔
5357
        )
254✔
5358
        if err != nil {
304✔
5359
                return 0, nil, err
50✔
5360
        }
50✔
5361

5362
        state := channelOpeningState(byteOrder.Uint16(value[:2]))
207✔
5363
        shortChanID := lnwire.NewShortChanIDFromInt(byteOrder.Uint64(value[2:]))
207✔
5364
        return state, &shortChanID, nil
207✔
5365
}
5366

5367
// deleteChannelOpeningState removes any state for chanPoint from the database.
5368
func (f *Manager) deleteChannelOpeningState(chanPoint *wire.OutPoint) error {
27✔
5369
        var outpointBytes bytes.Buffer
27✔
5370
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
27✔
5371
                return err
×
5372
        }
×
5373

5374
        return f.cfg.ChannelDB.DeleteChannelOpeningState(
27✔
5375
                outpointBytes.Bytes(),
27✔
5376
        )
27✔
5377
}
5378

5379
// selectShutdownScript selects the shutdown script we should send to the peer.
5380
// If we can use taproot, then we prefer that, otherwise we'll use a p2wkh
5381
// script.
5382
func (f *Manager) selectShutdownScript(taprootOK bool,
5383
) (lnwire.DeliveryAddress, error) {
×
5384

×
5385
        addrType := lnwallet.WitnessPubKey
×
5386
        if taprootOK {
×
5387
                addrType = lnwallet.TaprootPubkey
×
5388
        }
×
5389

5390
        addr, err := f.cfg.Wallet.NewAddress(
×
5391
                addrType, false, lnwallet.DefaultAccountName,
×
5392
        )
×
5393
        if err != nil {
×
5394
                return nil, err
×
5395
        }
×
5396

5397
        return txscript.PayToAddrScript(addr)
×
5398
}
5399

5400
// waitForPeerOnline blocks until the peer specified by peerPubkey comes online
5401
// and then returns the online peer.
5402
func (f *Manager) waitForPeerOnline(peerPubkey *btcec.PublicKey) (lnpeer.Peer,
5403
        error) {
108✔
5404

108✔
5405
        peerChan := make(chan lnpeer.Peer, 1)
108✔
5406

108✔
5407
        var peerKey [33]byte
108✔
5408
        copy(peerKey[:], peerPubkey.SerializeCompressed())
108✔
5409

108✔
5410
        f.cfg.NotifyWhenOnline(peerKey, peerChan)
108✔
5411

108✔
5412
        var peer lnpeer.Peer
108✔
5413
        select {
108✔
5414
        case peer = <-peerChan:
107✔
5415
        case <-f.quit:
1✔
5416
                return peer, ErrFundingManagerShuttingDown
1✔
5417
        }
5418
        return peer, nil
107✔
5419
}
5420

5421
// remotePubHex takes a *btcec.PublicKey and converts it to a hex-encoded
5422
// string.
5423
func remotePubHex(remotePub *btcec.PublicKey) string {
93✔
5424
        return hex.EncodeToString(remotePub.SerializeCompressed())
93✔
5425
}
93✔
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