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

lightningnetwork / lnd / 14271926334

04 Apr 2025 06:34PM UTC coverage: 58.598% (-0.04%) from 58.637%
14271926334

Pull #9677

github

web-flow
Merge 0e4bc790e into 6a3845b79
Pull Request #9677: Expose confirmation count for pending 'channel open' transactions

112 of 147 new or added lines in 3 files covered. (76.19%)

101 existing lines in 19 files now uncovered.

97159 of 165805 relevant lines covered (58.6%)

1.82 hits per line

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

71.23
/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✔
1207
                        return fmt.Errorf("failed to check if channel_ready "+
×
1208
                                "was received: %v", err)
×
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
        errorChan := make(chan error, 1)
3✔
3016

3✔
3017
        // If the channel is not a zero-conf channel, we add the SCID to the
3✔
3018
        // database once the channel is confirmed but not fully opened. This
3✔
3019
        // allows us to calculate the number of confirmations before the channel
3✔
3020
        // is fully opened.
3✔
3021
        if !ch.IsZeroConf() {
6✔
3022
                f.wg.Add(1)
3✔
3023
                go f.handleChannelConfirmation(ch, cancelChan, errorChan)
3✔
3024
        }
3✔
3025

3026
        f.wg.Add(1)
3✔
3027
        go f.waitForFundingConfirmation(ch, cancelChan, confChan)
3✔
3028

3✔
3029
        // If we are not the initiator, we have no money at stake and will
3✔
3030
        // timeout waiting for the funding transaction to confirm after a
3✔
3031
        // while.
3✔
3032
        if !ch.IsInitiator && !ch.IsZeroConf() {
6✔
3033
                f.wg.Add(1)
3✔
3034
                go f.waitForTimeout(ch, cancelChan, timeoutChan)
3✔
3035
        }
3✔
3036
        defer close(cancelChan)
3✔
3037

3✔
3038
        for {
6✔
3039
                select {
3✔
3040
                case err := <-errorChan:
3✔
3041
                        if err != nil {
3✔
NEW
3042
                                return nil, fmt.Errorf("waiting for funding"+
×
NEW
3043
                                        "confirmation failed: %v", err)
×
NEW
3044
                        }
×
3045

3046
                        // If the channel confirmation is handled successfully,
3047
                        // set errorChan to nil to disable this case in the
3048
                        // select statement for subsequent channel messages.
3049
                        errorChan = nil
3✔
3050

3051
                case err := <-timeoutChan:
3✔
3052
                        if err != nil {
3✔
NEW
3053
                                return nil, err
×
NEW
3054
                        }
×
3055

3056
                        return nil, ErrConfirmationTimeout
3✔
3057

3058
                case <-f.quit:
3✔
3059
                        // The fundingManager is shutting down, and will resume
3✔
3060
                        // wait on startup.
3✔
3061
                        return nil, ErrFundingManagerShuttingDown
3✔
3062

3063
                case confirmedChannel, ok := <-confChan:
3✔
3064
                        if !ok {
3✔
NEW
3065
                                return nil, fmt.Errorf("waiting for funding" +
×
NEW
3066
                                        "confirmation failed")
×
NEW
3067
                        }
×
3068

3069
                        return confirmedChannel, nil
3✔
3070
                }
3071
        }
3072
}
3073

3074
// makeFundingScript re-creates the funding script for the funding transaction
3075
// of the target channel.
3076
func makeFundingScript(channel *channeldb.OpenChannel) ([]byte, error) {
3✔
3077
        localKey := channel.LocalChanCfg.MultiSigKey.PubKey
3✔
3078
        remoteKey := channel.RemoteChanCfg.MultiSigKey.PubKey
3✔
3079

3✔
3080
        if channel.ChanType.IsTaproot() {
6✔
3081
                pkScript, _, err := input.GenTaprootFundingScript(
3✔
3082
                        localKey, remoteKey, int64(channel.Capacity),
3✔
3083
                        channel.TapscriptRoot,
3✔
3084
                )
3✔
3085
                if err != nil {
3✔
3086
                        return nil, err
×
3087
                }
×
3088

3089
                return pkScript, nil
3✔
3090
        }
3091

3092
        multiSigScript, err := input.GenMultiSigScript(
3✔
3093
                localKey.SerializeCompressed(),
3✔
3094
                remoteKey.SerializeCompressed(),
3✔
3095
        )
3✔
3096
        if err != nil {
3✔
3097
                return nil, err
×
3098
        }
×
3099

3100
        return input.WitnessScriptHash(multiSigScript)
3✔
3101
}
3102

3103
// handleChannelConfirmation manages the confirmation process of a channel's
3104
// funding transaction. It registers for confirmation notifications, waits for
3105
// the funding transaction to be confirmed, updates the channel state, and
3106
// handles shutdown signals or cancellations.
3107
//
3108
// NOTE: This MUST be run as a goroutine.
3109
func (f *Manager) handleChannelConfirmation(openChannel *channeldb.OpenChannel,
3110
        cancelChan <-chan struct{}, errorChan chan<- error) {
3✔
3111

3✔
3112
        defer f.wg.Done()
3✔
3113
        defer close(errorChan)
3✔
3114

3✔
3115
        // Generate the funding output script needed to detect the transaction
3✔
3116
        // confirmation
3✔
3117
        chanFundingScript, err := makeFundingScript(openChannel)
3✔
3118
        if err != nil {
3✔
NEW
3119
                errorChan <- fmt.Errorf("unable to create funding script for "+
×
NEW
3120
                        "ChannelPoint(%v): %v", openChannel.FundingOutpoint,
×
NEW
3121
                        err)
×
NEW
3122

×
NEW
3123
                return
×
NEW
3124
        }
×
3125

3126
        // Register for transaction confirmation notifications
3127
        chanConfNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
3✔
3128
                &openChannel.FundingOutpoint.Hash, chanFundingScript, 1,
3✔
3129
                openChannel.BroadcastHeight(),
3✔
3130
        )
3✔
3131
        if err != nil {
3✔
NEW
3132
                errorChan <- fmt.Errorf("unable to register for confirmation "+
×
NEW
3133
                        "of ChannelPoint(%v): %v", openChannel.FundingOutpoint,
×
NEW
3134
                        err)
×
NEW
3135

×
NEW
3136
                return
×
NEW
3137
        }
×
3138

3139
        var confDetails *chainntnfs.TxConfirmation
3✔
3140
        var ok bool
3✔
3141

3✔
3142
        // Wait for either the funding confirmation, cancellation, or manager
3✔
3143
        // shutdown
3✔
3144
        select {
3✔
3145
        case confDetails, ok = <-chanConfNtfn.Confirmed:
3✔
3146
                // fallthrough
3147

3148
        case <-cancelChan:
3✔
3149
                // canceled waiting for funding confirmation
3✔
3150
                return
3✔
3151

3152
        case <-f.quit:
3✔
3153
                // fundingManager is shutting down
3✔
3154
                return
3✔
3155
        }
3156

3157
        if !ok {
3✔
NEW
3158
                errorChan <- fmt.Errorf("ChainNotifier shutting down, can't "+
×
NEW
3159
                        "complete funding flow for ChannelPoint(%v)",
×
NEW
3160
                        openChannel.FundingOutpoint)
×
NEW
3161

×
NEW
3162
                return
×
NEW
3163
        }
×
3164

3165
        fundingPoint := openChannel.FundingOutpoint
3✔
3166
        log.Infof("ChannelPoint(%v) confirmed at block %d",
3✔
3167
                fundingPoint, confDetails.BlockHeight)
3✔
3168

3✔
3169
        // Construct short channel ID from confirmation details
3✔
3170
        shortChanID := lnwire.ShortChannelID{
3✔
3171
                BlockHeight: confDetails.BlockHeight,
3✔
3172
                TxIndex:     confDetails.TxIndex,
3✔
3173
                TxPosition:  uint16(fundingPoint.Index),
3✔
3174
        }
3✔
3175

3✔
3176
        // Update the channel's state in the database to mark it as confirmed.
3✔
3177
        err = openChannel.MarkConfirmedScid(shortChanID)
3✔
3178
        if err != nil {
3✔
NEW
3179
                errorChan <- fmt.Errorf("failed to update confirmed state for "+
×
NEW
3180
                        "ChannelPoint(%v): %v", fundingPoint, err)
×
NEW
3181
        }
×
3182
}
3183

3184
// waitForFundingConfirmation handles the final stages of the channel funding
3185
// process once the funding transaction has been broadcast. The primary
3186
// function of waitForFundingConfirmation is to wait for blockchain
3187
// confirmation, and then to notify the other systems that must be notified
3188
// when a channel has become active for lightning transactions.
3189
// The wait can be canceled by closing the cancelChan. In case of success,
3190
// a *lnwire.ShortChannelID will be passed to confChan.
3191
//
3192
// NOTE: This MUST be run as a goroutine.
3193
func (f *Manager) waitForFundingConfirmation(
3194
        completeChan *channeldb.OpenChannel, cancelChan <-chan struct{},
3195
        confChan chan<- *confirmedChannel) {
3✔
3196

3✔
3197
        defer f.wg.Done()
3✔
3198
        defer close(confChan)
3✔
3199

3✔
3200
        // Register with the ChainNotifier for a notification once the funding
3✔
3201
        // transaction reaches `numConfs` confirmations.
3✔
3202
        txid := completeChan.FundingOutpoint.Hash
3✔
3203
        fundingScript, err := makeFundingScript(completeChan)
3✔
3204
        if err != nil {
3✔
3205
                log.Errorf("unable to create funding script for "+
×
3206
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3207
                        err)
×
3208
                return
×
3209
        }
×
3210
        numConfs := uint32(completeChan.NumConfsRequired)
3✔
3211

3✔
3212
        // If the underlying channel is a zero-conf channel, we'll set numConfs
3✔
3213
        // to 6, since it will be zero here.
3✔
3214
        if completeChan.IsZeroConf() {
6✔
3215
                numConfs = 6
3✔
3216
        }
3✔
3217

3218
        confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
3✔
3219
                &txid, fundingScript, numConfs,
3✔
3220
                completeChan.BroadcastHeight(),
3✔
3221
        )
3✔
3222
        if err != nil {
3✔
3223
                log.Errorf("Unable to register for confirmation of "+
×
3224
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3225
                        err)
×
3226
                return
×
3227
        }
×
3228

3229
        log.Infof("Waiting for funding tx (%v) to reach %v confirmations",
3✔
3230
                txid, numConfs)
3✔
3231

3✔
3232
        var confDetails *chainntnfs.TxConfirmation
3✔
3233
        var ok bool
3✔
3234

3✔
3235
        // Wait until the specified number of confirmations has been reached,
3✔
3236
        // we get a cancel signal, or the wallet signals a shutdown.
3✔
3237
        select {
3✔
3238
        case confDetails, ok = <-confNtfn.Confirmed:
3✔
3239
                // fallthrough
3240

3241
        case <-cancelChan:
3✔
3242
                log.Warnf("canceled waiting for funding confirmation, "+
3✔
3243
                        "stopping funding flow for ChannelPoint(%v)",
3✔
3244
                        completeChan.FundingOutpoint)
3✔
3245
                return
3✔
3246

3247
        case <-f.quit:
3✔
3248
                log.Warnf("fundingManager shutting down, stopping funding "+
3✔
3249
                        "flow for ChannelPoint(%v)",
3✔
3250
                        completeChan.FundingOutpoint)
3✔
3251
                return
3✔
3252
        }
3253

3254
        if !ok {
3✔
3255
                log.Warnf("ChainNotifier shutting down, cannot complete "+
×
3256
                        "funding flow for ChannelPoint(%v)",
×
3257
                        completeChan.FundingOutpoint)
×
3258
                return
×
3259
        }
×
3260

3261
        fundingPoint := completeChan.FundingOutpoint
3✔
3262
        log.Infof("ChannelPoint(%v) is now active: ChannelID(%v)",
3✔
3263
                fundingPoint, lnwire.NewChanIDFromOutPoint(fundingPoint))
3✔
3264

3✔
3265
        // With the block height and the transaction index known, we can
3✔
3266
        // construct the compact chanID which is used on the network to unique
3✔
3267
        // identify channels.
3✔
3268
        shortChanID := lnwire.ShortChannelID{
3✔
3269
                BlockHeight: confDetails.BlockHeight,
3✔
3270
                TxIndex:     confDetails.TxIndex,
3✔
3271
                TxPosition:  uint16(fundingPoint.Index),
3✔
3272
        }
3✔
3273

3✔
3274
        select {
3✔
3275
        case confChan <- &confirmedChannel{
3276
                shortChanID: shortChanID,
3277
                fundingTx:   confDetails.Tx,
3278
        }:
3✔
3279
        case <-f.quit:
×
3280
                return
×
3281
        }
3282
}
3283

3284
// waitForTimeout will close the timeout channel if MaxWaitNumBlocksFundingConf
3285
// has passed from the broadcast height of the given channel. In case of error,
3286
// the error is sent on timeoutChan. The wait can be canceled by closing the
3287
// cancelChan.
3288
//
3289
// NOTE: timeoutChan MUST be buffered.
3290
// NOTE: This MUST be run as a goroutine.
3291
func (f *Manager) waitForTimeout(completeChan *channeldb.OpenChannel,
3292
        cancelChan <-chan struct{}, timeoutChan chan<- error) {
3✔
3293

3✔
3294
        defer f.wg.Done()
3✔
3295

3✔
3296
        epochClient, err := f.cfg.Notifier.RegisterBlockEpochNtfn(nil)
3✔
3297
        if err != nil {
3✔
3298
                timeoutChan <- fmt.Errorf("unable to register for epoch "+
×
3299
                        "notification: %v", err)
×
3300
                return
×
3301
        }
×
3302

3303
        defer epochClient.Cancel()
3✔
3304

3✔
3305
        // The value of waitBlocksForFundingConf is adjusted in a development
3✔
3306
        // environment to enhance test capabilities. Otherwise, it is set to
3✔
3307
        // DefaultMaxWaitNumBlocksFundingConf.
3✔
3308
        waitBlocksForFundingConf := uint32(
3✔
3309
                lncfg.DefaultMaxWaitNumBlocksFundingConf,
3✔
3310
        )
3✔
3311

3✔
3312
        if lncfg.IsDevBuild() {
6✔
3313
                waitBlocksForFundingConf =
3✔
3314
                        f.cfg.Dev.MaxWaitNumBlocksFundingConf
3✔
3315
        }
3✔
3316

3317
        // On block maxHeight we will cancel the funding confirmation wait.
3318
        broadcastHeight := completeChan.BroadcastHeight()
3✔
3319
        maxHeight := broadcastHeight + waitBlocksForFundingConf
3✔
3320
        for {
6✔
3321
                select {
3✔
3322
                case epoch, ok := <-epochClient.Epochs:
3✔
3323
                        if !ok {
3✔
3324
                                timeoutChan <- fmt.Errorf("epoch client " +
×
3325
                                        "shutting down")
×
3326
                                return
×
3327
                        }
×
3328

3329
                        // Close the timeout channel and exit if the block is
3330
                        // above the max height.
3331
                        if uint32(epoch.Height) >= maxHeight {
6✔
3332
                                log.Warnf("Waited for %v blocks without "+
3✔
3333
                                        "seeing funding transaction confirmed,"+
3✔
3334
                                        " cancelling.",
3✔
3335
                                        waitBlocksForFundingConf)
3✔
3336

3✔
3337
                                // Notify the caller of the timeout.
3✔
3338
                                close(timeoutChan)
3✔
3339
                                return
3✔
3340
                        }
3✔
3341

3342
                        // TODO: If we are the channel initiator implement
3343
                        // a method for recovering the funds from the funding
3344
                        // transaction
3345

3346
                case <-cancelChan:
3✔
3347
                        return
3✔
3348

3349
                case <-f.quit:
3✔
3350
                        // The fundingManager is shutting down, will resume
3✔
3351
                        // waiting for the funding transaction on startup.
3✔
3352
                        return
3✔
3353
                }
3354
        }
3355
}
3356

