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

lightningnetwork / lnd / 14977937992

12 May 2025 04:50PM UTC coverage: 58.596% (+0.04%) from 58.559%
14977937992

Pull #9677

github

web-flow
Merge 882e0ce18 into 1db6c31e2
Pull Request #9677: Expose confirmation count for pending 'channel open' transactions

142 of 178 new or added lines in 5 files covered. (79.78%)

35 existing lines in 6 files now uncovered.

97502 of 166397 relevant lines covered (58.6%)

1.82 hits per line

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

71.03
/funding/manager.go
1
package funding
2

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

12
        "github.com/btcsuite/btcd/blockchain"
13
        "github.com/btcsuite/btcd/btcec/v2"
14
        "github.com/btcsuite/btcd/btcec/v2/ecdsa"
15
        "github.com/btcsuite/btcd/btcec/v2/schnorr/musig2"
16
        "github.com/btcsuite/btcd/btcutil"
17
        "github.com/btcsuite/btcd/chaincfg/chainhash"
18
        "github.com/btcsuite/btcd/txscript"
19
        "github.com/btcsuite/btcd/wire"
20
        "github.com/davecgh/go-spew/spew"
21
        "github.com/go-errors/errors"
22
        "github.com/lightningnetwork/lnd/chainntnfs"
23
        "github.com/lightningnetwork/lnd/chanacceptor"
24
        "github.com/lightningnetwork/lnd/channeldb"
25
        "github.com/lightningnetwork/lnd/discovery"
26
        "github.com/lightningnetwork/lnd/fn/v2"
27
        "github.com/lightningnetwork/lnd/graph"
28
        "github.com/lightningnetwork/lnd/graph/db/models"
29
        "github.com/lightningnetwork/lnd/input"
30
        "github.com/lightningnetwork/lnd/keychain"
31
        "github.com/lightningnetwork/lnd/labels"
32
        "github.com/lightningnetwork/lnd/lncfg"
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 {
3✔
67
        scratch := make([]byte, 4)
3✔
68

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

73
        byteOrder.PutUint32(scratch, o.Index)
3✔
74
        _, err := w.Write(scratch)
3✔
75
        return err
3✔
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
        // pendingChansLimit is the maximum number of pending channels that we
106
        // can have. After this point, pending channel opens will start to be
107
        // rejected.
108
        pendingChansLimit = 50
109
)
110

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

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

124
        // errUpfrontShutdownScriptNotSupported is returned if an upfront
125
        // shutdown script is set for a peer that does not support the feature
126
        // bit.
127
        errUpfrontShutdownScriptNotSupported = errors.New("peer does not " +
128
                "support option upfront shutdown script")
129

130
        zeroID [32]byte
131
)
132

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

146
        chanAmt btcutil.Amount
147

148
        // forwardingPolicy is the policy provided by the initFundingMsg.
149
        forwardingPolicy models.ForwardingPolicy
150

151
        // Constraints we require for the remote.
152
        remoteCsvDelay    uint16
153
        remoteMinHtlc     lnwire.MilliSatoshi
154
        remoteMaxValue    lnwire.MilliSatoshi
155
        remoteMaxHtlcs    uint16
156
        remoteChanReserve btcutil.Amount
157

158
        // maxLocalCsv is the maximum csv we will accept from the remote.
159
        maxLocalCsv uint16
160

161
        // channelType is the explicit channel type proposed by the initiator of
162
        // the channel.
163
        channelType *lnwire.ChannelType
164

165
        updateMtx   sync.RWMutex
166
        lastUpdated time.Time
167

168
        updates chan *lnrpc.OpenStatusUpdate
169
        err     chan error
170
}
171

172
// isLocked checks the reservation's timestamp to determine whether it is
173
// locked.
174
func (r *reservationWithCtx) isLocked() bool {
3✔
175
        r.updateMtx.RLock()
3✔
176
        defer r.updateMtx.RUnlock()
3✔
177

3✔
178
        // The time zero value represents a locked reservation.
3✔
179
        return r.lastUpdated.IsZero()
3✔
180
}
3✔
181

182
// updateTimestamp updates the reservation's timestamp with the current time.
183
func (r *reservationWithCtx) updateTimestamp() {
3✔
184
        r.updateMtx.Lock()
3✔
185
        defer r.updateMtx.Unlock()
3✔
186

3✔
187
        r.lastUpdated = time.Now()
3✔
188
}
3✔
189

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

199
        // TargetPubkey is the public key of the peer.
200
        TargetPubkey *btcec.PublicKey
201

202
        // ChainHash is the target genesis hash for this channel.
203
        ChainHash chainhash.Hash
204

205
        // SubtractFees set to true means that fees will be subtracted
206
        // from the LocalFundingAmt.
207
        SubtractFees bool
208

209
        // LocalFundingAmt is the size of the channel.
210
        LocalFundingAmt btcutil.Amount
211

212
        // BaseFee is the base fee charged for routing payments regardless of
213
        // the number of milli-satoshis sent.
214
        BaseFee *uint64
215

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

222
        // PushAmt is the amount pushed to the counterparty.
223
        PushAmt lnwire.MilliSatoshi
224

225
        // FundingFeePerKw is the fee for the funding transaction.
226
        FundingFeePerKw chainfee.SatPerKWeight
227

228
        // Private determines whether or not this channel will be private.
229
        Private bool
230

231
        // MinHtlcIn is the minimum incoming HTLC that we accept.
232
        MinHtlcIn lnwire.MilliSatoshi
233

234
        // RemoteCsvDelay is the CSV delay we require for the remote peer.
235
        RemoteCsvDelay uint16
236

237
        // RemoteChanReserve is the channel reserve we required for the remote
238
        // peer.
239
        RemoteChanReserve btcutil.Amount
240

241
        // MinConfs indicates the minimum number of confirmations that each
242
        // output selected to fund the channel should satisfy.
243
        MinConfs int32
244

245
        // ShutdownScript is an optional upfront shutdown script for the
246
        // channel. This value is optional, so may be nil.
247
        ShutdownScript lnwire.DeliveryAddress
248

249
        // MaxValueInFlight is the maximum amount of coins in MilliSatoshi
250
        // that can be pending within the channel. It only applies to the
251
        // remote party.
252
        MaxValueInFlight lnwire.MilliSatoshi
253

254
        // MaxHtlcs is the maximum number of HTLCs that the remote peer
255
        // can offer us.
256
        MaxHtlcs uint16
257

258
        // MaxLocalCsv is the maximum local csv delay we will accept from our
259
        // peer.
260
        MaxLocalCsv uint16
261

262
        // FundUpToMaxAmt is the maximum amount to try to commit to. If set, the
263
        // MinFundAmt field denotes the acceptable minimum amount to commit to,
264
        // while trying to commit as many coins as possible up to this value.
265
        FundUpToMaxAmt btcutil.Amount
266

267
        // MinFundAmt must be set iff FundUpToMaxAmt is set. It denotes the
268
        // minimum amount to commit to.
269
        MinFundAmt btcutil.Amount
270

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

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

284
        // PendingChanID is not all zeroes (the default value), then this will
285
        // be the pending channel ID used for the funding flow within the wire
286
        // protocol.
287
        PendingChanID PendingChanID
288

289
        // ChannelType allows the caller to use an explicit channel type for the
290
        // funding negotiation. This type will only be observed if BOTH sides
291
        // support explicit channel type negotiation.
292
        ChannelType *lnwire.ChannelType
293

294
        // Memo is any arbitrary information we wish to store locally about the
295
        // channel that will be useful to our future selves.
296
        Memo []byte
297

298
        // Updates is a channel which updates to the opening status of the
299
        // channel are sent on.
300
        Updates chan *lnrpc.OpenStatusUpdate
301

302
        // Err is a channel which errors encountered during the funding flow are
303
        // sent on.
304
        Err chan error
305
}
306

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

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

319
// serializedPubKey is used within the FundingManager's activeReservations list
320
// to identify the nodes with which the FundingManager is actively working to
321
// initiate new channels.
322
type serializedPubKey [33]byte
323

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

332
// DevConfig specifies configs used for integration test only.
333
type DevConfig struct {
334
        // ProcessChannelReadyWait is the duration to sleep before processing
335
        // remote node's channel ready message once the channel as been marked
336
        // as `channelReadySent`.
337
        ProcessChannelReadyWait time.Duration
338

339
        // MaxWaitNumBlocksFundingConf is the maximum number of blocks to wait
340
        // for the funding transaction to be confirmed before forgetting
341
        // channels that aren't initiated by us.
342
        MaxWaitNumBlocksFundingConf uint32
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, *btcec.PublicKey) 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, *btcec.PublicKey) 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, *btcec.PublicKey) 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) {
3✔
683
        return &Manager{
3✔
684
                cfg:       &cfg,
3✔
685
                chanIDKey: cfg.TempChanIDSeed,
3✔
686
                activeReservations: make(
3✔
687
                        map[serializedPubKey]pendingChannels,
3✔
688
                ),
3✔
689
                signedReservations: make(
3✔
690
                        map[lnwire.ChannelID][32]byte,
3✔
691
                ),
3✔
692
                fundingMsgs: make(
3✔
693
                        chan *fundingMsg, msgBufferSize,
3✔
694
                ),
3✔
695
                fundingRequests: make(
3✔
696
                        chan *InitFundingMsg, msgBufferSize,
3✔
697
                ),
3✔
698
                localDiscoverySignals: &lnutils.SyncMap[
3✔
699
                        lnwire.ChannelID, chan struct{},
3✔
700
                ]{},
3✔
701
                handleChannelReadyBarriers: &lnutils.SyncMap[
3✔
702
                        lnwire.ChannelID, struct{},
3✔
703
                ]{},
3✔
704
                pendingMusigNonces: make(
3✔
705
                        map[lnwire.ChannelID]*musig2.Nonces,
3✔
706
                ),
3✔
707
                quit: make(chan struct{}),
3✔
708
        }, nil
3✔
709
}
3✔
710

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

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

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

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

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

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

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

×
765
                        // Rebroadcast the funding transaction for unconfirmed
×
766
                        // zero-conf channels if we have the funding tx and are
×
767
                        // also the initiator.
×
768
                        f.rebroadcastFundingTx(channel)
×
769
                }
×
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)
3✔
776
                go f.advanceFundingState(channel, chanID, nil)
3✔
777
        }
778

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

3✔
782
        return nil
3✔
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 {
3✔
788
        f.stopped.Do(func() {
6✔
789
                log.Info("Funding manager shutting down...")
3✔
790
                defer log.Debug("Funding manager shutdown complete")
3✔
791

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

796
        return nil
3✔
797
}
798

799
// rebroadcastFundingTx publishes the funding tx on startup for each
800
// unconfirmed channel.
801
func (f *Manager) rebroadcastFundingTx(c *channeldb.OpenChannel) {
3✔
802
        var fundingTxBuf bytes.Buffer
3✔
803
        err := c.FundingTxn.Serialize(&fundingTxBuf)
3✔
804
        if err != nil {
3✔
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 {
3✔
813
                log.Debugf("Rebroadcasting funding tx for ChannelPoint(%v): "+
3✔
814
                        "%x", c.FundingOutpoint, fundingTxBuf.Bytes())
3✔
815
        }
3✔
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)
3✔
820

3✔
821
        err = f.cfg.PublishTransaction(c.FundingTxn, label)
3✔
822
        if err != nil {
3✔
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 {
3✔
836
        // Obtain a fresh nonce. We do this by encoding the incremented nonce.
3✔
837
        nextNonce := f.chanIDNonce.Add(1)
3✔
838

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

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

3✔
852
        return nextChanID
3✔
853
}
3✔
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 {
3✔
916
        return &chanIdentifier{
3✔
917
                tempChanID: tempChanID,
3✔
918
        }
3✔
919
}
3✔
920

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

927
// hasChanID returns true if the active channel ID has been set.
928
func (c *chanIdentifier) hasChanID() bool {
3✔
929
        return c.chanIDSet
3✔
930
}
3✔
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) {
3✔
941

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

3✔
945
        // First, notify Brontide to remove the pending channel.
3✔
946
        //
3✔
947
        // NOTE: depending on where we fail the flow, we may not have the
3✔
948
        // active channel ID yet.
3✔
949
        if cid.hasChanID() {
6✔
950
                err := peer.RemovePendingChannel(cid.chanID)
3✔
951
                if err != nil {
3✔
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(
3✔
959
                peer.IdentityKey(), cid.tempChanID, false,
3✔
960
        )
3✔
961
        if err != nil {
6✔
962
                log.Errorf("unable to cancel reservation: %v", err)
3✔
963
        }
3✔
964

965
        // In case the case where the reservation existed, send the funding
966
        // error on the error channel.
967
        if ctx != nil {
6✔
968
                ctx.err <- fundingErr
3✔
969
        }
3✔
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
3✔
974
        switch e := fundingErr.(type) {
3✔
975
        // Let the actual error message be sent to the remote for the
976
        // whitelisted types.
977
        case lnwallet.ReservationError:
3✔
978
                msg = lnwire.ErrorData(e.Error())
3✔
979
        case lnwire.FundingError:
3✔
980
                msg = lnwire.ErrorData(e.Error())
3✔
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:
3✔
986
                msg = lnwire.ErrorData("funding failed due to internal error")
3✔
987
        }
988

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

3✔
994
        log.Debugf("Sending funding error to peer (%x): %v",
3✔
995
                peer.IdentityKey().SerializeCompressed(), spew.Sdump(errMsg))
3✔
996
        if err := peer.SendMessage(false, errMsg); err != nil {
3✔
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() {
3✔
1028
        defer f.wg.Done()
3✔
1029

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

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

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

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

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

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

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

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

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

1065
                case <-f.quit:
3✔
1066
                        return
3✔
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) {
3✔
1082

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

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

1097
        var chanOpts []lnwallet.ChannelOpt
3✔
1098
        f.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
3✔
1099
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
1100
        })
×
1101
        f.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
3✔
1102
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
1103
        })
×
1104
        f.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
3✔
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(
3✔
1110
                nil, channel, nil, chanOpts...,
3✔
1111
        )
3✔
1112
        if err != nil {
3✔
1113
                log.Errorf("Unable to create LightningChannel(%v): %v",
×
1114
                        channel.FundingOutpoint, err)
×
1115
                return
×
1116
        }
×
1117

1118
        for {
6✔
1119
                channelState, shortChanID, err := f.getChannelOpeningState(
3✔
1120
                        &channel.FundingOutpoint,
3✔
1121
                )
3✔
1122
                if err == channeldb.ErrChannelNotFound {
6✔
1123
                        // Channel not in fundingManager's opening database,
3✔
1124
                        // meaning it was successfully announced to the
3✔
1125
                        // network.
3✔
1126
                        // TODO(halseth): could do graph consistency check
3✔
1127
                        // here, and re-add the edge if missing.
3✔
1128
                        log.Debugf("ChannelPoint(%v) with chan_id=%x not "+
3✔
1129
                                "found in opening database, assuming already "+
3✔
1130
                                "announced to the network",
3✔
1131
                                channel.FundingOutpoint, pendingChanID)
3✔
1132
                        return
3✔
1133
                } else if err != nil {
6✔
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(
3✔
1145
                        channel, lnChannel, shortChanID, pendingChanID,
3✔
1146
                        channelState, updateChan,
3✔
1147
                )
3✔
1148
                if err != nil {
6✔
1149
                        log.Errorf("Unable to advance state(%v): %v",
3✔
1150
                                channel.FundingOutpoint, err)
3✔
1151
                        return
3✔
1152
                }
3✔
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 {
3✔
1165

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

3✔
1170
        switch channelState {
3✔
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:
3✔
1174
                err := f.sendChannelReady(channel, lnChannel)
3✔
1175
                if err != nil {
3✔
1176
                        return fmt.Errorf("failed sending channelReady: %w",
×
1177
                                err)
×
1178
                }
×
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(
3✔
1185
                        &channel.FundingOutpoint, channelReadySent,
3✔
1186
                        shortChanID,
3✔
1187
                )
3✔
1188
                if err != nil {
3✔
1189
                        return fmt.Errorf("error setting channel state to"+
×
1190
                                " channelReadySent: %w", err)
×
1191
                }
×
1192

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

3✔
1196
                return nil
3✔
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:
3✔
1201
                // We must wait until we've received the peer's channel_ready
3✔
1202
                // before sending a channel_update according to BOLT#07.
3✔
1203
                received, err := f.receivedChannelReady(
3✔
1204
                        channel.IdentityPub, chanID,
3✔
1205
                )
3✔
1206
                if err != nil {
3✔
UNCOV
1207
                        return fmt.Errorf("failed to check if channel_ready "+
×
UNCOV
1208
                                "was received: %v", err)
×
UNCOV
1209
                }
×
1210

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

1221
                        return nil
3✔
1222
                }
1223

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

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

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

1247
                err := f.annAfterSixConfs(channel, shortChanID)
3✔
1248
                if err != nil {
6✔
1249
                        return fmt.Errorf("error sending channel "+
3✔
1250
                                "announcement: %v", err)
3✔
1251
                }
3✔
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)
3✔
1259
                if err != nil {
3✔
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)
3✔
1269
                if err != nil {
3✔
1270
                        log.Infof("Could not delete initial policy for chanId "+
×
1271
                                "%x", chanID)
×
1272
                }
×
1273

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

3✔
1277
                return nil
3✔
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 {
3✔
1287

3✔
1288
        if channel.IsZeroConf() {
6✔
1289
                // Persist the alias to the alias database.
3✔
1290
                baseScid := channel.ShortChannelID
3✔
1291
                err := f.cfg.AliasManager.AddLocalAlias(
3✔
1292
                        baseScid, baseScid, true, false,
3✔
1293
                )
3✔
1294
                if err != nil {
3✔
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(
3✔
1304
                        &channel.FundingOutpoint, markedOpen,
3✔
1305
                        &channel.ShortChannelID,
3✔
1306
                )
3✔
1307
                if err != nil {
3✔
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)
3✔
1315
                if err != nil {
3✔
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
                if err := f.cfg.NotifyOpenChannelEvent(
3✔
1323
                        channel.FundingOutpoint, channel.IdentityPub,
3✔
1324
                ); err != nil {
3✔
1325
                        log.Errorf("Unable to notify open channel event for "+
×
1326
                                "ChannelPoint(%v): %v",
×
1327
                                channel.FundingOutpoint, err)
×
1328
                }
×
1329

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

1338
                return nil
3✔
1339
        }
1340

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

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

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

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

×
1368
                        return err
×
1369
                }
×
1370

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

×
1380
                        return err
×
1381
                }
×
1382

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

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

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

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

1409
        return nil
3✔
1410
}
1411

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

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

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

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

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

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

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

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

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

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

3✔
1485
                return
3✔
1486
        }
3✔
1487

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1648
                return
×
1649

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

×
1658
                return
×
1659
        }
1660

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

×
1675
                return
×
1676
        }
×
1677

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

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

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

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

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

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

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

1738
        reservation.SetNumConfsRequired(numConfsReq)
3✔
1739

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1927
                        return
×
1928
                }
×
1929

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2116
                minDepth = 1
×
2117
        }
×
2118

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

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

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

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

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

×
2187
                        return
×
2188
                }