3357
// makeLabelForTx updates the label for the confirmed funding transaction. If
3358
// we opened the channel, and lnd's wallet published our funding tx (which is
3359
// not the case for some channels) then we update our transaction label with
3360
// our short channel ID, which is known now that our funding transaction has
3361
// confirmed. We do not label transactions we did not publish, because our
3362
// wallet has no knowledge of them.
3363
func (f *Manager) makeLabelForTx(c *channeldb.OpenChannel) {
3✔
3364
        if c.IsInitiator && c.ChanType.HasFundingTx() {
6✔
3365
                shortChanID := c.ShortChanID()
3✔
3366

3✔
3367
                // For zero-conf channels, we'll use the actually-confirmed
3✔
3368
                // short channel id.
3✔
3369
                if c.IsZeroConf() {
6✔
3370
                        shortChanID = c.ZeroConfRealScid()
3✔
3371
                }
3✔
3372

3373
                label := labels.MakeLabel(
3✔
3374
                        labels.LabelTypeChannelOpen, &shortChanID,
3✔
3375
                )
3✔
3376

3✔
3377
                err := f.cfg.UpdateLabel(c.FundingOutpoint.Hash, label)
3✔
3378
                if err != nil {
3✔
3379
                        log.Errorf("unable to update label: %v", err)
×
3380
                }
×
3381
        }
3382
}
3383

3384
// handleFundingConfirmation marks a channel as open in the database, and set
3385
// the channelOpeningState markedOpen. In addition it will report the now
3386
// decided short channel ID to the switch, and close the local discovery signal
3387
// for this channel.
3388
func (f *Manager) handleFundingConfirmation(
3389
        completeChan *channeldb.OpenChannel,
3390
        confChannel *confirmedChannel) error {
3✔
3391

3✔
3392
        fundingPoint := completeChan.FundingOutpoint
3✔
3393
        chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
3✔
3394

3✔
3395
        // TODO(roasbeef): ideally persistent state update for chan above
3✔
3396
        // should be abstracted
3✔
3397

3✔
3398
        // Now that that the channel has been fully confirmed, we'll request
3✔
3399
        // that the wallet fully verify this channel to ensure that it can be
3✔
3400
        // used.
3✔
3401
        err := f.cfg.Wallet.ValidateChannel(completeChan, confChannel.fundingTx)
3✔
3402
        if err != nil {
3✔
3403
                // TODO(roasbeef): delete chan state?
×
3404
                return fmt.Errorf("unable to validate channel: %w", err)
×
3405
        }
×
3406

3407
        // Now that the channel has been validated, we'll persist an alias for
3408
        // this channel if the option-scid-alias feature-bit was negotiated.
3409
        if completeChan.NegotiatedAliasFeature() {
6✔
3410
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
3✔
3411
                if err != nil {
3✔
3412
                        return fmt.Errorf("unable to request alias: %w", err)
×
3413
                }
×
3414

3415
                err = f.cfg.AliasManager.AddLocalAlias(
3✔
3416
                        aliasScid, confChannel.shortChanID, true, false,
3✔
3417
                )
3✔
3418
                if err != nil {
3✔
3419
                        return fmt.Errorf("unable to request alias: %w", err)
×
3420
                }
×
3421
        }
3422

3423
        // The funding transaction now being confirmed, we add this channel to
3424
        // the fundingManager's internal persistent state machine that we use
3425
        // to track the remaining process of the channel opening. This is
3426
        // useful to resume the opening process in case of restarts. We set the
3427
        // opening state before we mark the channel opened in the database,
3428
        // such that we can receover from one of the db writes failing.
3429
        err = f.saveChannelOpeningState(
3✔
3430
                &fundingPoint, markedOpen, &confChannel.shortChanID,
3✔
3431
        )
3✔
3432
        if err != nil {
3✔
3433
                return fmt.Errorf("error setting channel state to "+
×
3434
                        "markedOpen: %v", err)
×
3435
        }
×
3436

3437
        // Now that the channel has been fully confirmed and we successfully
3438
        // saved the opening state, we'll mark it as open within the database.
3439
        err = completeChan.MarkAsOpen(confChannel.shortChanID)
3✔
3440
        if err != nil {
3✔
3441
                return fmt.Errorf("error setting channel pending flag to "+
×
3442
                        "false:        %v", err)
×
3443
        }
×
3444

3445
        // Update the confirmed funding transaction label.
3446
        f.makeLabelForTx(completeChan)
3✔
3447

3✔
3448
        // Inform the ChannelNotifier that the channel has transitioned from
3✔
3449
        // pending open to open.
3✔
3450
        if err := f.cfg.NotifyOpenChannelEvent(
3✔
3451
                completeChan.FundingOutpoint, completeChan.IdentityPub,
3✔
3452
        ); err != nil {
6✔
3453
                log.Errorf("Unable to notify open channel event for "+
3✔
3454
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
3✔
3455
                        err)
3✔
3456
        }
3✔
3457

3458
        // Close the discoverySignal channel, indicating to a separate
3459
        // goroutine that the channel now is marked as open in the database
3460
        // and that it is acceptable to process channel_ready messages
3461
        // from the peer.
3462
        if discoverySignal, ok := f.localDiscoverySignals.Load(chanID); ok {
6✔
3463
                close(discoverySignal)
3✔
3464
        }
3✔
3465

3466
        return nil
3✔
3467
}
3468

3469
// sendChannelReady creates and sends the channelReady message.
3470
// This should be called after the funding transaction has been confirmed,
3471
// and the channelState is 'markedOpen'.
3472
func (f *Manager) sendChannelReady(completeChan *channeldb.OpenChannel,
3473
        channel *lnwallet.LightningChannel) error {
3✔
3474

3✔
3475
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
3✔
3476

3✔
3477
        var peerKey [33]byte
3✔
3478
        copy(peerKey[:], completeChan.IdentityPub.SerializeCompressed())
3✔
3479

3✔
3480
        // Next, we'll send over the channel_ready message which marks that we
3✔
3481
        // consider the channel open by presenting the remote party with our
3✔
3482
        // next revocation key. Without the revocation key, the remote party
3✔
3483
        // will be unable to propose state transitions.
3✔
3484
        nextRevocation, err := channel.NextRevocationKey()
3✔
3485
        if err != nil {
3✔
3486
                return fmt.Errorf("unable to create next revocation: %w", err)
×
3487
        }
×
3488
        channelReadyMsg := lnwire.NewChannelReady(chanID, nextRevocation)
3✔
3489

3✔
3490
        // If this is a taproot channel, then we also need to send along our
3✔
3491
        // set of musig2 nonces as well.
3✔
3492
        if completeChan.ChanType.IsTaproot() {
6✔
3493
                log.Infof("ChanID(%v): generating musig2 nonces...",
3✔
3494
                        chanID)
3✔
3495

3✔
3496
                f.nonceMtx.Lock()
3✔
3497
                localNonce, ok := f.pendingMusigNonces[chanID]
3✔
3498
                if !ok {
6✔
3499
                        // If we don't have any nonces generated yet for this
3✔
3500
                        // first state, then we'll generate them now and stow
3✔
3501
                        // them away.  When we receive the funding locked
3✔
3502
                        // message, we'll then pass along this same set of
3✔
3503
                        // nonces.
3✔
3504
                        newNonce, err := channel.GenMusigNonces()
3✔
3505
                        if err != nil {
3✔
3506
                                f.nonceMtx.Unlock()
×
3507
                                return err
×
3508
                        }
×
3509

3510
                        // Now that we've generated the nonce for this channel,
3511
                        // we'll store it in the set of pending nonces.
3512
                        localNonce = newNonce
3✔
3513
                        f.pendingMusigNonces[chanID] = localNonce
3✔
3514
                }
3515
                f.nonceMtx.Unlock()
3✔
3516

3✔
3517
                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
3✔
3518
                        localNonce.PubNonce,
3✔
3519
                )
3✔
3520
        }
3521

3522
        // If the channel negotiated the option-scid-alias feature bit, we'll
3523
        // send a TLV segment that includes an alias the peer can use in their
3524
        // invoice hop hints. We'll send the first alias we find for the
3525
        // channel since it does not matter which alias we send. We'll error
3526
        // out in the odd case that no aliases are found.
3527
        if completeChan.NegotiatedAliasFeature() {
6✔
3528
                aliases := f.cfg.AliasManager.GetAliases(
3✔
3529
                        completeChan.ShortChanID(),
3✔
3530
                )
3✔
3531
                if len(aliases) == 0 {
3✔
3532
                        return fmt.Errorf("no aliases found")
×
3533
                }
×
3534

3535
                // We can use a pointer to aliases since GetAliases returns a
3536
                // copy of the alias slice.
3537
                channelReadyMsg.AliasScid = &aliases[0]
3✔
3538
        }
3539

3540
        // If the peer has disconnected before we reach this point, we will need
3541
        // to wait for him to come back online before sending the channelReady
3542
        // message. This is special for channelReady, since failing to send any
3543
        // of the previous messages in the funding flow just cancels the flow.
3544
        // But now the funding transaction is confirmed, the channel is open
3545
        // and we have to make sure the peer gets the channelReady message when
3546
        // it comes back online. This is also crucial during restart of lnd,
3547
        // where we might try to resend the channelReady message before the
3548
        // server has had the time to connect to the peer. We keep trying to
3549
        // send channelReady until we succeed, or the fundingManager is shut
3550
        // down.
3551
        for {
6✔
3552
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
3✔
3553
                if err != nil {
3✔
3554
                        return err
×
3555
                }
×
3556

3557
                localAlias := peer.LocalFeatures().HasFeature(
3✔
3558
                        lnwire.ScidAliasOptional,
3✔
3559
                )
3✔
3560
                remoteAlias := peer.RemoteFeatures().HasFeature(
3✔
3561
                        lnwire.ScidAliasOptional,
3✔
3562
                )
3✔
3563

3✔
3564
                // We could also refresh the channel state instead of checking
3✔
3565
                // whether the feature was negotiated, but this saves us a
3✔
3566
                // database read.
3✔
3567
                if channelReadyMsg.AliasScid == nil && localAlias &&
3✔
3568
                        remoteAlias {
3✔
3569

×
3570
                        // If an alias was not assigned above and the scid
×
3571
                        // alias feature was negotiated, check if we already
×
3572
                        // have an alias stored in case handleChannelReady was
×
3573
                        // called before this. If an alias exists, use that in
×
3574
                        // channel_ready. Otherwise, request and store an
×
3575
                        // alias and use that.
×
3576
                        aliases := f.cfg.AliasManager.GetAliases(
×
3577
                                completeChan.ShortChannelID,
×
3578
                        )
×
3579
                        if len(aliases) == 0 {
×
3580
                                // No aliases were found.
×
3581
                                alias, err := f.cfg.AliasManager.RequestAlias()
×
3582
                                if err != nil {
×
3583
                                        return err
×
3584
                                }
×
3585

3586
                                err = f.cfg.AliasManager.AddLocalAlias(
×
3587
                                        alias, completeChan.ShortChannelID,
×
3588
                                        false, false,
×
3589
                                )
×
3590
                                if err != nil {
×
3591
                                        return err
×
3592
                                }
×
3593

3594
                                channelReadyMsg.AliasScid = &alias
×
3595
                        } else {
×
3596
                                channelReadyMsg.AliasScid = &aliases[0]
×
3597
                        }
×
3598
                }
3599

3600
                log.Infof("Peer(%x) is online, sending ChannelReady "+
3✔
3601
                        "for ChannelID(%v)", peerKey, chanID)
3✔
3602

3✔
3603
                if err := peer.SendMessage(true, channelReadyMsg); err == nil {
6✔
3604
                        // Sending succeeded, we can break out and continue the
3✔
3605
                        // funding flow.
3✔
3606
                        break
3✔
3607
                }
3608

3609
                log.Warnf("Unable to send channelReady to peer %x: %v. "+
×
3610
                        "Will retry when online", peerKey, err)
×
3611
        }
3612

3613
        return nil
3✔
3614
}
3615

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

3✔
3621
        // If the funding manager has exited, return an error to stop looping.
3✔
3622
        // Note that the peer may appear as online while the funding manager
3✔
3623
        // has stopped due to the shutdown order in the server.
3✔
3624
        select {
3✔
3625
        case <-f.quit:
×
3626
                return false, ErrFundingManagerShuttingDown
×
3627
        default:
3✔
3628
        }
3629

3630
        // Avoid a tight loop if peer is offline.
3631
        if _, err := f.waitForPeerOnline(node); err != nil {
3✔
3632
                log.Errorf("Wait for peer online failed: %v", err)
×
3633
                return false, err
×
3634
        }
×
3635

3636
        // If we cannot find the channel, then we haven't processed the
3637
        // remote's channelReady message.
3638
        channel, err := f.cfg.FindChannel(node, chanID)
3✔
3639
        if err != nil {
3✔
3640
                log.Errorf("Unable to locate ChannelID(%v) to determine if "+
×
3641
                        "ChannelReady was received", chanID)
×
3642
                return false, err
×
3643
        }
×
3644

3645
        // If we haven't insert the next revocation point, we haven't finished
3646
        // processing the channel ready message.
3647
        if channel.RemoteNextRevocation == nil {
6✔
3648
                return false, nil
3✔
3649
        }
3✔
3650

3651
        // Finally, the barrier signal is removed once we finish
3652
        // `handleChannelReady`. If we can still find the signal, we haven't
3653
        // finished processing it yet.
3654
        _, loaded := f.handleChannelReadyBarriers.Load(chanID)
3✔
3655

3✔
3656
        return !loaded, nil
3✔
3657
}
3658

3659
// extractAnnounceParams extracts the various channel announcement and update
3660
// parameters that will be needed to construct a ChannelAnnouncement and a
3661
// ChannelUpdate.
3662
func (f *Manager) extractAnnounceParams(c *channeldb.OpenChannel) (
3663
        lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
3✔
3664

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

3✔
3671
        // We don't necessarily want to go as low as the remote party allows.
3✔
3672
        // Check it against our default forwarding policy.
3✔
3673
        if fwdMinHTLC < f.cfg.DefaultRoutingPolicy.MinHTLCOut {
6✔
3674
                fwdMinHTLC = f.cfg.DefaultRoutingPolicy.MinHTLCOut
3✔
3675
        }
3✔
3676

3677
        // We'll obtain the max HTLC value we can forward in our direction, as
3678
        // we'll use this value within our ChannelUpdate. This value must be <=
3679
        // channel capacity and <= the maximum in-flight msats set by the peer.
3680
        fwdMaxHTLC := c.LocalChanCfg.MaxPendingAmount
3✔
3681
        capacityMSat := lnwire.NewMSatFromSatoshis(c.Capacity)
3✔
3682
        if fwdMaxHTLC > capacityMSat {
3✔
3683
                fwdMaxHTLC = capacityMSat
×
3684
        }
×
3685

3686
        return fwdMinHTLC, fwdMaxHTLC
3✔
3687
}
3688

3689
// addToGraph sends a ChannelAnnouncement and a ChannelUpdate to the
3690
// gossiper so that the channel is added to the graph builder's internal graph.
3691
// These announcement messages are NOT broadcasted to the greater network,
3692
// only to the channel counter party. The proofs required to announce the
3693
// channel to the greater network will be created and sent in annAfterSixConfs.
3694
// The peerAlias is used for zero-conf channels to give the counter-party a
3695
// ChannelUpdate they understand. ourPolicy may be set for various
3696
// option-scid-alias channels to re-use the same policy.
3697
func (f *Manager) addToGraph(completeChan *channeldb.OpenChannel,
3698
        shortChanID *lnwire.ShortChannelID,
3699
        peerAlias *lnwire.ShortChannelID,
3700
        ourPolicy *models.ChannelEdgePolicy) error {
3✔
3701

3✔
3702
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
3✔
3703

3✔
3704
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
3✔
3705

3✔
3706
        ann, err := f.newChanAnnouncement(
3✔
3707
                f.cfg.IDKey, completeChan.IdentityPub,
3✔
3708
                &completeChan.LocalChanCfg.MultiSigKey,
3✔
3709
                completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
3✔
3710
                chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
3✔
3711
                completeChan.ChanType,
3✔
3712
        )
3✔
3713
        if err != nil {
3✔
3714
                return fmt.Errorf("error generating channel "+
×
3715
                        "announcement: %v", err)
×
3716
        }
×
3717

3718
        // Send ChannelAnnouncement and ChannelUpdate to the gossiper to add
3719
        // to the Router's topology.
3720
        errChan := f.cfg.SendAnnouncement(
3✔
3721
                ann.chanAnn, discovery.ChannelCapacity(completeChan.Capacity),
3✔
3722
                discovery.ChannelPoint(completeChan.FundingOutpoint),
3✔
3723
                discovery.TapscriptRoot(completeChan.TapscriptRoot),
3✔
3724
        )
3✔
3725
        select {
3✔
3726
        case err := <-errChan:
3✔
3727
                if err != nil {
3✔
3728
                        if graph.IsError(err, graph.ErrOutdated,
×
3729
                                graph.ErrIgnored) {
×
3730

×
3731
                                log.Debugf("Graph rejected "+
×
3732
                                        "ChannelAnnouncement: %v", err)
×
3733
                        } else {
×
3734
                                return fmt.Errorf("error sending channel "+
×
3735
                                        "announcement: %v", err)
×
3736
                        }
×
3737
                }
3738
        case <-f.quit:
×
3739
                return ErrFundingManagerShuttingDown
×
3740
        }
3741

3742
        errChan = f.cfg.SendAnnouncement(
3✔
3743
                ann.chanUpdateAnn, discovery.RemoteAlias(peerAlias),
3✔
3744
        )
3✔
3745
        select {
3✔
3746
        case err := <-errChan:
3✔
3747
                if err != nil {
3✔
3748
                        if graph.IsError(err, graph.ErrOutdated,
×
3749
                                graph.ErrIgnored) {
×
3750

×
3751
                                log.Debugf("Graph rejected "+
×
3752
                                        "ChannelUpdate: %v", err)
×
3753
                        } else {
×
3754
                                return fmt.Errorf("error sending channel "+
×
3755
                                        "update: %v", err)
×
3756
                        }
×
3757
                }
3758
        case <-f.quit:
×
3759
                return ErrFundingManagerShuttingDown
×
3760
        }
3761

3762
        return nil
3✔
3763
}
3764

3765
// annAfterSixConfs broadcasts the necessary channel announcement messages to
3766
// the network after 6 confs. Should be called after the channelReady message
3767
// is sent and the channel is added to the graph (channelState is
3768
// 'addedToGraph') and the channel is ready to be used. This is the last
3769
// step in the channel opening process, and the opening state will be deleted
3770
// from the database if successful.
3771
func (f *Manager) annAfterSixConfs(completeChan *channeldb.OpenChannel,
3772
        shortChanID *lnwire.ShortChannelID) error {
3✔
3773

3✔
3774
        // If this channel is not meant to be announced to the greater network,
3✔
3775
        // we'll only send our NodeAnnouncement to our counterparty to ensure we
3✔
3776
        // don't leak any of our information.
3✔
3777
        announceChan := completeChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
3778
        if !announceChan {
6✔
3779
                log.Debugf("Will not announce private channel %v.",
3✔
3780
                        shortChanID.ToUint64())
3✔
3781

3✔
3782
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
3✔
3783
                if err != nil {
3✔
3784
                        return err
×
3785
                }
×
3786

3787
                nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
3✔
3788
                if err != nil {
3✔
3789
                        return fmt.Errorf("unable to retrieve current node "+
×
3790
                                "announcement: %v", err)
×
3791
                }
×
3792

3793
                chanID := lnwire.NewChanIDFromOutPoint(
3✔
3794
                        completeChan.FundingOutpoint,
3✔
3795
                )
3✔
3796
                pubKey := peer.PubKey()
3✔
3797
                log.Debugf("Sending our NodeAnnouncement for "+
3✔
3798
                        "ChannelID(%v) to %x", chanID, pubKey)
3✔
3799

3✔
3800
                // TODO(halseth): make reliable. If the peer is not online this
3✔
3801
                // will fail, and the opening process will stop. Should instead
3✔
3802
                // block here, waiting for the peer to come online.
3✔
3803
                if err := peer.SendMessage(true, &nodeAnn); err != nil {
3✔
3804
                        return fmt.Errorf("unable to send node announcement "+
×
3805
                                "to peer %x: %v", pubKey, err)
×
3806
                }
×
3807
        } else {
3✔
3808
                // Otherwise, we'll wait until the funding transaction has
3✔
3809
                // reached 6 confirmations before announcing it.
3✔
3810
                numConfs := uint32(completeChan.NumConfsRequired)
3✔
3811
                if numConfs < 6 {
6✔
3812
                        numConfs = 6
3✔
3813
                }
3✔
3814
                txid := completeChan.FundingOutpoint.Hash
3✔
3815
                log.Debugf("Will announce channel %v after ChannelPoint"+
3✔
3816
                        "(%v) has gotten %d confirmations",
3✔
3817
                        shortChanID.ToUint64(), completeChan.FundingOutpoint,
3✔
3818
                        numConfs)
3✔
3819

3✔
3820
                fundingScript, err := makeFundingScript(completeChan)
3✔
3821
                if err != nil {
3✔
3822
                        return fmt.Errorf("unable to create funding script "+
×
3823
                                "for ChannelPoint(%v): %v",
×
3824
                                completeChan.FundingOutpoint, err)
×
3825
                }
×
3826

3827
                // Register with the ChainNotifier for a notification once the
3828
                // funding transaction reaches at least 6 confirmations.
3829
                confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
3✔
3830
                        &txid, fundingScript, numConfs,
3✔
3831
                        completeChan.BroadcastHeight(),
3✔
3832
                )
3✔
3833
                if err != nil {
3✔
3834
                        return fmt.Errorf("unable to register for "+
×
3835
                                "confirmation of ChannelPoint(%v): %v",
×
3836
                                completeChan.FundingOutpoint, err)
×
3837
                }
×
3838

3839
                // Wait until 6 confirmations has been reached or the wallet
3840
                // signals a shutdown.
3841
                select {
3✔
3842
                case _, ok := <-confNtfn.Confirmed:
3✔
3843
                        if !ok {
3✔
3844
                                return fmt.Errorf("ChainNotifier shutting "+
×
3845
                                        "down, cannot complete funding flow "+
×
3846
                                        "for ChannelPoint(%v)",
×
3847
                                        completeChan.FundingOutpoint)
×
3848
                        }
×
3849
                        // Fallthrough.
3850

3851
                case <-f.quit:
3✔
3852
                        return fmt.Errorf("%v, stopping funding flow for "+
3✔
3853
                                "ChannelPoint(%v)",
3✔
3854
                                ErrFundingManagerShuttingDown,
3✔
3855
                                completeChan.FundingOutpoint)
3✔
3856
                }
3857

3858
                fundingPoint := completeChan.FundingOutpoint
3✔
3859
                chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
3✔
3860

3✔
3861
                log.Infof("Announcing ChannelPoint(%v), short_chan_id=%v",
3✔
3862
                        &fundingPoint, shortChanID)
3✔
3863

3✔
3864
                // If this is a non-zero-conf option-scid-alias channel, we'll
3✔
3865
                // delete the mappings the gossiper uses so that ChannelUpdates
3✔
3866
                // with aliases won't be accepted. This is done elsewhere for
3✔
3867
                // zero-conf channels.
3✔
3868
                isScidFeature := completeChan.NegotiatedAliasFeature()
3✔
3869
                isZeroConf := completeChan.IsZeroConf()
3✔
3870
                if isScidFeature && !isZeroConf {
6✔
3871
                        baseScid := completeChan.ShortChanID()
3✔
3872
                        err := f.cfg.AliasManager.DeleteSixConfs(baseScid)
3✔
3873
                        if err != nil {
3✔
3874
                                return fmt.Errorf("failed deleting six confs "+
×
3875
                                        "maps: %v", err)
×
3876
                        }
×
3877

3878
                        // We'll delete the edge and add it again via
3879
                        // addToGraph. This is because the peer may have
3880
                        // sent us a ChannelUpdate with an alias and we don't
3881
                        // want to relay this.
3882
                        ourPolicy, err := f.cfg.DeleteAliasEdge(baseScid)
3✔
3883
                        if err != nil {
3✔
3884
                                return fmt.Errorf("failed deleting real edge "+
×
3885
                                        "for alias channel from graph: %v",
×
3886
                                        err)
×
3887
                        }
×
3888

3889
                        err = f.addToGraph(
3✔
3890
                                completeChan, &baseScid, nil, ourPolicy,
3✔
3891
                        )
3✔
3892
                        if err != nil {
3✔
3893
                                return fmt.Errorf("failed to re-add to "+
×
3894
                                        "graph: %v", err)
×
3895
                        }
×
3896
                }
3897

3898
                // Create and broadcast the proofs required to make this channel
3899
                // public and usable for other nodes for routing.
3900
                err = f.announceChannel(
3✔
3901
                        f.cfg.IDKey, completeChan.IdentityPub,
3✔
3902
                        &completeChan.LocalChanCfg.MultiSigKey,
3✔
3903
                        completeChan.RemoteChanCfg.MultiSigKey.PubKey,
3✔
3904
                        *shortChanID, chanID, completeChan.ChanType,
3✔
3905
                )
3✔
3906
                if err != nil {
6✔
3907
                        return fmt.Errorf("channel announcement failed: %w",
3✔
3908
                                err)
3✔
3909
                }
3✔
3910

3911
                log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+
3✔
3912
                        "sent to gossiper", &fundingPoint, shortChanID)
3✔
3913
        }
3914

3915
        return nil
3✔
3916
}
3917

3918
// waitForZeroConfChannel is called when the state is addedToGraph with
3919
// a zero-conf channel. This will wait for the real confirmation, add the
3920
// confirmed SCID to the router graph, and then announce after six confs.
3921
func (f *Manager) waitForZeroConfChannel(c *channeldb.OpenChannel) error {
3✔
3922
        // First we'll check whether the channel is confirmed on-chain. If it
3✔
3923
        // is already confirmed, the chainntnfs subsystem will return with the
3✔
3924
        // confirmed tx. Otherwise, we'll wait here until confirmation occurs.
3✔
3925
        confChan, err := f.waitForFundingWithTimeout(c)
3✔
3926
        if err != nil {
6✔
3927
                return fmt.Errorf("error waiting for zero-conf funding "+
3✔
3928
                        "confirmation for ChannelPoint(%v): %v",
3✔
3929
                        c.FundingOutpoint, err)
3✔
3930
        }
3✔
3931

3932
        // We'll need to refresh the channel state so that things are properly
3933
        // populated when validating the channel state. Otherwise, a panic may
3934
        // occur due to inconsistency in the OpenChannel struct.
3935
        err = c.Refresh()
3✔
3936
        if err != nil {
6✔
3937
                return fmt.Errorf("unable to refresh channel state: %w", err)
3✔
3938
        }
3✔
3939

3940
        // Now that we have the confirmed transaction and the proper SCID,
3941
        // we'll call ValidateChannel to ensure the confirmed tx is properly
3942
        // formatted.
3943
        err = f.cfg.Wallet.ValidateChannel(c, confChan.fundingTx)
3✔
3944
        if err != nil {
3✔
3945
                return fmt.Errorf("unable to validate zero-conf channel: "+
×
3946
                        "%v", err)
×
3947
        }
×
3948

3949
        // Once we know the confirmed ShortChannelID, we'll need to save it to
3950
        // the database and refresh the OpenChannel struct with it.
3951
        err = c.MarkRealScid(confChan.shortChanID)
3✔
3952
        if err != nil {
3✔
3953
                return fmt.Errorf("unable to set confirmed SCID for zero "+
×
3954
                        "channel: %v", err)
×
3955
        }
×
3956

3957
        // Six confirmations have been reached. If this channel is public,
3958
        // we'll delete some of the alias mappings the gossiper uses.
3959
        isPublic := c.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
3960
        if isPublic {
6✔
3961
                err = f.cfg.AliasManager.DeleteSixConfs(c.ShortChannelID)
3✔
3962
                if err != nil {
3✔
3963
                        return fmt.Errorf("unable to delete base alias after "+
×
3964
                                "six confirmations: %v", err)
×
3965
                }
×
3966

3967
                // TODO: Make this atomic!
3968
                ourPolicy, err := f.cfg.DeleteAliasEdge(c.ShortChanID())
3✔
3969
                if err != nil {
3✔
3970
                        return fmt.Errorf("unable to delete alias edge from "+
×
3971
                                "graph: %v", err)
×
3972
                }
×
3973

3974
                // We'll need to update the graph with the new ShortChannelID
3975
                // via an addToGraph call. We don't pass in the peer's
3976
                // alias since we'll be using the confirmed SCID from now on
3977
                // regardless if it's public or not.
3978
                err = f.addToGraph(
3✔
3979
                        c, &confChan.shortChanID, nil, ourPolicy,
3✔
3980
                )
3✔
3981
                if err != nil {
3✔
3982
                        return fmt.Errorf("failed adding confirmed zero-conf "+
×
3983
                                "SCID to graph: %v", err)
×
3984
                }
×
3985
        }
3986

3987
        // Since we have now marked down the confirmed SCID, we'll also need to
3988
        // tell the Switch to refresh the relevant ChannelLink so that forwards
3989
        // under the confirmed SCID are possible if this is a public channel.
3990
        err = f.cfg.ReportShortChanID(c.FundingOutpoint)
3✔
3991
        if err != nil {
3✔
3992
                // This should only fail if the link is not found in the
×
3993
                // Switch's linkIndex map. If this is the case, then the peer
×
3994
                // has gone offline and the next time the link is loaded, it
×
3995
                // will have a refreshed state. Just log an error here.
×
3996
                log.Errorf("unable to report scid for zero-conf channel "+
×
3997
                        "channel: %v", err)
×
3998
        }
×
3999

4000
        // Update the confirmed transaction's label.
4001
        f.makeLabelForTx(c)
3✔
4002

3✔
4003
        return nil
3✔
4004
}
4005