×
2189

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2427
                        return
×
2428
                }
×
2429

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

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

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

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

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

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

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

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

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

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

×
2495
                        return
×
2496
                }
×
2497

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

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

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

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

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

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

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

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

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

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

×
2602
                        return
×
2603
                }
×
2604

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

×
2615
                        return
×
2616
                }
×
2617
        }
2618

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2752
                return
×
2753
        }
×
2754

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

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

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

×
2781
                        return
×
2782
                }
×
2783

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2979
                // nil error means we continue on.
2980
                case nil:
3✔
2981

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

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

3✔
2993
                // TODO(halseth): should this send be made
3✔
2994
                // reliable?
3✔
2995

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

3001
        return timeoutErr
3✔
3002
}
3003

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

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

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

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

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

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

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

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

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

3064
                return pkScript, nil
3✔
3065
        }
3066

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

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

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

3✔
3092
        defer f.wg.Done()
3✔
3093
        defer close(confChan)
3✔
3094

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

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

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

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

3✔
3127
        // Monitor the confirmation event for the funding transaction. And
3✔
3128
        // return when the funding tx has received the required number of
3✔
3129
        // confirmations.
3✔
3130
        for {
6✔
3131
                select {
3✔
3132
                case updDetails := <-confNtfn.Updates:
3✔
3133
                        log.Tracef("funding tx %s received a confirmation, %d "+
3✔
3134
                                " number of confirmations still required", txid,
3✔
3135
                                updDetails.NumConfsLeft)
3✔
3136

3✔
3137
                        // Handle first confirmation of the funding transaction.
3✔
3138
                        if updDetails.NumConfsLeft == numConfs-1 {
6✔
3139
                                log.Infof("funding tx %s received first "+
3✔
3140
                                        "confirmation", txid)
3✔
3141

3✔
3142
                                err := completeChan.MarkConfirmationHeight(
3✔
3143
                                        updDetails.BlockHeight,
3✔
3144
                                )
3✔
3145
                                if err != nil {
3✔
NEW
3146
                                        log.Errorf("failed to mark "+
×
NEW
3147
                                                "confirmation height: %v", err)
×
UNCOV
3148

×
NEW
3149
                                        return
×
NEW
3150
                                }
×
3151
                        }
3152

3153
                        // If we haven't reached final confirmation, continue
3154
                        // waiting for confirmations.
3155
                        if updDetails.NumConfsLeft > 0 {
6✔
3156
                                continue
3✔
3157
                        }
3158

3159
                        log.Infof("funding tx %s received all confirmations",
3✔
3160
                                txid)
3✔
3161

3✔
3162
                        // We've reached final confirmation. Wait for the
3✔
3163
                        // confirmation event to trigger and then send the
3✔
3164
                        // result to the confirmation channel.
3✔
3165
                        err := f.handleFinalConfirmation(
3✔
3166
                                confNtfn, confChan, completeChan,
3✔
3167
                        )
3✔
3168
                        if err != nil {
3✔
NEW
3169
                                log.Errorf("failed to handle final "+
×
NEW
3170
                                        "confirmation: %v", err)
×
NEW
3171
                        }
×
3172

3173
                        return
3✔
3174

NEW
3175
                case <-confNtfn.NegativeConf:
×
NEW
3176
                        log.Warnf("funding tx %s was reorged out; channel "+
×
NEW
3177
                                "point: %s", txid, completeChan.FundingOutpoint)
×
NEW
3178

×
NEW
3179
                        // Reset the confirmation height to 0 because the
×
NEW
3180
                        // funding transaction was reorged out.
×
NEW
3181
                        err := completeChan.MarkConfirmationHeight(uint32(0))
×
NEW
3182
                        if err != nil {
×
NEW
3183
                                log.Errorf("failed to update state for "+
×
NEW
3184
                                        "ChannelPoint(%v): %v",
×
NEW
3185
                                        completeChan.FundingOutpoint, err)
×
NEW
3186

×
NEW
3187
                                return
×
NEW
3188
                        }
×
3189

3190
                case <-cancelChan:
3✔
3191
                        log.Warnf("canceled waiting for funding confirmation, "+
3✔
3192
                                "stopping funding flow for ChannelPoint(%v)",
3✔
3193
                                completeChan.FundingOutpoint)
3✔
3194

3✔
3195
                        return
3✔
3196

3197
                case <-f.quit:
3✔
3198
                        log.Warnf("fundingManager shutting down, stopping "+
3✔
3199
                                "funding flow for ChannelPoint(%v)",
3✔
3200
                                completeChan.FundingOutpoint)
3✔
3201

3✔
3202
                        return
3✔
3203
                }
3204
        }
3205
}
3206

3207
// handleFinalConfirmation is a helper function that listens for the final
3208
// confirmation event and sends the final confirmation to the confirmation
3209
// channel which was provided by the caller.
3210
func (f *Manager) handleFinalConfirmation(
3211
        confNtfn *chainntnfs.ConfirmationEvent,
3212
        confChan chan<- *confirmedChannel,
3213
        completeChan *channeldb.OpenChannel) error {
3✔
3214

3✔
3215
        select {
3✔
3216
        case confDetails, ok := <-confNtfn.Confirmed:
3✔
3217
                if !ok {
3✔
NEW
3218
                        return fmt.Errorf("confirmation channel closed " +
×
NEW
3219
                                "unexpectedly")
×
NEW
3220
                }
×
3221

3222
                // Send the result to the confirmation channel.
3223
                shortChanID := lnwire.ShortChannelID{
3✔
3224
                        BlockHeight: confDetails.BlockHeight,
3✔
3225
                        TxIndex:     confDetails.TxIndex,
3✔
3226
                        TxPosition:  uint16(completeChan.FundingOutpoint.Index),
3✔
3227
                }
3✔
3228

3✔
3229
                if !fn.SendOrQuit(confChan, &confirmedChannel{
3✔
3230
                        shortChanID: shortChanID,
3✔
3231
                        fundingTx:   confDetails.Tx,
3✔
3232
                }, f.quit) {
3✔
NEW
3233

×
NEW
3234
                        return fmt.Errorf("failed to send confirmation")
×
NEW
3235
                }
×
3236

3237
                return nil
3✔
3238

3239
        case <-f.quit:
×
NEW
3240
                return fmt.Errorf("funding manager shutting down")
×
3241
        }
3242
}
3243

3244
// waitForTimeout will close the timeout channel if MaxWaitNumBlocksFundingConf
3245
// has passed from the broadcast height of the given channel. In case of error,
3246
// the error is sent on timeoutChan. The wait can be canceled by closing the
3247
// cancelChan.
3248
//
3249
// NOTE: timeoutChan MUST be buffered.
3250
// NOTE: This MUST be run as a goroutine.
3251
func (f *Manager) waitForTimeout(completeChan *channeldb.OpenChannel,
3252
        cancelChan <-chan struct{}, timeoutChan chan<- error) {
3✔
3253

3✔
3254
        defer f.wg.Done()
3✔
3255

3✔
3256
        epochClient, err := f.cfg.Notifier.RegisterBlockEpochNtfn(nil)
3✔
3257
        if err != nil {
3✔
3258
                timeoutChan <- fmt.Errorf("unable to register for epoch "+
×
3259
                        "notification: %v", err)
×
3260
                return
×
3261
        }
×
3262

3263
        defer epochClient.Cancel()
3✔
3264

3✔
3265
        // The value of waitBlocksForFundingConf is adjusted in a development
3✔
3266
        // environment to enhance test capabilities. Otherwise, it is set to
3✔
3267
        // DefaultMaxWaitNumBlocksFundingConf.
3✔
3268
        waitBlocksForFundingConf := uint32(
3✔
3269
                lncfg.DefaultMaxWaitNumBlocksFundingConf,
3✔
3270
        )
3✔
3271

3✔
3272
        if lncfg.IsDevBuild() {
6✔
3273
                waitBlocksForFundingConf =
3✔
3274
                        f.cfg.Dev.MaxWaitNumBlocksFundingConf
3✔
3275
        }
3✔
3276

3277
        // On block maxHeight we will cancel the funding confirmation wait.
3278
        broadcastHeight := completeChan.BroadcastHeight()
3✔
3279
        maxHeight := broadcastHeight + waitBlocksForFundingConf
3✔
3280
        for {
6✔
3281
                select {
3✔
3282
                case epoch, ok := <-epochClient.Epochs:
3✔
3283
                        if !ok {
3✔
3284
                                timeoutChan <- fmt.Errorf("epoch client " +
×
3285
                                        "shutting down")
×
3286
                                return
×
3287
                        }
×
3288

3289
                        // Close the timeout channel and exit if the block is
3290
                        // above the max height.
3291
                        if uint32(epoch.Height) >= maxHeight {
6✔
3292
                                log.Warnf("Waited for %v blocks without "+
3✔
3293
                                        "seeing funding transaction confirmed,"+
3✔
3294
                                        " cancelling.",
3✔
3295
                                        waitBlocksForFundingConf)
3✔
3296

3✔
3297
                                // Notify the caller of the timeout.
3✔
3298
                                close(timeoutChan)
3✔
3299
                                return
3✔
3300
                        }
3✔
3301

3302
                        // TODO: If we are the channel initiator implement
3303
                        // a method for recovering the funds from the funding
3304
                        // transaction
3305

3306
                case <-cancelChan:
3✔
3307
                        return
3✔
3308

3309
                case <-f.quit:
3✔
3310
                        // The fundingManager is shutting down, will resume
3✔
3311
                        // waiting for the funding transaction on startup.
3✔
3312
                        return
3✔
3313
                }
3314
        }
3315
}
3316

3317
// makeLabelForTx updates the label for the confirmed funding transaction. If
3318
// we opened the channel, and lnd's wallet published our funding tx (which is
3319
// not the case for some channels) then we update our transaction label with
3320
// our short channel ID, which is known now that our funding transaction has
3321
// confirmed. We do not label transactions we did not publish, because our
3322
// wallet has no knowledge of them.
3323
func (f *Manager) makeLabelForTx(c *channeldb.OpenChannel) {
3✔
3324
        if c.IsInitiator && c.ChanType.HasFundingTx() {
6✔
3325
                shortChanID := c.ShortChanID()
3✔
3326

3✔
3327
                // For zero-conf channels, we'll use the actually-confirmed
3✔
3328
                // short channel id.
3✔
3329
                if c.IsZeroConf() {
6✔
3330
                        shortChanID = c.ZeroConfRealScid()
3✔
3331
                }
3✔
3332

3333
                label := labels.MakeLabel(
3✔
3334
                        labels.LabelTypeChannelOpen, &shortChanID,
3✔
3335
                )
3✔
3336

3✔
3337
                err := f.cfg.UpdateLabel(c.FundingOutpoint.Hash, label)
3✔
3338
                if err != nil {
3✔
3339
                        log.Errorf("unable to update label: %v", err)
×
3340
                }
×
3341
        }
3342
}
3343

3344
// handleFundingConfirmation marks a channel as open in the database, and set
3345
// the channelOpeningState markedOpen. In addition it will report the now
3346
// decided short channel ID to the switch, and close the local discovery signal
3347
// for this channel.
3348
func (f *Manager) handleFundingConfirmation(
3349
        completeChan *channeldb.OpenChannel,
3350
        confChannel *confirmedChannel) error {
3✔
3351

3✔
3352
        fundingPoint := completeChan.FundingOutpoint
3✔
3353
        chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
3✔
3354

3✔
3355
        // TODO(roasbeef): ideally persistent state update for chan above
3✔
3356
        // should be abstracted
3✔
3357

3✔
3358
        // Now that that the channel has been fully confirmed, we'll request
3✔
3359
        // that the wallet fully verify this channel to ensure that it can be
3✔
3360
        // used.
3✔
3361
        err := f.cfg.Wallet.ValidateChannel(completeChan, confChannel.fundingTx)
3✔
3362
        if err != nil {
3✔
3363
                // TODO(roasbeef): delete chan state?
×
3364
                return fmt.Errorf("unable to validate channel: %w", err)
×
3365
        }
×
3366

3367
        // Now that the channel has been validated, we'll persist an alias for
3368
        // this channel if the option-scid-alias feature-bit was negotiated.
3369
        if completeChan.NegotiatedAliasFeature() {
6✔
3370
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
3✔
3371
                if err != nil {
3✔
3372
                        return fmt.Errorf("unable to request alias: %w", err)
×
3373
                }
×
3374

3375
                err = f.cfg.AliasManager.AddLocalAlias(
3✔
3376
                        aliasScid, confChannel.shortChanID, true, false,
3✔
3377
                )
3✔
3378
                if err != nil {
3✔
3379
                        return fmt.Errorf("unable to request alias: %w", err)
×
3380
                }
×
3381
        }
3382

3383
        // The funding transaction now being confirmed, we add this channel to
3384
        // the fundingManager's internal persistent state machine that we use
3385
        // to track the remaining process of the channel opening. This is
3386
        // useful to resume the opening process in case of restarts. We set the
3387
        // opening state before we mark the channel opened in the database,
3388
        // such that we can receover from one of the db writes failing.
3389
        err = f.saveChannelOpeningState(
3✔
3390
                &fundingPoint, markedOpen, &confChannel.shortChanID,
3✔
3391
        )
3✔
3392
        if err != nil {
3✔
3393
                return fmt.Errorf("error setting channel state to "+
×
3394
                        "markedOpen: %v", err)
×
3395
        }
×
3396

3397
        // Now that the channel has been fully confirmed and we successfully
3398
        // saved the opening state, we'll mark it as open within the database.
3399
        err = completeChan.MarkAsOpen(confChannel.shortChanID)
3✔
3400
        if err != nil {
3✔
3401
                return fmt.Errorf("error setting channel pending flag to "+
×
3402
                        "false:        %v", err)
×
3403
        }
×
3404

3405
        // Update the confirmed funding transaction label.
3406
        f.makeLabelForTx(completeChan)
3✔
3407

3✔
3408
        // Inform the ChannelNotifier that the channel has transitioned from
3✔
3409
        // pending open to open.
3✔
3410
        if err := f.cfg.NotifyOpenChannelEvent(
3✔
3411
                completeChan.FundingOutpoint, completeChan.IdentityPub,
3✔
3412
        ); err != nil {
6✔
3413
                log.Errorf("Unable to notify open channel event for "+
3✔
3414
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
3✔
3415
                        err)
3✔
3416
        }
3✔
3417

3418
        // Close the discoverySignal channel, indicating to a separate
3419
        // goroutine that the channel now is marked as open in the database
3420
        // and that it is acceptable to process channel_ready messages
3421
        // from the peer.
3422
        if discoverySignal, ok := f.localDiscoverySignals.Load(chanID); ok {
6✔
3423
                close(discoverySignal)
3✔
3424
        }
3✔
3425

3426
        return nil
3✔
3427
}
3428

3429
// sendChannelReady creates and sends the channelReady message.
3430
// This should be called after the funding transaction has been confirmed,
3431
// and the channelState is 'markedOpen'.
3432
func (f *Manager) sendChannelReady(completeChan *channeldb.OpenChannel,
3433
        channel *lnwallet.LightningChannel) error {
3✔
3434

3✔
3435
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
3✔
3436

3✔
3437
        var peerKey [33]byte
3✔
3438
        copy(peerKey[:], completeChan.IdentityPub.SerializeCompressed())
3✔
3439

3✔
3440
        // Next, we'll send over the channel_ready message which marks that we
3✔
3441
        // consider the channel open by presenting the remote party with our
3✔
3442
        // next revocation key. Without the revocation key, the remote party
3✔
3443
        // will be unable to propose state transitions.
3✔
3444
        nextRevocation, err := channel.NextRevocationKey()
3✔
3445
        if err != nil {
3✔
3446
                return fmt.Errorf("unable to create next revocation: %w", err)
×
3447
        }
×
3448
        channelReadyMsg := lnwire.NewChannelReady(chanID, nextRevocation)
3✔
3449

3✔
3450
        // If this is a taproot channel, then we also need to send along our
3✔
3451
        // set of musig2 nonces as well.
3✔
3452
        if completeChan.ChanType.IsTaproot() {
6✔
3453
                log.Infof("ChanID(%v): generating musig2 nonces...",
3✔
3454
                        chanID)
3✔
3455

3✔
3456
                f.nonceMtx.Lock()
3✔
3457
                localNonce, ok := f.pendingMusigNonces[chanID]
3✔
3458
                if !ok {
6✔
3459
                        // If we don't have any nonces generated yet for this
3✔
3460
                        // first state, then we'll generate them now and stow
3✔
3461
                        // them away.  When we receive the funding locked
3✔
3462
                        // message, we'll then pass along this same set of
3✔
3463
                        // nonces.
3✔
3464
                        newNonce, err := channel.GenMusigNonces()
3✔
3465
                        if err != nil {
3✔
3466
                                f.nonceMtx.Unlock()
×
3467
                                return err
×
3468
                        }
×
3469

3470
                        // Now that we've generated the nonce for this channel,
3471
                        // we'll store it in the set of pending nonces.
3472
                        localNonce = newNonce
3✔
3473
                        f.pendingMusigNonces[chanID] = localNonce
3✔
3474
                }
3475
                f.nonceMtx.Unlock()
3✔
3476

3✔
3477
                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
3✔
3478
                        localNonce.PubNonce,
3✔
3479
                )
3✔
3480
        }
3481

3482
        // If the channel negotiated the option-scid-alias feature bit, we'll
3483
        // send a TLV segment that includes an alias the peer can use in their
3484
        // invoice hop hints. We'll send the first alias we find for the
3485
        // channel since it does not matter which alias we send. We'll error
3486
        // out in the odd case that no aliases are found.
3487
        if completeChan.NegotiatedAliasFeature() {
6✔
3488
                aliases := f.cfg.AliasManager.GetAliases(
3✔
3489
                        completeChan.ShortChanID(),
3✔
3490
                )
3✔
3491
                if len(aliases) == 0 {
3✔
3492
                        return fmt.Errorf("no aliases found")
×
3493
                }
×
3494

3495
                // We can use a pointer to aliases since GetAliases returns a
3496
                // copy of the alias slice.
3497
                channelReadyMsg.AliasScid = &aliases[0]
3✔
3498
        }
3499

3500
        // If the peer has disconnected before we reach this point, we will need
3501
        // to wait for him to come back online before sending the channelReady
3502
        // message. This is special for channelReady, since failing to send any
3503
        // of the previous messages in the funding flow just cancels the flow.
3504
        // But now the funding transaction is confirmed, the channel is open
3505
        // and we have to make sure the peer gets the channelReady message when
3506
        // it comes back online. This is also crucial during restart of lnd,
3507
        // where we might try to resend the channelReady message before the
3508
        // server has had the time to connect to the peer. We keep trying to
3509
        // send channelReady until we succeed, or the fundingManager is shut
3510
        // down.
3511
        for {
6✔
3512
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
3✔
3513
                if err != nil {
3✔
3514
                        return err
×
3515
                }
×
3516

3517
                localAlias := peer.LocalFeatures().HasFeature(
3✔
3518
                        lnwire.ScidAliasOptional,
3✔
3519
                )
3✔
3520
                remoteAlias := peer.RemoteFeatures().HasFeature(
3✔
3521
                        lnwire.ScidAliasOptional,
3✔
3522
                )
3✔
3523

3✔
3524
                // We could also refresh the channel state instead of checking
3✔
3525
                // whether the feature was negotiated, but this saves us a
3✔
3526
                // database read.
3✔
3527
                if channelReadyMsg.AliasScid == nil && localAlias &&
3✔
3528
                        remoteAlias {
3✔
3529

×
3530
                        // If an alias was not assigned above and the scid
×
3531
                        // alias feature was negotiated, check if we already
×
3532
                        // have an alias stored in case handleChannelReady was
×
3533
                        // called before this. If an alias exists, use that in
×
3534
                        // channel_ready. Otherwise, request and store an
×
3535
                        // alias and use that.
×
3536
                        aliases := f.cfg.AliasManager.GetAliases(
×
3537
                                completeChan.ShortChannelID,
×
3538
                        )
×
3539
                        if len(aliases) == 0 {
×
3540
                                // No aliases were found.
×
3541
                                alias, err := f.cfg.AliasManager.RequestAlias()
×
3542
                                if err != nil {
×
3543
                                        return err
×
3544
                                }
×
3545

3546
                                err = f.cfg.AliasManager.AddLocalAlias(
×
3547
                                        alias, completeChan.ShortChannelID,
×
3548
                                        false, false,
×
3549
                                )
×
3550
                                if err != nil {
×
3551
                                        return err
×
3552
                                }
×
3553

3554
                                channelReadyMsg.AliasScid = &alias
×
3555
                        } else {
×
3556
                                channelReadyMsg.AliasScid = &aliases[0]
×
3557
                        }
×
3558
                }
3559

3560
                log.Infof("Peer(%x) is online, sending ChannelReady "+
3✔
3561
                        "for ChannelID(%v)", peerKey, chanID)
3✔
3562

3✔
3563
                if err := peer.SendMessage(true, channelReadyMsg); err == nil {
6✔
3564
                        // Sending succeeded, we can break out and continue the
3✔
3565
                        // funding flow.
3✔
3566
                        break
3✔
3567
                }
3568

3569
                log.Warnf("Unable to send channelReady to peer %x: %v. "+
×
3570
                        "Will retry when online", peerKey, err)
×
3571
        }
3572

3573
        return nil
3✔
3574
}
3575

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

3✔
3581
        // If the funding manager has exited, return an error to stop looping.
3✔
3582
        // Note that the peer may appear as online while the funding manager
3✔
3583
        // has stopped due to the shutdown order in the server.
3✔
3584
        select {
3✔
3585
        case <-f.quit:
×
3586
                return false, ErrFundingManagerShuttingDown
×
3587
        default:
3✔
3588
        }
3589

3590
        // Avoid a tight loop if peer is offline.
3591
        if _, err := f.waitForPeerOnline(node); err != nil {
3✔
UNCOV
3592
                log.Errorf("Wait for peer online failed: %v", err)
×
UNCOV
3593
                return false, err
×
UNCOV
3594
        }
×
3595

3596
        // If we cannot find the channel, then we haven't processed the
3597
        // remote's channelReady message.
3598
        channel, err := f.cfg.FindChannel(node, chanID)
3✔
3599
        if err != nil {
3✔
3600
                log.Errorf("Unable to locate ChannelID(%v) to determine if "+
×
3601
                        "ChannelReady was received", chanID)
×
3602
                return false, err
×
3603
        }
×
3604

3605
        // If we haven't insert the next revocation point, we haven't finished
3606
        // processing the channel ready message.
3607
        if channel.RemoteNextRevocation == nil {
6✔
3608
                return false, nil
3✔
3609
        }
3✔
3610

3611
        // Finally, the barrier signal is removed once we finish
3612
        // `handleChannelReady`. If we can still find the signal, we haven't
3613
        // finished processing it yet.
3614
        _, loaded := f.handleChannelReadyBarriers.Load(chanID)
3✔
3615

3✔
3616
        return !loaded, nil
3✔
3617
}
3618

3619
// extractAnnounceParams extracts the various channel announcement and update
3620
// parameters that will be needed to construct a ChannelAnnouncement and a
3621
// ChannelUpdate.
3622
func (f *Manager) extractAnnounceParams(c *channeldb.OpenChannel) (
3623
        lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
3✔
3624

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

3✔
3631
        // We don't necessarily want to go as low as the remote party allows.
3✔
3632
        // Check it against our default forwarding policy.
3✔
3633
        if fwdMinHTLC < f.cfg.DefaultRoutingPolicy.MinHTLCOut {
6✔
3634
                fwdMinHTLC = f.cfg.DefaultRoutingPolicy.MinHTLCOut
3✔
3635
        }
3✔
3636

3637
        // We'll obtain the max HTLC value we can forward in our direction, as
3638
        // we'll use this value within our ChannelUpdate. This value must be <=
3639
        // channel capacity and <= the maximum in-flight msats set by the peer.
3640
        fwdMaxHTLC := c.LocalChanCfg.MaxPendingAmount
3✔
3641
        capacityMSat := lnwire.NewMSatFromSatoshis(c.Capacity)
3✔
3642
        if fwdMaxHTLC > capacityMSat {
3✔
3643
                fwdMaxHTLC = capacityMSat
×
3644
        }
×
3645

3646
        return fwdMinHTLC, fwdMaxHTLC
3✔
3647
}
3648

3649
// addToGraph sends a ChannelAnnouncement and a ChannelUpdate to the
3650
// gossiper so that the channel is added to the graph builder's internal graph.
3651
// These announcement messages are NOT broadcasted to the greater network,
3652
// only to the channel counter party. The proofs required to announce the
3653
// channel to the greater network will be created and sent in annAfterSixConfs.
3654
// The peerAlias is used for zero-conf channels to give the counter-party a
3655
// ChannelUpdate they understand. ourPolicy may be set for various
3656
// option-scid-alias channels to re-use the same policy.
3657
func (f *Manager) addToGraph(completeChan *channeldb.OpenChannel,
3658
        shortChanID *lnwire.ShortChannelID,
3659
        peerAlias *lnwire.ShortChannelID,
3660
        ourPolicy *models.ChannelEdgePolicy) error {
3✔
3661

3✔
3662
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
3✔
3663

3✔
3664
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
3✔
3665

3✔
3666
        ann, err := f.newChanAnnouncement(
3✔
3667
                f.cfg.IDKey, completeChan.IdentityPub,
3✔
3668
                &completeChan.LocalChanCfg.MultiSigKey,
3✔
3669
                completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
3✔
3670
                chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
3✔
3671
                completeChan.ChanType,
3✔
3672
        )
3✔
3673
        if err != nil {
3✔
3674
                return fmt.Errorf("error generating channel "+
×
3675
                        "announcement: %v", err)
×
3676
        }
×
3677

3678
        // Send ChannelAnnouncement and ChannelUpdate to the gossiper to add
3679
        // to the Router's topology.
3680
        errChan := f.cfg.SendAnnouncement(
3✔
3681
                ann.chanAnn, discovery.ChannelCapacity(completeChan.Capacity),
3✔
3682
                discovery.ChannelPoint(completeChan.FundingOutpoint),
3✔
3683
                discovery.TapscriptRoot(completeChan.TapscriptRoot),
3✔
3684
        )
3✔
3685
        select {
3✔
3686
        case err := <-errChan:
3✔
3687
                if err != nil {
3✔
3688
                        if graph.IsError(err, graph.ErrOutdated,
×
3689
                                graph.ErrIgnored) {
×
3690

×
3691
                                log.Debugf("Graph rejected "+
×
3692
                                        "ChannelAnnouncement: %v", err)
×
3693
                        } else {
×
3694
                                return fmt.Errorf("error sending channel "+
×
3695
                                        "announcement: %v", err)
×
3696
                        }
×
3697
                }
3698
        case <-f.quit:
×
3699
                return ErrFundingManagerShuttingDown
×
3700
        }
3701

3702
        errChan = f.cfg.SendAnnouncement(
3✔
3703
                ann.chanUpdateAnn, discovery.RemoteAlias(peerAlias),
3✔
3704
        )
3✔
3705
        select {
3✔
3706
        case err := <-errChan:
3✔
3707
                if err != nil {
3✔
3708
                        if graph.IsError(err, graph.ErrOutdated,
×
3709
                                graph.ErrIgnored) {
×
3710

×
3711
                                log.Debugf("Graph rejected "+
×
3712
                                        "ChannelUpdate: %v", err)
×
3713
                        } else {
×
3714
                                return fmt.Errorf("error sending channel "+
×
3715
                                        "update: %v", err)
×
3716
                        }
×
3717
                }
3718
        case <-f.quit:
×
3719
                return ErrFundingManagerShuttingDown
×
3720
        }
3721

3722
        return nil
3✔
3723
}
3724