4006
// genFirstStateMusigNonce generates a nonces for the "first" local state. This
4007
// is the verification nonce for the state created for us after the initial
4008
// commitment transaction signed as part of the funding flow.
4009
func genFirstStateMusigNonce(channel *channeldb.OpenChannel,
4010
) (*musig2.Nonces, error) {
3✔
4011

3✔
4012
        musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
3✔
4013
                channel.RevocationProducer,
3✔
4014
        )
3✔
4015
        if err != nil {
3✔
4016
                return nil, fmt.Errorf("unable to generate musig channel "+
×
4017
                        "nonces: %v", err)
×
4018
        }
×
4019

4020
        // We use the _next_ commitment height here as we need to generate the
4021
        // nonce for the next state the remote party will sign for us.
4022
        verNonce, err := channeldb.NewMusigVerificationNonce(
3✔
4023
                channel.LocalChanCfg.MultiSigKey.PubKey,
3✔
4024
                channel.LocalCommitment.CommitHeight+1,
3✔
4025
                musig2ShaChain,
3✔
4026
        )
3✔
4027
        if err != nil {
3✔
4028
                return nil, fmt.Errorf("unable to generate musig channel "+
×
4029
                        "nonces: %v", err)
×
4030
        }
×
4031

4032
        return verNonce, nil
3✔
4033
}
4034

4035
// handleChannelReady finalizes the channel funding process and enables the
4036
// channel to enter normal operating mode.
4037
func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen
4038
        msg *lnwire.ChannelReady) {
3✔
4039

3✔
4040
        defer f.wg.Done()
3✔
4041

3✔
4042
        // If we are in development mode, we'll wait for specified duration
3✔
4043
        // before processing the channel ready message.
3✔
4044
        if f.cfg.Dev != nil {
6✔
4045
                duration := f.cfg.Dev.ProcessChannelReadyWait
3✔
4046
                log.Warnf("Channel(%v): sleeping %v before processing "+
3✔
4047
                        "channel_ready", msg.ChanID, duration)
3✔
4048

3✔
4049
                select {
3✔
4050
                case <-time.After(duration):
3✔
4051
                        log.Warnf("Channel(%v): slept %v before processing "+
3✔
4052
                                "channel_ready", msg.ChanID, duration)
3✔
4053
                case <-f.quit:
×
4054
                        log.Warnf("Channel(%v): quit sleeping", msg.ChanID)
×
4055
                        return
×
4056
                }
4057
        }
4058

4059
        log.Debugf("Received ChannelReady for ChannelID(%v) from "+
3✔
4060
                "peer %x", msg.ChanID,
3✔
4061
                peer.IdentityKey().SerializeCompressed())
3✔
4062

3✔
4063
        // We now load or create a new channel barrier for this channel.
3✔
4064
        _, loaded := f.handleChannelReadyBarriers.LoadOrStore(
3✔
4065
                msg.ChanID, struct{}{},
3✔
4066
        )
3✔
4067

3✔
4068
        // If we are currently in the process of handling a channel_ready
3✔
4069
        // message for this channel, ignore.
3✔
4070
        if loaded {
6✔
4071
                log.Infof("Already handling channelReady for "+
3✔
4072
                        "ChannelID(%v), ignoring.", msg.ChanID)
3✔
4073
                return
3✔
4074
        }
3✔
4075

4076
        // If not already handling channelReady for this channel, then the
4077
        // `LoadOrStore` has set up a barrier, and it will be removed once this
4078
        // function exits.
4079
        defer f.handleChannelReadyBarriers.Delete(msg.ChanID)
3✔
4080

3✔
4081
        localDiscoverySignal, ok := f.localDiscoverySignals.Load(msg.ChanID)
3✔
4082
        if ok {
6✔
4083
                // Before we proceed with processing the channel_ready
3✔
4084
                // message, we'll wait for the local waitForFundingConfirmation
3✔
4085
                // goroutine to signal that it has the necessary state in
3✔
4086
                // place. Otherwise, we may be missing critical information
3✔
4087
                // required to handle forwarded HTLC's.
3✔
4088
                select {
3✔
4089
                case <-localDiscoverySignal:
3✔
4090
                        // Fallthrough
4091
                case <-f.quit:
3✔
4092
                        return
3✔
4093
                }
4094

4095
                // With the signal received, we can now safely delete the entry
4096
                // from the map.
4097
                f.localDiscoverySignals.Delete(msg.ChanID)
3✔
4098
        }
4099

4100
        // First, we'll attempt to locate the channel whose funding workflow is
4101
        // being finalized by this message. We go to the database rather than
4102
        // our reservation map as we may have restarted, mid funding flow. Also
4103
        // provide the node's public key to make the search faster.
4104
        chanID := msg.ChanID
3✔
4105
        channel, err := f.cfg.FindChannel(peer.IdentityKey(), chanID)
3✔
4106
        if err != nil {
3✔
4107
                log.Errorf("Unable to locate ChannelID(%v), cannot complete "+
×
4108
                        "funding", chanID)
×
4109
                return
×
4110
        }
×
4111

4112
        // If this is a taproot channel, then we can generate the set of nonces
4113
        // the remote party needs to send the next remote commitment here.
4114
        var firstVerNonce *musig2.Nonces
3✔
4115
        if channel.ChanType.IsTaproot() {
6✔
4116
                firstVerNonce, err = genFirstStateMusigNonce(channel)
3✔
4117
                if err != nil {
3✔
4118
                        log.Error(err)
×
4119
                        return
×
4120
                }
×
4121
        }
4122

4123
        // We'll need to store the received TLV alias if the option_scid_alias
4124
        // feature was negotiated. This will be used to provide route hints
4125
        // during invoice creation. In the zero-conf case, it is also used to
4126
        // provide a ChannelUpdate to the remote peer. This is done before the
4127
        // call to InsertNextRevocation in case the call to PutPeerAlias fails.
4128
        // If it were to fail on the first call to handleChannelReady, we
4129
        // wouldn't want the channel to be usable yet.
4130
        if channel.NegotiatedAliasFeature() {
6✔
4131
                // If the AliasScid field is nil, we must fail out. We will
3✔
4132
                // most likely not be able to route through the peer.
3✔
4133
                if msg.AliasScid == nil {
3✔
4134
                        log.Debugf("Consider closing ChannelID(%v), peer "+
×
4135
                                "does not implement the option-scid-alias "+
×
4136
                                "feature properly", chanID)
×
4137
                        return
×
4138
                }
×
4139

4140
                // We'll store the AliasScid so that invoice creation can use
4141
                // it.
4142
                err = f.cfg.AliasManager.PutPeerAlias(chanID, *msg.AliasScid)
3✔
4143
                if err != nil {
3✔
4144
                        log.Errorf("unable to store peer's alias: %v", err)
×
4145
                        return
×
4146
                }
×
4147

4148
                // If we do not have an alias stored, we'll create one now.
4149
                // This is only used in the upgrade case where a user toggles
4150
                // the option-scid-alias feature-bit to on. We'll also send the
4151
                // channel_ready message here in case the link is created
4152
                // before sendChannelReady is called.
4153
                aliases := f.cfg.AliasManager.GetAliases(
3✔
4154
                        channel.ShortChannelID,
3✔
4155
                )
3✔
4156
                if len(aliases) == 0 {
3✔
4157
                        // No aliases were found so we'll request and store an
×
4158
                        // alias and use it in the channel_ready message.
×
4159
                        alias, err := f.cfg.AliasManager.RequestAlias()
×
4160
                        if err != nil {
×
4161
                                log.Errorf("unable to request alias: %v", err)
×
4162
                                return
×
4163
                        }
×
4164

4165
                        err = f.cfg.AliasManager.AddLocalAlias(
×
4166
                                alias, channel.ShortChannelID, false, false,
×
4167
                        )
×
4168
                        if err != nil {
×
4169
                                log.Errorf("unable to add local alias: %v",
×
4170
                                        err)
×
4171
                                return
×
4172
                        }
×
4173

4174
                        secondPoint, err := channel.SecondCommitmentPoint()
×
4175
                        if err != nil {
×
4176
                                log.Errorf("unable to fetch second "+
×
4177
                                        "commitment point: %v", err)
×
4178
                                return
×
4179
                        }
×
4180

4181
                        channelReadyMsg := lnwire.NewChannelReady(
×
4182
                                chanID, secondPoint,
×
4183
                        )
×
4184
                        channelReadyMsg.AliasScid = &alias
×
4185

×
4186
                        if firstVerNonce != nil {
×
4187
                                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:ll
×
4188
                                        firstVerNonce.PubNonce,
×
4189
                                )
×
4190
                        }
×
4191

4192
                        err = peer.SendMessage(true, channelReadyMsg)
×
4193
                        if err != nil {
×
4194
                                log.Errorf("unable to send channel_ready: %v",
×
4195
                                        err)
×
4196
                                return
×
4197
                        }
×
4198
                }
4199
        }
4200

4201
        // If the RemoteNextRevocation is non-nil, it means that we have
4202
        // already processed channelReady for this channel, so ignore. This
4203
        // check is after the alias logic so we store the peer's most recent
4204
        // alias. The spec requires us to validate that subsequent
4205
        // channel_ready messages use the same per commitment point (the
4206
        // second), but it is not actually necessary since we'll just end up
4207
        // ignoring it. We are, however, required to *send* the same per
4208
        // commitment point, since another pedantic implementation might
4209
        // verify it.
4210
        if channel.RemoteNextRevocation != nil {
6✔
4211
                log.Infof("Received duplicate channelReady for "+
3✔
4212
                        "ChannelID(%v), ignoring.", chanID)
3✔
4213
                return
3✔
4214
        }
3✔
4215

4216
        // If this is a taproot channel, then we'll need to map the received
4217
        // nonces to a nonce pair, and also fetch our pending nonces, which are
4218
        // required in order to make the channel whole.
4219
        var chanOpts []lnwallet.ChannelOpt
3✔
4220
        if channel.ChanType.IsTaproot() {
6✔
4221
                f.nonceMtx.Lock()
3✔
4222
                localNonce, ok := f.pendingMusigNonces[chanID]
3✔
4223
                if !ok {
6✔
4224
                        // If there's no pending nonce for this channel ID,
3✔
4225
                        // we'll use the one generated above.
3✔
4226
                        localNonce = firstVerNonce
3✔
4227
                        f.pendingMusigNonces[chanID] = firstVerNonce
3✔
4228
                }
3✔
4229
                f.nonceMtx.Unlock()
3✔
4230

3✔
4231
                log.Infof("ChanID(%v): applying local+remote musig2 nonces",
3✔
4232
                        chanID)
3✔
4233

3✔
4234
                remoteNonce, err := msg.NextLocalNonce.UnwrapOrErrV(
3✔
4235
                        errNoLocalNonce,
3✔
4236
                )
3✔
4237
                if err != nil {
3✔
4238
                        cid := newChanIdentifier(msg.ChanID)
×
4239
                        f.sendWarning(peer, cid, err)
×
4240

×
4241
                        return
×
4242
                }
×
4243

4244
                chanOpts = append(
3✔
4245
                        chanOpts,
3✔
4246
                        lnwallet.WithLocalMusigNonces(localNonce),
3✔
4247
                        lnwallet.WithRemoteMusigNonces(&musig2.Nonces{
3✔
4248
                                PubNonce: remoteNonce,
3✔
4249
                        }),
3✔
4250
                )
3✔
4251

3✔
4252
                // Inform the aux funding controller that the liquidity in the
3✔
4253
                // custom channel is now ready to be advertised. We potentially
3✔
4254
                // haven't sent our own channel ready message yet, but other
3✔
4255
                // than that the channel is ready to count toward available
3✔
4256
                // liquidity.
3✔
4257
                err = fn.MapOptionZ(
3✔
4258
                        f.cfg.AuxFundingController,
3✔
4259
                        func(controller AuxFundingController) error {
3✔
4260
                                return controller.ChannelReady(
×
4261
                                        lnwallet.NewAuxChanState(channel),
×
4262
                                )
×
4263
                        },
×
4264
                )
4265
                if err != nil {
3✔
4266
                        cid := newChanIdentifier(msg.ChanID)
×
4267
                        f.sendWarning(peer, cid, err)
×
4268

×
4269
                        return
×
4270
                }
×
4271
        }
4272

4273
        // The channel_ready message contains the next commitment point we'll
4274
        // need to create the next commitment state for the remote party. So
4275
        // we'll insert that into the channel now before passing it along to
4276
        // other sub-systems.
4277
        err = channel.InsertNextRevocation(msg.NextPerCommitmentPoint)
3✔
4278
        if err != nil {
3✔
4279
                log.Errorf("unable to insert next commitment point: %v", err)
×
4280
                return
×
4281
        }
×
4282

4283
        // Before we can add the channel to the peer, we'll need to ensure that
4284
        // we have an initial forwarding policy set.
4285
        if err := f.ensureInitialForwardingPolicy(chanID, channel); err != nil {
3✔
4286
                log.Errorf("Unable to ensure initial forwarding policy: %v",
×
4287
                        err)
×
4288
        }
×
4289

4290
        err = peer.AddNewChannel(&lnpeer.NewChannel{
3✔
4291
                OpenChannel: channel,
3✔
4292
                ChanOpts:    chanOpts,
3✔
4293
        }, f.quit)
3✔
4294
        if err != nil {
3✔
4295
                log.Errorf("Unable to add new channel %v with peer %x: %v",
×
4296
                        channel.FundingOutpoint,
×
4297
                        peer.IdentityKey().SerializeCompressed(), err,
×
4298
                )
×
4299
        }
×
4300
}
4301

4302
// handleChannelReadyReceived is called once the remote's channelReady message
4303
// is received and processed. At this stage, we must have sent out our
4304
// channelReady message, once the remote's channelReady is processed, the
4305
// channel is now active, thus we change its state to `addedToGraph` to
4306
// let the channel start handling routing.
4307
func (f *Manager) handleChannelReadyReceived(channel *channeldb.OpenChannel,
4308
        scid *lnwire.ShortChannelID, pendingChanID PendingChanID,
4309
        updateChan chan<- *lnrpc.OpenStatusUpdate) error {
3✔
4310

3✔
4311
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
3✔
4312

3✔
4313
        // Since we've sent+received funding locked at this point, we
3✔
4314
        // can clean up the pending musig2 nonce state.
3✔
4315
        f.nonceMtx.Lock()
3✔
4316
        delete(f.pendingMusigNonces, chanID)
3✔
4317
        f.nonceMtx.Unlock()
3✔
4318

3✔
4319
        var peerAlias *lnwire.ShortChannelID
3✔
4320
        if channel.IsZeroConf() {
6✔
4321
                // We'll need to wait until channel_ready has been received and
3✔
4322
                // the peer lets us know the alias they want to use for the
3✔
4323
                // channel. With this information, we can then construct a
3✔
4324
                // ChannelUpdate for them.  If an alias does not yet exist,
3✔
4325
                // we'll just return, letting the next iteration of the loop
3✔
4326
                // check again.
3✔
4327
                var defaultAlias lnwire.ShortChannelID
3✔
4328
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
3✔
4329
                foundAlias, _ := f.cfg.AliasManager.GetPeerAlias(chanID)
3✔
4330
                if foundAlias == defaultAlias {
3✔
4331
                        return nil
×
4332
                }
×
4333

4334
                peerAlias = &foundAlias
3✔
4335
        }
4336

4337
        err := f.addToGraph(channel, scid, peerAlias, nil)
3✔
4338
        if err != nil {
3✔
4339
                return fmt.Errorf("failed adding to graph: %w", err)
×
4340
        }
×
4341

4342
        // As the channel is now added to the ChannelRouter's topology, the
4343
        // channel is moved to the next state of the state machine. It will be
4344
        // moved to the last state (actually deleted from the database) after
4345
        // the channel is finally announced.
4346
        err = f.saveChannelOpeningState(
3✔
4347
                &channel.FundingOutpoint, addedToGraph, scid,
3✔
4348
        )
3✔
4349
        if err != nil {
3✔
4350
                return fmt.Errorf("error setting channel state to"+
×
4351
                        " addedToGraph: %w", err)
×
4352
        }
×
4353

4354
        log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
3✔
4355
                "added to graph", chanID, scid)
3✔
4356

3✔
4357
        err = fn.MapOptionZ(
3✔
4358
                f.cfg.AuxFundingController,
3✔
4359
                func(controller AuxFundingController) error {
3✔
4360
                        return controller.ChannelReady(
×
4361
                                lnwallet.NewAuxChanState(channel),
×
4362
                        )
×
4363
                },
×
4364
        )
4365
        if err != nil {
3✔
4366
                return fmt.Errorf("failed notifying aux funding controller "+
×
4367
                        "about channel ready: %w", err)
×
4368
        }
×
4369

4370
        // Give the caller a final update notifying them that the channel is
4371
        fundingPoint := channel.FundingOutpoint
3✔
4372
        cp := &lnrpc.ChannelPoint{
3✔
4373
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
3✔
4374
                        FundingTxidBytes: fundingPoint.Hash[:],
3✔
4375
                },
3✔
4376
                OutputIndex: fundingPoint.Index,
3✔
4377
        }
3✔
4378

3✔
4379
        if updateChan != nil {
6✔
4380
                upd := &lnrpc.OpenStatusUpdate{
3✔
4381
                        Update: &lnrpc.OpenStatusUpdate_ChanOpen{
3✔
4382
                                ChanOpen: &lnrpc.ChannelOpenUpdate{
3✔
4383
                                        ChannelPoint: cp,
3✔
4384
                                },
3✔
4385
                        },
3✔
4386
                        PendingChanId: pendingChanID[:],
3✔
4387
                }
3✔
4388

3✔
4389
                select {
3✔
4390
                case updateChan <- upd:
3✔
4391
                case <-f.quit:
×
4392
                        return ErrFundingManagerShuttingDown
×
4393
                }
4394
        }
4395

4396
        return nil
3✔
4397
}
4398

4399
// ensureInitialForwardingPolicy ensures that we have an initial forwarding
4400
// policy set for the given channel. If we don't, we'll fall back to the default
4401
// values.
4402
func (f *Manager) ensureInitialForwardingPolicy(chanID lnwire.ChannelID,
4403
        channel *channeldb.OpenChannel) error {
3✔
4404

3✔
4405
        // Before we can add the channel to the peer, we'll need to ensure that
3✔
4406
        // we have an initial forwarding policy set. This should always be the
3✔
4407
        // case except for a channel that was created with lnd <= 0.15.5 and
3✔
4408
        // is still pending while updating to this version.
3✔
4409
        var needDBUpdate bool
3✔
4410
        forwardingPolicy, err := f.getInitialForwardingPolicy(chanID)
3✔
4411
        if err != nil {
3✔
4412
                log.Errorf("Unable to fetch initial forwarding policy, "+
×
4413
                        "falling back to default values: %v", err)
×
4414

×
4415
                forwardingPolicy = f.defaultForwardingPolicy(
×
4416
                        channel.LocalChanCfg.ChannelStateBounds,
×
4417
                )
×
4418
                needDBUpdate = true
×
4419
        }
×
4420

4421
        // We only started storing the actual values for MinHTLCOut and MaxHTLC
4422
        // after 0.16.x, so if a channel was opened with such a version and is
4423
        // still pending while updating to this version, we'll need to set the
4424
        // values to the default values.
4425
        if forwardingPolicy.MinHTLCOut == 0 {
6✔
4426
                forwardingPolicy.MinHTLCOut = channel.LocalChanCfg.MinHTLC
3✔
4427
                needDBUpdate = true
3✔
4428
        }
3✔
4429
        if forwardingPolicy.MaxHTLC == 0 {
6✔
4430
                forwardingPolicy.MaxHTLC = channel.LocalChanCfg.MaxPendingAmount
3✔
4431
                needDBUpdate = true
3✔
4432
        }
3✔
4433

4434
        // And finally, if we found that the values currently stored aren't
4435
        // sufficient for the link, we'll update the database.
4436
        if needDBUpdate {
6✔
4437
                err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
3✔
4438
                if err != nil {
3✔
4439
                        return fmt.Errorf("unable to update initial "+
×
4440
                                "forwarding policy: %v", err)
×
4441
                }
×
4442
        }
4443

4444
        return nil
3✔
4445
}
4446

4447
// chanAnnouncement encapsulates the two authenticated announcements that we
4448
// send out to the network after a new channel has been created locally.
4449
type chanAnnouncement struct {
4450
        chanAnn       *lnwire.ChannelAnnouncement1
4451
        chanUpdateAnn *lnwire.ChannelUpdate1
4452
        chanProof     *lnwire.AnnounceSignatures1
4453
}
4454

4455
// newChanAnnouncement creates the authenticated channel announcement messages
4456
// required to broadcast a newly created channel to the network. The
4457
// announcement is two part: the first part authenticates the existence of the
4458
// channel and contains four signatures binding the funding pub keys and
4459
// identity pub keys of both parties to the channel, and the second segment is
4460
// authenticated only by us and contains our directional routing policy for the
4461
// channel. ourPolicy may be set in order to re-use an existing, non-default
4462
// policy.
4463
func (f *Manager) newChanAnnouncement(localPubKey,
4464
        remotePubKey *btcec.PublicKey, localFundingKey *keychain.KeyDescriptor,
4465
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4466
        chanID lnwire.ChannelID, fwdMinHTLC, fwdMaxHTLC lnwire.MilliSatoshi,
4467
        ourPolicy *models.ChannelEdgePolicy,
4468
        chanType channeldb.ChannelType) (*chanAnnouncement, error) {
3✔
4469

3✔
4470
        chainHash := *f.cfg.Wallet.Cfg.NetParams.GenesisHash
3✔
4471

3✔
4472
        // The unconditional section of the announcement is the ShortChannelID
3✔
4473
        // itself which compactly encodes the location of the funding output
3✔
4474
        // within the blockchain.
3✔
4475
        chanAnn := &lnwire.ChannelAnnouncement1{
3✔
4476
                ShortChannelID: shortChanID,
3✔
4477
                Features:       lnwire.NewRawFeatureVector(),
3✔
4478
                ChainHash:      chainHash,
3✔
4479
        }
3✔
4480

3✔
4481
        // If this is a taproot channel, then we'll set a special bit in the
3✔
4482
        // feature vector to indicate to the routing layer that this needs a
3✔
4483
        // slightly different type of validation.
3✔
4484
        //
3✔
4485
        // TODO(roasbeef): temp, remove after gossip 1.5
3✔
4486
        if chanType.IsTaproot() {
6✔
4487
                log.Debugf("Applying taproot feature bit to "+
3✔
4488
                        "ChannelAnnouncement for %v", chanID)
3✔
4489

3✔
4490
                chanAnn.Features.Set(
3✔
4491
                        lnwire.SimpleTaprootChannelsRequiredStaging,
3✔
4492
                )
3✔
4493
        }
3✔
4494

4495
        // The chanFlags field indicates which directed edge of the channel is
4496
        // being updated within the ChannelUpdateAnnouncement announcement
4497
        // below. A value of zero means it's the edge of the "first" node and 1
4498
        // being the other node.
4499
        var chanFlags lnwire.ChanUpdateChanFlags
3✔
4500

3✔
4501
        // The lexicographical ordering of the two identity public keys of the
3✔
4502
        // nodes indicates which of the nodes is "first". If our serialized
3✔
4503
        // identity key is lower than theirs then we're the "first" node and
3✔
4504
        // second otherwise.
3✔
4505
        selfBytes := localPubKey.SerializeCompressed()
3✔
4506
        remoteBytes := remotePubKey.SerializeCompressed()
3✔
4507
        if bytes.Compare(selfBytes, remoteBytes) == -1 {
6✔
4508
                copy(chanAnn.NodeID1[:], localPubKey.SerializeCompressed())
3✔
4509
                copy(chanAnn.NodeID2[:], remotePubKey.SerializeCompressed())
3✔
4510
                copy(
3✔
4511
                        chanAnn.BitcoinKey1[:],
3✔
4512
                        localFundingKey.PubKey.SerializeCompressed(),
3✔
4513
                )
3✔
4514
                copy(
3✔
4515
                        chanAnn.BitcoinKey2[:],
3✔
4516
                        remoteFundingKey.SerializeCompressed(),
3✔
4517
                )
3✔
4518

3✔
4519
                // If we're the first node then update the chanFlags to
3✔
4520
                // indicate the "direction" of the update.
3✔
4521
                chanFlags = 0
3✔
4522
        } else {
6✔
4523
                copy(chanAnn.NodeID1[:], remotePubKey.SerializeCompressed())
3✔
4524
                copy(chanAnn.NodeID2[:], localPubKey.SerializeCompressed())
3✔
4525
                copy(
3✔
4526
                        chanAnn.BitcoinKey1[:],
3✔
4527
                        remoteFundingKey.SerializeCompressed(),
3✔
4528
                )
3✔
4529
                copy(
3✔
4530
                        chanAnn.BitcoinKey2[:],
3✔
4531
                        localFundingKey.PubKey.SerializeCompressed(),
3✔
4532
                )
3✔
4533

3✔
4534
                // If we're the second node then update the chanFlags to
3✔
4535
                // indicate the "direction" of the update.
3✔
4536
                chanFlags = 1
3✔
4537
        }
3✔
4538

4539
        // Our channel update message flags will signal that we support the
4540
        // max_htlc field.
4541
        msgFlags := lnwire.ChanUpdateRequiredMaxHtlc
3✔
4542

3✔
4543
        // We announce the channel with the default values. Some of
3✔
4544
        // these values can later be changed by crafting a new ChannelUpdate.
3✔
4545
        chanUpdateAnn := &lnwire.ChannelUpdate1{
3✔
4546
                ShortChannelID: shortChanID,
3✔
4547
                ChainHash:      chainHash,
3✔
4548
                Timestamp:      uint32(time.Now().Unix()),
3✔
4549
                MessageFlags:   msgFlags,
3✔
4550
                ChannelFlags:   chanFlags,
3✔
4551
                TimeLockDelta: uint16(
3✔
4552
                        f.cfg.DefaultRoutingPolicy.TimeLockDelta,
3✔
4553
                ),
3✔
4554
                HtlcMinimumMsat: fwdMinHTLC,
3✔
4555
                HtlcMaximumMsat: fwdMaxHTLC,
3✔
4556
        }
3✔
4557

3✔
4558
        // The caller of newChanAnnouncement is expected to provide the initial
3✔
4559
        // forwarding policy to be announced. If no persisted initial policy
3✔
4560
        // values are found, then we will use the default policy values in the
3✔
4561
        // channel announcement.
3✔
4562
        storedFwdingPolicy, err := f.getInitialForwardingPolicy(chanID)
3✔
4563
        if err != nil && !errors.Is(err, channeldb.ErrChannelNotFound) {
3✔
4564
                return nil, errors.Errorf("unable to generate channel "+
×
4565
                        "update announcement: %v", err)
×
4566
        }
×
4567

4568
        switch {
3✔
4569
        case ourPolicy != nil:
3✔
4570
                // If ourPolicy is non-nil, modify the default parameters of the
3✔
4571
                // ChannelUpdate.
3✔
4572
                chanUpdateAnn.MessageFlags = ourPolicy.MessageFlags
3✔
4573
                chanUpdateAnn.ChannelFlags = ourPolicy.ChannelFlags
3✔
4574
                chanUpdateAnn.TimeLockDelta = ourPolicy.TimeLockDelta
3✔
4575
                chanUpdateAnn.HtlcMinimumMsat = ourPolicy.MinHTLC
3✔
4576
                chanUpdateAnn.HtlcMaximumMsat = ourPolicy.MaxHTLC
3✔
4577
                chanUpdateAnn.BaseFee = uint32(ourPolicy.FeeBaseMSat)
3✔
4578
                chanUpdateAnn.FeeRate = uint32(
3✔
4579
                        ourPolicy.FeeProportionalMillionths,
3✔
4580
                )
3✔
4581

4582
        case storedFwdingPolicy != nil:
3✔
4583
                chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
3✔
4584
                chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
3✔
4585

4586
        default:
×
4587
                log.Infof("No channel forwarding policy specified for channel "+
×
4588
                        "announcement of ChannelID(%v). "+
×
4589
                        "Assuming default fee parameters.", chanID)
×
4590
                chanUpdateAnn.BaseFee = uint32(
×
4591
                        f.cfg.DefaultRoutingPolicy.BaseFee,
×
4592
                )
×
4593
                chanUpdateAnn.FeeRate = uint32(
×
4594
                        f.cfg.DefaultRoutingPolicy.FeeRate,
×
4595
                )
×
4596
        }
4597

4598
        // With the channel update announcement constructed, we'll generate a
4599
        // signature that signs a double-sha digest of the announcement.
4600
        // This'll serve to authenticate this announcement and any other future
4601
        // updates we may send.
4602
        chanUpdateMsg, err := chanUpdateAnn.DataToSign()
3✔
4603
        if err != nil {
3✔
4604
                return nil, err
×
4605
        }
×
4606
        sig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanUpdateMsg, true)