3725
// annAfterSixConfs broadcasts the necessary channel announcement messages to
3726
// the network after 6 confs. Should be called after the channelReady message
3727
// is sent and the channel is added to the graph (channelState is
3728
// 'addedToGraph') and the channel is ready to be used. This is the last
3729
// step in the channel opening process, and the opening state will be deleted
3730
// from the database if successful.
3731
func (f *Manager) annAfterSixConfs(completeChan *channeldb.OpenChannel,
3732
        shortChanID *lnwire.ShortChannelID) error {
3✔
3733

3✔
3734
        // If this channel is not meant to be announced to the greater network,
3✔
3735
        // we'll only send our NodeAnnouncement to our counterparty to ensure we
3✔
3736
        // don't leak any of our information.
3✔
3737
        announceChan := completeChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
3738
        if !announceChan {
6✔
3739
                log.Debugf("Will not announce private channel %v.",
3✔
3740
                        shortChanID.ToUint64())
3✔
3741

3✔
3742
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
3✔
3743
                if err != nil {
3✔
3744
                        return err
×
3745
                }
×
3746

3747
                nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
3✔
3748
                if err != nil {
3✔
3749
                        return fmt.Errorf("unable to retrieve current node "+
×
3750
                                "announcement: %v", err)
×
3751
                }
×
3752

3753
                chanID := lnwire.NewChanIDFromOutPoint(
3✔
3754
                        completeChan.FundingOutpoint,
3✔
3755
                )
3✔
3756
                pubKey := peer.PubKey()
3✔
3757
                log.Debugf("Sending our NodeAnnouncement for "+
3✔
3758
                        "ChannelID(%v) to %x", chanID, pubKey)
3✔
3759

3✔
3760
                // TODO(halseth): make reliable. If the peer is not online this
3✔
3761
                // will fail, and the opening process will stop. Should instead
3✔
3762
                // block here, waiting for the peer to come online.
3✔
3763
                if err := peer.SendMessage(true, &nodeAnn); err != nil {
3✔
3764
                        return fmt.Errorf("unable to send node announcement "+
×
3765
                                "to peer %x: %v", pubKey, err)
×
3766
                }
×
3767
        } else {
3✔
3768
                // Otherwise, we'll wait until the funding transaction has
3✔
3769
                // reached 6 confirmations before announcing it.
3✔
3770
                numConfs := uint32(completeChan.NumConfsRequired)
3✔
3771
                if numConfs < 6 {
6✔
3772
                        numConfs = 6
3✔
3773
                }
3✔
3774
                txid := completeChan.FundingOutpoint.Hash
3✔
3775
                log.Debugf("Will announce channel %v after ChannelPoint"+
3✔
3776
                        "(%v) has gotten %d confirmations",
3✔
3777
                        shortChanID.ToUint64(), completeChan.FundingOutpoint,
3✔
3778
                        numConfs)
3✔
3779

3✔
3780
                fundingScript, err := makeFundingScript(completeChan)
3✔
3781
                if err != nil {
3✔
3782
                        return fmt.Errorf("unable to create funding script "+
×
3783
                                "for ChannelPoint(%v): %v",
×
3784
                                completeChan.FundingOutpoint, err)
×
3785
                }
×
3786

3787
                // Register with the ChainNotifier for a notification once the
3788
                // funding transaction reaches at least 6 confirmations.
3789
                confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
3✔
3790
                        &txid, fundingScript, numConfs,
3✔
3791
                        completeChan.BroadcastHeight(),
3✔
3792
                )
3✔
3793
                if err != nil {
3✔
3794
                        return fmt.Errorf("unable to register for "+
×
3795
                                "confirmation of ChannelPoint(%v): %v",
×
3796
                                completeChan.FundingOutpoint, err)
×
3797
                }
×
3798

3799
                // Wait until 6 confirmations has been reached or the wallet
3800
                // signals a shutdown.
3801
                select {
3✔
3802
                case _, ok := <-confNtfn.Confirmed:
3✔
3803
                        if !ok {
3✔
3804
                                return fmt.Errorf("ChainNotifier shutting "+
×
3805
                                        "down, cannot complete funding flow "+
×
3806
                                        "for ChannelPoint(%v)",
×
3807
                                        completeChan.FundingOutpoint)
×
3808
                        }
×
3809
                        // Fallthrough.
3810

3811
                case <-f.quit:
3✔
3812
                        return fmt.Errorf("%v, stopping funding flow for "+
3✔
3813
                                "ChannelPoint(%v)",
3✔
3814
                                ErrFundingManagerShuttingDown,
3✔
3815
                                completeChan.FundingOutpoint)
3✔
3816
                }
3817

3818
                fundingPoint := completeChan.FundingOutpoint
3✔
3819
                chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
3✔
3820

3✔
3821
                log.Infof("Announcing ChannelPoint(%v), short_chan_id=%v",
3✔
3822
                        &fundingPoint, shortChanID)
3✔
3823

3✔
3824
                // If this is a non-zero-conf option-scid-alias channel, we'll
3✔
3825
                // delete the mappings the gossiper uses so that ChannelUpdates
3✔
3826
                // with aliases won't be accepted. This is done elsewhere for
3✔
3827
                // zero-conf channels.
3✔
3828
                isScidFeature := completeChan.NegotiatedAliasFeature()
3✔
3829
                isZeroConf := completeChan.IsZeroConf()
3✔
3830
                if isScidFeature && !isZeroConf {
6✔
3831
                        baseScid := completeChan.ShortChanID()
3✔
3832
                        err := f.cfg.AliasManager.DeleteSixConfs(baseScid)
3✔
3833
                        if err != nil {
3✔
3834
                                return fmt.Errorf("failed deleting six confs "+
×
3835
                                        "maps: %v", err)
×
3836
                        }
×
3837

3838
                        // We'll delete the edge and add it again via
3839
                        // addToGraph. This is because the peer may have
3840
                        // sent us a ChannelUpdate with an alias and we don't
3841
                        // want to relay this.
3842
                        ourPolicy, err := f.cfg.DeleteAliasEdge(baseScid)
3✔
3843
                        if err != nil {
3✔
3844
                                return fmt.Errorf("failed deleting real edge "+
×
3845
                                        "for alias channel from graph: %v",
×
3846
                                        err)
×
3847
                        }
×
3848

3849
                        err = f.addToGraph(
3✔
3850
                                completeChan, &baseScid, nil, ourPolicy,
3✔
3851
                        )
3✔
3852
                        if err != nil {
3✔
3853
                                return fmt.Errorf("failed to re-add to "+
×
3854
                                        "graph: %v", err)
×
3855
                        }
×
3856
                }
3857

3858
                // Create and broadcast the proofs required to make this channel
3859
                // public and usable for other nodes for routing.
3860
                err = f.announceChannel(
3✔
3861
                        f.cfg.IDKey, completeChan.IdentityPub,
3✔
3862
                        &completeChan.LocalChanCfg.MultiSigKey,
3✔
3863
                        completeChan.RemoteChanCfg.MultiSigKey.PubKey,
3✔
3864
                        *shortChanID, chanID, completeChan.ChanType,
3✔
3865
                )
3✔
3866
                if err != nil {
6✔
3867
                        return fmt.Errorf("channel announcement failed: %w",
3✔
3868
                                err)
3✔
3869
                }
3✔
3870

3871
                log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+
3✔
3872
                        "sent to gossiper", &fundingPoint, shortChanID)
3✔
3873
        }
3874

3875
        return nil
3✔
3876
}
3877

3878
// waitForZeroConfChannel is called when the state is addedToGraph with
3879
// a zero-conf channel. This will wait for the real confirmation, add the
3880
// confirmed SCID to the router graph, and then announce after six confs.
3881
func (f *Manager) waitForZeroConfChannel(c *channeldb.OpenChannel) error {
3✔
3882
        // First we'll check whether the channel is confirmed on-chain. If it
3✔
3883
        // is already confirmed, the chainntnfs subsystem will return with the
3✔
3884
        // confirmed tx. Otherwise, we'll wait here until confirmation occurs.
3✔
3885
        confChan, err := f.waitForFundingWithTimeout(c)
3✔
3886
        if err != nil {
6✔
3887
                return fmt.Errorf("error waiting for zero-conf funding "+
3✔
3888
                        "confirmation for ChannelPoint(%v): %v",
3✔
3889
                        c.FundingOutpoint, err)
3✔
3890
        }
3✔
3891

3892
        // We'll need to refresh the channel state so that things are properly
3893
        // populated when validating the channel state. Otherwise, a panic may
3894
        // occur due to inconsistency in the OpenChannel struct.
3895
        err = c.Refresh()
3✔
3896
        if err != nil {
6✔
3897
                return fmt.Errorf("unable to refresh channel state: %w", err)
3✔
3898
        }
3✔
3899

3900
        // Now that we have the confirmed transaction and the proper SCID,
3901
        // we'll call ValidateChannel to ensure the confirmed tx is properly
3902
        // formatted.
3903
        err = f.cfg.Wallet.ValidateChannel(c, confChan.fundingTx)
3✔
3904
        if err != nil {
3✔
3905
                return fmt.Errorf("unable to validate zero-conf channel: "+
×
3906
                        "%v", err)
×
3907
        }
×
3908

3909
        // Once we know the confirmed ShortChannelID, we'll need to save it to
3910
        // the database and refresh the OpenChannel struct with it.
3911
        err = c.MarkRealScid(confChan.shortChanID)
3✔
3912
        if err != nil {
3✔
3913
                return fmt.Errorf("unable to set confirmed SCID for zero "+
×
3914
                        "channel: %v", err)
×
3915
        }
×
3916

3917
        // Six confirmations have been reached. If this channel is public,
3918
        // we'll delete some of the alias mappings the gossiper uses.
3919
        isPublic := c.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
3920
        if isPublic {
6✔
3921
                err = f.cfg.AliasManager.DeleteSixConfs(c.ShortChannelID)
3✔
3922
                if err != nil {
3✔
3923
                        return fmt.Errorf("unable to delete base alias after "+
×
3924
                                "six confirmations: %v", err)
×
3925
                }
×
3926

3927
                // TODO: Make this atomic!
3928
                ourPolicy, err := f.cfg.DeleteAliasEdge(c.ShortChanID())
3✔
3929
                if err != nil {
3✔
3930
                        return fmt.Errorf("unable to delete alias edge from "+
×
3931
                                "graph: %v", err)
×
3932
                }
×
3933

3934
                // We'll need to update the graph with the new ShortChannelID
3935
                // via an addToGraph call. We don't pass in the peer's
3936
                // alias since we'll be using the confirmed SCID from now on
3937
                // regardless if it's public or not.
3938
                err = f.addToGraph(
3✔
3939
                        c, &confChan.shortChanID, nil, ourPolicy,
3✔
3940
                )
3✔
3941
                if err != nil {
3✔
3942
                        return fmt.Errorf("failed adding confirmed zero-conf "+
×
3943
                                "SCID to graph: %v", err)
×
3944
                }
×
3945
        }
3946

3947
        // Since we have now marked down the confirmed SCID, we'll also need to
3948
        // tell the Switch to refresh the relevant ChannelLink so that forwards
3949
        // under the confirmed SCID are possible if this is a public channel.
3950
        err = f.cfg.ReportShortChanID(c.FundingOutpoint)
3✔
3951
        if err != nil {
3✔
3952
                // This should only fail if the link is not found in the
×
3953
                // Switch's linkIndex map. If this is the case, then the peer
×
3954
                // has gone offline and the next time the link is loaded, it
×
3955
                // will have a refreshed state. Just log an error here.
×
3956
                log.Errorf("unable to report scid for zero-conf channel "+
×
3957
                        "channel: %v", err)
×
3958
        }
×
3959

3960
        // Update the confirmed transaction's label.
3961
        f.makeLabelForTx(c)
3✔
3962

3✔
3963
        return nil
3✔
3964
}
3965

3966
// genFirstStateMusigNonce generates a nonces for the "first" local state. This
3967
// is the verification nonce for the state created for us after the initial
3968
// commitment transaction signed as part of the funding flow.
3969
func genFirstStateMusigNonce(channel *channeldb.OpenChannel,
3970
) (*musig2.Nonces, error) {
3✔
3971

3✔
3972
        musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
3✔
3973
                channel.RevocationProducer,
3✔
3974
        )
3✔
3975
        if err != nil {
3✔
3976
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3977
                        "nonces: %v", err)
×
3978
        }
×
3979

3980
        // We use the _next_ commitment height here as we need to generate the
3981
        // nonce for the next state the remote party will sign for us.
3982
        verNonce, err := channeldb.NewMusigVerificationNonce(
3✔
3983
                channel.LocalChanCfg.MultiSigKey.PubKey,
3✔
3984
                channel.LocalCommitment.CommitHeight+1,
3✔
3985
                musig2ShaChain,
3✔
3986
        )
3✔
3987
        if err != nil {
3✔
3988
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3989
                        "nonces: %v", err)
×
3990
        }
×
3991

3992
        return verNonce, nil
3✔
3993
}
3994

3995
// handleChannelReady finalizes the channel funding process and enables the
3996
// channel to enter normal operating mode.
3997
func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen
3998
        msg *lnwire.ChannelReady) {
3✔
3999

3✔
4000
        defer f.wg.Done()
3✔
4001

3✔
4002
        // If we are in development mode, we'll wait for specified duration
3✔
4003
        // before processing the channel ready message.
3✔
4004
        if f.cfg.Dev != nil {
6✔
4005
                duration := f.cfg.Dev.ProcessChannelReadyWait
3✔
4006
                log.Warnf("Channel(%v): sleeping %v before processing "+
3✔
4007
                        "channel_ready", msg.ChanID, duration)
3✔
4008

3✔
4009
                select {
3✔
4010
                case <-time.After(duration):
3✔
4011
                        log.Warnf("Channel(%v): slept %v before processing "+
3✔
4012
                                "channel_ready", msg.ChanID, duration)
3✔
4013
                case <-f.quit:
×
4014
                        log.Warnf("Channel(%v): quit sleeping", msg.ChanID)
×
4015
                        return
×
4016
                }
4017
        }
4018

4019
        log.Debugf("Received ChannelReady for ChannelID(%v) from "+
3✔
4020
                "peer %x", msg.ChanID,
3✔
4021
                peer.IdentityKey().SerializeCompressed())
3✔
4022

3✔
4023
        // We now load or create a new channel barrier for this channel.
3✔
4024
        _, loaded := f.handleChannelReadyBarriers.LoadOrStore(
3✔
4025
                msg.ChanID, struct{}{},
3✔
4026
        )
3✔
4027

3✔
4028
        // If we are currently in the process of handling a channel_ready
3✔
4029
        // message for this channel, ignore.
3✔
4030
        if loaded {
6✔
4031
                log.Infof("Already handling channelReady for "+
3✔
4032
                        "ChannelID(%v), ignoring.", msg.ChanID)
3✔
4033
                return
3✔
4034
        }
3✔
4035

4036
        // If not already handling channelReady for this channel, then the
4037
        // `LoadOrStore` has set up a barrier, and it will be removed once this
4038
        // function exits.
4039
        defer f.handleChannelReadyBarriers.Delete(msg.ChanID)
3✔
4040

3✔
4041
        localDiscoverySignal, ok := f.localDiscoverySignals.Load(msg.ChanID)
3✔
4042
        if ok {
6✔
4043
                // Before we proceed with processing the channel_ready
3✔
4044
                // message, we'll wait for the local waitForFundingConfirmation
3✔
4045
                // goroutine to signal that it has the necessary state in
3✔
4046
                // place. Otherwise, we may be missing critical information
3✔
4047
                // required to handle forwarded HTLC's.
3✔
4048
                select {
3✔
4049
                case <-localDiscoverySignal:
3✔
4050
                        // Fallthrough
4051
                case <-f.quit:
3✔
4052
                        return
3✔
4053
                }
4054

4055
                // With the signal received, we can now safely delete the entry
4056
                // from the map.
4057
                f.localDiscoverySignals.Delete(msg.ChanID)
3✔
4058
        }
4059

4060
        // First, we'll attempt to locate the channel whose funding workflow is
4061
        // being finalized by this message. We go to the database rather than
4062
        // our reservation map as we may have restarted, mid funding flow. Also
4063
        // provide the node's public key to make the search faster.
4064
        chanID := msg.ChanID
3✔
4065
        channel, err := f.cfg.FindChannel(peer.IdentityKey(), chanID)
3✔
4066
        if err != nil {
3✔
4067
                log.Errorf("Unable to locate ChannelID(%v), cannot complete "+
×
4068
                        "funding", chanID)
×
4069
                return
×
4070
        }
×
4071

4072
        // If this is a taproot channel, then we can generate the set of nonces
4073
        // the remote party needs to send the next remote commitment here.
4074
        var firstVerNonce *musig2.Nonces
3✔
4075
        if channel.ChanType.IsTaproot() {
6✔
4076
                firstVerNonce, err = genFirstStateMusigNonce(channel)
3✔
4077
                if err != nil {
3✔
4078
                        log.Error(err)
×
4079
                        return
×
4080
                }
×
4081
        }
4082

4083
        // We'll need to store the received TLV alias if the option_scid_alias
4084
        // feature was negotiated. This will be used to provide route hints
4085
        // during invoice creation. In the zero-conf case, it is also used to
4086
        // provide a ChannelUpdate to the remote peer. This is done before the
4087
        // call to InsertNextRevocation in case the call to PutPeerAlias fails.
4088
        // If it were to fail on the first call to handleChannelReady, we
4089
        // wouldn't want the channel to be usable yet.
4090
        if channel.NegotiatedAliasFeature() {
6✔
4091
                // If the AliasScid field is nil, we must fail out. We will
3✔
4092
                // most likely not be able to route through the peer.
3✔
4093
                if msg.AliasScid == nil {
3✔
4094
                        log.Debugf("Consider closing ChannelID(%v), peer "+
×
4095
                                "does not implement the option-scid-alias "+
×
4096
                                "feature properly", chanID)
×
4097
                        return
×
4098
                }
×
4099

4100
                // We'll store the AliasScid so that invoice creation can use
4101
                // it.
4102
                err = f.cfg.AliasManager.PutPeerAlias(chanID, *msg.AliasScid)
3✔
4103
                if err != nil {
3✔
4104
                        log.Errorf("unable to store peer's alias: %v", err)
×
4105
                        return
×
4106
                }
×
4107

4108
                // If we do not have an alias stored, we'll create one now.
4109
                // This is only used in the upgrade case where a user toggles
4110
                // the option-scid-alias feature-bit to on. We'll also send the
4111
                // channel_ready message here in case the link is created
4112
                // before sendChannelReady is called.
4113
                aliases := f.cfg.AliasManager.GetAliases(
3✔
4114
                        channel.ShortChannelID,
3✔
4115
                )
3✔
4116
                if len(aliases) == 0 {
3✔
4117
                        // No aliases were found so we'll request and store an
×
4118
                        // alias and use it in the channel_ready message.
×
4119
                        alias, err := f.cfg.AliasManager.RequestAlias()
×
4120
                        if err != nil {
×
4121
                                log.Errorf("unable to request alias: %v", err)
×
4122
                                return
×
4123
                        }
×
4124

4125
                        err = f.cfg.AliasManager.AddLocalAlias(
×
4126
                                alias, channel.ShortChannelID, false, false,
×
4127
                        )
×
4128
                        if err != nil {
×
4129
                                log.Errorf("unable to add local alias: %v",
×
4130
                                        err)
×
4131
                                return
×
4132
                        }
×
4133

4134
                        secondPoint, err := channel.SecondCommitmentPoint()
×
4135
                        if err != nil {
×
4136
                                log.Errorf("unable to fetch second "+
×
4137
                                        "commitment point: %v", err)
×
4138
                                return
×
4139
                        }
×
4140

4141
                        channelReadyMsg := lnwire.NewChannelReady(
×
4142
                                chanID, secondPoint,
×
4143
                        )
×
4144
                        channelReadyMsg.AliasScid = &alias
×
4145

×
4146
                        if firstVerNonce != nil {
×
4147
                                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:ll
×
4148
                                        firstVerNonce.PubNonce,
×
4149
                                )
×
4150
                        }
×
4151

4152
                        err = peer.SendMessage(true, channelReadyMsg)
×
4153
                        if err != nil {
×
4154
                                log.Errorf("unable to send channel_ready: %v",
×
4155
                                        err)
×
4156
                                return
×
4157
                        }
×
4158
                }
4159
        }
4160

4161
        // If the RemoteNextRevocation is non-nil, it means that we have
4162
        // already processed channelReady for this channel, so ignore. This
4163
        // check is after the alias logic so we store the peer's most recent
4164
        // alias. The spec requires us to validate that subsequent
4165
        // channel_ready messages use the same per commitment point (the
4166
        // second), but it is not actually necessary since we'll just end up
4167
        // ignoring it. We are, however, required to *send* the same per
4168
        // commitment point, since another pedantic implementation might
4169
        // verify it.
4170
        if channel.RemoteNextRevocation != nil {
6✔
4171
                log.Infof("Received duplicate channelReady for "+
3✔
4172
                        "ChannelID(%v), ignoring.", chanID)
3✔
4173
                return
3✔
4174
        }
3✔
4175

4176
        // If this is a taproot channel, then we'll need to map the received
4177
        // nonces to a nonce pair, and also fetch our pending nonces, which are
4178
        // required in order to make the channel whole.
4179
        var chanOpts []lnwallet.ChannelOpt
3✔
4180
        if channel.ChanType.IsTaproot() {
6✔
4181
                f.nonceMtx.Lock()
3✔
4182
                localNonce, ok := f.pendingMusigNonces[chanID]
3✔
4183
                if !ok {
6✔
4184
                        // If there's no pending nonce for this channel ID,
3✔
4185
                        // we'll use the one generated above.
3✔
4186
                        localNonce = firstVerNonce
3✔
4187
                        f.pendingMusigNonces[chanID] = firstVerNonce
3✔
4188
                }
3✔
4189
                f.nonceMtx.Unlock()
3✔
4190

3✔
4191
                log.Infof("ChanID(%v): applying local+remote musig2 nonces",
3✔
4192
                        chanID)
3✔
4193

3✔
4194
                remoteNonce, err := msg.NextLocalNonce.UnwrapOrErrV(
3✔
4195
                        errNoLocalNonce,
3✔
4196
                )
3✔
4197
                if err != nil {
3✔
4198
                        cid := newChanIdentifier(msg.ChanID)
×
4199
                        f.sendWarning(peer, cid, err)
×
4200

×
4201
                        return
×
4202
                }
×
4203

4204
                chanOpts = append(
3✔
4205
                        chanOpts,
3✔
4206
                        lnwallet.WithLocalMusigNonces(localNonce),
3✔
4207
                        lnwallet.WithRemoteMusigNonces(&musig2.Nonces{
3✔
4208
                                PubNonce: remoteNonce,
3✔
4209
                        }),
3✔
4210
                )
3✔
4211

3✔
4212
                // Inform the aux funding controller that the liquidity in the
3✔
4213
                // custom channel is now ready to be advertised. We potentially
3✔
4214
                // haven't sent our own channel ready message yet, but other
3✔
4215
                // than that the channel is ready to count toward available
3✔
4216
                // liquidity.
3✔
4217
                err = fn.MapOptionZ(
3✔
4218
                        f.cfg.AuxFundingController,
3✔
4219
                        func(controller AuxFundingController) error {
3✔
4220
                                return controller.ChannelReady(
×
4221
                                        lnwallet.NewAuxChanState(channel),
×
4222
                                )
×
4223
                        },
×
4224
                )
4225
                if err != nil {
3✔
4226
                        cid := newChanIdentifier(msg.ChanID)
×
4227
                        f.sendWarning(peer, cid, err)
×
4228

×
4229
                        return
×
4230
                }
×
4231
        }
4232

4233
        // The channel_ready message contains the next commitment point we'll
4234
        // need to create the next commitment state for the remote party. So
4235
        // we'll insert that into the channel now before passing it along to
4236
        // other sub-systems.
4237
        err = channel.InsertNextRevocation(msg.NextPerCommitmentPoint)
3✔
4238
        if err != nil {
3✔
4239
                log.Errorf("unable to insert next commitment point: %v", err)
×
4240
                return
×
4241
        }
×
4242

4243
        // Before we can add the channel to the peer, we'll need to ensure that
4244
        // we have an initial forwarding policy set.
4245
        if err := f.ensureInitialForwardingPolicy(chanID, channel); err != nil {
3✔
4246
                log.Errorf("Unable to ensure initial forwarding policy: %v",
×
4247
                        err)
×
4248
        }
×
4249

4250
        err = peer.AddNewChannel(&lnpeer.NewChannel{
3✔
4251
                OpenChannel: channel,
3✔
4252
                ChanOpts:    chanOpts,
3✔
4253
        }, f.quit)
3✔
4254
        if err != nil {
3✔
4255
                log.Errorf("Unable to add new channel %v with peer %x: %v",
×
4256
                        channel.FundingOutpoint,
×
4257
                        peer.IdentityKey().SerializeCompressed(), err,
×
4258
                )
×
4259
        }
×
4260
}
4261

4262
// handleChannelReadyReceived is called once the remote's channelReady message
4263
// is received and processed. At this stage, we must have sent out our
4264
// channelReady message, once the remote's channelReady is processed, the
4265
// channel is now active, thus we change its state to `addedToGraph` to
4266
// let the channel start handling routing.
4267
func (f *Manager) handleChannelReadyReceived(channel *channeldb.OpenChannel,
4268
        scid *lnwire.ShortChannelID, pendingChanID PendingChanID,
4269
        updateChan chan<- *lnrpc.OpenStatusUpdate) error {
3✔
4270

3✔
4271
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
3✔
4272

3✔
4273
        // Since we've sent+received funding locked at this point, we
3✔
4274
        // can clean up the pending musig2 nonce state.
3✔
4275
        f.nonceMtx.Lock()
3✔
4276
        delete(f.pendingMusigNonces, chanID)
3✔
4277
        f.nonceMtx.Unlock()
3✔
4278

3✔
4279
        var peerAlias *lnwire.ShortChannelID
3✔
4280
        if channel.IsZeroConf() {
6✔
4281
                // We'll need to wait until channel_ready has been received and
3✔
4282
                // the peer lets us know the alias they want to use for the
3✔
4283
                // channel. With this information, we can then construct a
3✔
4284
                // ChannelUpdate for them.  If an alias does not yet exist,
3✔
4285
                // we'll just return, letting the next iteration of the loop
3✔
4286
                // check again.
3✔
4287
                var defaultAlias lnwire.ShortChannelID
3✔
4288
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
3✔
4289
                foundAlias, _ := f.cfg.AliasManager.GetPeerAlias(chanID)
3✔
4290
                if foundAlias == defaultAlias {
3✔
4291
                        return nil
×
4292
                }
×
4293

4294
                peerAlias = &foundAlias
3✔
4295
        }
4296

4297
        err := f.addToGraph(channel, scid, peerAlias, nil)
3✔
4298
        if err != nil {
3✔
4299
                return fmt.Errorf("failed adding to graph: %w", err)
×
4300
        }
×
4301

4302
        // As the channel is now added to the ChannelRouter's topology, the
4303
        // channel is moved to the next state of the state machine. It will be
4304
        // moved to the last state (actually deleted from the database) after
4305
        // the channel is finally announced.
4306
        err = f.saveChannelOpeningState(
3✔
4307
                &channel.FundingOutpoint, addedToGraph, scid,
3✔
4308
        )
3✔
4309
        if err != nil {
3✔
4310
                return fmt.Errorf("error setting channel state to"+
×
4311
                        " addedToGraph: %w", err)
×
4312
        }
×
4313

4314
        log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
3✔
4315
                "added to graph", chanID, scid)
3✔
4316

3✔
4317
        err = fn.MapOptionZ(
3✔
4318
                f.cfg.AuxFundingController,
3✔
4319
                func(controller AuxFundingController) error {
3✔
4320
                        return controller.ChannelReady(
×
4321
                                lnwallet.NewAuxChanState(channel),
×
4322
                        )
×
4323
                },
×
4324
        )
4325
        if err != nil {
3✔
4326
                return fmt.Errorf("failed notifying aux funding controller "+
×
4327
                        "about channel ready: %w", err)
×
4328
        }
×
4329

4330
        // Give the caller a final update notifying them that the channel is
4331
        fundingPoint := channel.FundingOutpoint
3✔
4332
        cp := &lnrpc.ChannelPoint{
3✔
4333
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
3✔
4334
                        FundingTxidBytes: fundingPoint.Hash[:],
3✔
4335
                },
3✔
4336
                OutputIndex: fundingPoint.Index,
3✔
4337
        }
3✔
4338

3✔
4339
        if updateChan != nil {
6✔
4340
                upd := &lnrpc.OpenStatusUpdate{
3✔
4341
                        Update: &lnrpc.OpenStatusUpdate_ChanOpen{
3✔
4342
                                ChanOpen: &lnrpc.ChannelOpenUpdate{
3✔
4343
                                        ChannelPoint: cp,
3✔
4344
                                },
3✔
4345
                        },
3✔
4346
                        PendingChanId: pendingChanID[:],
3✔
4347
                }
3✔
4348

3✔
4349
                select {
3✔
4350
                case updateChan <- upd:
3✔
4351
                case <-f.quit:
×
4352
                        return ErrFundingManagerShuttingDown
×
4353
                }
4354
        }
4355

4356
        return nil
3✔
4357
}
4358

4359
// ensureInitialForwardingPolicy ensures that we have an initial forwarding
4360
// policy set for the given channel. If we don't, we'll fall back to the default
4361
// values.
4362
func (f *Manager) ensureInitialForwardingPolicy(chanID lnwire.ChannelID,
4363
        channel *channeldb.OpenChannel) error {
3✔
4364

3✔
4365
        // Before we can add the channel to the peer, we'll need to ensure that
3✔
4366
        // we have an initial forwarding policy set. This should always be the
3✔
4367
        // case except for a channel that was created with lnd <= 0.15.5 and
3✔
4368
        // is still pending while updating to this version.
3✔
4369
        var needDBUpdate bool
3✔
4370
        forwardingPolicy, err := f.getInitialForwardingPolicy(chanID)
3✔
4371
        if err != nil {
3✔
4372
                log.Errorf("Unable to fetch initial forwarding policy, "+
×
4373
                        "falling back to default values: %v", err)
×
4374

×
4375
                forwardingPolicy = f.defaultForwardingPolicy(
×
4376
                        channel.LocalChanCfg.ChannelStateBounds,
×
4377
                )
×
4378
                needDBUpdate = true
×
4379
        }
×
4380

4381
        // We only started storing the actual values for MinHTLCOut and MaxHTLC
4382
        // after 0.16.x, so if a channel was opened with such a version and is
4383
        // still pending while updating to this version, we'll need to set the
4384
        // values to the default values.
4385
        if forwardingPolicy.MinHTLCOut == 0 {
6✔
4386
                forwardingPolicy.MinHTLCOut = channel.LocalChanCfg.MinHTLC
3✔
4387
                needDBUpdate = true
3✔
4388
        }
3✔
4389
        if forwardingPolicy.MaxHTLC == 0 {
6✔
4390
                forwardingPolicy.MaxHTLC = channel.LocalChanCfg.MaxPendingAmount
3✔
4391
                needDBUpdate = true
3✔
4392
        }
3✔
4393

4394
        // And finally, if we found that the values currently stored aren't
4395
        // sufficient for the link, we'll update the database.
4396
        if needDBUpdate {
6✔
4397
                err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
3✔
4398
                if err != nil {
3✔
4399
                        return fmt.Errorf("unable to update initial "+
×
4400
                                "forwarding policy: %v", err)
×
4401
                }
×
4402
        }
4403

4404
        return nil
3✔
4405
}
4406

4407
// chanAnnouncement encapsulates the two authenticated announcements that we
4408
// send out to the network after a new channel has been created locally.
4409
type chanAnnouncement struct {
4410
        chanAnn       *lnwire.ChannelAnnouncement1
4411
        chanUpdateAnn *lnwire.ChannelUpdate1
4412
        chanProof     *lnwire.AnnounceSignatures1
4413
}
4414