3✔
4607
        if err != nil {
3✔
4608
                return nil, errors.Errorf("unable to generate channel "+
×
4609
                        "update announcement signature: %v", err)
×
4610
        }
×
4611
        chanUpdateAnn.Signature, err = lnwire.NewSigFromSignature(sig)
3✔
4612
        if err != nil {
3✔
4613
                return nil, errors.Errorf("unable to generate channel "+
×
4614
                        "update announcement signature: %v", err)
×
4615
        }
×
4616

4617
        // The channel existence proofs itself is currently announced in
4618
        // distinct message. In order to properly authenticate this message, we
4619
        // need two signatures: one under the identity public key used which
4620
        // signs the message itself and another signature of the identity
4621
        // public key under the funding key itself.
4622
        //
4623
        // TODO(roasbeef): use SignAnnouncement here instead?
4624
        chanAnnMsg, err := chanAnn.DataToSign()
3✔
4625
        if err != nil {
3✔
4626
                return nil, err
×
4627
        }
×
4628
        nodeSig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanAnnMsg, true)
3✔
4629
        if err != nil {
3✔
4630
                return nil, errors.Errorf("unable to generate node "+
×
4631
                        "signature for channel announcement: %v", err)
×
4632
        }
×
4633
        bitcoinSig, err := f.cfg.SignMessage(
3✔
4634
                localFundingKey.KeyLocator, chanAnnMsg, true,
3✔
4635
        )
3✔
4636
        if err != nil {
3✔
4637
                return nil, errors.Errorf("unable to generate bitcoin "+
×
4638
                        "signature for node public key: %v", err)
×
4639
        }
×
4640

4641
        // Finally, we'll generate the announcement proof which we'll use to
4642
        // provide the other side with the necessary signatures required to
4643
        // allow them to reconstruct the full channel announcement.
4644
        proof := &lnwire.AnnounceSignatures1{
3✔
4645
                ChannelID:      chanID,
3✔
4646
                ShortChannelID: shortChanID,
3✔
4647
        }
3✔
4648
        proof.NodeSignature, err = lnwire.NewSigFromSignature(nodeSig)
3✔
4649
        if err != nil {
3✔
4650
                return nil, err
×
4651
        }
×
4652
        proof.BitcoinSignature, err = lnwire.NewSigFromSignature(bitcoinSig)
3✔
4653
        if err != nil {
3✔
4654
                return nil, err
×
4655
        }
×
4656

4657
        return &chanAnnouncement{
3✔
4658
                chanAnn:       chanAnn,
3✔
4659
                chanUpdateAnn: chanUpdateAnn,
3✔
4660
                chanProof:     proof,
3✔
4661
        }, nil
3✔
4662
}
4663

4664
// announceChannel announces a newly created channel to the rest of the network
4665
// by crafting the two authenticated announcements required for the peers on
4666
// the network to recognize the legitimacy of the channel. The crafted
4667
// announcements are then sent to the channel router to handle broadcasting to
4668
// the network during its next trickle.
4669
// This method is synchronous and will return when all the network requests
4670
// finish, either successfully or with an error.
4671
func (f *Manager) announceChannel(localIDKey, remoteIDKey *btcec.PublicKey,
4672
        localFundingKey *keychain.KeyDescriptor,
4673
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4674
        chanID lnwire.ChannelID, chanType channeldb.ChannelType) error {
3✔
4675

3✔
4676
        // First, we'll create the batch of announcements to be sent upon
3✔
4677
        // initial channel creation. This includes the channel announcement
3✔
4678
        // itself, the channel update announcement, and our half of the channel
3✔
4679
        // proof needed to fully authenticate the channel.
3✔
4680
        //
3✔
4681
        // We can pass in zeroes for the min and max htlc policy, because we
3✔
4682
        // only use the channel announcement message from the returned struct.
3✔
4683
        ann, err := f.newChanAnnouncement(
3✔
4684
                localIDKey, remoteIDKey, localFundingKey, remoteFundingKey,
3✔
4685
                shortChanID, chanID, 0, 0, nil, chanType,
3✔
4686
        )
3✔
4687
        if err != nil {
3✔
4688
                log.Errorf("can't generate channel announcement: %v", err)
×
4689
                return err
×
4690
        }
×
4691

4692
        // We only send the channel proof announcement and the node announcement
4693
        // because addToGraph previously sent the ChannelAnnouncement and
4694
        // the ChannelUpdate announcement messages. The channel proof and node
4695
        // announcements are broadcast to the greater network.
4696
        errChan := f.cfg.SendAnnouncement(ann.chanProof)
3✔
4697
        select {
3✔
4698
        case err := <-errChan:
3✔
4699
                if err != nil {
6✔
4700
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4701
                                graph.ErrIgnored) {
3✔
4702

×
4703
                                log.Debugf("Graph rejected "+
×
4704
                                        "AnnounceSignatures: %v", err)
×
4705
                        } else {
3✔
4706
                                log.Errorf("Unable to send channel "+
3✔
4707
                                        "proof: %v", err)
3✔
4708
                                return err
3✔
4709
                        }
3✔
4710
                }
4711

4712
        case <-f.quit:
×
4713
                return ErrFundingManagerShuttingDown
×
4714
        }
4715

4716
        // Now that the channel is announced to the network, we will also
4717
        // obtain and send a node announcement. This is done since a node
4718
        // announcement is only accepted after a channel is known for that
4719
        // particular node, and this might be our first channel.
4720
        nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
3✔
4721
        if err != nil {
3✔
4722
                log.Errorf("can't generate node announcement: %v", err)
×
4723
                return err
×
4724
        }
×
4725

4726
        errChan = f.cfg.SendAnnouncement(&nodeAnn)
3✔
4727
        select {
3✔
4728
        case err := <-errChan:
3✔
4729
                if err != nil {
6✔
4730
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4731
                                graph.ErrIgnored) {
6✔
4732

3✔
4733
                                log.Debugf("Graph rejected "+
3✔
4734
                                        "NodeAnnouncement: %v", err)
3✔
4735
                        } else {
3✔
4736
                                log.Errorf("Unable to send node "+
×
4737
                                        "announcement: %v", err)
×
4738
                                return err
×
4739
                        }
×
4740
                }
4741

4742
        case <-f.quit:
×
4743
                return ErrFundingManagerShuttingDown
×
4744
        }
4745

4746
        return nil
3✔
4747
}
4748

4749
// InitFundingWorkflow sends a message to the funding manager instructing it
4750
// to initiate a single funder workflow with the source peer.
4751
func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg) {
3✔
4752
        f.fundingRequests <- msg
3✔
4753
}
3✔
4754

4755
// getUpfrontShutdownScript takes a user provided script and a getScript
4756
// function which can be used to generate an upfront shutdown script. If our
4757
// peer does not support the feature, this function will error if a non-zero
4758
// script was provided by the user, and return an empty script otherwise. If
4759
// our peer does support the feature, we will return the user provided script
4760
// if non-zero, or a freshly generated script if our node is configured to set
4761
// upfront shutdown scripts automatically.
4762
func getUpfrontShutdownScript(enableUpfrontShutdown bool, peer lnpeer.Peer,
4763
        script lnwire.DeliveryAddress,
4764
        getScript func(bool) (lnwire.DeliveryAddress, error)) (lnwire.DeliveryAddress,
4765
        error) {
3✔
4766

3✔
4767
        // Check whether the remote peer supports upfront shutdown scripts.
3✔
4768
        remoteUpfrontShutdown := peer.RemoteFeatures().HasFeature(
3✔
4769
                lnwire.UpfrontShutdownScriptOptional,
3✔
4770
        )
3✔
4771

3✔
4772
        // If the peer does not support upfront shutdown scripts, and one has been
3✔
4773
        // provided, return an error because the feature is not supported.
3✔
4774
        if !remoteUpfrontShutdown && len(script) != 0 {
3✔
4775
                return nil, errUpfrontShutdownScriptNotSupported
×
4776
        }
×
4777

4778
        // If the peer does not support upfront shutdown, return an empty address.
4779
        if !remoteUpfrontShutdown {
3✔
4780
                return nil, nil
×
4781
        }
×
4782

4783
        // If the user has provided an script and the peer supports the feature,
4784
        // return it. Note that user set scripts override the enable upfront
4785
        // shutdown flag.
4786
        if len(script) > 0 {
6✔
4787
                return script, nil
3✔
4788
        }
3✔
4789

4790
        // If we do not have setting of upfront shutdown script enabled, return
4791
        // an empty script.
4792
        if !enableUpfrontShutdown {
6✔
4793
                return nil, nil
3✔
4794
        }
3✔
4795

4796
        // We can safely send a taproot address iff, both sides have negotiated
4797
        // the shutdown-any-segwit feature.
4798
        taprootOK := peer.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
×
4799
                peer.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
×
4800

×
4801
        return getScript(taprootOK)
×
4802
}
4803

4804
// handleInitFundingMsg creates a channel reservation within the daemon's
4805
// wallet, then sends a funding request to the remote peer kicking off the
4806
// funding workflow.
4807
func (f *Manager) handleInitFundingMsg(msg *InitFundingMsg) {
3✔
4808
        var (
3✔
4809
                peerKey        = msg.Peer.IdentityKey()
3✔
4810
                localAmt       = msg.LocalFundingAmt
3✔
4811
                baseFee        = msg.BaseFee
3✔
4812
                feeRate        = msg.FeeRate
3✔
4813
                minHtlcIn      = msg.MinHtlcIn
3✔
4814
                remoteCsvDelay = msg.RemoteCsvDelay
3✔
4815
                maxValue       = msg.MaxValueInFlight
3✔
4816
                maxHtlcs       = msg.MaxHtlcs
3✔
4817
                maxCSV         = msg.MaxLocalCsv
3✔
4818
                chanReserve    = msg.RemoteChanReserve
3✔
4819
                outpoints      = msg.Outpoints
3✔
4820
        )
3✔
4821

3✔
4822
        // If no maximum CSV delay was set for this channel, we use our default
3✔
4823
        // value.
3✔
4824
        if maxCSV == 0 {
6✔
4825
                maxCSV = f.cfg.MaxLocalCSVDelay
3✔
4826
        }
3✔
4827

4828
        log.Infof("Initiating fundingRequest(local_amt=%v "+
3✔
4829
                "(subtract_fees=%v), push_amt=%v, chain_hash=%v, peer=%x, "+
3✔
4830
                "min_confs=%v)", localAmt, msg.SubtractFees, msg.PushAmt,
3✔
4831
                msg.ChainHash, peerKey.SerializeCompressed(), msg.MinConfs)
3✔
4832

3✔
4833
        // We set the channel flags to indicate whether we want this channel to
3✔
4834
        // be announced to the network.
3✔
4835
        var channelFlags lnwire.FundingFlag
3✔
4836
        if !msg.Private {
6✔
4837
                // This channel will be announced.
3✔
4838
                channelFlags = lnwire.FFAnnounceChannel
3✔
4839
        }
3✔
4840

4841
        // If the caller specified their own channel ID, then we'll use that.
4842
        // Otherwise we'll generate a fresh one as normal.  This will be used
4843
        // to track this reservation throughout its lifetime.
4844
        var chanID PendingChanID
3✔
4845
        if msg.PendingChanID == zeroID {
6✔
4846
                chanID = f.nextPendingChanID()
3✔
4847
        } else {
6✔
4848
                // If the user specified their own pending channel ID, then
3✔
4849
                // we'll ensure it doesn't collide with any existing pending
3✔
4850
                // channel ID.
3✔
4851
                chanID = msg.PendingChanID
3✔
4852
                if _, err := f.getReservationCtx(peerKey, chanID); err == nil {
3✔
4853
                        msg.Err <- fmt.Errorf("pendingChannelID(%x) "+
×
4854
                                "already present", chanID[:])
×
4855
                        return
×
4856
                }
×
4857
        }
4858

4859
        // Check whether the peer supports upfront shutdown, and get an address
4860
        // which should be used (either a user specified address or a new
4861
        // address from the wallet if our node is configured to set shutdown
4862
        // address by default).
4863
        shutdown, err := getUpfrontShutdownScript(
3✔
4864
                f.cfg.EnableUpfrontShutdown, msg.Peer, msg.ShutdownScript,
3✔
4865
                f.selectShutdownScript,
3✔
4866
        )
3✔
4867
        if err != nil {
3✔
4868
                msg.Err <- err
×
4869
                return
×
4870
        }
×
4871

4872
        // Initialize a funding reservation with the local wallet. If the
4873
        // wallet doesn't have enough funds to commit to this channel, then the
4874
        // request will fail, and be aborted.
4875
        //
4876
        // Before we init the channel, we'll also check to see what commitment
4877
        // format we can use with this peer. This is dependent on *both* us and
4878
        // the remote peer are signaling the proper feature bit.
4879
        chanType, commitType, err := negotiateCommitmentType(
3✔
4880
                msg.ChannelType, msg.Peer.LocalFeatures(),
3✔
4881
                msg.Peer.RemoteFeatures(),
3✔
4882
        )
3✔
4883
        if err != nil {
6✔
4884
                log.Errorf("channel type negotiation failed: %v", err)
3✔
4885
                msg.Err <- err
3✔
4886
                return
3✔
4887
        }
3✔
4888

4889
        var (
3✔
4890
                zeroConf bool
3✔
4891
                scid     bool
3✔
4892
        )
3✔
4893

3✔
4894
        if chanType != nil {
6✔
4895
                // Check if the returned chanType includes either the zero-conf
3✔
4896
                // or scid-alias bits.
3✔
4897
                featureVec := lnwire.RawFeatureVector(*chanType)
3✔
4898
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
3✔
4899
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
3✔
4900

3✔
4901
                // The option-scid-alias channel type for a public channel is
3✔
4902
                // disallowed.
3✔
4903
                if scid && !msg.Private {
3✔
4904
                        err = fmt.Errorf("option-scid-alias chantype for " +
×
4905
                                "public channel")
×
4906
                        log.Error(err)
×
4907
                        msg.Err <- err
×
4908

×
4909
                        return
×
4910
                }
×
4911
        }
4912

4913
        // First, we'll query the fee estimator for a fee that should get the
4914
        // commitment transaction confirmed by the next few blocks (conf target
4915
        // of 3). We target the near blocks here to ensure that we'll be able
4916
        // to execute a timely unilateral channel closure if needed.
4917
        commitFeePerKw, err := f.cfg.FeeEstimator.EstimateFeePerKW(3)
3✔
4918
        if err != nil {
3✔
4919
                msg.Err <- err
×
4920
                return
×
4921
        }
×
4922

4923
        // For anchor channels cap the initial commit fee rate at our defined
4924
        // maximum.
4925
        if commitType.HasAnchors() &&
3✔
4926
                commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
6✔
4927

3✔
4928
                commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate
3✔
4929
        }