4415
// newChanAnnouncement creates the authenticated channel announcement messages
4416
// required to broadcast a newly created channel to the network. The
4417
// announcement is two part: the first part authenticates the existence of the
4418
// channel and contains four signatures binding the funding pub keys and
4419
// identity pub keys of both parties to the channel, and the second segment is
4420
// authenticated only by us and contains our directional routing policy for the
4421
// channel. ourPolicy may be set in order to re-use an existing, non-default
4422
// policy.
4423
func (f *Manager) newChanAnnouncement(localPubKey,
4424
        remotePubKey *btcec.PublicKey, localFundingKey *keychain.KeyDescriptor,
4425
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4426
        chanID lnwire.ChannelID, fwdMinHTLC, fwdMaxHTLC lnwire.MilliSatoshi,
4427
        ourPolicy *models.ChannelEdgePolicy,
4428
        chanType channeldb.ChannelType) (*chanAnnouncement, error) {
3✔
4429

3✔
4430
        chainHash := *f.cfg.Wallet.Cfg.NetParams.GenesisHash
3✔
4431

3✔
4432
        // The unconditional section of the announcement is the ShortChannelID
3✔
4433
        // itself which compactly encodes the location of the funding output
3✔
4434
        // within the blockchain.
3✔
4435
        chanAnn := &lnwire.ChannelAnnouncement1{
3✔
4436
                ShortChannelID: shortChanID,
3✔
4437
                Features:       lnwire.NewRawFeatureVector(),
3✔
4438
                ChainHash:      chainHash,
3✔
4439
        }
3✔
4440

3✔
4441
        // If this is a taproot channel, then we'll set a special bit in the
3✔
4442
        // feature vector to indicate to the routing layer that this needs a
3✔
4443
        // slightly different type of validation.
3✔
4444
        //
3✔
4445
        // TODO(roasbeef): temp, remove after gossip 1.5
3✔
4446
        if chanType.IsTaproot() {
6✔
4447
                log.Debugf("Applying taproot feature bit to "+
3✔
4448
                        "ChannelAnnouncement for %v", chanID)
3✔
4449

3✔
4450
                chanAnn.Features.Set(
3✔
4451
                        lnwire.SimpleTaprootChannelsRequiredStaging,
3✔
4452
                )
3✔
4453
        }
3✔
4454

4455
        // The chanFlags field indicates which directed edge of the channel is
4456
        // being updated within the ChannelUpdateAnnouncement announcement
4457
        // below. A value of zero means it's the edge of the "first" node and 1
4458
        // being the other node.
4459
        var chanFlags lnwire.ChanUpdateChanFlags
3✔
4460

3✔
4461
        // The lexicographical ordering of the two identity public keys of the
3✔
4462
        // nodes indicates which of the nodes is "first". If our serialized
3✔
4463
        // identity key is lower than theirs then we're the "first" node and
3✔
4464
        // second otherwise.
3✔
4465
        selfBytes := localPubKey.SerializeCompressed()
3✔
4466
        remoteBytes := remotePubKey.SerializeCompressed()
3✔
4467
        if bytes.Compare(selfBytes, remoteBytes) == -1 {
6✔
4468
                copy(chanAnn.NodeID1[:], localPubKey.SerializeCompressed())
3✔
4469
                copy(chanAnn.NodeID2[:], remotePubKey.SerializeCompressed())
3✔
4470
                copy(
3✔
4471
                        chanAnn.BitcoinKey1[:],
3✔
4472
                        localFundingKey.PubKey.SerializeCompressed(),
3✔
4473
                )
3✔
4474
                copy(
3✔
4475
                        chanAnn.BitcoinKey2[:],
3✔
4476
                        remoteFundingKey.SerializeCompressed(),
3✔
4477
                )
3✔
4478

3✔
4479
                // If we're the first node then update the chanFlags to
3✔
4480
                // indicate the "direction" of the update.
3✔
4481
                chanFlags = 0
3✔
4482
        } else {
6✔
4483
                copy(chanAnn.NodeID1[:], remotePubKey.SerializeCompressed())
3✔
4484
                copy(chanAnn.NodeID2[:], localPubKey.SerializeCompressed())
3✔
4485
                copy(
3✔
4486
                        chanAnn.BitcoinKey1[:],
3✔
4487
                        remoteFundingKey.SerializeCompressed(),
3✔
4488
                )
3✔
4489
                copy(
3✔
4490
                        chanAnn.BitcoinKey2[:],
3✔
4491
                        localFundingKey.PubKey.SerializeCompressed(),
3✔
4492
                )
3✔
4493

3✔
4494
                // If we're the second node then update the chanFlags to
3✔
4495
                // indicate the "direction" of the update.
3✔
4496
                chanFlags = 1
3✔
4497
        }
3✔
4498

4499
        // Our channel update message flags will signal that we support the
4500
        // max_htlc field.
4501
        msgFlags := lnwire.ChanUpdateRequiredMaxHtlc
3✔
4502

3✔
4503
        // We announce the channel with the default values. Some of
3✔
4504
        // these values can later be changed by crafting a new ChannelUpdate.
3✔
4505
        chanUpdateAnn := &lnwire.ChannelUpdate1{
3✔
4506
                ShortChannelID: shortChanID,
3✔
4507
                ChainHash:      chainHash,
3✔
4508
                Timestamp:      uint32(time.Now().Unix()),
3✔
4509
                MessageFlags:   msgFlags,
3✔
4510
                ChannelFlags:   chanFlags,
3✔
4511
                TimeLockDelta: uint16(
3✔
4512
                        f.cfg.DefaultRoutingPolicy.TimeLockDelta,
3✔
4513
                ),
3✔
4514
                HtlcMinimumMsat: fwdMinHTLC,
3✔
4515
                HtlcMaximumMsat: fwdMaxHTLC,
3✔
4516
        }
3✔
4517

3✔
4518
        // The caller of newChanAnnouncement is expected to provide the initial
3✔
4519
        // forwarding policy to be announced. If no persisted initial policy
3✔
4520
        // values are found, then we will use the default policy values in the
3✔
4521
        // channel announcement.
3✔
4522
        storedFwdingPolicy, err := f.getInitialForwardingPolicy(chanID)
3✔
4523
        if err != nil && !errors.Is(err, channeldb.ErrChannelNotFound) {
3✔
4524
                return nil, errors.Errorf("unable to generate channel "+
×
4525
                        "update announcement: %v", err)
×
4526
        }
×
4527

4528
        switch {
3✔
4529
        case ourPolicy != nil:
3✔
4530
                // If ourPolicy is non-nil, modify the default parameters of the
3✔
4531
                // ChannelUpdate.
3✔
4532
                chanUpdateAnn.MessageFlags = ourPolicy.MessageFlags
3✔
4533
                chanUpdateAnn.ChannelFlags = ourPolicy.ChannelFlags
3✔
4534
                chanUpdateAnn.TimeLockDelta = ourPolicy.TimeLockDelta
3✔
4535
                chanUpdateAnn.HtlcMinimumMsat = ourPolicy.MinHTLC
3✔
4536
                chanUpdateAnn.HtlcMaximumMsat = ourPolicy.MaxHTLC
3✔
4537
                chanUpdateAnn.BaseFee = uint32(ourPolicy.FeeBaseMSat)
3✔
4538
                chanUpdateAnn.FeeRate = uint32(
3✔
4539
                        ourPolicy.FeeProportionalMillionths,
3✔
4540
                )
3✔
4541

4542
        case storedFwdingPolicy != nil:
3✔
4543
                chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
3✔
4544
                chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
3✔
4545

4546
        default:
×
4547
                log.Infof("No channel forwarding policy specified for channel "+
×
4548
                        "announcement of ChannelID(%v). "+
×
4549
                        "Assuming default fee parameters.", chanID)
×
4550
                chanUpdateAnn.BaseFee = uint32(
×
4551
                        f.cfg.DefaultRoutingPolicy.BaseFee,
×
4552
                )
×
4553
                chanUpdateAnn.FeeRate = uint32(
×
4554
                        f.cfg.DefaultRoutingPolicy.FeeRate,
×
4555
                )
×
4556
        }
4557

4558
        // With the channel update announcement constructed, we'll generate a
4559
        // signature that signs a double-sha digest of the announcement.
4560
        // This'll serve to authenticate this announcement and any other future
4561
        // updates we may send.
4562
        chanUpdateMsg, err := chanUpdateAnn.DataToSign()
3✔
4563
        if err != nil {
3✔
4564
                return nil, err
×
4565
        }
×
4566
        sig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanUpdateMsg, true)
3✔
4567
        if err != nil {
3✔
4568
                return nil, errors.Errorf("unable to generate channel "+
×
4569
                        "update announcement signature: %v", err)
×
4570
        }
×
4571
        chanUpdateAnn.Signature, err = lnwire.NewSigFromSignature(sig)
3✔
4572
        if err != nil {
3✔
4573
                return nil, errors.Errorf("unable to generate channel "+
×
4574
                        "update announcement signature: %v", err)
×
4575
        }
×
4576

4577
        // The channel existence proofs itself is currently announced in
4578
        // distinct message. In order to properly authenticate this message, we
4579
        // need two signatures: one under the identity public key used which
4580
        // signs the message itself and another signature of the identity
4581
        // public key under the funding key itself.
4582
        //
4583
        // TODO(roasbeef): use SignAnnouncement here instead?
4584
        chanAnnMsg, err := chanAnn.DataToSign()
3✔
4585
        if err != nil {
3✔
4586
                return nil, err
×
4587
        }
×
4588
        nodeSig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanAnnMsg, true)
3✔
4589
        if err != nil {
3✔
4590
                return nil, errors.Errorf("unable to generate node "+
×
4591
                        "signature for channel announcement: %v", err)
×
4592
        }
×
4593
        bitcoinSig, err := f.cfg.SignMessage(
3✔
4594
                localFundingKey.KeyLocator, chanAnnMsg, true,
3✔
4595
        )
3✔
4596
        if err != nil {
3✔
4597
                return nil, errors.Errorf("unable to generate bitcoin "+
×
4598
                        "signature for node public key: %v", err)
×
4599
        }
×
4600

4601
        // Finally, we'll generate the announcement proof which we'll use to
4602
        // provide the other side with the necessary signatures required to
4603
        // allow them to reconstruct the full channel announcement.
4604
        proof := &lnwire.AnnounceSignatures1{
3✔
4605
                ChannelID:      chanID,
3✔
4606
                ShortChannelID: shortChanID,
3✔
4607
        }
3✔
4608
        proof.NodeSignature, err = lnwire.NewSigFromSignature(nodeSig)
3✔
4609
        if err != nil {
3✔
4610
                return nil, err
×
4611
        }
×
4612
        proof.BitcoinSignature, err = lnwire.NewSigFromSignature(bitcoinSig)
3✔
4613
        if err != nil {
3✔
4614
                return nil, err
×
4615
        }
×
4616

4617
        return &chanAnnouncement{
3✔
4618
                chanAnn:       chanAnn,
3✔
4619
                chanUpdateAnn: chanUpdateAnn,
3✔
4620
                chanProof:     proof,
3✔
4621
        }, nil
3✔
4622
}
4623

4624
// announceChannel announces a newly created channel to the rest of the network
4625
// by crafting the two authenticated announcements required for the peers on
4626
// the network to recognize the legitimacy of the channel. The crafted
4627
// announcements are then sent to the channel router to handle broadcasting to
4628
// the network during its next trickle.
4629
// This method is synchronous and will return when all the network requests
4630
// finish, either successfully or with an error.
4631
func (f *Manager) announceChannel(localIDKey, remoteIDKey *btcec.PublicKey,
4632
        localFundingKey *keychain.KeyDescriptor,
4633
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4634
        chanID lnwire.ChannelID, chanType channeldb.ChannelType) error {
3✔
4635

3✔
4636
        // First, we'll create the batch of announcements to be sent upon
3✔
4637
        // initial channel creation. This includes the channel announcement
3✔
4638
        // itself, the channel update announcement, and our half of the channel
3✔
4639
        // proof needed to fully authenticate the channel.
3✔
4640
        //
3✔
4641
        // We can pass in zeroes for the min and max htlc policy, because we
3✔
4642
        // only use the channel announcement message from the returned struct.
3✔
4643
        ann, err := f.newChanAnnouncement(
3✔
4644
                localIDKey, remoteIDKey, localFundingKey, remoteFundingKey,
3✔
4645
                shortChanID, chanID, 0, 0, nil, chanType,
3✔
4646
        )
3✔
4647
        if err != nil {
3✔
4648
                log.Errorf("can't generate channel announcement: %v", err)
×
4649
                return err
×
4650
        }
×
4651

4652
        // We only send the channel proof announcement and the node announcement
4653
        // because addToGraph previously sent the ChannelAnnouncement and
4654
        // the ChannelUpdate announcement messages. The channel proof and node
4655
        // announcements are broadcast to the greater network.
4656
        errChan := f.cfg.SendAnnouncement(ann.chanProof)
3✔
4657
        select {
3✔
4658
        case err := <-errChan:
3✔
4659
                if err != nil {
6✔
4660
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4661
                                graph.ErrIgnored) {
3✔
4662

×
4663
                                log.Debugf("Graph rejected "+
×
4664
                                        "AnnounceSignatures: %v", err)
×
4665
                        } else {
3✔
4666
                                log.Errorf("Unable to send channel "+
3✔
4667
                                        "proof: %v", err)
3✔
4668
                                return err
3✔
4669
                        }
3✔
4670
                }
4671

4672
        case <-f.quit:
×
4673
                return ErrFundingManagerShuttingDown
×
4674
        }
4675

4676
        // Now that the channel is announced to the network, we will also
4677
        // obtain and send a node announcement. This is done since a node
4678
        // announcement is only accepted after a channel is known for that
4679
        // particular node, and this might be our first channel.
4680
        nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
3✔
4681
        if err != nil {
3✔
4682
                log.Errorf("can't generate node announcement: %v", err)
×
4683
                return err
×
4684
        }
×
4685

4686
        errChan = f.cfg.SendAnnouncement(&nodeAnn)
3✔
4687
        select {
3✔
4688
        case err := <-errChan:
3✔
4689
                if err != nil {
6✔
4690
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4691
                                graph.ErrIgnored) {
6✔
4692

3✔
4693
                                log.Debugf("Graph rejected "+
3✔
4694
                                        "NodeAnnouncement: %v", err)
3✔
4695
                        } else {
3✔
4696
                                log.Errorf("Unable to send node "+
×
4697
                                        "announcement: %v", err)
×
4698
                                return err
×
4699
                        }
×
4700
                }
4701

4702
        case <-f.quit:
×
4703
                return ErrFundingManagerShuttingDown
×
4704
        }
4705

4706
        return nil
3✔
4707
}
4708

4709
// InitFundingWorkflow sends a message to the funding manager instructing it
4710
// to initiate a single funder workflow with the source peer.
4711
func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg) {
3✔
4712
        f.fundingRequests <- msg
3✔
4713
}
3✔
4714

4715
// getUpfrontShutdownScript takes a user provided script and a getScript
4716
// function which can be used to generate an upfront shutdown script. If our
4717
// peer does not support the feature, this function will error if a non-zero
4718
// script was provided by the user, and return an empty script otherwise. If
4719
// our peer does support the feature, we will return the user provided script
4720
// if non-zero, or a freshly generated script if our node is configured to set
4721
// upfront shutdown scripts automatically.
4722
func getUpfrontShutdownScript(enableUpfrontShutdown bool, peer lnpeer.Peer,
4723
        script lnwire.DeliveryAddress,
4724
        getScript func(bool) (lnwire.DeliveryAddress, error)) (lnwire.DeliveryAddress,
4725
        error) {
3✔
4726

3✔
4727
        // Check whether the remote peer supports upfront shutdown scripts.
3✔
4728
        remoteUpfrontShutdown := peer.RemoteFeatures().HasFeature(
3✔
4729
                lnwire.UpfrontShutdownScriptOptional,
3✔
4730
        )
3✔
4731

3✔
4732
        // If the peer does not support upfront shutdown scripts, and one has been
3✔
4733
        // provided, return an error because the feature is not supported.
3✔
4734
        if !remoteUpfrontShutdown && len(script) != 0 {
3✔
4735
                return nil, errUpfrontShutdownScriptNotSupported
×
4736
        }
×
4737

4738
        // If the peer does not support upfront shutdown, return an empty address.
4739
        if !remoteUpfrontShutdown {
3✔
4740
                return nil, nil
×
4741
        }
×
4742

4743
        // If the user has provided an script and the peer supports the feature,
4744
        // return it. Note that user set scripts override the enable upfront
4745
        // shutdown flag.
4746
        if len(script) > 0 {
6✔
4747
                return script, nil
3✔
4748
        }
3✔
4749

4750
        // If we do not have setting of upfront shutdown script enabled, return
4751
        // an empty script.
4752
        if !enableUpfrontShutdown {
6✔
4753
                return nil, nil
3✔
4754
        }
3✔
4755

4756
        // We can safely send a taproot address iff, both sides have negotiated
4757
        // the shutdown-any-segwit feature.
4758
        taprootOK := peer.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
×
4759
                peer.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
×
4760

×
4761
        return getScript(taprootOK)
×
4762
}
4763