3✔
4930

4931
        var scidFeatureVal bool
3✔
4932
        if hasFeatures(
3✔
4933
                msg.Peer.LocalFeatures(), msg.Peer.RemoteFeatures(),
3✔
4934
                lnwire.ScidAliasOptional,
3✔
4935
        ) {
6✔
4936

3✔
4937
                scidFeatureVal = true
3✔
4938
        }
3✔
4939

4940
        // At this point, if we have an AuxFundingController active, we'll check
4941
        // to see if we have a special tapscript root to use in our MuSig2
4942
        // funding output.
4943
        tapscriptRoot, err := fn.MapOptionZ(
3✔
4944
                f.cfg.AuxFundingController,
3✔
4945
                func(c AuxFundingController) AuxTapscriptResult {
3✔
4946
                        return c.DeriveTapscriptRoot(chanID)
×
4947
                },
×
4948
        ).Unpack()
4949
        if err != nil {
3✔
4950
                err = fmt.Errorf("error deriving tapscript root: %w", err)
×
4951
                log.Error(err)
×
4952
                msg.Err <- err
×
4953

×
4954
                return
×
4955
        }
×
4956

4957
        req := &lnwallet.InitFundingReserveMsg{
3✔
4958
                ChainHash:         &msg.ChainHash,
3✔
4959
                PendingChanID:     chanID,
3✔
4960
                NodeID:            peerKey,
3✔
4961
                NodeAddr:          msg.Peer.Address(),
3✔
4962
                SubtractFees:      msg.SubtractFees,
3✔
4963
                LocalFundingAmt:   localAmt,
3✔
4964
                RemoteFundingAmt:  0,
3✔
4965
                FundUpToMaxAmt:    msg.FundUpToMaxAmt,
3✔
4966
                MinFundAmt:        msg.MinFundAmt,
3✔
4967
                RemoteChanReserve: chanReserve,
3✔
4968
                Outpoints:         outpoints,
3✔
4969
                CommitFeePerKw:    commitFeePerKw,
3✔
4970
                FundingFeePerKw:   msg.FundingFeePerKw,
3✔
4971
                PushMSat:          msg.PushAmt,
3✔
4972
                Flags:             channelFlags,
3✔
4973
                MinConfs:          msg.MinConfs,
3✔
4974
                CommitType:        commitType,
3✔
4975
                ChanFunder:        msg.ChanFunder,
3✔
4976
                // Unconfirmed Utxos which are marked by the sweeper subsystem
3✔
4977
                // are excluded from the coin selection because they are not
3✔
4978
                // final and can be RBFed by the sweeper subsystem.
3✔
4979
                AllowUtxoForFunding: func(u lnwallet.Utxo) bool {
6✔
4980
                        // Utxos with at least 1 confirmation are safe to use
3✔
4981
                        // for channel openings because they don't bare the risk
3✔
4982
                        // of being replaced (BIP 125 RBF).
3✔
4983
                        if u.Confirmations > 0 {
6✔
4984
                                return true
3✔
4985
                        }
3✔
4986

4987
                        // Query the sweeper storage to make sure we don't use
4988
                        // an unconfirmed utxo still in use by the sweeper
4989
                        // subsystem.
4990
                        return !f.cfg.IsSweeperOutpoint(u.OutPoint)
3✔
4991
                },
4992
                ZeroConf:         zeroConf,
4993
                OptionScidAlias:  scid,
4994
                ScidAliasFeature: scidFeatureVal,
4995
                Memo:             msg.Memo,
4996
                TapscriptRoot:    tapscriptRoot,
4997
        }
4998

4999
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
3✔
5000
        if err != nil {
6✔
5001
                msg.Err <- err
3✔
5002
                return
3✔
5003
        }
3✔
5004

5005
        if zeroConf {
6✔
5006
                // Store the alias for zero-conf channels in the underlying
3✔
5007
                // partial channel state.
3✔
5008
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
3✔
5009
                if err != nil {
3✔
5010
                        msg.Err <- err
×
5011
                        return
×
5012
                }
×
5013

5014
                reservation.AddAlias(aliasScid)
3✔
5015
        }
5016

5017
        // Set our upfront shutdown address in the existing reservation.
5018
        reservation.SetOurUpfrontShutdown(shutdown)
3✔
5019

3✔
5020
        // Now that we have successfully reserved funds for this channel in the
3✔
5021
        // wallet, we can fetch the final channel capacity. This is done at
3✔
5022
        // this point since the final capacity might change in case of
3✔
5023
        // SubtractFees=true.
3✔
5024
        capacity := reservation.Capacity()
3✔
5025

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

3✔
5029
        // If the remote CSV delay was not set in the open channel request,
3✔
5030
        // we'll use the RequiredRemoteDelay closure to compute the delay we
3✔
5031
        // require given the total amount of funds within the channel.
3✔
5032
        if remoteCsvDelay == 0 {
6✔
5033
                remoteCsvDelay = f.cfg.RequiredRemoteDelay(capacity)
3✔
5034
        }
3✔
5035

5036
        // If no minimum HTLC value was specified, use the default one.
5037
        if minHtlcIn == 0 {
6✔
5038
                minHtlcIn = f.cfg.DefaultMinHtlcIn
3✔
5039
        }
3✔
5040

5041
        // If no max value was specified, use the default one.
5042
        if maxValue == 0 {
6✔
5043
                maxValue = f.cfg.RequiredRemoteMaxValue(capacity)
3✔
5044
        }
3✔
5045

5046
        if maxHtlcs == 0 {
6✔
5047
                maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
3✔
5048
        }
3✔
5049

5050
        // Once the reservation has been created, and indexed, queue a funding
5051
        // request to the remote peer, kicking off the funding workflow.
5052
        ourContribution := reservation.OurContribution()
3✔
5053

3✔
5054
        // Prepare the optional channel fee values from the initFundingMsg. If
3✔
5055
        // useBaseFee or useFeeRate are false the client did not provide fee
3✔
5056
        // values hence we assume default fee settings from the config.
3✔
5057
        forwardingPolicy := f.defaultForwardingPolicy(
3✔
5058
                ourContribution.ChannelStateBounds,
3✔
5059
        )
3✔
5060
        if baseFee != nil {
6✔
5061
                forwardingPolicy.BaseFee = lnwire.MilliSatoshi(*baseFee)
3✔
5062
        }
3✔
5063

5064
        if feeRate != nil {
6✔
5065
                forwardingPolicy.FeeRate = lnwire.MilliSatoshi(*feeRate)
3✔
5066
        }
3✔
5067

5068
        // Fetch our dust limit which is part of the default channel
5069
        // constraints, and log it.
5070
        ourDustLimit := ourContribution.DustLimit
3✔
5071

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

3✔
5074
        // If the channel reserve is not specified, then we calculate an
3✔
5075
        // appropriate amount here.
3✔
5076
        if chanReserve == 0 {
6✔
5077
                chanReserve = f.cfg.RequiredRemoteChanReserve(
3✔
5078
                        capacity, ourDustLimit,
3✔
5079
                )
3✔
5080
        }
3✔
5081

5082
        // If a pending channel map for this peer isn't already created, then
5083
        // we create one, ultimately allowing us to track this pending
5084
        // reservation within the target peer.
5085
        peerIDKey := newSerializedKey(peerKey)
3✔
5086
        f.resMtx.Lock()
3✔
5087
        if _, ok := f.activeReservations[peerIDKey]; !ok {
6✔
5088
                f.activeReservations[peerIDKey] = make(pendingChannels)
3✔
5089
        }
3✔
5090

5091
        resCtx := &reservationWithCtx{
3✔
5092
                chanAmt:           capacity,
3✔
5093
                forwardingPolicy:  *forwardingPolicy,
3✔
5094
                remoteCsvDelay:    remoteCsvDelay,
3✔
5095
                remoteMinHtlc:     minHtlcIn,
3✔
5096
                remoteMaxValue:    maxValue,
3✔
5097
                remoteMaxHtlcs:    maxHtlcs,
3✔
5098
                remoteChanReserve: chanReserve,
3✔
5099
                maxLocalCsv:       maxCSV,
3✔
5100
                channelType:       chanType,
3✔
5101
                reservation:       reservation,
3✔
5102
                peer:              msg.Peer,
3✔
5103
                updates:           msg.Updates,
3✔
5104
                err:               msg.Err,
3✔
5105
        }
3✔
5106
        f.activeReservations[peerIDKey][chanID] = resCtx
3✔
5107
        f.resMtx.Unlock()
3✔
5108

3✔
5109
        // Update the timestamp once the InitFundingMsg has been handled.
3✔
5110
        defer resCtx.updateTimestamp()
3✔
5111

3✔
5112
        // Check the sanity of the selected channel constraints.
3✔
5113
        bounds := &channeldb.ChannelStateBounds{
3✔
5114
                ChanReserve:      chanReserve,
3✔
5115
                MaxPendingAmount: maxValue,
3✔
5116
                MinHTLC:          minHtlcIn,
3✔
5117
                MaxAcceptedHtlcs: maxHtlcs,
3✔
5118
        }
3✔
5119
        commitParams := &channeldb.CommitmentParams{
3✔
5120
                DustLimit: ourDustLimit,
3✔
5121
                CsvDelay:  remoteCsvDelay,
3✔
5122
        }
3✔
5123
        err = lnwallet.VerifyConstraints(
3✔
5124
                bounds, commitParams, resCtx.maxLocalCsv, capacity,
3✔
5125
        )
3✔
5126
        if err != nil {
3✔
5127
                _, reserveErr := f.cancelReservationCtx(peerKey, chanID, false)
×
5128
                if reserveErr != nil {
×
5129
                        log.Errorf("unable to cancel reservation: %v",
×
5130
                                reserveErr)
×
5131
                }
×
5132

5133
                msg.Err <- err
×
5134
                return
×
5135
        }
5136

5137
        // When opening a script enforced channel lease, include the required
5138
        // expiry TLV record in our proposal.
5139
        var leaseExpiry *lnwire.LeaseExpiry
3✔
5140
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
6✔
5141
                leaseExpiry = new(lnwire.LeaseExpiry)
3✔
5142
                *leaseExpiry = lnwire.LeaseExpiry(reservation.LeaseExpiry())
3✔
5143
        }
3✔
5144

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

3✔
5148
        reservation.SetState(lnwallet.SentOpenChannel)
3✔
5149

3✔
5150
        fundingOpen := lnwire.OpenChannel{
3✔
5151
                ChainHash:             *f.cfg.Wallet.Cfg.NetParams.GenesisHash,
3✔
5152
                PendingChannelID:      chanID,
3✔
5153
                FundingAmount:         capacity,
3✔
5154
                PushAmount:            msg.PushAmt,
3✔
5155
                DustLimit:             ourDustLimit,
3✔
5156
                MaxValueInFlight:      maxValue,
3✔
5157
                ChannelReserve:        chanReserve,
3✔
5158
                HtlcMinimum:           minHtlcIn,
3✔
5159
                FeePerKiloWeight:      uint32(commitFeePerKw),
3✔
5160
                CsvDelay:              remoteCsvDelay,
3✔
5161
                MaxAcceptedHTLCs:      maxHtlcs,
3✔
5162
                FundingKey:            ourContribution.MultiSigKey.PubKey,
3✔
5163
                RevocationPoint:       ourContribution.RevocationBasePoint.PubKey,
3✔
5164
                PaymentPoint:          ourContribution.PaymentBasePoint.PubKey,
3✔
5165
                HtlcPoint:             ourContribution.HtlcBasePoint.PubKey,
3✔
5166
                DelayedPaymentPoint:   ourContribution.DelayBasePoint.PubKey,
3✔
5167
                FirstCommitmentPoint:  ourContribution.FirstCommitmentPoint,
3✔
5168
                ChannelFlags:          channelFlags,
3✔
5169
                UpfrontShutdownScript: shutdown,
3✔
5170
                ChannelType:           chanType,
3✔
5171
                LeaseExpiry:           leaseExpiry,
3✔
5172
        }
3✔
5173

3✔
5174
        if commitType.IsTaproot() {
6✔
5175
                fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
3✔
5176
                        ourContribution.LocalNonce.PubNonce,
3✔
5177
                )
3✔
5178
        }
3✔
5179

5180
        if err := msg.Peer.SendMessage(true, &fundingOpen); err != nil {
3✔
5181
                e := fmt.Errorf("unable to send funding request message: %w",
×
5182
                        err)
×
5183
                log.Errorf(e.Error())
×
5184

×
5185
                // Since we were unable to send the initial message to the peer
×
5186
                // and start the funding flow, we'll cancel this reservation.
×
5187
                _, err := f.cancelReservationCtx(peerKey, chanID, false)
×
5188
                if err != nil {
×
5189
                        log.Errorf("unable to cancel reservation: %v", err)
×
5190
                }
×
5191

5192
                msg.Err <- e
×
5193
                return
×
5194
        }
5195
}
5196

5197
// handleWarningMsg processes the warning which was received from remote peer.
5198
func (f *Manager) handleWarningMsg(peer lnpeer.Peer, msg *lnwire.Warning) {
×
5199
        log.Warnf("received warning message from peer %x: %v",
×
5200
                peer.IdentityKey().SerializeCompressed(), msg.Warning())
×
5201
}
×
5202

5203
// handleErrorMsg processes the error which was received from remote peer,
5204
// depending on the type of error we should do different clean up steps and
5205
// inform the user about it.
5206
func (f *Manager) handleErrorMsg(peer lnpeer.Peer, msg *lnwire.Error) {
3✔
5207
        chanID := msg.ChanID
3✔
5208
        peerKey := peer.IdentityKey()
3✔
5209

3✔
5210
        // First, we'll attempt to retrieve and cancel the funding workflow
3✔
5211
        // that this error was tied to. If we're unable to do so, then we'll
3✔
5212
        // exit early as this was an unwarranted error.
3✔
5213
        resCtx, err := f.cancelReservationCtx(peerKey, chanID, true)
3✔
5214
        if err != nil {
3✔
5215
                log.Warnf("Received error for non-existent funding "+
×
5216
                        "flow: %v (%v)", err, msg.Error())
×
5217
                return
×
5218
        }
×
5219

5220
        // If we did indeed find the funding workflow, then we'll return the
5221
        // error back to the caller (if any), and cancel the workflow itself.
5222
        fundingErr := fmt.Errorf("received funding error from %x: %v",
3✔
5223
                peerKey.SerializeCompressed(), msg.Error(),
3✔
5224
        )
3✔
5225
        log.Errorf(fundingErr.Error())
3✔
5226

3✔
5227
        // If this was a PSBT funding flow, the remote likely timed out because
3✔
5228
        // we waited too long. Return a nice error message to the user in that
3✔
5229
        // case so the user knows what's the problem.
3✔
5230
        if resCtx.reservation.IsPsbt() {
6✔
5231
                fundingErr = fmt.Errorf("%w: %v", chanfunding.ErrRemoteCanceled,
3✔
5232
                        fundingErr)
3✔
5233
        }
3✔
5234

5235
        resCtx.err <- fundingErr
3✔
5236
}
5237

5238
// pruneZombieReservations loops through all pending reservations and fails the
5239
// funding flow for any reservations that have not been updated since the
5240
// ReservationTimeout and are not locked waiting for the funding transaction.
5241
func (f *Manager) pruneZombieReservations() {
3✔
5242
        zombieReservations := make(pendingChannels)
3✔
5243

3✔
5244
        f.resMtx.RLock()
3✔
5245
        for _, pendingReservations := range f.activeReservations {
6✔
5246
                for pendingChanID, resCtx := range pendingReservations {
6✔
5247
                        if resCtx.isLocked() {
3✔
5248
                                continue
×
5249
                        }
5250

5251
                        // We don't want to expire PSBT funding reservations.
5252
                        // These reservations are always initiated by us and the
5253
                        // remote peer is likely going to cancel them after some
5254
                        // idle time anyway. So no need for us to also prune
5255
                        // them.
5256
                        sinceLastUpdate := time.Since(resCtx.lastUpdated)
3✔
5257
                        isExpired := sinceLastUpdate > f.cfg.ReservationTimeout
3✔
5258
                        if !resCtx.reservation.IsPsbt() && isExpired {
6✔
5259
                                zombieReservations[pendingChanID] = resCtx
3✔
5260
                        }
3✔
5261
                }
5262
        }
5263
        f.resMtx.RUnlock()
3✔
5264

3✔
5265
        for pendingChanID, resCtx := range zombieReservations {
6✔
5266
                err := fmt.Errorf("reservation timed out waiting for peer "+
3✔
5267
                        "(peer_id:%x, chan_id:%x)",
3✔
5268
                        resCtx.peer.IdentityKey().SerializeCompressed(),
3✔
5269
                        pendingChanID[:])
3✔
5270
                log.Warnf(err.Error())
3✔
5271

3✔
5272
                chanID := lnwire.NewChanIDFromOutPoint(
3✔
5273
                        *resCtx.reservation.FundingOutpoint(),
3✔
5274
                )
3✔
5275

3✔
5276
                // Create channel identifier and set the channel ID.
3✔
5277
                cid := newChanIdentifier(pendingChanID)
3✔
5278
                cid.setChanID(chanID)
3✔
5279

3✔
5280
                f.failFundingFlow(resCtx.peer, cid, err)
3✔
5281
        }
3✔
5282
}
5283

5284
// cancelReservationCtx does all needed work in order to securely cancel the
5285
// reservation.
5286
func (f *Manager) cancelReservationCtx(peerKey *btcec.PublicKey,
5287
        pendingChanID PendingChanID,
5288
        byRemote bool) (*reservationWithCtx, error) {
3✔
5289

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

3✔
5293
        peerIDKey := newSerializedKey(peerKey)
3✔
5294
        f.resMtx.Lock()
3✔
5295
        defer f.resMtx.Unlock()
3✔
5296

3✔
5297
        nodeReservations, ok := f.activeReservations[peerIDKey]
3✔
5298
        if !ok {
6✔
5299
                // No reservations for this node.
3✔
5300
                return nil, errors.Errorf("no active reservations for peer(%x)",
3✔
5301
                        peerIDKey[:])
3✔
5302
        }
3✔
5303

5304
        ctx, ok := nodeReservations[pendingChanID]
3✔
5305
        if !ok {
3✔
5306
                return nil, errors.Errorf("unknown channel (id: %x) for "+
×
5307
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
×
5308
        }
×
5309

5310
        // If the reservation was a PSBT funding flow and it was canceled by the
5311
        // remote peer, then we need to thread through a different error message
5312
        // to the subroutine that's waiting for the user input so it can return
5313
        // a nice error message to the user.
5314
        if ctx.reservation.IsPsbt() && byRemote {
6✔
5315
                ctx.reservation.RemoteCanceled()
3✔
5316
        }
3✔
5317

5318
        if err := ctx.reservation.Cancel(); err != nil {
3✔
5319
                return nil, errors.Errorf("unable to cancel reservation: %v",
×
5320
                        err)
×
5321
        }
×
5322

5323
        delete(nodeReservations, pendingChanID)
3✔
5324

3✔
5325
        // If this was the last active reservation for this peer, delete the
3✔
5326
        // peer's entry altogether.
3✔
5327
        if len(nodeReservations) == 0 {
6✔
5328
                delete(f.activeReservations, peerIDKey)
3✔
5329
        }
3✔
5330
        return ctx, nil
3✔
5331
}
5332

5333
// deleteReservationCtx deletes the reservation uniquely identified by the
5334
// target public key of the peer, and the specified pending channel ID.
5335
func (f *Manager) deleteReservationCtx(peerKey *btcec.PublicKey,
5336
        pendingChanID PendingChanID) {
3✔
5337

3✔
5338
        peerIDKey := newSerializedKey(peerKey)
3✔
5339
        f.resMtx.Lock()
3✔
5340
        defer f.resMtx.Unlock()
3✔
5341

3✔
5342
        nodeReservations, ok := f.activeReservations[peerIDKey]
3✔
5343
        if !ok {
3✔
5344
                // No reservations for this node.
×
5345
                return
×
5346
        }
×
5347
        delete(nodeReservations, pendingChanID)
3✔
5348

3✔
5349
        // If this was the last active reservation for this peer, delete the
3✔
5350
        // peer's entry altogether.
3✔
5351
        if len(nodeReservations) == 0 {
6✔
5352
                delete(f.activeReservations, peerIDKey)
3✔
5353
        }
3✔
5354
}
5355

5356
// getReservationCtx returns the reservation context for a particular pending
5357
// channel ID for a target peer.
5358
func (f *Manager) getReservationCtx(peerKey *btcec.PublicKey,
5359
        pendingChanID PendingChanID) (*reservationWithCtx, error) {
3✔
5360

3✔
5361
        peerIDKey := newSerializedKey(peerKey)
3✔
5362
        f.resMtx.RLock()
3✔
5363
        resCtx, ok := f.activeReservations[peerIDKey][pendingChanID]
3✔
5364
        f.resMtx.RUnlock()
3✔
5365

3✔
5366
        if !ok {
6✔
5367
                return nil, errors.Errorf("unknown channel (id: %x) for "+
3✔
5368
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
3✔
5369
        }
3✔
5370

5371
        return resCtx, nil
3✔
5372
}
5373

5374
// IsPendingChannel returns a boolean indicating whether the channel identified
5375
// by the pendingChanID and given peer is pending, meaning it is in the process
5376
// of being funded. After the funding transaction has been confirmed, the
5377
// channel will receive a new, permanent channel ID, and will no longer be
5378
// considered pending.
5379
func (f *Manager) IsPendingChannel(pendingChanID PendingChanID,
5380
        peer lnpeer.Peer) bool {
3✔
5381

3✔
5382
        peerIDKey := newSerializedKey(peer.IdentityKey())
3✔
5383
        f.resMtx.RLock()
3✔
5384
        _, ok := f.activeReservations[peerIDKey][pendingChanID]
3✔
5385
        f.resMtx.RUnlock()
3✔
5386

3✔
5387
        return ok
3✔
5388
}
3✔
5389

5390
func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
3✔
5391
        var tmp btcec.JacobianPoint
3✔
5392
        pub.AsJacobian(&tmp)
3✔
5393
        tmp.ToAffine()
3✔
5394
        return btcec.NewPublicKey(&tmp.X, &tmp.Y)
3✔
5395
}
3✔
5396

5397
// defaultForwardingPolicy returns the default forwarding policy based on the
5398
// default routing policy and our local channel constraints.
5399
func (f *Manager) defaultForwardingPolicy(
5400
        bounds channeldb.ChannelStateBounds) *models.ForwardingPolicy {
3✔
5401

3✔
5402
        return &models.ForwardingPolicy{
3✔
5403
                MinHTLCOut:    bounds.MinHTLC,
3✔
5404
                MaxHTLC:       bounds.MaxPendingAmount,
3✔
5405
                BaseFee:       f.cfg.DefaultRoutingPolicy.BaseFee,
3✔
5406
                FeeRate:       f.cfg.DefaultRoutingPolicy.FeeRate,
3✔
5407
                TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
3✔
5408
        }
3✔
5409
}
3✔
5410

5411
// saveInitialForwardingPolicy saves the forwarding policy for the provided
5412
// chanPoint in the channelOpeningStateBucket.
5413
func (f *Manager) saveInitialForwardingPolicy(chanID lnwire.ChannelID,
5414
        forwardingPolicy *models.ForwardingPolicy) error {
3✔
5415

3✔
5416
        return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
3✔
5417
                chanID, forwardingPolicy,
3✔
5418
        )
3✔
5419
}
3✔
5420

5421
// getInitialForwardingPolicy fetches the initial forwarding policy for a given
5422
// channel id from the database which will be applied during the channel
5423
// announcement phase.
5424
func (f *Manager) getInitialForwardingPolicy(
5425
        chanID lnwire.ChannelID) (*models.ForwardingPolicy, error) {
3✔
5426

3✔
5427
        return f.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
3✔
5428
}
3✔
5429

5430
// deleteInitialForwardingPolicy removes channel fees for this chanID from
5431
// the database.
5432
func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
3✔
5433
        return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
3✔
5434
}
3✔
5435

5436
// saveChannelOpeningState saves the channelOpeningState for the provided
5437
// chanPoint to the channelOpeningStateBucket.
5438
func (f *Manager) saveChannelOpeningState(chanPoint *wire.OutPoint,
5439
        state channelOpeningState, shortChanID *lnwire.ShortChannelID) error {
3✔
5440

3✔
5441
        var outpointBytes bytes.Buffer
3✔
5442
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
3✔
5443
                return err
×
5444
        }
×
5445

5446
        // Save state and the uint64 representation of the shortChanID
5447
        // for later use.
5448
        scratch := make([]byte, 10)
3✔
5449
        byteOrder.PutUint16(scratch[:2], uint16(state))
3✔
5450
        byteOrder.PutUint64(scratch[2:], shortChanID.ToUint64())
3✔
5451

3✔
5452
        return f.cfg.ChannelDB.SaveChannelOpeningState(
3✔
5453
                outpointBytes.Bytes(), scratch,
3✔
5454
        )
3✔
5455
}
5456

5457
// getChannelOpeningState fetches the channelOpeningState for the provided
5458
// chanPoint from the database, or returns ErrChannelNotFound if the channel
5459
// is not found.
5460
func (f *Manager) getChannelOpeningState(chanPoint *wire.OutPoint) (
5461
        channelOpeningState, *lnwire.ShortChannelID, error) {
3✔
5462

3✔
5463
        var outpointBytes bytes.Buffer
3✔
5464
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
3✔
5465
                return 0, nil, err
×
5466
        }
×
5467

5468
        value, err := f.cfg.ChannelDB.GetChannelOpeningState(
3✔
5469
                outpointBytes.Bytes(),
3✔
5470
        )
3✔
5471
        if err != nil {
6✔
5472
                return 0, nil, err
3✔
5473
        }
3✔
5474

5475
        state := channelOpeningState(byteOrder.Uint16(value[:2]))
3✔
5476
        shortChanID := lnwire.NewShortChanIDFromInt(byteOrder.Uint64(value[2:]))
3✔
5477
        return state, &shortChanID, nil
3✔
5478
}
5479

5480
// deleteChannelOpeningState removes any state for chanPoint from the database.
5481
func (f *Manager) deleteChannelOpeningState(chanPoint *wire.OutPoint) error {
3✔
5482
        var outpointBytes bytes.Buffer
3✔
5483
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
3✔
5484
                return err
×
5485
        }
×
5486

5487
        return f.cfg.ChannelDB.DeleteChannelOpeningState(
3✔
5488
                outpointBytes.Bytes(),
3✔
5489
        )
3✔
5490
}
5491

5492
// selectShutdownScript selects the shutdown script we should send to the peer.
5493
// If we can use taproot, then we prefer that, otherwise we'll use a p2wkh
5494
// script.
5495
func (f *Manager) selectShutdownScript(taprootOK bool,
5496
) (lnwire.DeliveryAddress, error) {
×
5497

×
5498
        addrType := lnwallet.WitnessPubKey
×
5499
        if taprootOK {
×
5500
                addrType = lnwallet.TaprootPubkey
×
5501
        }
×
5502

5503
        addr, err := f.cfg.Wallet.NewAddress(
×
5504
                addrType, false, lnwallet.DefaultAccountName,
×
5505
        )
×
5506
        if err != nil {
×
5507
                return nil, err
×
5508
        }
×
5509

5510
        return txscript.PayToAddrScript(addr)
×
5511
}
5512

5513
// waitForPeerOnline blocks until the peer specified by peerPubkey comes online
5514
// and then returns the online peer.
5515
func (f *Manager) waitForPeerOnline(peerPubkey *btcec.PublicKey) (lnpeer.Peer,
5516
        error) {
3✔
5517

3✔
5518
        peerChan := make(chan lnpeer.Peer, 1)
3✔
5519

3✔
5520
        var peerKey [33]byte
3✔
5521
        copy(peerKey[:], peerPubkey.SerializeCompressed())
3✔
5522

3✔
5523
        f.cfg.NotifyWhenOnline(peerKey, peerChan)
3✔
5524

3✔
5525
        var peer lnpeer.Peer
3✔
5526
        select {
3✔
5527
        case peer = <-peerChan:
3✔
5528
        case <-f.quit:
×
5529
                return peer, ErrFundingManagerShuttingDown
×
5530
        }
5531
        return peer, nil
3✔
5532
}
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