4764
// handleInitFundingMsg creates a channel reservation within the daemon's
4765
// wallet, then sends a funding request to the remote peer kicking off the
4766
// funding workflow.
4767
func (f *Manager) handleInitFundingMsg(msg *InitFundingMsg) {
3✔
4768
        var (
3✔
4769
                peerKey        = msg.Peer.IdentityKey()
3✔
4770
                localAmt       = msg.LocalFundingAmt
3✔
4771
                baseFee        = msg.BaseFee
3✔
4772
                feeRate        = msg.FeeRate
3✔
4773
                minHtlcIn      = msg.MinHtlcIn
3✔
4774
                remoteCsvDelay = msg.RemoteCsvDelay
3✔
4775
                maxValue       = msg.MaxValueInFlight
3✔
4776
                maxHtlcs       = msg.MaxHtlcs
3✔
4777
                maxCSV         = msg.MaxLocalCsv
3✔
4778
                chanReserve    = msg.RemoteChanReserve
3✔
4779
                outpoints      = msg.Outpoints
3✔
4780
        )
3✔
4781

3✔
4782
        // If no maximum CSV delay was set for this channel, we use our default
3✔
4783
        // value.
3✔
4784
        if maxCSV == 0 {
6✔
4785
                maxCSV = f.cfg.MaxLocalCSVDelay
3✔
4786
        }
3✔
4787

4788
        log.Infof("Initiating fundingRequest(local_amt=%v "+
3✔
4789
                "(subtract_fees=%v), push_amt=%v, chain_hash=%v, peer=%x, "+
3✔
4790
                "min_confs=%v)", localAmt, msg.SubtractFees, msg.PushAmt,
3✔
4791
                msg.ChainHash, peerKey.SerializeCompressed(), msg.MinConfs)
3✔
4792

3✔
4793
        // We set the channel flags to indicate whether we want this channel to
3✔
4794
        // be announced to the network.
3✔
4795
        var channelFlags lnwire.FundingFlag
3✔
4796
        if !msg.Private {
6✔
4797
                // This channel will be announced.
3✔
4798
                channelFlags = lnwire.FFAnnounceChannel
3✔
4799
        }
3✔
4800

4801
        // If the caller specified their own channel ID, then we'll use that.
4802
        // Otherwise we'll generate a fresh one as normal.  This will be used
4803
        // to track this reservation throughout its lifetime.
4804
        var chanID PendingChanID
3✔
4805
        if msg.PendingChanID == zeroID {
6✔
4806
                chanID = f.nextPendingChanID()
3✔
4807
        } else {
6✔
4808
                // If the user specified their own pending channel ID, then
3✔
4809
                // we'll ensure it doesn't collide with any existing pending
3✔
4810
                // channel ID.
3✔
4811
                chanID = msg.PendingChanID
3✔
4812
                if _, err := f.getReservationCtx(peerKey, chanID); err == nil {
3✔
4813
                        msg.Err <- fmt.Errorf("pendingChannelID(%x) "+
×
4814
                                "already present", chanID[:])
×
4815
                        return
×
4816
                }
×
4817
        }
4818

4819
        // Check whether the peer supports upfront shutdown, and get an address
4820
        // which should be used (either a user specified address or a new
4821
        // address from the wallet if our node is configured to set shutdown
4822
        // address by default).
4823
        shutdown, err := getUpfrontShutdownScript(
3✔
4824
                f.cfg.EnableUpfrontShutdown, msg.Peer, msg.ShutdownScript,
3✔
4825
                f.selectShutdownScript,
3✔
4826
        )
3✔
4827
        if err != nil {
3✔
4828
                msg.Err <- err
×
4829
                return
×
4830
        }
×
4831

4832
        // Initialize a funding reservation with the local wallet. If the
4833
        // wallet doesn't have enough funds to commit to this channel, then the
4834
        // request will fail, and be aborted.
4835
        //
4836
        // Before we init the channel, we'll also check to see what commitment
4837
        // format we can use with this peer. This is dependent on *both* us and
4838
        // the remote peer are signaling the proper feature bit.
4839
        chanType, commitType, err := negotiateCommitmentType(
3✔
4840
                msg.ChannelType, msg.Peer.LocalFeatures(),
3✔
4841
                msg.Peer.RemoteFeatures(),
3✔
4842
        )
3✔
4843
        if err != nil {
6✔
4844
                log.Errorf("channel type negotiation failed: %v", err)
3✔
4845
                msg.Err <- err
3✔
4846
                return
3✔
4847
        }
3✔
4848

4849
        var (
3✔
4850
                zeroConf bool
3✔
4851
                scid     bool
3✔
4852
        )
3✔
4853

3✔
4854
        if chanType != nil {
6✔
4855
                // Check if the returned chanType includes either the zero-conf
3✔
4856
                // or scid-alias bits.
3✔
4857
                featureVec := lnwire.RawFeatureVector(*chanType)
3✔
4858
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
3✔
4859
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
3✔
4860

3✔
4861
                // The option-scid-alias channel type for a public channel is
3✔
4862
                // disallowed.
3✔
4863
                if scid && !msg.Private {
3✔
4864
                        err = fmt.Errorf("option-scid-alias chantype for " +
×
4865
                                "public channel")
×
4866
                        log.Error(err)
×
4867
                        msg.Err <- err
×
4868

×
4869
                        return
×
4870
                }
×
4871
        }
4872

4873
        // First, we'll query the fee estimator for a fee that should get the
4874
        // commitment transaction confirmed by the next few blocks (conf target
4875
        // of 3). We target the near blocks here to ensure that we'll be able
4876
        // to execute a timely unilateral channel closure if needed.
4877
        commitFeePerKw, err := f.cfg.FeeEstimator.EstimateFeePerKW(3)
3✔
4878
        if err != nil {
3✔
4879
                msg.Err <- err
×
4880
                return
×
4881
        }
×
4882

4883
        // For anchor channels cap the initial commit fee rate at our defined
4884
        // maximum.
4885
        if commitType.HasAnchors() &&
3✔
4886
                commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
6✔
4887

3✔
4888
                commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate
3✔
4889
        }
3✔
4890

4891
        var scidFeatureVal bool
3✔
4892
        if hasFeatures(
3✔
4893
                msg.Peer.LocalFeatures(), msg.Peer.RemoteFeatures(),
3✔
4894
                lnwire.ScidAliasOptional,
3✔
4895
        ) {
6✔
4896

3✔
4897
                scidFeatureVal = true
3✔
4898
        }
3✔
4899

4900
        // At this point, if we have an AuxFundingController active, we'll check
4901
        // to see if we have a special tapscript root to use in our MuSig2
4902
        // funding output.
4903
        tapscriptRoot, err := fn.MapOptionZ(
3✔
4904
                f.cfg.AuxFundingController,
3✔
4905
                func(c AuxFundingController) AuxTapscriptResult {
3✔
4906
                        return c.DeriveTapscriptRoot(chanID)
×
4907
                },
×
4908
        ).Unpack()
4909
        if err != nil {
3✔
4910
                err = fmt.Errorf("error deriving tapscript root: %w", err)
×
4911
                log.Error(err)
×
4912
                msg.Err <- err
×
4913

×
4914
                return
×
4915
        }
×
4916

4917
        req := &lnwallet.InitFundingReserveMsg{
3✔
4918
                ChainHash:         &msg.ChainHash,
3✔
4919
                PendingChanID:     chanID,
3✔
4920
                NodeID:            peerKey,
3✔
4921
                NodeAddr:          msg.Peer.Address(),
3✔
4922
                SubtractFees:      msg.SubtractFees,
3✔
4923
                LocalFundingAmt:   localAmt,
3✔
4924
                RemoteFundingAmt:  0,
3✔
4925
                FundUpToMaxAmt:    msg.FundUpToMaxAmt,
3✔
4926
                MinFundAmt:        msg.MinFundAmt,
3✔
4927
                RemoteChanReserve: chanReserve,
3✔
4928
                Outpoints:         outpoints,
3✔
4929
                CommitFeePerKw:    commitFeePerKw,
3✔
4930
                FundingFeePerKw:   msg.FundingFeePerKw,
3✔
4931
                PushMSat:          msg.PushAmt,
3✔
4932
                Flags:             channelFlags,
3✔
4933
                MinConfs:          msg.MinConfs,
3✔
4934
                CommitType:        commitType,
3✔
4935
                ChanFunder:        msg.ChanFunder,
3✔
4936
                // Unconfirmed Utxos which are marked by the sweeper subsystem
3✔
4937
                // are excluded from the coin selection because they are not
3✔
4938
                // final and can be RBFed by the sweeper subsystem.
3✔
4939
                AllowUtxoForFunding: func(u lnwallet.Utxo) bool {
6✔
4940
                        // Utxos with at least 1 confirmation are safe to use
3✔
4941
                        // for channel openings because they don't bare the risk
3✔
4942
                        // of being replaced (BIP 125 RBF).
3✔
4943
                        if u.Confirmations > 0 {
6✔
4944
                                return true
3✔
4945
                        }
3✔
4946

4947
                        // Query the sweeper storage to make sure we don't use
4948
                        // an unconfirmed utxo still in use by the sweeper
4949
                        // subsystem.
4950
                        return !f.cfg.IsSweeperOutpoint(u.OutPoint)
3✔
4951
                },
4952
                ZeroConf:         zeroConf,
4953
                OptionScidAlias:  scid,
4954
                ScidAliasFeature: scidFeatureVal,
4955
                Memo:             msg.Memo,
4956
                TapscriptRoot:    tapscriptRoot,
4957
        }
4958

4959
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
3✔
4960
        if err != nil {
6✔
4961
                msg.Err <- err
3✔
4962
                return
3✔
4963
        }
3✔
4964

4965
        if zeroConf {
6✔
4966
                // Store the alias for zero-conf channels in the underlying
3✔
4967
                // partial channel state.
3✔
4968
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
3✔
4969
                if err != nil {
3✔
4970
                        msg.Err <- err
×
4971
                        return
×
4972
                }
×
4973

4974
                reservation.AddAlias(aliasScid)
3✔
4975
        }
4976

4977
        // Set our upfront shutdown address in the existing reservation.
4978
        reservation.SetOurUpfrontShutdown(shutdown)
3✔
4979

3✔
4980
        // Now that we have successfully reserved funds for this channel in the
3✔
4981
        // wallet, we can fetch the final channel capacity. This is done at
3✔
4982
        // this point since the final capacity might change in case of
3✔
4983
        // SubtractFees=true.
3✔
4984
        capacity := reservation.Capacity()
3✔
4985

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

3✔
4989
        // If the remote CSV delay was not set in the open channel request,
3✔
4990
        // we'll use the RequiredRemoteDelay closure to compute the delay we
3✔
4991
        // require given the total amount of funds within the channel.
3✔
4992
        if remoteCsvDelay == 0 {
6✔
4993
                remoteCsvDelay = f.cfg.RequiredRemoteDelay(capacity)
3✔
4994
        }
3✔
4995

4996
        // If no minimum HTLC value was specified, use the default one.
4997
        if minHtlcIn == 0 {
6✔
4998
                minHtlcIn = f.cfg.DefaultMinHtlcIn
3✔
4999
        }
3✔
5000

5001
        // If no max value was specified, use the default one.
5002
        if maxValue == 0 {
6✔
5003
                maxValue = f.cfg.RequiredRemoteMaxValue(capacity)
3✔
5004
        }
3✔
5005

5006
        if maxHtlcs == 0 {
6✔
5007
                maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
3✔
5008
        }
3✔
5009

5010
        // Once the reservation has been created, and indexed, queue a funding
5011
        // request to the remote peer, kicking off the funding workflow.
5012
        ourContribution := reservation.OurContribution()
3✔
5013

3✔
5014
        // Prepare the optional channel fee values from the initFundingMsg. If
3✔
5015
        // useBaseFee or useFeeRate are false the client did not provide fee
3✔
5016
        // values hence we assume default fee settings from the config.
3✔
5017
        forwardingPolicy := f.defaultForwardingPolicy(
3✔
5018
                ourContribution.ChannelStateBounds,
3✔
5019
        )
3✔
5020
        if baseFee != nil {
6✔
5021
                forwardingPolicy.BaseFee = lnwire.MilliSatoshi(*baseFee)
3✔
5022
        }
3✔
5023

5024
        if feeRate != nil {
6✔
5025
                forwardingPolicy.FeeRate = lnwire.MilliSatoshi(*feeRate)
3✔
5026
        }
3✔
5027

5028
        // Fetch our dust limit which is part of the default channel
5029
        // constraints, and log it.
5030
        ourDustLimit := ourContribution.DustLimit
3✔
5031

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

3✔
5034
        // If the channel reserve is not specified, then we calculate an
3✔
5035
        // appropriate amount here.
3✔
5036
        if chanReserve == 0 {
6✔
5037
                chanReserve = f.cfg.RequiredRemoteChanReserve(
3✔
5038
                        capacity, ourDustLimit,
3✔
5039
                )
3✔
5040
        }
3✔
5041

5042
        // If a pending channel map for this peer isn't already created, then
5043
        // we create one, ultimately allowing us to track this pending
5044
        // reservation within the target peer.
5045
        peerIDKey := newSerializedKey(peerKey)
3✔
5046
        f.resMtx.Lock()
3✔
5047
        if _, ok := f.activeReservations[peerIDKey]; !ok {
6✔
5048
                f.activeReservations[peerIDKey] = make(pendingChannels)
3✔
5049
        }
3✔
5050

5051
        resCtx := &reservationWithCtx{
3✔
5052
                chanAmt:           capacity,
3✔
5053
                forwardingPolicy:  *forwardingPolicy,
3✔
5054
                remoteCsvDelay:    remoteCsvDelay,
3✔
5055
                remoteMinHtlc:     minHtlcIn,
3✔
5056
                remoteMaxValue:    maxValue,
3✔
5057
                remoteMaxHtlcs:    maxHtlcs,
3✔
5058
                remoteChanReserve: chanReserve,
3✔
5059
                maxLocalCsv:       maxCSV,
3✔
5060
                channelType:       chanType,
3✔
5061
                reservation:       reservation,
3✔
5062
                peer:              msg.Peer,
3✔
5063
                updates:           msg.Updates,
3✔
5064
                err:               msg.Err,
3✔
5065
        }
3✔
5066
        f.activeReservations[peerIDKey][chanID] = resCtx
3✔
5067
        f.resMtx.Unlock()
3✔
5068

3✔
5069
        // Update the timestamp once the InitFundingMsg has been handled.
3✔
5070
        defer resCtx.updateTimestamp()
3✔
5071

3✔
5072
        // Check the sanity of the selected channel constraints.
3✔
5073
        bounds := &channeldb.ChannelStateBounds{
3✔
5074
                ChanReserve:      chanReserve,
3✔
5075
                MaxPendingAmount: maxValue,
3✔
5076
                MinHTLC:          minHtlcIn,
3✔
5077
                MaxAcceptedHtlcs: maxHtlcs,
3✔
5078
        }
3✔
5079
        commitParams := &channeldb.CommitmentParams{
3✔
5080
                DustLimit: ourDustLimit,
3✔
5081
                CsvDelay:  remoteCsvDelay,
3✔
5082
        }
3✔
5083
        err = lnwallet.VerifyConstraints(
3✔
5084
                bounds, commitParams, resCtx.maxLocalCsv, capacity,
3✔
5085
        )
3✔
5086
        if err != nil {
3✔
5087
                _, reserveErr := f.cancelReservationCtx(peerKey, chanID, false)
×
5088
                if reserveErr != nil {
×
5089
                        log.Errorf("unable to cancel reservation: %v",
×
5090
                                reserveErr)
×
5091
                }
×
5092

5093
                msg.Err <- err
×
5094
                return
×
5095
        }
5096

5097
        // When opening a script enforced channel lease, include the required
5098
        // expiry TLV record in our proposal.
5099
        var leaseExpiry *lnwire.LeaseExpiry
3✔
5100
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
6✔
5101
                leaseExpiry = new(lnwire.LeaseExpiry)
3✔
5102
                *leaseExpiry = lnwire.LeaseExpiry(reservation.LeaseExpiry())
3✔
5103
        }
3✔
5104

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

3✔
5108
        reservation.SetState(lnwallet.SentOpenChannel)
3✔
5109

3✔
5110
        fundingOpen := lnwire.OpenChannel{
3✔
5111
                ChainHash:             *f.cfg.Wallet.Cfg.NetParams.GenesisHash,
3✔
5112
                PendingChannelID:      chanID,
3✔
5113
                FundingAmount:         capacity,
3✔
5114
                PushAmount:            msg.PushAmt,
3✔
5115
                DustLimit:             ourDustLimit,
3✔
5116
                MaxValueInFlight:      maxValue,
3✔
5117
                ChannelReserve:        chanReserve,
3✔
5118
                HtlcMinimum:           minHtlcIn,
3✔
5119
                FeePerKiloWeight:      uint32(commitFeePerKw),
3✔
5120
                CsvDelay:              remoteCsvDelay,
3✔
5121
                MaxAcceptedHTLCs:      maxHtlcs,
3✔
5122
                FundingKey:            ourContribution.MultiSigKey.PubKey,
3✔
5123
                RevocationPoint:       ourContribution.RevocationBasePoint.PubKey,
3✔
5124
                PaymentPoint:          ourContribution.PaymentBasePoint.PubKey,
3✔
5125
                HtlcPoint:             ourContribution.HtlcBasePoint.PubKey,
3✔
5126
                DelayedPaymentPoint:   ourContribution.DelayBasePoint.PubKey,
3✔
5127
                FirstCommitmentPoint:  ourContribution.FirstCommitmentPoint,
3✔
5128
                ChannelFlags:          channelFlags,
3✔
5129
                UpfrontShutdownScript: shutdown,
3✔
5130
                ChannelType:           chanType,
3✔
5131
                LeaseExpiry:           leaseExpiry,
3✔
5132
        }
3✔
5133

3✔
5134
        if commitType.IsTaproot() {
6✔
5135
                fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
3✔
5136
                        ourContribution.LocalNonce.PubNonce,
3✔
5137
                )
3✔
5138
        }
3✔
5139

5140
        if err := msg.Peer.SendMessage(true, &fundingOpen); err != nil {
3✔
5141
                e := fmt.Errorf("unable to send funding request message: %w",
×
5142
                        err)
×
5143
                log.Errorf(e.Error())
×
5144

×
5145
                // Since we were unable to send the initial message to the peer
×
5146
                // and start the funding flow, we'll cancel this reservation.
×
5147
                _, err := f.cancelReservationCtx(peerKey, chanID, false)
×
5148
                if err != nil {
×
5149
                        log.Errorf("unable to cancel reservation: %v", err)
×
5150
                }
×
5151

5152
                msg.Err <- e
×
5153
                return
×
5154
        }
5155
}
5156

5157
// handleWarningMsg processes the warning which was received from remote peer.
5158
func (f *Manager) handleWarningMsg(peer lnpeer.Peer, msg *lnwire.Warning) {
×
5159
        log.Warnf("received warning message from peer %x: %v",
×
5160
                peer.IdentityKey().SerializeCompressed(), msg.Warning())
×
5161
}
×
5162

5163
// handleErrorMsg processes the error which was received from remote peer,
5164
// depending on the type of error we should do different clean up steps and
5165
// inform the user about it.
5166
func (f *Manager) handleErrorMsg(peer lnpeer.Peer, msg *lnwire.Error) {
3✔
5167
        chanID := msg.ChanID
3✔
5168
        peerKey := peer.IdentityKey()
3✔
5169

3✔
5170
        // First, we'll attempt to retrieve and cancel the funding workflow
3✔
5171
        // that this error was tied to. If we're unable to do so, then we'll
3✔
5172
        // exit early as this was an unwarranted error.
3✔
5173
        resCtx, err := f.cancelReservationCtx(peerKey, chanID, true)
3✔
5174
        if err != nil {
3✔
5175
                log.Warnf("Received error for non-existent funding "+
×
5176
                        "flow: %v (%v)", err, msg.Error())
×
5177
                return
×
5178
        }
×
5179

5180
        // If we did indeed find the funding workflow, then we'll return the
5181
        // error back to the caller (if any), and cancel the workflow itself.
5182
        fundingErr := fmt.Errorf("received funding error from %x: %v",
3✔
5183
                peerKey.SerializeCompressed(), msg.Error(),
3✔
5184
        )
3✔
5185
        log.Errorf(fundingErr.Error())
3✔
5186

3✔
5187
        // If this was a PSBT funding flow, the remote likely timed out because
3✔
5188
        // we waited too long. Return a nice error message to the user in that
3✔
5189
        // case so the user knows what's the problem.
3✔
5190
        if resCtx.reservation.IsPsbt() {
6✔
5191
                fundingErr = fmt.Errorf("%w: %v", chanfunding.ErrRemoteCanceled,
3✔
5192
                        fundingErr)
3✔
5193
        }
3✔
5194

5195
        resCtx.err <- fundingErr
3✔
5196
}
5197

5198
// pruneZombieReservations loops through all pending reservations and fails the
5199
// funding flow for any reservations that have not been updated since the
5200
// ReservationTimeout and are not locked waiting for the funding transaction.
5201
func (f *Manager) pruneZombieReservations() {
3✔
5202
        zombieReservations := make(pendingChannels)
3✔
5203

3✔
5204
        f.resMtx.RLock()
3✔
5205
        for _, pendingReservations := range f.activeReservations {
6✔
5206
                for pendingChanID, resCtx := range pendingReservations {
6✔
5207
                        if resCtx.isLocked() {
3✔
5208
                                continue
×
5209
                        }
5210

5211
                        // We don't want to expire PSBT funding reservations.
5212
                        // These reservations are always initiated by us and the
5213
                        // remote peer is likely going to cancel them after some
5214
                        // idle time anyway. So no need for us to also prune
5215
                        // them.
5216
                        sinceLastUpdate := time.Since(resCtx.lastUpdated)
3✔
5217
                        isExpired := sinceLastUpdate > f.cfg.ReservationTimeout
3✔
5218
                        if !resCtx.reservation.IsPsbt() && isExpired {
6✔
5219
                                zombieReservations[pendingChanID] = resCtx
3✔
5220
                        }
3✔
5221
                }
5222
        }
5223
        f.resMtx.RUnlock()
3✔
5224

3✔
5225
        for pendingChanID, resCtx := range zombieReservations {
6✔
5226
                err := fmt.Errorf("reservation timed out waiting for peer "+
3✔
5227
                        "(peer_id:%x, chan_id:%x)",
3✔
5228
                        resCtx.peer.IdentityKey().SerializeCompressed(),
3✔
5229
                        pendingChanID[:])
3✔
5230
                log.Warnf(err.Error())
3✔
5231

3✔
5232
                chanID := lnwire.NewChanIDFromOutPoint(
3✔
5233
                        *resCtx.reservation.FundingOutpoint(),
3✔
5234
                )
3✔
5235

3✔
5236
                // Create channel identifier and set the channel ID.
3✔
5237
                cid := newChanIdentifier(pendingChanID)
3✔
5238
                cid.setChanID(chanID)
3✔
5239

3✔
5240
                f.failFundingFlow(resCtx.peer, cid, err)
3✔
5241
        }
3✔
5242
}
5243

5244
// cancelReservationCtx does all needed work in order to securely cancel the
5245
// reservation.
5246
func (f *Manager) cancelReservationCtx(peerKey *btcec.PublicKey,
5247
        pendingChanID PendingChanID,
5248
        byRemote bool) (*reservationWithCtx, error) {
3✔
5249

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

3✔
5253
        peerIDKey := newSerializedKey(peerKey)
3✔
5254
        f.resMtx.Lock()
3✔
5255
        defer f.resMtx.Unlock()
3✔
5256

3✔
5257
        nodeReservations, ok := f.activeReservations[peerIDKey]
3✔
5258
        if !ok {
6✔
5259
                // No reservations for this node.
3✔
5260
                return nil, errors.Errorf("no active reservations for peer(%x)",
3✔
5261
                        peerIDKey[:])
3✔
5262
        }
3✔
5263

5264
        ctx, ok := nodeReservations[pendingChanID]
3✔
5265
        if !ok {
3✔
5266
                return nil, errors.Errorf("unknown channel (id: %x) for "+
×
5267
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
×
5268
        }
×
5269

5270
        // If the reservation was a PSBT funding flow and it was canceled by the
5271
        // remote peer, then we need to thread through a different error message
5272
        // to the subroutine that's waiting for the user input so it can return
5273
        // a nice error message to the user.
5274
        if ctx.reservation.IsPsbt() && byRemote {
6✔
5275
                ctx.reservation.RemoteCanceled()
3✔
5276
        }
3✔
5277

5278
        if err := ctx.reservation.Cancel(); err != nil {
3✔
5279
                return nil, errors.Errorf("unable to cancel reservation: %v",
×
5280
                        err)
×
5281
        }
×
5282

5283
        delete(nodeReservations, pendingChanID)
3✔
5284

3✔
5285
        // If this was the last active reservation for this peer, delete the
3✔
5286
        // peer's entry altogether.
3✔
5287
        if len(nodeReservations) == 0 {
6✔
5288
                delete(f.activeReservations, peerIDKey)
3✔
5289
        }
3✔
5290
        return ctx, nil
3✔
5291
}
5292

5293
// deleteReservationCtx deletes the reservation uniquely identified by the
5294
// target public key of the peer, and the specified pending channel ID.
5295
func (f *Manager) deleteReservationCtx(peerKey *btcec.PublicKey,
5296
        pendingChanID PendingChanID) {
3✔
5297

3✔
5298
        peerIDKey := newSerializedKey(peerKey)
3✔
5299
        f.resMtx.Lock()
3✔
5300
        defer f.resMtx.Unlock()
3✔
5301

3✔
5302
        nodeReservations, ok := f.activeReservations[peerIDKey]
3✔
5303
        if !ok {
3✔
5304
                // No reservations for this node.
×
5305
                return
×
5306
        }
×
5307
        delete(nodeReservations, pendingChanID)
3✔
5308

3✔
5309
        // If this was the last active reservation for this peer, delete the
3✔
5310
        // peer's entry altogether.
3✔
5311
        if len(nodeReservations) == 0 {
6✔
5312
                delete(f.activeReservations, peerIDKey)
3✔
5313
        }
3✔
5314
}
5315

5316
// getReservationCtx returns the reservation context for a particular pending
5317
// channel ID for a target peer.
5318
func (f *Manager) getReservationCtx(peerKey *btcec.PublicKey,
5319
        pendingChanID PendingChanID) (*reservationWithCtx, error) {
3✔
5320

3✔
5321
        peerIDKey := newSerializedKey(peerKey)
3✔
5322
        f.resMtx.RLock()
3✔
5323
        resCtx, ok := f.activeReservations[peerIDKey][pendingChanID]
3✔
5324
        f.resMtx.RUnlock()
3✔
5325

3✔
5326
        if !ok {
6✔
5327
                return nil, errors.Errorf("unknown channel (id: %x) for "+
3✔
5328
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
3✔
5329
        }
3✔
5330

5331
        return resCtx, nil
3✔
5332
}
5333

5334
// IsPendingChannel returns a boolean indicating whether the channel identified
5335
// by the pendingChanID and given peer is pending, meaning it is in the process
5336
// of being funded. After the funding transaction has been confirmed, the
5337
// channel will receive a new, permanent channel ID, and will no longer be
5338
// considered pending.
5339
func (f *Manager) IsPendingChannel(pendingChanID PendingChanID,
5340
        peer lnpeer.Peer) bool {
3✔
5341

3✔
5342
        peerIDKey := newSerializedKey(peer.IdentityKey())
3✔
5343
        f.resMtx.RLock()
3✔
5344
        _, ok := f.activeReservations[peerIDKey][pendingChanID]
3✔
5345
        f.resMtx.RUnlock()
3✔
5346

3✔
5347
        return ok
3✔
5348
}
3✔
5349

5350
func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
3✔
5351
        var tmp btcec.JacobianPoint
3✔
5352
        pub.AsJacobian(&tmp)
3✔
5353
        tmp.ToAffine()
3✔
5354
        return btcec.NewPublicKey(&tmp.X, &tmp.Y)
3✔
5355
}
3✔
5356

5357
// defaultForwardingPolicy returns the default forwarding policy based on the
5358
// default routing policy and our local channel constraints.
5359
func (f *Manager) defaultForwardingPolicy(
5360
        bounds channeldb.ChannelStateBounds) *models.ForwardingPolicy {
3✔
5361

3✔
5362
        return &models.ForwardingPolicy{
3✔
5363
                MinHTLCOut:    bounds.MinHTLC,
3✔
5364
                MaxHTLC:       bounds.MaxPendingAmount,
3✔
5365
                BaseFee:       f.cfg.DefaultRoutingPolicy.BaseFee,
3✔
5366
                FeeRate:       f.cfg.DefaultRoutingPolicy.FeeRate,
3✔
5367
                TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
3✔
5368
        }
3✔
5369
}
3✔
5370

5371
// saveInitialForwardingPolicy saves the forwarding policy for the provided
5372
// chanPoint in the channelOpeningStateBucket.
5373
func (f *Manager) saveInitialForwardingPolicy(chanID lnwire.ChannelID,
5374
        forwardingPolicy *models.ForwardingPolicy) error {
3✔
5375

3✔
5376
        return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
3✔
5377
                chanID, forwardingPolicy,
3✔
5378
        )
3✔
5379
}
3✔
5380

5381
// getInitialForwardingPolicy fetches the initial forwarding policy for a given
5382
// channel id from the database which will be applied during the channel
5383
// announcement phase.
5384
func (f *Manager) getInitialForwardingPolicy(
5385
        chanID lnwire.ChannelID) (*models.ForwardingPolicy, error) {
3✔
5386

3✔
5387
        return f.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
3✔
5388
}
3✔
5389

5390
// deleteInitialForwardingPolicy removes channel fees for this chanID from
5391
// the database.
5392
func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
3✔
5393
        return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
3✔
5394
}
3✔
5395

5396
// saveChannelOpeningState saves the channelOpeningState for the provided
5397
// chanPoint to the channelOpeningStateBucket.
5398
func (f *Manager) saveChannelOpeningState(chanPoint *wire.OutPoint,
5399
        state channelOpeningState, shortChanID *lnwire.ShortChannelID) error {
3✔
5400

3✔
5401
        var outpointBytes bytes.Buffer
3✔
5402
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
3✔
5403
                return err
×
5404
        }
×
5405

5406
        // Save state and the uint64 representation of the shortChanID
5407
        // for later use.
5408
        scratch := make([]byte, 10)
3✔
5409
        byteOrder.PutUint16(scratch[:2], uint16(state))
3✔
5410
        byteOrder.PutUint64(scratch[2:], shortChanID.ToUint64())
3✔
5411

3✔
5412
        return f.cfg.ChannelDB.SaveChannelOpeningState(
3✔
5413
                outpointBytes.Bytes(), scratch,
3✔
5414
        )
3✔
5415
}
5416

5417
// getChannelOpeningState fetches the channelOpeningState for the provided
5418
// chanPoint from the database, or returns ErrChannelNotFound if the channel
5419
// is not found.
5420
func (f *Manager) getChannelOpeningState(chanPoint *wire.OutPoint) (
5421
        channelOpeningState, *lnwire.ShortChannelID, error) {
3✔
5422

3✔
5423
        var outpointBytes bytes.Buffer
3✔
5424
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
3✔
5425
                return 0, nil, err
×
5426
        }
×
5427

5428
        value, err := f.cfg.ChannelDB.GetChannelOpeningState(
3✔
5429
                outpointBytes.Bytes(),
3✔
5430
        )
3✔
5431
        if err != nil {
6✔
5432
                return 0, nil, err
3✔
5433
        }
3✔
5434

5435
        state := channelOpeningState(byteOrder.Uint16(value[:2]))
3✔
5436
        shortChanID := lnwire.NewShortChanIDFromInt(byteOrder.Uint64(value[2:]))
3✔
5437
        return state, &shortChanID, nil
3✔
5438
}
5439

5440
// deleteChannelOpeningState removes any state for chanPoint from the database.
5441
func (f *Manager) deleteChannelOpeningState(chanPoint *wire.OutPoint) error {
3✔
5442
        var outpointBytes bytes.Buffer
3✔
5443
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
3✔
5444
                return err
×
5445
        }
×
5446

5447
        return f.cfg.ChannelDB.DeleteChannelOpeningState(
3✔
5448
                outpointBytes.Bytes(),
3✔
5449
        )
3✔
5450
}
5451

5452
// selectShutdownScript selects the shutdown script we should send to the peer.
5453
// If we can use taproot, then we prefer that, otherwise we'll use a p2wkh
5454
// script.
5455
func (f *Manager) selectShutdownScript(taprootOK bool,
5456
) (lnwire.DeliveryAddress, error) {
×
5457

×
5458
        addrType := lnwallet.WitnessPubKey
×
5459
        if taprootOK {
×
5460
                addrType = lnwallet.TaprootPubkey
×
5461
        }
×
5462

5463
        addr, err := f.cfg.Wallet.NewAddress(
×
5464
                addrType, false, lnwallet.DefaultAccountName,
×
5465
        )
×
5466
        if err != nil {
×
5467
                return nil, err
×
5468
        }
×
5469

5470
        return txscript.PayToAddrScript(addr)
×
5471
}
5472

5473
// waitForPeerOnline blocks until the peer specified by peerPubkey comes online
5474
// and then returns the online peer.
5475
func (f *Manager) waitForPeerOnline(peerPubkey *btcec.PublicKey) (lnpeer.Peer,
5476
        error) {
3✔
5477

3✔
5478
        peerChan := make(chan lnpeer.Peer, 1)
3✔
5479

3✔
5480
        var peerKey [33]byte
3✔
5481
        copy(peerKey[:], peerPubkey.SerializeCompressed())
3✔
5482

3✔
5483
        f.cfg.NotifyWhenOnline(peerKey, peerChan)
3✔
5484

3✔
5485
        var peer lnpeer.Peer
3✔
5486
        select {
3✔
5487
        case peer = <-peerChan:
3✔
UNCOV
5488
        case <-f.quit:
×
UNCOV
5489
                return peer, ErrFundingManagerShuttingDown
×
5490
        }
5491
        return peer, nil
3✔
5492
}
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