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

lightningnetwork / lnd / 17340972986

30 Aug 2025 07:20AM UTC coverage: 66.741% (+9.4%) from 57.321%
17340972986

Pull #9677

github

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

132 of 173 new or added lines in 5 files covered. (76.3%)

12 existing lines in 6 files now uncovered.

136038 of 203829 relevant lines covered (66.74%)

21470.79 hits per line

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

73.95
/funding/manager.go
1
package funding
2

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

13
        "github.com/btcsuite/btcd/blockchain"
14
        "github.com/btcsuite/btcd/btcec/v2"
15
        "github.com/btcsuite/btcd/btcec/v2/ecdsa"
16
        "github.com/btcsuite/btcd/btcec/v2/schnorr/musig2"
17
        "github.com/btcsuite/btcd/btcutil"
18
        "github.com/btcsuite/btcd/chaincfg/chainhash"
19
        "github.com/btcsuite/btcd/txscript"
20
        "github.com/btcsuite/btcd/wire"
21
        "github.com/davecgh/go-spew/spew"
22
        "github.com/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 {
371✔
67
        scratch := make([]byte, 4)
371✔
68

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

73
        byteOrder.PutUint32(scratch, o.Index)
371✔
74
        _, err := w.Write(scratch)
371✔
75
        return err
371✔
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 {
6✔
175
        r.updateMtx.RLock()
6✔
176
        defer r.updateMtx.RUnlock()
6✔
177

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

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

140✔
187
        r.lastUpdated = time.Now()
140✔
188
}
140✔
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 {
394✔
327
        var s serializedPubKey
394✔
328
        copy(s[:], pubKey.SerializeCompressed())
394✔
329
        return s
394✔
330
}
394✔
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)
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)
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)
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) {
112✔
683
        return &Manager{
112✔
684
                cfg:       &cfg,
112✔
685
                chanIDKey: cfg.TempChanIDSeed,
112✔
686
                activeReservations: make(
112✔
687
                        map[serializedPubKey]pendingChannels,
112✔
688
                ),
112✔
689
                signedReservations: make(
112✔
690
                        map[lnwire.ChannelID][32]byte,
112✔
691
                ),
112✔
692
                fundingMsgs: make(
112✔
693
                        chan *fundingMsg, msgBufferSize,
112✔
694
                ),
112✔
695
                fundingRequests: make(
112✔
696
                        chan *InitFundingMsg, msgBufferSize,
112✔
697
                ),
112✔
698
                localDiscoverySignals: &lnutils.SyncMap[
112✔
699
                        lnwire.ChannelID, chan struct{},
112✔
700
                ]{},
112✔
701
                handleChannelReadyBarriers: &lnutils.SyncMap[
112✔
702
                        lnwire.ChannelID, struct{},
112✔
703
                ]{},
112✔
704
                pendingMusigNonces: make(
112✔
705
                        map[lnwire.ChannelID]*musig2.Nonces,
112✔
706
                ),
112✔
707
                quit: make(chan struct{}),
112✔
708
        }, nil
112✔
709
}
112✔
710

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

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

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

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

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

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

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

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

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

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

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

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

796
        return nil
109✔
797
}
798

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

37✔
1196
                return nil
37✔
1197

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

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

1221
                        return nil
27✔
1222
                }
1223

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

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

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

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

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

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

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

27✔
1277
                return nil
27✔
1278
        }
1279

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

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

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

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

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

1320
                // Inform the ChannelNotifier that the channel has transitioned
1321
                // from pending open to open.
1322
                f.cfg.NotifyOpenChannelEvent(
7✔
1323
                        channel.FundingOutpoint, channel.IdentityPub,
7✔
1324
                )
7✔
1325

7✔
1326
                // Find and close the discoverySignal for this channel such
7✔
1327
                // that ChannelReady messages will be processed.
7✔
1328
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
7✔
1329
                discoverySignal, ok := f.localDiscoverySignals.Load(chanID)
7✔
1330
                if ok {
14✔
1331
                        close(discoverySignal)
7✔
1332
                }
7✔
1333

1334
                return nil
7✔
1335
        }
1336

1337
        confChannel, err := f.waitForFundingWithTimeout(channel)
56✔
1338
        if err == ErrConfirmationTimeout {
61✔
1339
                return f.fundingTimeout(channel, pendingChanID)
5✔
1340
        } else if err != nil {
83✔
1341
                return fmt.Errorf("error waiting for funding "+
24✔
1342
                        "confirmation for ChannelPoint(%v): %v",
24✔
1343
                        channel.FundingOutpoint, err)
24✔
1344
        }
24✔
1345

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

2✔
1353
                if channel.NumConfsRequired > maturity {
2✔
1354
                        numCoinbaseConfs = uint32(channel.NumConfsRequired)
×
1355
                }
×
1356

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

×
1364
                        return err
×
1365
                }
×
1366

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

×
1376
                        return err
×
1377
                }
×
1378

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

1388
                case <-f.quit:
×
1389
                        return ErrFundingManagerShuttingDown
×
1390
                }
1391
        }
1392

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

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

1405
        return nil
33✔
1406
}
1407

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

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

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

58✔
1435
        amt := msg.FundingAmount
58✔
1436

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

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

58✔
1453
        // Create the channel identifier.
58✔
1454
        cid := newChanIdentifier(msg.PendingChannelID)
58✔
1455

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

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

1476
        // TODO(roasbeef): modify to only accept a _single_ pending channel per
1477
        // block unless white listed
1478
        if numPending >= f.cfg.MaxPendingChannels {
65✔
1479
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
7✔
1480

7✔
1481
                return
7✔
1482
        }
7✔
1483

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

1491
        if len(pendingChans) > pendingChansLimit {
54✔
1492
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
×
1493
                return
×
1494
        }
×
1495

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

1509
        // Ensure that the remote party respects our maximum channel size.
1510
        if amt > f.cfg.MaxChanSize {
59✔
1511
                f.failFundingFlow(
5✔
1512
                        peer, cid,
5✔
1513
                        lnwallet.ErrChanTooLarge(amt, f.cfg.MaxChanSize),
5✔
1514
                )
5✔
1515
                return
5✔
1516
        }
5✔
1517

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

1528
        // If request specifies non-zero push amount and 'rejectpush' is set,
1529
        // signal an error.
1530
        if f.cfg.RejectPush && msg.PushAmount > 0 {
53✔
1531
                f.failFundingFlow(peer, cid, lnwallet.ErrNonZeroPushAmount())
1✔
1532
                return
1✔
1533
        }
1✔
1534

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

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

1550
        log.Infof("Recv'd fundingRequest(amt=%v, push=%v, delay=%v, "+
51✔
1551
                "pendingId=%x) from peer(%x)", amt, msg.PushAmount,
51✔
1552
                msg.CsvDelay, msg.PendingChannelID,
51✔
1553
                peer.IdentityKey().SerializeCompressed())
51✔
1554

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

1576
        var scidFeatureVal bool
51✔
1577
        if hasFeatures(
51✔
1578
                peer.LocalFeatures(), peer.RemoteFeatures(),
51✔
1579
                lnwire.ScidAliasOptional,
51✔
1580
        ) {
57✔
1581

6✔
1582
                scidFeatureVal = true
6✔
1583
        }
6✔
1584

1585
        var (
51✔
1586
                zeroConf bool
51✔
1587
                scid     bool
51✔
1588
        )
51✔
1589

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

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

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

1628
                        // Set zeroConf to true to enable the zero-conf flow.
1629
                        zeroConf = true
×
1630
                }
1631
        }
1632

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

×
1644
                return
×
1645

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

×
1654
                return
×
1655
        }
1656

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

×
1671
                return
×
1672
        }
×
1673

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

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

1700
        log.Debugf("Initialized channel reservation: zeroConf=%v, psbt=%v, "+
51✔
1701
                "cannedShim=%v", reservation.IsZeroConf(),
51✔
1702
                reservation.IsPsbt(), reservation.IsCannedShim())
51✔
1703

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

1714
                reservation.AddAlias(aliasScid)
5✔
1715
        }
1716

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

1728
        // We'll ignore the min_depth calculated above if this is a zero-conf
1729
        // channel.
1730
        if zeroConf {
56✔
1731
                numConfsReq = 0
5✔
1732
        }
5✔
1733

1734
        reservation.SetNumConfsRequired(numConfsReq)
51✔
1735

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

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

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

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

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

1798
        log.Infof("Requiring %v confirmations for pendingChan(%x): "+
50✔
1799
                "amt=%v, push_amt=%v, committype=%v, upfrontShutdown=%x",
50✔
1800
                numConfsReq, msg.PendingChannelID, amt, msg.PushAmount,
50✔
1801
                commitType, msg.UpfrontShutdownScript)
50✔
1802

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

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

1822
        chanReserve := f.cfg.RequiredRemoteChanReserve(amt, maxDustLimit)
50✔
1823
        if acceptorResp.Reserve != 0 {
50✔
1824
                chanReserve = acceptorResp.Reserve
×
1825
        }
×
1826

1827
        remoteMaxValue := f.cfg.RequiredRemoteMaxValue(amt)
50✔
1828
        if acceptorResp.InFlightTotal != 0 {
50✔
1829
                remoteMaxValue = acceptorResp.InFlightTotal
×
1830
        }
×
1831

1832
        maxHtlcs := f.cfg.RequiredRemoteMaxHTLCs(amt)
50✔
1833
        if acceptorResp.HtlcLimit != 0 {
50✔
1834
                maxHtlcs = acceptorResp.HtlcLimit
×
1835
        }
×
1836

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

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

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

50✔
1876
        // Update the timestamp once the fundingOpenMsg has been handled.
50✔
1877
        defer resCtx.updateTimestamp()
50✔
1878

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

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

50✔
1916
        if resCtx.reservation.IsTaproot() {
55✔
1917
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
5✔
1918
                if err != nil {
5✔
1919
                        log.Error(errNoLocalNonce)
×
1920

×
1921
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
1922

×
1923
                        return
×
1924
                }
×
1925

1926
                remoteContribution.LocalNonce = &musig2.Nonces{
5✔
1927
                        PubNonce: localNonce,
5✔
1928
                }
5✔
1929
        }
1930

1931
        err = reservation.ProcessSingleContribution(remoteContribution)
50✔
1932
        if err != nil {
56✔
1933
                log.Errorf("unable to add contribution reservation: %v", err)
6✔
1934
                f.failFundingFlow(peer, cid, err)
6✔
1935
                return
6✔
1936
        }
6✔
1937

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

44✔
1947
        reservation.SetState(lnwallet.SentAcceptChannel)
44✔
1948

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

44✔
1971
        if commitType.IsTaproot() {
49✔
1972
                fundingAccept.LocalNonce = lnwire.SomeMusig2Nonce(
5✔
1973
                        ourContribution.LocalNonce.PubNonce,
5✔
1974
                )
5✔
1975
        }
5✔
1976

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

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

36✔
1992
        pendingChanID := msg.PendingChannelID
36✔
1993
        peerKey := peer.IdentityKey()
36✔
1994
        var peerKeyBytes []byte
36✔
1995
        if peerKey != nil {
72✔
1996
                peerKeyBytes = peerKey.SerializeCompressed()
36✔
1997
        }
36✔
1998

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

2006
        // Update the timestamp once the fundingAcceptMsg has been handled.
2007
        defer resCtx.updateTimestamp()
36✔
2008

36✔
2009
        if resCtx.reservation.State() != lnwallet.SentOpenChannel {
36✔
2010
                return
×
2011
        }
×
2012

2013
        log.Infof("Recv'd fundingResponse for pending_id(%x)",
36✔
2014
                pendingChanID[:])
36✔
2015

36✔
2016
        // Create the channel identifier.
36✔
2017
        cid := newChanIdentifier(msg.PendingChannelID)
36✔
2018

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

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

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

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

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

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

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

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

×
2112
                minDepth = 1
×
2113
        }
×
2114

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

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

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

33✔
2176
        if resCtx.reservation.IsTaproot() {
38✔
2177
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
5✔
2178
                if err != nil {
5✔
2179
                        log.Error(errNoLocalNonce)
×
2180

×
2181
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
2182

×
2183
                        return
×
2184
                }
×
2185

2186
                remoteContribution.LocalNonce = &musig2.Nonces{
5✔
2187
                        PubNonce: localNonce,
5✔
2188
                }
5✔
2189
        }
2190

2191
        err = resCtx.reservation.ProcessContribution(remoteContribution)
33✔
2192

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

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

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

3✔
2254
                        f.waitForPsbt(psbtIntent, resCtx, cid)
3✔
2255
                }()
3✔
2256

2257
                // With the new goroutine spawned, we can now exit to unblock
2258
                // the main event loop.
2259
                return
3✔
2260
        }
2261

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

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

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

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

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

2307
                // Nil error means the flow continues normally now.
2308
                case nil:
3✔
2309

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

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

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

2349
                // We are now ready to continue the funding flow.
2350
                f.continueFundingAccept(resCtx, cid)
3✔
2351

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

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

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

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

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

33✔
2390
        log.Infof("Generated ChannelPoint(%v) for pending_id(%x)", outPoint,
33✔
2391
                cid.tempChanID[:])
33✔
2392

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

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

33✔
2407
        // Send the FundingCreated msg.
33✔
2408
        fundingCreated := &lnwire.FundingCreated{
33✔
2409
                PendingChannelID: cid.tempChanID,
33✔
2410
                FundingPoint:     *outPoint,
33✔
2411
        }
33✔
2412

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

×
2423
                        return
×
2424
                }
×
2425

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

2438
        resCtx.reservation.SetState(lnwallet.SentFundingCreated)
33✔
2439

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

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

31✔
2457
        peerKey := peer.IdentityKey()
31✔
2458
        pendingChanID := msg.PendingChannelID
31✔
2459

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

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

31✔
2475
        if resCtx.reservation.State() != lnwallet.SentAcceptChannel {
31✔
2476
                return
×
2477
        }
×
2478

2479
        // Create the channel identifier without setting the active channel ID.
2480
        cid := newChanIdentifier(pendingChanID)
31✔
2481

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

×
2491
                        return
×
2492
                }
×
2493

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

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

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

2543
        // Get forwarding policy before deleting the reservation context.
2544
        forwardingPolicy := resCtx.forwardingPolicy
31✔
2545

31✔
2546
        // The channel is marked IsPending in the database, and can be removed
31✔
2547
        // from the set of active reservations.
31✔
2548
        f.deleteReservationCtx(peerKey, cid.tempChanID)
31✔
2549

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

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

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

31✔
2584
        fundingSigned := &lnwire.FundingSigned{}
31✔
2585

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

×
2598
                        return
×
2599
                }
×
2600

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

×
2611
                        return
×
2612
                }
×
2613
        }
2614

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

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

31✔
2628
        fundingSigned.ChanID = cid.chanID
31✔
2629

31✔
2630
        log.Infof("sending FundingSigned for pending_id(%x) over "+
31✔
2631
                "ChannelPoint(%v)", pendingChanID[:], fundingOut)
31✔
2632

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

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

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

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

31✔
2663
        // Inform the ChannelNotifier that the channel has entered
31✔
2664
        // pending open state.
31✔
2665
        f.cfg.NotifyPendingOpenChannelEvent(
31✔
2666
                fundingOut, completeChan, completeChan.IdentityPub,
31✔
2667
        )
31✔
2668

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

2689
// funderProcessFundingSigned processes the final message received in a single
2690
// funder workflow. Once this message is processed, the funding transaction is
2691
// broadcast. Once the funding transaction reaches a sufficient number of
2692
// confirmations, a message is sent to the responding peer along with a compact
2693
// encoding of the location of the channel within the blockchain.
2694
func (f *Manager) funderProcessFundingSigned(peer lnpeer.Peer,
2695
        msg *lnwire.FundingSigned) {
31✔
2696

31✔
2697
        // As the funding signed message will reference the reservation by its
31✔
2698
        // permanent channel ID, we'll need to perform an intermediate look up
31✔
2699
        // before we can obtain the reservation.
31✔
2700
        f.resMtx.Lock()
31✔
2701
        pendingChanID, ok := f.signedReservations[msg.ChanID]
31✔
2702
        delete(f.signedReservations, msg.ChanID)
31✔
2703
        f.resMtx.Unlock()
31✔
2704

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

31✔
2716
        // If the pending channel ID is not found, fail the funding flow.
31✔
2717
        if !ok {
31✔
2718
                // NOTE: we directly overwrite the pending channel ID here for
×
2719
                // this rare case since we don't have a valid pending channel
×
2720
                // ID.
×
2721
                cid.tempChanID = msg.ChanID
×
2722

×
2723
                err := fmt.Errorf("unable to find signed reservation for "+
×
2724
                        "chan_id=%x", msg.ChanID)
×
2725
                log.Warnf(err.Error())
×
2726
                f.failFundingFlow(peer, cid, err)
×
2727
                return
×
2728
        }
×
2729

2730
        peerKey := peer.IdentityKey()
31✔
2731
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
31✔
2732
        if err != nil {
31✔
2733
                log.Warnf("Unable to find reservation (peer_id:%v, "+
×
2734
                        "chan_id:%x)", peerKey, pendingChanID[:])
×
2735
                // TODO: add ErrChanNotFound?
×
2736
                f.failFundingFlow(peer, cid, err)
×
2737
                return
×
2738
        }
×
2739

2740
        if resCtx.reservation.State() != lnwallet.SentFundingCreated {
31✔
2741
                err := fmt.Errorf("unable to find reservation for chan_id=%x",
×
2742
                        msg.ChanID)
×
2743
                f.failFundingFlow(peer, cid, err)
×
2744

×
2745
                return
×
2746
        }
×
2747

2748
        // Create an entry in the local discovery map so we can ensure that we
2749
        // process the channel confirmation fully before we receive a
2750
        // channel_ready message.
2751
        fundingPoint := resCtx.reservation.FundingOutpoint()
31✔
2752
        permChanID := lnwire.NewChanIDFromOutPoint(*fundingPoint)
31✔
2753
        f.localDiscoverySignals.Store(permChanID, make(chan struct{}))
31✔
2754

31✔
2755
        // We have to store the forwardingPolicy before the reservation context
31✔
2756
        // is deleted. The policy will then be read and applied in
31✔
2757
        // newChanAnnouncement.
31✔
2758
        err = f.saveInitialForwardingPolicy(
31✔
2759
                permChanID, &resCtx.forwardingPolicy,
31✔
2760
        )
31✔
2761
        if err != nil {
31✔
2762
                log.Errorf("Unable to store the forwarding policy: %v", err)
×
2763
        }
×
2764

2765
        // For taproot channels, the commit signature is actually the partial
2766
        // signature. Otherwise, we can convert the ECDSA commit signature into
2767
        // our internal input.Signature type.
2768
        var commitSig input.Signature
31✔
2769
        if resCtx.reservation.IsTaproot() {
36✔
2770
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
5✔
2771
                if err != nil {
5✔
2772
                        f.failFundingFlow(peer, cid, err)
×
2773

×
2774
                        return
×
2775
                }
×
2776

2777
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
5✔
2778
                        &partialSig,
5✔
2779
                )
5✔
2780
        } else {
29✔
2781
                commitSig, err = msg.CommitSig.ToSignature()
29✔
2782
                if err != nil {
29✔
2783
                        log.Errorf("unable to parse signature: %v", err)
×
2784
                        f.failFundingFlow(peer, cid, err)
×
2785
                        return
×
2786
                }
×
2787
        }
2788

2789
        completeChan, err := resCtx.reservation.CompleteReservation(
31✔
2790
                nil, commitSig,
31✔
2791
        )
31✔
2792
        if err != nil {
31✔
2793
                log.Errorf("Unable to complete reservation sign "+
×
2794
                        "complete: %v", err)
×
2795
                f.failFundingFlow(peer, cid, err)
×
2796
                return
×
2797
        }
×
2798

2799
        // The channel is now marked IsPending in the database, and we can
2800
        // delete it from our set of active reservations.
2801
        f.deleteReservationCtx(peerKey, pendingChanID)
31✔
2802

31✔
2803
        // Broadcast the finalized funding transaction to the network, but only
31✔
2804
        // if we actually have the funding transaction.
31✔
2805
        if completeChan.ChanType.HasFundingTx() {
61✔
2806
                fundingTx := completeChan.FundingTxn
30✔
2807
                var fundingTxBuf bytes.Buffer
30✔
2808
                if err := fundingTx.Serialize(&fundingTxBuf); err != nil {
30✔
2809
                        log.Errorf("Unable to serialize funding "+
×
2810
                                "transaction %v: %v", fundingTx.TxHash(), err)
×
2811

×
2812
                        // Clear the buffer of any bytes that were written
×
2813
                        // before the serialization error to prevent logging an
×
2814
                        // incomplete transaction.
×
2815
                        fundingTxBuf.Reset()
×
2816
                }
×
2817

2818
                log.Infof("Broadcasting funding tx for ChannelPoint(%v): %x",
30✔
2819
                        completeChan.FundingOutpoint, fundingTxBuf.Bytes())
30✔
2820

30✔
2821
                // Set a nil short channel ID at this stage because we do not
30✔
2822
                // know it until our funding tx confirms.
30✔
2823
                label := labels.MakeLabel(
30✔
2824
                        labels.LabelTypeChannelOpen, nil,
30✔
2825
                )
30✔
2826

30✔
2827
                err = f.cfg.PublishTransaction(fundingTx, label)
30✔
2828
                if err != nil {
30✔
2829
                        log.Errorf("Unable to broadcast funding tx %x for "+
×
2830
                                "ChannelPoint(%v): %v", fundingTxBuf.Bytes(),
×
2831
                                completeChan.FundingOutpoint, err)
×
2832

×
2833
                        // We failed to broadcast the funding transaction, but
×
2834
                        // watch the channel regardless, in case the
×
2835
                        // transaction made it to the network. We will retry
×
2836
                        // broadcast at startup.
×
2837
                        //
×
2838
                        // TODO(halseth): retry more often? Handle with CPFP?
×
2839
                        // Just delete from the DB?
×
2840
                }
×
2841
        }
2842

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

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

2867
        log.Infof("Finalizing pending_id(%x) over ChannelPoint(%v), "+
31✔
2868
                "waiting for channel open on-chain", pendingChanID[:],
31✔
2869
                fundingPoint)
31✔
2870

31✔
2871
        // Send an update to the upstream client that the negotiation process
31✔
2872
        // is over.
31✔
2873
        upd := &lnrpc.OpenStatusUpdate{
31✔
2874
                Update: &lnrpc.OpenStatusUpdate_ChanPending{
31✔
2875
                        ChanPending: &lnrpc.PendingUpdate{
31✔
2876
                                Txid:        fundingPoint.Hash[:],
31✔
2877
                                OutputIndex: fundingPoint.Index,
31✔
2878
                        },
31✔
2879
                },
31✔
2880
                PendingChanId: pendingChanID[:],
31✔
2881
        }
31✔
2882

31✔
2883
        select {
31✔
2884
        case resCtx.updates <- upd:
31✔
2885
                // Inform the ChannelNotifier that the channel has entered
31✔
2886
                // pending open state.
31✔
2887
                f.cfg.NotifyPendingOpenChannelEvent(
31✔
2888
                        *fundingPoint, completeChan, completeChan.IdentityPub,
31✔
2889
                )
31✔
2890

2891
        case <-f.quit:
×
2892
                return
×
2893
        }
2894

2895
        // At this point we have broadcast the funding transaction and done all
2896
        // necessary processing.
2897
        f.wg.Add(1)
31✔
2898
        go f.advanceFundingState(completeChan, pendingChanID, resCtx.updates)
31✔
2899
}
2900

2901
// confirmedChannel wraps a confirmed funding transaction, as well as the short
2902
// channel ID which identifies that channel into a single struct. We'll use
2903
// this to pass around the final state of a channel after it has been
2904
// confirmed.
2905
type confirmedChannel struct {
2906
        // shortChanID expresses where in the block the funding transaction was
2907
        // located.
2908
        shortChanID lnwire.ShortChannelID
2909

2910
        // fundingTx is the funding transaction that created the channel.
2911
        fundingTx *wire.MsgTx
2912
}
2913

2914
// fundingTimeout is called when callers of waitForFundingWithTimeout receive
2915
// an ErrConfirmationTimeout. It is used to clean-up channel state and mark the
2916
// channel as closed. The error is only returned for the responder of the
2917
// channel flow.
2918
func (f *Manager) fundingTimeout(c *channeldb.OpenChannel,
2919
        pendingID PendingChanID) error {
5✔
2920

5✔
2921
        // We'll get a timeout if the number of blocks mined since the channel
5✔
2922
        // was initiated reaches MaxWaitNumBlocksFundingConf and we are not the
5✔
2923
        // channel initiator.
5✔
2924
        localBalance := c.LocalCommitment.LocalBalance.ToSatoshis()
5✔
2925
        closeInfo := &channeldb.ChannelCloseSummary{
5✔
2926
                ChainHash:               c.ChainHash,
5✔
2927
                ChanPoint:               c.FundingOutpoint,
5✔
2928
                RemotePub:               c.IdentityPub,
5✔
2929
                Capacity:                c.Capacity,
5✔
2930
                SettledBalance:          localBalance,
5✔
2931
                CloseType:               channeldb.FundingCanceled,
5✔
2932
                RemoteCurrentRevocation: c.RemoteCurrentRevocation,
5✔
2933
                RemoteNextRevocation:    c.RemoteNextRevocation,
5✔
2934
                LocalChanConfig:         c.LocalChanCfg,
5✔
2935
        }
5✔
2936

5✔
2937
        // Close the channel with us as the initiator because we are timing the
5✔
2938
        // channel out.
5✔
2939
        if err := c.CloseChannel(
5✔
2940
                closeInfo, channeldb.ChanStatusLocalCloseInitiator,
5✔
2941
        ); err != nil {
5✔
2942
                return fmt.Errorf("failed closing channel %v: %w",
×
2943
                        c.FundingOutpoint, err)
×
2944
        }
×
2945

2946
        // Notify other subsystems about the funding timeout.
2947
        f.cfg.NotifyFundingTimeout(c.FundingOutpoint, c.IdentityPub)
5✔
2948

5✔
2949
        timeoutErr := fmt.Errorf("timeout waiting for funding tx (%v) to "+
5✔
2950
                "confirm", c.FundingOutpoint)
5✔
2951

5✔
2952
        // When the peer comes online, we'll notify it that we are now
5✔
2953
        // considering the channel flow canceled.
5✔
2954
        f.wg.Add(1)
5✔
2955
        go func() {
10✔
2956
                defer f.wg.Done()
5✔
2957

5✔
2958
                peer, err := f.waitForPeerOnline(c.IdentityPub)
5✔
2959
                switch err {
5✔
2960
                // We're already shutting down, so we can just return.
2961
                case ErrFundingManagerShuttingDown:
×
2962
                        return
×
2963

2964
                // nil error means we continue on.
2965
                case nil:
5✔
2966

2967
                // For unexpected errors, we print the error and still try to
2968
                // fail the funding flow.
2969
                default:
×
2970
                        log.Errorf("Unexpected error while waiting for peer "+
×
2971
                                "to come online: %v", err)
×
2972
                }
2973

2974
                // Create channel identifier and set the channel ID.
2975
                cid := newChanIdentifier(pendingID)
5✔
2976
                cid.setChanID(lnwire.NewChanIDFromOutPoint(c.FundingOutpoint))
5✔
2977

5✔
2978
                // TODO(halseth): should this send be made
5✔
2979
                // reliable?
5✔
2980

5✔
2981
                // The reservation won't exist at this point, but we'll send an
5✔
2982
                // Error message over anyways with ChanID set to pendingID.
5✔
2983
                f.failFundingFlow(peer, cid, timeoutErr)
5✔
2984
        }()
2985

2986
        return timeoutErr
5✔
2987
}
2988

2989
// waitForFundingWithTimeout is a wrapper around waitForFundingConfirmation and
2990
// waitForTimeout that will return ErrConfirmationTimeout if we are not the
2991
// channel initiator and the MaxWaitNumBlocksFundingConf has passed from the
2992
// funding broadcast height. In case of confirmation, the short channel ID of
2993
// the channel and the funding transaction will be returned.
2994
func (f *Manager) waitForFundingWithTimeout(
2995
        ch *channeldb.OpenChannel) (*confirmedChannel, error) {
62✔
2996

62✔
2997
        confChan := make(chan *confirmedChannel)
62✔
2998
        timeoutChan := make(chan error, 1)
62✔
2999
        cancelChan := make(chan struct{})
62✔
3000

62✔
3001
        f.wg.Add(1)
62✔
3002
        go f.waitForFundingConfirmation(ch, cancelChan, confChan)
62✔
3003

62✔
3004
        // If we are not the initiator, we have no money at stake and will
62✔
3005
        // timeout waiting for the funding transaction to confirm after a
62✔
3006
        // while.
62✔
3007
        if !ch.IsInitiator && !ch.IsZeroConf() {
91✔
3008
                f.wg.Add(1)
29✔
3009
                go f.waitForTimeout(ch, cancelChan, timeoutChan)
29✔
3010
        }
29✔
3011
        defer close(cancelChan)
62✔
3012

62✔
3013
        select {
62✔
3014
        case err := <-timeoutChan:
5✔
3015
                if err != nil {
5✔
3016
                        return nil, err
×
3017
                }
×
3018
                return nil, ErrConfirmationTimeout
5✔
3019

3020
        case <-f.quit:
26✔
3021
                // The fundingManager is shutting down, and will resume wait on
26✔
3022
                // startup.
26✔
3023
                return nil, ErrFundingManagerShuttingDown
26✔
3024

3025
        case confirmedChannel, ok := <-confChan:
37✔
3026
                if !ok {
37✔
3027
                        return nil, fmt.Errorf("waiting for funding" +
×
3028
                                "confirmation failed")
×
3029
                }
×
3030
                return confirmedChannel, nil
37✔
3031
        }
3032
}
3033

3034
// makeFundingScript re-creates the funding script for the funding transaction
3035
// of the target channel.
3036
func makeFundingScript(channel *channeldb.OpenChannel) ([]byte, error) {
82✔
3037
        localKey := channel.LocalChanCfg.MultiSigKey.PubKey
82✔
3038
        remoteKey := channel.RemoteChanCfg.MultiSigKey.PubKey
82✔
3039

82✔
3040
        if channel.ChanType.IsTaproot() {
90✔
3041
                pkScript, _, err := input.GenTaprootFundingScript(
8✔
3042
                        localKey, remoteKey, int64(channel.Capacity),
8✔
3043
                        channel.TapscriptRoot,
8✔
3044
                )
8✔
3045
                if err != nil {
8✔
3046
                        return nil, err
×
3047
                }
×
3048

3049
                return pkScript, nil
8✔
3050
        }
3051

3052
        multiSigScript, err := input.GenMultiSigScript(
77✔
3053
                localKey.SerializeCompressed(),
77✔
3054
                remoteKey.SerializeCompressed(),
77✔
3055
        )
77✔
3056
        if err != nil {
77✔
3057
                return nil, err
×
3058
        }
×
3059

3060
        return input.WitnessScriptHash(multiSigScript)
77✔
3061
}
3062

3063
// waitForFundingConfirmation handles the final stages of the channel funding
3064
// process once the funding transaction has been broadcast. The primary
3065
// function of waitForFundingConfirmation is to wait for blockchain
3066
// confirmation, and then to notify the other systems that must be notified
3067
// when a channel has become active for lightning transactions. It also updates
3068
// the channel’s opening transaction block height in the database.
3069
// The wait can be canceled by closing the cancelChan. In case of success,
3070
// a *lnwire.ShortChannelID will be passed to confChan.
3071
//
3072
// NOTE: This MUST be run as a goroutine.
3073
func (f *Manager) waitForFundingConfirmation(
3074
        completeChan *channeldb.OpenChannel, cancelChan <-chan struct{},
3075
        confChan chan<- *confirmedChannel) {
62✔
3076

62✔
3077
        defer f.wg.Done()
62✔
3078
        defer close(confChan)
62✔
3079

62✔
3080
        // Register with the ChainNotifier for a notification once the funding
62✔
3081
        // transaction reaches `numConfs` confirmations.
62✔
3082
        txid := completeChan.FundingOutpoint.Hash
62✔
3083
        fundingScript, err := makeFundingScript(completeChan)
62✔
3084
        if err != nil {
62✔
3085
                log.Errorf("unable to create funding script for "+
×
3086
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3087
                        err)
×
3088
                return
×
3089
        }
×
3090
        numConfs := uint32(completeChan.NumConfsRequired)
62✔
3091

62✔
3092
        // If the underlying channel is a zero-conf channel, we'll set numConfs
62✔
3093
        // to 6, since it will be zero here.
62✔
3094
        if completeChan.IsZeroConf() {
71✔
3095
                numConfs = 6
9✔
3096
        }
9✔
3097

3098
        confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
62✔
3099
                &txid, fundingScript, numConfs,
62✔
3100
                completeChan.BroadcastHeight(),
62✔
3101
        )
62✔
3102
        if err != nil {
62✔
3103
                log.Errorf("Unable to register for confirmation of "+
×
3104
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3105
                        err)
×
3106
                return
×
3107
        }
×
3108

3109
        log.Infof("Waiting for funding tx (%v) to reach %v confirmations",
62✔
3110
                txid, numConfs)
62✔
3111

62✔
3112
        // Wait until the specified number of confirmations has been reached,
62✔
3113
        // we get a cancel signal, or the wallet signals a shutdown.
62✔
3114
        for {
134✔
3115
                select {
72✔
3116
                case updDetails := <-confNtfn.Updates:
11✔
3117
                        log.Debugf("funding tx %s received confirmation in "+
11✔
3118
                                "block %d", txid, updDetails.BlockHeight)
11✔
3119

11✔
3120
                        // Only update the ConfirmationHeight the first time a
11✔
3121
                        // confirmation is received, since on subsequent
11✔
3122
                        // confirmations the block height will remain the same.
11✔
3123
                        if completeChan.ConfirmationHeight == 0 {
22✔
3124
                                err := completeChan.MarkConfirmationHeight(
11✔
3125
                                        updDetails.BlockHeight,
11✔
3126
                                )
11✔
3127
                                if err != nil {
11✔
NEW
3128
                                        log.Errorf("failed to update "+
×
NEW
3129
                                                "confirmed state for "+
×
NEW
3130
                                                "ChannelPoint(%v): %v",
×
NEW
3131
                                                completeChan.FundingOutpoint,
×
NEW
3132
                                                err)
×
UNCOV
3133

×
NEW
3134
                                        return
×
NEW
3135
                                }
×
3136
                        }
3137

3138
                case <-confNtfn.NegativeConf:
2✔
3139
                        log.Warnf("funding tx %s was reorged out; channel "+
2✔
3140
                                "point: %s", txid, completeChan.FundingOutpoint)
2✔
3141

2✔
3142
                        // Reset the confirmation height to 0 because the
2✔
3143
                        // funding transaction was reorged out.
2✔
3144
                        err := completeChan.MarkConfirmationHeight(uint32(0))
2✔
3145
                        if err != nil {
2✔
NEW
3146
                                log.Errorf("failed to update state for "+
×
NEW
3147
                                        "ChannelPoint(%v): %v",
×
NEW
3148
                                        completeChan.FundingOutpoint, err)
×
NEW
3149

×
NEW
3150
                                return
×
NEW
3151
                        }
×
3152

3153
                case confDetails, ok := <-confNtfn.Confirmed:
37✔
3154
                        if !ok {
37✔
NEW
3155
                                log.Warnf("ChainNotifier shutting down, "+
×
NEW
3156
                                        "cannot complete funding flow for "+
×
NEW
3157
                                        "ChannelPoint(%v)",
×
NEW
3158
                                        completeChan.FundingOutpoint)
×
NEW
3159

×
NEW
3160
                                return
×
NEW
3161
                        }
×
3162

3163
                        // Handle the case where numConfs is 1 and the Confirmed
3164
                        // channel fires before Updates. When multiple cases in
3165
                        // a select are ready, Go makes a uniform pseudo-random
3166
                        // choice between them.
3167
                        if completeChan.ConfirmationHeight == 0 {
67✔
3168
                                err := completeChan.MarkConfirmationHeight(
30✔
3169
                                        confDetails.BlockHeight,
30✔
3170
                                )
30✔
3171
                                if err != nil {
30✔
NEW
3172
                                        log.Errorf("failed to update "+
×
NEW
3173
                                                "confirmed state for "+
×
NEW
3174
                                                "ChannelPoint(%v): %v",
×
NEW
3175
                                                completeChan.FundingOutpoint,
×
NEW
3176
                                                err)
×
NEW
3177

×
NEW
3178
                                        return
×
NEW
3179
                                }
×
3180
                        }
3181

3182
                        err := f.handleConfirmation(
37✔
3183
                                confDetails, completeChan, confChan,
37✔
3184
                        )
37✔
3185
                        if err != nil {
37✔
NEW
3186
                                log.Errorf("Error handling confirmation for "+
×
NEW
3187
                                        "ChannelPoint(%v), txid=%v: %v",
×
NEW
3188
                                        completeChan.FundingOutpoint, txid, err)
×
NEW
3189
                        }
×
3190

3191
                        return
37✔
3192

3193
                case <-cancelChan:
6✔
3194
                        log.Warnf("canceled waiting for funding confirmation, "+
6✔
3195
                                "stopping funding flow for ChannelPoint(%v)",
6✔
3196
                                completeChan.FundingOutpoint)
6✔
3197

6✔
3198
                        return
6✔
3199

3200
                case <-f.quit:
25✔
3201
                        log.Warnf("fundingManager shutting down, stopping "+
25✔
3202
                                "funding flow for ChannelPoint(%v)",
25✔
3203
                                completeChan.FundingOutpoint)
25✔
3204

25✔
3205
                        return
25✔
3206
                }
3207
        }
3208
}
3209

3210
// handleConfirmation is a helper function that constructs a ShortChannelID
3211
// based on the confirmation details and sends this information, along with the
3212
// funding transaction, to the provided confirmation channel.
3213
func (f *Manager) handleConfirmation(confDetails *chainntnfs.TxConfirmation,
3214
        completeChan *channeldb.OpenChannel,
3215
        confChan chan<- *confirmedChannel) error {
37✔
3216

37✔
3217
        fundingPoint := completeChan.FundingOutpoint
37✔
3218
        log.Infof("ChannelPoint(%v) is now active: ChannelID(%v)",
37✔
3219
                fundingPoint, lnwire.NewChanIDFromOutPoint(fundingPoint))
37✔
3220

37✔
3221
        // With the block height and the transaction index known, we can
37✔
3222
        // construct the compact chanID which is used on the network to unique
37✔
3223
        // identify channels.
37✔
3224
        shortChanID := lnwire.ShortChannelID{
37✔
3225
                BlockHeight: confDetails.BlockHeight,
37✔
3226
                TxIndex:     confDetails.TxIndex,
37✔
3227
                TxPosition:  uint16(fundingPoint.Index),
37✔
3228
        }
37✔
3229

37✔
3230
        select {
37✔
3231
        case confChan <- &confirmedChannel{
3232
                shortChanID: shortChanID,
3233
                fundingTx:   confDetails.Tx,
3234
        }:
37✔
3235
        case <-f.quit:
×
NEW
3236
                return fmt.Errorf("manager shutting down")
×
3237
        }
3238

3239
        return nil
37✔
3240
}
3241

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

29✔
3252
        defer f.wg.Done()
29✔
3253

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

3261
        defer epochClient.Cancel()
29✔
3262

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

29✔
3270
        if lncfg.IsDevBuild() {
32✔
3271
                waitBlocksForFundingConf =
3✔
3272
                        f.cfg.Dev.MaxWaitNumBlocksFundingConf
3✔
3273
        }
3✔
3274

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

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

5✔
3295
                                // Notify the caller of the timeout.
5✔
3296
                                close(timeoutChan)
5✔
3297
                                return
5✔
3298
                        }
5✔
3299

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

3304
                case <-cancelChan:
18✔
3305
                        return
18✔
3306

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

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

19✔
3325
                // For zero-conf channels, we'll use the actually-confirmed
19✔
3326
                // short channel id.
19✔
3327
                if c.IsZeroConf() {
24✔
3328
                        shortChanID = c.ZeroConfRealScid()
5✔
3329
                }
5✔
3330

3331
                label := labels.MakeLabel(
19✔
3332
                        labels.LabelTypeChannelOpen, &shortChanID,
19✔
3333
                )
19✔
3334

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

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

33✔
3350
        fundingPoint := completeChan.FundingOutpoint
33✔
3351
        chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
33✔
3352

33✔
3353
        // TODO(roasbeef): ideally persistent state update for chan above
33✔
3354
        // should be abstracted
33✔
3355

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

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

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

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

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

3403
        // Update the confirmed funding transaction label.
3404
        f.makeLabelForTx(completeChan)
33✔
3405

33✔
3406
        // Inform the ChannelNotifier that the channel has transitioned from
33✔
3407
        // pending open to open.
33✔
3408
        f.cfg.NotifyOpenChannelEvent(
33✔
3409
                completeChan.FundingOutpoint, completeChan.IdentityPub,
33✔
3410
        )
33✔
3411

33✔
3412
        // Close the discoverySignal channel, indicating to a separate
33✔
3413
        // goroutine that the channel now is marked as open in the database
33✔
3414
        // and that it is acceptable to process channel_ready messages
33✔
3415
        // from the peer.
33✔
3416
        if discoverySignal, ok := f.localDiscoverySignals.Load(chanID); ok {
66✔
3417
                close(discoverySignal)
33✔
3418
        }
33✔
3419

3420
        return nil
33✔
3421
}
3422

3423
// sendChannelReady creates and sends the channelReady message.
3424
// This should be called after the funding transaction has been confirmed,
3425
// and the channelState is 'markedOpen'.
3426
func (f *Manager) sendChannelReady(completeChan *channeldb.OpenChannel,
3427
        channel *lnwallet.LightningChannel) error {
38✔
3428

38✔
3429
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
38✔
3430

38✔
3431
        var peerKey [33]byte
38✔
3432
        copy(peerKey[:], completeChan.IdentityPub.SerializeCompressed())
38✔
3433

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

38✔
3444
        // If this is a taproot channel, then we also need to send along our
38✔
3445
        // set of musig2 nonces as well.
38✔
3446
        if completeChan.ChanType.IsTaproot() {
45✔
3447
                log.Infof("ChanID(%v): generating musig2 nonces...",
7✔
3448
                        chanID)
7✔
3449

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

3464
                        // Now that we've generated the nonce for this channel,
3465
                        // we'll store it in the set of pending nonces.
3466
                        localNonce = newNonce
7✔
3467
                        f.pendingMusigNonces[chanID] = localNonce
7✔
3468
                }
3469
                f.nonceMtx.Unlock()
7✔
3470

7✔
3471
                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
7✔
3472
                        localNonce.PubNonce,
7✔
3473
                )
7✔
3474
        }
3475

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

3489
                // We can use a pointer to aliases since GetAliases returns a
3490
                // copy of the alias slice.
3491
                channelReadyMsg.AliasScid = &aliases[0]
9✔
3492
        }
3493

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

3511
                localAlias := peer.LocalFeatures().HasFeature(
37✔
3512
                        lnwire.ScidAliasOptional,
37✔
3513
                )
37✔
3514
                remoteAlias := peer.RemoteFeatures().HasFeature(
37✔
3515
                        lnwire.ScidAliasOptional,
37✔
3516
                )
37✔
3517

37✔
3518
                // We could also refresh the channel state instead of checking
37✔
3519
                // whether the feature was negotiated, but this saves us a
37✔
3520
                // database read.
37✔
3521
                if channelReadyMsg.AliasScid == nil && localAlias &&
37✔
3522
                        remoteAlias {
37✔
3523

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

3540
                                err = f.cfg.AliasManager.AddLocalAlias(
×
3541
                                        alias, completeChan.ShortChannelID,
×
3542
                                        false, false,
×
3543
                                )
×
3544
                                if err != nil {
×
3545
                                        return err
×
3546
                                }
×
3547

3548
                                channelReadyMsg.AliasScid = &alias
×
3549
                        } else {
×
3550
                                channelReadyMsg.AliasScid = &aliases[0]
×
3551
                        }
×
3552
                }
3553

3554
                log.Infof("Peer(%x) is online, sending ChannelReady "+
37✔
3555
                        "for ChannelID(%v)", peerKey, chanID)
37✔
3556

37✔
3557
                if err := peer.SendMessage(true, channelReadyMsg); err == nil {
74✔
3558
                        // Sending succeeded, we can break out and continue the
37✔
3559
                        // funding flow.
37✔
3560
                        break
37✔
3561
                }
3562

3563
                log.Warnf("Unable to send channelReady to peer %x: %v. "+
×
3564
                        "Will retry when online", peerKey, err)
×
3565
        }
3566

3567
        return nil
37✔
3568
}
3569

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

63✔
3575
        // If the funding manager has exited, return an error to stop looping.
63✔
3576
        // Note that the peer may appear as online while the funding manager
63✔
3577
        // has stopped due to the shutdown order in the server.
63✔
3578
        select {
63✔
3579
        case <-f.quit:
×
3580
                return false, ErrFundingManagerShuttingDown
×
3581
        default:
63✔
3582
        }
3583

3584
        // Avoid a tight loop if peer is offline.
3585
        if _, err := f.waitForPeerOnline(node); err != nil {
63✔
3586
                log.Errorf("Wait for peer online failed: %v", err)
×
3587
                return false, err
×
3588
        }
×
3589

3590
        // If we cannot find the channel, then we haven't processed the
3591
        // remote's channelReady message.
3592
        channel, err := f.cfg.FindChannel(node, chanID)
63✔
3593
        if err != nil {
63✔
3594
                log.Errorf("Unable to locate ChannelID(%v) to determine if "+
×
3595
                        "ChannelReady was received", chanID)
×
3596
                return false, err
×
3597
        }
×
3598

3599
        // If we haven't insert the next revocation point, we haven't finished
3600
        // processing the channel ready message.
3601
        if channel.RemoteNextRevocation == nil {
102✔
3602
                return false, nil
39✔
3603
        }
39✔
3604

3605
        // Finally, the barrier signal is removed once we finish
3606
        // `handleChannelReady`. If we can still find the signal, we haven't
3607
        // finished processing it yet.
3608
        _, loaded := f.handleChannelReadyBarriers.Load(chanID)
27✔
3609

27✔
3610
        return !loaded, nil
27✔
3611
}
3612

3613
// extractAnnounceParams extracts the various channel announcement and update
3614
// parameters that will be needed to construct a ChannelAnnouncement and a
3615
// ChannelUpdate.
3616
func (f *Manager) extractAnnounceParams(c *channeldb.OpenChannel) (
3617
        lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
29✔
3618

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

29✔
3625
        // We don't necessarily want to go as low as the remote party allows.
29✔
3626
        // Check it against our default forwarding policy.
29✔
3627
        if fwdMinHTLC < f.cfg.DefaultRoutingPolicy.MinHTLCOut {
32✔
3628
                fwdMinHTLC = f.cfg.DefaultRoutingPolicy.MinHTLCOut
3✔
3629
        }
3✔
3630

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

3640
        return fwdMinHTLC, fwdMaxHTLC
29✔
3641
}
3642

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

29✔
3656
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
29✔
3657

29✔
3658
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
29✔
3659

29✔
3660
        ann, err := f.newChanAnnouncement(
29✔
3661
                f.cfg.IDKey, completeChan.IdentityPub,
29✔
3662
                &completeChan.LocalChanCfg.MultiSigKey,
29✔
3663
                completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
29✔
3664
                chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
29✔
3665
                completeChan.ChanType,
29✔
3666
        )
29✔
3667
        if err != nil {
29✔
3668
                return fmt.Errorf("error generating channel "+
×
3669
                        "announcement: %v", err)
×
3670
        }
×
3671

3672
        // Send ChannelAnnouncement and ChannelUpdate to the gossiper to add
3673
        // to the Router's topology.
3674
        errChan := f.cfg.SendAnnouncement(
29✔
3675
                ann.chanAnn, discovery.ChannelCapacity(completeChan.Capacity),
29✔
3676
                discovery.ChannelPoint(completeChan.FundingOutpoint),
29✔
3677
                discovery.TapscriptRoot(completeChan.TapscriptRoot),
29✔
3678
        )
29✔
3679
        select {
29✔
3680
        case err := <-errChan:
29✔
3681
                if err != nil {
29✔
3682
                        if graph.IsError(err, graph.ErrOutdated,
×
3683
                                graph.ErrIgnored) {
×
3684

×
3685
                                log.Debugf("Graph rejected "+
×
3686
                                        "ChannelAnnouncement: %v", err)
×
3687
                        } else {
×
3688
                                return fmt.Errorf("error sending channel "+
×
3689
                                        "announcement: %v", err)
×
3690
                        }
×
3691
                }
3692
        case <-f.quit:
×
3693
                return ErrFundingManagerShuttingDown
×
3694
        }
3695

3696
        errChan = f.cfg.SendAnnouncement(
29✔
3697
                ann.chanUpdateAnn, discovery.RemoteAlias(peerAlias),
29✔
3698
        )
29✔
3699
        select {
29✔
3700
        case err := <-errChan:
29✔
3701
                if err != nil {
29✔
3702
                        if graph.IsError(err, graph.ErrOutdated,
×
3703
                                graph.ErrIgnored) {
×
3704

×
3705
                                log.Debugf("Graph rejected "+
×
3706
                                        "ChannelUpdate: %v", err)
×
3707
                        } else {
×
3708
                                return fmt.Errorf("error sending channel "+
×
3709
                                        "update: %v", err)
×
3710
                        }
×
3711
                }
3712
        case <-f.quit:
×
3713
                return ErrFundingManagerShuttingDown
×
3714
        }
3715

3716
        return nil
29✔
3717
}
3718

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

29✔
3728
        // If this channel is not meant to be announced to the greater network,
29✔
3729
        // we'll only send our NodeAnnouncement to our counterparty to ensure we
29✔
3730
        // don't leak any of our information.
29✔
3731
        announceChan := completeChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
29✔
3732
        if !announceChan {
40✔
3733
                log.Debugf("Will not announce private channel %v.",
11✔
3734
                        shortChanID.ToUint64())
11✔
3735

11✔
3736
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
11✔
3737
                if err != nil {
11✔
3738
                        return err
×
3739
                }
×
3740

3741
                nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
11✔
3742
                if err != nil {
11✔
3743
                        return fmt.Errorf("unable to retrieve current node "+
×
3744
                                "announcement: %v", err)
×
3745
                }
×
3746

3747
                chanID := lnwire.NewChanIDFromOutPoint(
11✔
3748
                        completeChan.FundingOutpoint,
11✔
3749
                )
11✔
3750
                pubKey := peer.PubKey()
11✔
3751
                log.Debugf("Sending our NodeAnnouncement for "+
11✔
3752
                        "ChannelID(%v) to %x", chanID, pubKey)
11✔
3753

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

21✔
3774
                fundingScript, err := makeFundingScript(completeChan)
21✔
3775
                if err != nil {
21✔
3776
                        return fmt.Errorf("unable to create funding script "+
×
3777
                                "for ChannelPoint(%v): %v",
×
3778
                                completeChan.FundingOutpoint, err)
×
3779
                }
×
3780

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

3793
                // Wait until 6 confirmations has been reached or the wallet
3794
                // signals a shutdown.
3795
                select {
21✔
3796
                case _, ok := <-confNtfn.Confirmed:
19✔
3797
                        if !ok {
19✔
3798
                                return fmt.Errorf("ChainNotifier shutting "+
×
3799
                                        "down, cannot complete funding flow "+
×
3800
                                        "for ChannelPoint(%v)",
×
3801
                                        completeChan.FundingOutpoint)
×
3802
                        }
×
3803
                        // Fallthrough.
3804

3805
                case <-f.quit:
5✔
3806
                        return fmt.Errorf("%v, stopping funding flow for "+
5✔
3807
                                "ChannelPoint(%v)",
5✔
3808
                                ErrFundingManagerShuttingDown,
5✔
3809
                                completeChan.FundingOutpoint)
5✔
3810
                }
3811

3812
                fundingPoint := completeChan.FundingOutpoint
19✔
3813
                chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
19✔
3814

19✔
3815
                log.Infof("Announcing ChannelPoint(%v), short_chan_id=%v",
19✔
3816
                        &fundingPoint, shortChanID)
19✔
3817

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

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

3843
                        err = f.addToGraph(
3✔
3844
                                completeChan, &baseScid, nil, ourPolicy,
3✔
3845
                        )
3✔
3846
                        if err != nil {
3✔
3847
                                return fmt.Errorf("failed to re-add to "+
×
3848
                                        "graph: %v", err)
×
3849
                        }
×
3850
                }
3851

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

3865
                log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+
19✔
3866
                        "sent to gossiper", &fundingPoint, shortChanID)
19✔
3867
        }
3868

3869
        return nil
27✔
3870
}
3871

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

3886
        // We'll need to refresh the channel state so that things are properly
3887
        // populated when validating the channel state. Otherwise, a panic may
3888
        // occur due to inconsistency in the OpenChannel struct.
3889
        err = c.Refresh()
7✔
3890
        if err != nil {
10✔
3891
                return fmt.Errorf("unable to refresh channel state: %w", err)
3✔
3892
        }
3✔
3893

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

3903
        // Once we know the confirmed ShortChannelID, we'll need to save it to
3904
        // the database and refresh the OpenChannel struct with it.
3905
        err = c.MarkRealScid(confChan.shortChanID)
7✔
3906
        if err != nil {
7✔
3907
                return fmt.Errorf("unable to set confirmed SCID for zero "+
×
3908
                        "channel: %v", err)
×
3909
        }
×
3910

3911
        // Six confirmations have been reached. If this channel is public,
3912
        // we'll delete some of the alias mappings the gossiper uses.
3913
        isPublic := c.ChannelFlags&lnwire.FFAnnounceChannel != 0
7✔
3914
        if isPublic {
12✔
3915
                err = f.cfg.AliasManager.DeleteSixConfs(c.ShortChannelID)
5✔
3916
                if err != nil {
5✔
3917
                        return fmt.Errorf("unable to delete base alias after "+
×
3918
                                "six confirmations: %v", err)
×
3919
                }
×
3920

3921
                // TODO: Make this atomic!
3922
                ourPolicy, err := f.cfg.DeleteAliasEdge(c.ShortChanID())
5✔
3923
                if err != nil {
5✔
3924
                        return fmt.Errorf("unable to delete alias edge from "+
×
3925
                                "graph: %v", err)
×
3926
                }
×
3927

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

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

3954
        // Update the confirmed transaction's label.
3955
        f.makeLabelForTx(c)
7✔
3956

7✔
3957
        return nil
7✔
3958
}
3959

3960
// genFirstStateMusigNonce generates a nonces for the "first" local state. This
3961
// is the verification nonce for the state created for us after the initial
3962
// commitment transaction signed as part of the funding flow.
3963
func genFirstStateMusigNonce(channel *channeldb.OpenChannel,
3964
) (*musig2.Nonces, error) {
7✔
3965

7✔
3966
        musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
7✔
3967
                channel.RevocationProducer,
7✔
3968
        )
7✔
3969
        if err != nil {
7✔
3970
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3971
                        "nonces: %v", err)
×
3972
        }
×
3973

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

3986
        return verNonce, nil
7✔
3987
}
3988

3989
// handleChannelReady finalizes the channel funding process and enables the
3990
// channel to enter normal operating mode.
3991
func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen
3992
        msg *lnwire.ChannelReady) {
31✔
3993

31✔
3994
        defer f.wg.Done()
31✔
3995

31✔
3996
        // If we are in development mode, we'll wait for specified duration
31✔
3997
        // before processing the channel ready message.
31✔
3998
        if f.cfg.Dev != nil {
34✔
3999
                duration := f.cfg.Dev.ProcessChannelReadyWait
3✔
4000
                log.Warnf("Channel(%v): sleeping %v before processing "+
3✔
4001
                        "channel_ready", msg.ChanID, duration)
3✔
4002

3✔
4003
                select {
3✔
4004
                case <-time.After(duration):
3✔
4005
                        log.Warnf("Channel(%v): slept %v before processing "+
3✔
4006
                                "channel_ready", msg.ChanID, duration)
3✔
4007
                case <-f.quit:
×
4008
                        log.Warnf("Channel(%v): quit sleeping", msg.ChanID)
×
4009
                        return
×
4010
                }
4011
        }
4012

4013
        log.Debugf("Received ChannelReady for ChannelID(%v) from "+
31✔
4014
                "peer %x", msg.ChanID,
31✔
4015
                peer.IdentityKey().SerializeCompressed())
31✔
4016

31✔
4017
        // We now load or create a new channel barrier for this channel.
31✔
4018
        _, loaded := f.handleChannelReadyBarriers.LoadOrStore(
31✔
4019
                msg.ChanID, struct{}{},
31✔
4020
        )
31✔
4021

31✔
4022
        // If we are currently in the process of handling a channel_ready
31✔
4023
        // message for this channel, ignore.
31✔
4024
        if loaded {
35✔
4025
                log.Infof("Already handling channelReady for "+
4✔
4026
                        "ChannelID(%v), ignoring.", msg.ChanID)
4✔
4027
                return
4✔
4028
        }
4✔
4029

4030
        // If not already handling channelReady for this channel, then the
4031
        // `LoadOrStore` has set up a barrier, and it will be removed once this
4032
        // function exits.
4033
        defer f.handleChannelReadyBarriers.Delete(msg.ChanID)
30✔
4034

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

4049
                // With the signal received, we can now safely delete the entry
4050
                // from the map.
4051
                f.localDiscoverySignals.Delete(msg.ChanID)
28✔
4052
        }
4053

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

4066
        // If this is a taproot channel, then we can generate the set of nonces
4067
        // the remote party needs to send the next remote commitment here.
4068
        var firstVerNonce *musig2.Nonces
30✔
4069
        if channel.ChanType.IsTaproot() {
37✔
4070
                firstVerNonce, err = genFirstStateMusigNonce(channel)
7✔
4071
                if err != nil {
7✔
4072
                        log.Error(err)
×
4073
                        return
×
4074
                }
×
4075
        }
4076

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

4094
                // We'll store the AliasScid so that invoice creation can use
4095
                // it.
4096
                err = f.cfg.AliasManager.PutPeerAlias(chanID, *msg.AliasScid)
9✔
4097
                if err != nil {
9✔
4098
                        log.Errorf("unable to store peer's alias: %v", err)
×
4099
                        return
×
4100
                }
×
4101

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

4119
                        err = f.cfg.AliasManager.AddLocalAlias(
×
4120
                                alias, channel.ShortChannelID, false, false,
×
4121
                        )
×
4122
                        if err != nil {
×
4123
                                log.Errorf("unable to add local alias: %v",
×
4124
                                        err)
×
4125
                                return
×
4126
                        }
×
4127

4128
                        secondPoint, err := channel.SecondCommitmentPoint()
×
4129
                        if err != nil {
×
4130
                                log.Errorf("unable to fetch second "+
×
4131
                                        "commitment point: %v", err)
×
4132
                                return
×
4133
                        }
×
4134

4135
                        channelReadyMsg := lnwire.NewChannelReady(
×
4136
                                chanID, secondPoint,
×
4137
                        )
×
4138
                        channelReadyMsg.AliasScid = &alias
×
4139

×
4140
                        if firstVerNonce != nil {
×
4141
                                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:ll
×
4142
                                        firstVerNonce.PubNonce,
×
4143
                                )
×
4144
                        }
×
4145

4146
                        err = peer.SendMessage(true, channelReadyMsg)
×
4147
                        if err != nil {
×
4148
                                log.Errorf("unable to send channel_ready: %v",
×
4149
                                        err)
×
4150
                                return
×
4151
                        }
×
4152
                }
4153
        }
4154

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

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

7✔
4185
                log.Infof("ChanID(%v): applying local+remote musig2 nonces",
7✔
4186
                        chanID)
7✔
4187

7✔
4188
                remoteNonce, err := msg.NextLocalNonce.UnwrapOrErrV(
7✔
4189
                        errNoLocalNonce,
7✔
4190
                )
7✔
4191
                if err != nil {
7✔
4192
                        cid := newChanIdentifier(msg.ChanID)
×
4193
                        f.sendWarning(peer, cid, err)
×
4194

×
4195
                        return
×
4196
                }
×
4197

4198
                chanOpts = append(
7✔
4199
                        chanOpts,
7✔
4200
                        lnwallet.WithLocalMusigNonces(localNonce),
7✔
4201
                        lnwallet.WithRemoteMusigNonces(&musig2.Nonces{
7✔
4202
                                PubNonce: remoteNonce,
7✔
4203
                        }),
7✔
4204
                )
7✔
4205

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

×
4223
                        return
×
4224
                }
×
4225
        }
4226

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

4237
        // Before we can add the channel to the peer, we'll need to ensure that
4238
        // we have an initial forwarding policy set.
4239
        if err := f.ensureInitialForwardingPolicy(chanID, channel); err != nil {
29✔
4240
                log.Errorf("Unable to ensure initial forwarding policy: %v",
×
4241
                        err)
×
4242
        }
×
4243

4244
        err = peer.AddNewChannel(&lnpeer.NewChannel{
29✔
4245
                OpenChannel: channel,
29✔
4246
                ChanOpts:    chanOpts,
29✔
4247
        }, f.quit)
29✔
4248
        if err != nil {
29✔
4249
                log.Errorf("Unable to add new channel %v with peer %x: %v",
×
4250
                        channel.FundingOutpoint,
×
4251
                        peer.IdentityKey().SerializeCompressed(), err,
×
4252
                )
×
4253
        }
×
4254
}
4255

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

27✔
4265
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
27✔
4266

27✔
4267
        // Since we've sent+received funding locked at this point, we
27✔
4268
        // can clean up the pending musig2 nonce state.
27✔
4269
        f.nonceMtx.Lock()
27✔
4270
        delete(f.pendingMusigNonces, chanID)
27✔
4271
        f.nonceMtx.Unlock()
27✔
4272

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

4288
                peerAlias = &foundAlias
7✔
4289
        }
4290

4291
        err := f.addToGraph(channel, scid, peerAlias, nil)
27✔
4292
        if err != nil {
27✔
4293
                return fmt.Errorf("failed adding to graph: %w", err)
×
4294
        }
×
4295

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

4308
        log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
27✔
4309
                "added to graph", chanID, scid)
27✔
4310

27✔
4311
        err = fn.MapOptionZ(
27✔
4312
                f.cfg.AuxFundingController,
27✔
4313
                func(controller AuxFundingController) error {
27✔
4314
                        return controller.ChannelReady(
×
4315
                                lnwallet.NewAuxChanState(channel),
×
4316
                        )
×
4317
                },
×
4318
        )
4319
        if err != nil {
27✔
4320
                return fmt.Errorf("failed notifying aux funding controller "+
×
4321
                        "about channel ready: %w", err)
×
4322
        }
×
4323

4324
        // Give the caller a final update notifying them that the channel is
4325
        fundingPoint := channel.FundingOutpoint
27✔
4326
        cp := &lnrpc.ChannelPoint{
27✔
4327
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
27✔
4328
                        FundingTxidBytes: fundingPoint.Hash[:],
27✔
4329
                },
27✔
4330
                OutputIndex: fundingPoint.Index,
27✔
4331
        }
27✔
4332

27✔
4333
        if updateChan != nil {
40✔
4334
                upd := &lnrpc.OpenStatusUpdate{
13✔
4335
                        Update: &lnrpc.OpenStatusUpdate_ChanOpen{
13✔
4336
                                ChanOpen: &lnrpc.ChannelOpenUpdate{
13✔
4337
                                        ChannelPoint: cp,
13✔
4338
                                },
13✔
4339
                        },
13✔
4340
                        PendingChanId: pendingChanID[:],
13✔
4341
                }
13✔
4342

13✔
4343
                select {
13✔
4344
                case updateChan <- upd:
13✔
4345
                case <-f.quit:
×
4346
                        return ErrFundingManagerShuttingDown
×
4347
                }
4348
        }
4349

4350
        return nil
27✔
4351
}
4352

4353
// ensureInitialForwardingPolicy ensures that we have an initial forwarding
4354
// policy set for the given channel. If we don't, we'll fall back to the default
4355
// values.
4356
func (f *Manager) ensureInitialForwardingPolicy(chanID lnwire.ChannelID,
4357
        channel *channeldb.OpenChannel) error {
29✔
4358

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

×
4369
                forwardingPolicy = f.defaultForwardingPolicy(
×
4370
                        channel.LocalChanCfg.ChannelStateBounds,
×
4371
                )
×
4372
                needDBUpdate = true
×
4373
        }
×
4374

4375
        // We only started storing the actual values for MinHTLCOut and MaxHTLC
4376
        // after 0.16.x, so if a channel was opened with such a version and is
4377
        // still pending while updating to this version, we'll need to set the
4378
        // values to the default values.
4379
        if forwardingPolicy.MinHTLCOut == 0 {
45✔
4380
                forwardingPolicy.MinHTLCOut = channel.LocalChanCfg.MinHTLC
16✔
4381
                needDBUpdate = true
16✔
4382
        }
16✔
4383
        if forwardingPolicy.MaxHTLC == 0 {
45✔
4384
                forwardingPolicy.MaxHTLC = channel.LocalChanCfg.MaxPendingAmount
16✔
4385
                needDBUpdate = true
16✔
4386
        }
16✔
4387

4388
        // And finally, if we found that the values currently stored aren't
4389
        // sufficient for the link, we'll update the database.
4390
        if needDBUpdate {
45✔
4391
                err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
16✔
4392
                if err != nil {
16✔
4393
                        return fmt.Errorf("unable to update initial "+
×
4394
                                "forwarding policy: %v", err)
×
4395
                }
×
4396
        }
4397

4398
        return nil
29✔
4399
}
4400

4401
// chanAnnouncement encapsulates the two authenticated announcements that we
4402
// send out to the network after a new channel has been created locally.
4403
type chanAnnouncement struct {
4404
        chanAnn       *lnwire.ChannelAnnouncement1
4405
        chanUpdateAnn *lnwire.ChannelUpdate1
4406
        chanProof     *lnwire.AnnounceSignatures1
4407
}
4408

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

45✔
4424
        chainHash := *f.cfg.Wallet.Cfg.NetParams.GenesisHash
45✔
4425

45✔
4426
        // The unconditional section of the announcement is the ShortChannelID
45✔
4427
        // itself which compactly encodes the location of the funding output
45✔
4428
        // within the blockchain.
45✔
4429
        chanAnn := &lnwire.ChannelAnnouncement1{
45✔
4430
                ShortChannelID: shortChanID,
45✔
4431
                Features:       lnwire.NewRawFeatureVector(),
45✔
4432
                ChainHash:      chainHash,
45✔
4433
        }
45✔
4434

45✔
4435
        // If this is a taproot channel, then we'll set a special bit in the
45✔
4436
        // feature vector to indicate to the routing layer that this needs a
45✔
4437
        // slightly different type of validation.
45✔
4438
        //
45✔
4439
        // TODO(roasbeef): temp, remove after gossip 1.5
45✔
4440
        if chanType.IsTaproot() {
52✔
4441
                log.Debugf("Applying taproot feature bit to "+
7✔
4442
                        "ChannelAnnouncement for %v", chanID)
7✔
4443

7✔
4444
                chanAnn.Features.Set(
7✔
4445
                        lnwire.SimpleTaprootChannelsRequiredStaging,
7✔
4446
                )
7✔
4447
        }
7✔
4448

4449
        // The chanFlags field indicates which directed edge of the channel is
4450
        // being updated within the ChannelUpdateAnnouncement announcement
4451
        // below. A value of zero means it's the edge of the "first" node and 1
4452
        // being the other node.
4453
        var chanFlags lnwire.ChanUpdateChanFlags
45✔
4454

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

24✔
4473
                // If we're the first node then update the chanFlags to
24✔
4474
                // indicate the "direction" of the update.
24✔
4475
                chanFlags = 0
24✔
4476
        } else {
48✔
4477
                copy(chanAnn.NodeID1[:], remotePubKey.SerializeCompressed())
24✔
4478
                copy(chanAnn.NodeID2[:], localPubKey.SerializeCompressed())
24✔
4479
                copy(
24✔
4480
                        chanAnn.BitcoinKey1[:],
24✔
4481
                        remoteFundingKey.SerializeCompressed(),
24✔
4482
                )
24✔
4483
                copy(
24✔
4484
                        chanAnn.BitcoinKey2[:],
24✔
4485
                        localFundingKey.PubKey.SerializeCompressed(),
24✔
4486
                )
24✔
4487

24✔
4488
                // If we're the second node then update the chanFlags to
24✔
4489
                // indicate the "direction" of the update.
24✔
4490
                chanFlags = 1
24✔
4491
        }
24✔
4492

4493
        // Our channel update message flags will signal that we support the
4494
        // max_htlc field.
4495
        msgFlags := lnwire.ChanUpdateRequiredMaxHtlc
45✔
4496

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

45✔
4512
        // The caller of newChanAnnouncement is expected to provide the initial
45✔
4513
        // forwarding policy to be announced. If no persisted initial policy
45✔
4514
        // values are found, then we will use the default policy values in the
45✔
4515
        // channel announcement.
45✔
4516
        storedFwdingPolicy, err := f.getInitialForwardingPolicy(chanID)
45✔
4517
        if err != nil && !errors.Is(err, channeldb.ErrChannelNotFound) {
45✔
4518
                return nil, fmt.Errorf("unable to generate channel "+
×
4519
                        "update announcement: %w", err)
×
4520
        }
×
4521

4522
        switch {
45✔
4523
        case ourPolicy != nil:
3✔
4524
                // If ourPolicy is non-nil, modify the default parameters of the
3✔
4525
                // ChannelUpdate.
3✔
4526
                chanUpdateAnn.MessageFlags = ourPolicy.MessageFlags
3✔
4527
                chanUpdateAnn.ChannelFlags = ourPolicy.ChannelFlags
3✔
4528
                chanUpdateAnn.TimeLockDelta = ourPolicy.TimeLockDelta
3✔
4529
                chanUpdateAnn.HtlcMinimumMsat = ourPolicy.MinHTLC
3✔
4530
                chanUpdateAnn.HtlcMaximumMsat = ourPolicy.MaxHTLC
3✔
4531
                chanUpdateAnn.BaseFee = uint32(ourPolicy.FeeBaseMSat)
3✔
4532
                chanUpdateAnn.FeeRate = uint32(
3✔
4533
                        ourPolicy.FeeProportionalMillionths,
3✔
4534
                )
3✔
4535

4536
        case storedFwdingPolicy != nil:
45✔
4537
                chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
45✔
4538
                chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
45✔
4539

4540
        default:
×
4541
                log.Infof("No channel forwarding policy specified for channel "+
×
4542
                        "announcement of ChannelID(%v). "+
×
4543
                        "Assuming default fee parameters.", chanID)
×
4544
                chanUpdateAnn.BaseFee = uint32(
×
4545
                        f.cfg.DefaultRoutingPolicy.BaseFee,
×
4546
                )
×
4547
                chanUpdateAnn.FeeRate = uint32(
×
4548
                        f.cfg.DefaultRoutingPolicy.FeeRate,
×
4549
                )
×
4550
        }
4551

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

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

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

4611
        return &chanAnnouncement{
45✔
4612
                chanAnn:       chanAnn,
45✔
4613
                chanUpdateAnn: chanUpdateAnn,
45✔
4614
                chanProof:     proof,
45✔
4615
        }, nil
45✔
4616
}
4617

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

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

4646
        // We only send the channel proof announcement and the node announcement
4647
        // because addToGraph previously sent the ChannelAnnouncement and
4648
        // the ChannelUpdate announcement messages. The channel proof and node
4649
        // announcements are broadcast to the greater network.
4650
        errChan := f.cfg.SendAnnouncement(ann.chanProof)
19✔
4651
        select {
19✔
4652
        case err := <-errChan:
19✔
4653
                if err != nil {
22✔
4654
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4655
                                graph.ErrIgnored) {
3✔
4656

×
4657
                                log.Debugf("Graph rejected "+
×
4658
                                        "AnnounceSignatures: %v", err)
×
4659
                        } else {
3✔
4660
                                log.Errorf("Unable to send channel "+
3✔
4661
                                        "proof: %v", err)
3✔
4662
                                return err
3✔
4663
                        }
3✔
4664
                }
4665

4666
        case <-f.quit:
×
4667
                return ErrFundingManagerShuttingDown
×
4668
        }
4669

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

4680
        errChan = f.cfg.SendAnnouncement(&nodeAnn)
19✔
4681
        select {
19✔
4682
        case err := <-errChan:
19✔
4683
                if err != nil {
21✔
4684
                        if graph.IsError(err, graph.ErrOutdated,
2✔
4685
                                graph.ErrIgnored) {
4✔
4686

2✔
4687
                                log.Debugf("Graph rejected "+
2✔
4688
                                        "NodeAnnouncement: %v", err)
2✔
4689
                        } else {
2✔
4690
                                log.Errorf("Unable to send node "+
×
4691
                                        "announcement: %v", err)
×
4692
                                return err
×
4693
                        }
×
4694
                }
4695

4696
        case <-f.quit:
×
4697
                return ErrFundingManagerShuttingDown
×
4698
        }
4699

4700
        return nil
19✔
4701
}
4702

4703
// InitFundingWorkflow sends a message to the funding manager instructing it
4704
// to initiate a single funder workflow with the source peer.
4705
func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg) {
60✔
4706
        f.fundingRequests <- msg
60✔
4707
}
60✔
4708

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

113✔
4721
        // Check whether the remote peer supports upfront shutdown scripts.
113✔
4722
        remoteUpfrontShutdown := peer.RemoteFeatures().HasFeature(
113✔
4723
                lnwire.UpfrontShutdownScriptOptional,
113✔
4724
        )
113✔
4725

113✔
4726
        // If the peer does not support upfront shutdown scripts, and one has been
113✔
4727
        // provided, return an error because the feature is not supported.
113✔
4728
        if !remoteUpfrontShutdown && len(script) != 0 {
114✔
4729
                return nil, errUpfrontShutdownScriptNotSupported
1✔
4730
        }
1✔
4731

4732
        // If the peer does not support upfront shutdown, return an empty address.
4733
        if !remoteUpfrontShutdown {
217✔
4734
                return nil, nil
105✔
4735
        }
105✔
4736

4737
        // If the user has provided an script and the peer supports the feature,
4738
        // return it. Note that user set scripts override the enable upfront
4739
        // shutdown flag.
4740
        if len(script) > 0 {
12✔
4741
                return script, nil
5✔
4742
        }
5✔
4743

4744
        // If we do not have setting of upfront shutdown script enabled, return
4745
        // an empty script.
4746
        if !enableUpfrontShutdown {
9✔
4747
                return nil, nil
4✔
4748
        }
4✔
4749

4750
        // We can safely send a taproot address iff, both sides have negotiated
4751
        // the shutdown-any-segwit feature.
4752
        taprootOK := peer.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
1✔
4753
                peer.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
1✔
4754

1✔
4755
        return getScript(taprootOK)
1✔
4756
}
4757

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

60✔
4776
        // If no maximum CSV delay was set for this channel, we use our default
60✔
4777
        // value.
60✔
4778
        if maxCSV == 0 {
120✔
4779
                maxCSV = f.cfg.MaxLocalCSVDelay
60✔
4780
        }
60✔
4781

4782
        log.Infof("Initiating fundingRequest(local_amt=%v "+
60✔
4783
                "(subtract_fees=%v), push_amt=%v, chain_hash=%v, peer=%x, "+
60✔
4784
                "min_confs=%v)", localAmt, msg.SubtractFees, msg.PushAmt,
60✔
4785
                msg.ChainHash, peerKey.SerializeCompressed(), msg.MinConfs)
60✔
4786

60✔
4787
        // We set the channel flags to indicate whether we want this channel to
60✔
4788
        // be announced to the network.
60✔
4789
        var channelFlags lnwire.FundingFlag
60✔
4790
        if !msg.Private {
115✔
4791
                // This channel will be announced.
55✔
4792
                channelFlags = lnwire.FFAnnounceChannel
55✔
4793
        }
55✔
4794

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

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

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

4843
        var (
60✔
4844
                zeroConf bool
60✔
4845
                scid     bool
60✔
4846
        )
60✔
4847

60✔
4848
        if chanType != nil {
67✔
4849
                // Check if the returned chanType includes either the zero-conf
7✔
4850
                // or scid-alias bits.
7✔
4851
                featureVec := lnwire.RawFeatureVector(*chanType)
7✔
4852
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
7✔
4853
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
7✔
4854

7✔
4855
                // The option-scid-alias channel type for a public channel is
7✔
4856
                // disallowed.
7✔
4857
                if scid && !msg.Private {
7✔
4858
                        err = fmt.Errorf("option-scid-alias chantype for " +
×
4859
                                "public channel")
×
4860
                        log.Error(err)
×
4861
                        msg.Err <- err
×
4862

×
4863
                        return
×
4864
                }
×
4865
        }
4866

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

4877
        // For anchor channels cap the initial commit fee rate at our defined
4878
        // maximum.
4879
        if commitType.HasAnchors() &&
60✔
4880
                commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
67✔
4881

7✔
4882
                commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate
7✔
4883
        }
7✔
4884

4885
        var scidFeatureVal bool
60✔
4886
        if hasFeatures(
60✔
4887
                msg.Peer.LocalFeatures(), msg.Peer.RemoteFeatures(),
60✔
4888
                lnwire.ScidAliasOptional,
60✔
4889
        ) {
66✔
4890

6✔
4891
                scidFeatureVal = true
6✔
4892
        }
6✔
4893

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

×
4908
                return
×
4909
        }
×
4910

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

4941
                        // Query the sweeper storage to make sure we don't use
4942
                        // an unconfirmed utxo still in use by the sweeper
4943
                        // subsystem.
4944
                        return !f.cfg.IsSweeperOutpoint(u.OutPoint)
61✔
4945
                },
4946
                ZeroConf:         zeroConf,
4947
                OptionScidAlias:  scid,
4948
                ScidAliasFeature: scidFeatureVal,
4949
                Memo:             msg.Memo,
4950
                TapscriptRoot:    tapscriptRoot,
4951
        }
4952

4953
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
60✔
4954
        if err != nil {
63✔
4955
                msg.Err <- err
3✔
4956
                return
3✔
4957
        }
3✔
4958

4959
        if zeroConf {
65✔
4960
                // Store the alias for zero-conf channels in the underlying
5✔
4961
                // partial channel state.
5✔
4962
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
5✔
4963
                if err != nil {
5✔
4964
                        msg.Err <- err
×
4965
                        return
×
4966
                }
×
4967

4968
                reservation.AddAlias(aliasScid)
5✔
4969
        }
4970

4971
        // Set our upfront shutdown address in the existing reservation.
4972
        reservation.SetOurUpfrontShutdown(shutdown)
60✔
4973

60✔
4974
        // Now that we have successfully reserved funds for this channel in the
60✔
4975
        // wallet, we can fetch the final channel capacity. This is done at
60✔
4976
        // this point since the final capacity might change in case of
60✔
4977
        // SubtractFees=true.
60✔
4978
        capacity := reservation.Capacity()
60✔
4979

60✔
4980
        log.Infof("Target commit tx sat/kw for pendingID(%x): %v", chanID,
60✔
4981
                int64(commitFeePerKw))
60✔
4982

60✔
4983
        // If the remote CSV delay was not set in the open channel request,
60✔
4984
        // we'll use the RequiredRemoteDelay closure to compute the delay we
60✔
4985
        // require given the total amount of funds within the channel.
60✔
4986
        if remoteCsvDelay == 0 {
119✔
4987
                remoteCsvDelay = f.cfg.RequiredRemoteDelay(capacity)
59✔
4988
        }
59✔
4989

4990
        // If no minimum HTLC value was specified, use the default one.
4991
        if minHtlcIn == 0 {
119✔
4992
                minHtlcIn = f.cfg.DefaultMinHtlcIn
59✔
4993
        }
59✔
4994

4995
        // If no max value was specified, use the default one.
4996
        if maxValue == 0 {
119✔
4997
                maxValue = f.cfg.RequiredRemoteMaxValue(capacity)
59✔
4998
        }
59✔
4999

5000
        if maxHtlcs == 0 {
120✔
5001
                maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
60✔
5002
        }
60✔
5003

5004
        // Once the reservation has been created, and indexed, queue a funding
5005
        // request to the remote peer, kicking off the funding workflow.
5006
        ourContribution := reservation.OurContribution()
60✔
5007

60✔
5008
        // Prepare the optional channel fee values from the initFundingMsg. If
60✔
5009
        // useBaseFee or useFeeRate are false the client did not provide fee
60✔
5010
        // values hence we assume default fee settings from the config.
60✔
5011
        forwardingPolicy := f.defaultForwardingPolicy(
60✔
5012
                ourContribution.ChannelStateBounds,
60✔
5013
        )
60✔
5014
        if baseFee != nil {
64✔
5015
                forwardingPolicy.BaseFee = lnwire.MilliSatoshi(*baseFee)
4✔
5016
        }
4✔
5017

5018
        if feeRate != nil {
64✔
5019
                forwardingPolicy.FeeRate = lnwire.MilliSatoshi(*feeRate)
4✔
5020
        }
4✔
5021

5022
        // Fetch our dust limit which is part of the default channel
5023
        // constraints, and log it.
5024
        ourDustLimit := ourContribution.DustLimit
60✔
5025

60✔
5026
        log.Infof("Dust limit for pendingID(%x): %v", chanID, ourDustLimit)
60✔
5027

60✔
5028
        // If the channel reserve is not specified, then we calculate an
60✔
5029
        // appropriate amount here.
60✔
5030
        if chanReserve == 0 {
116✔
5031
                chanReserve = f.cfg.RequiredRemoteChanReserve(
56✔
5032
                        capacity, ourDustLimit,
56✔
5033
                )
56✔
5034
        }
56✔
5035

5036
        // If a pending channel map for this peer isn't already created, then
5037
        // we create one, ultimately allowing us to track this pending
5038
        // reservation within the target peer.
5039
        peerIDKey := newSerializedKey(peerKey)
60✔
5040
        f.resMtx.Lock()
60✔
5041
        if _, ok := f.activeReservations[peerIDKey]; !ok {
113✔
5042
                f.activeReservations[peerIDKey] = make(pendingChannels)
53✔
5043
        }
53✔
5044

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

60✔
5063
        // Update the timestamp once the InitFundingMsg has been handled.
60✔
5064
        defer resCtx.updateTimestamp()
60✔
5065

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

5087
                msg.Err <- err
2✔
5088
                return
2✔
5089
        }
5090

5091
        // When opening a script enforced channel lease, include the required
5092
        // expiry TLV record in our proposal.
5093
        var leaseExpiry *lnwire.LeaseExpiry
58✔
5094
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
61✔
5095
                leaseExpiry = new(lnwire.LeaseExpiry)
3✔
5096
                *leaseExpiry = lnwire.LeaseExpiry(reservation.LeaseExpiry())
3✔
5097
        }
3✔
5098

5099
        log.Infof("Starting funding workflow with %v for pending_id(%x), "+
58✔
5100
                "committype=%v", msg.Peer.Address(), chanID, commitType)
58✔
5101

58✔
5102
        reservation.SetState(lnwallet.SentOpenChannel)
58✔
5103

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

58✔
5128
        if commitType.IsTaproot() {
63✔
5129
                fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
5✔
5130
                        ourContribution.LocalNonce.PubNonce,
5✔
5131
                )
5✔
5132
        }
5✔
5133

5134
        if err := msg.Peer.SendMessage(true, &fundingOpen); err != nil {
58✔
5135
                e := fmt.Errorf("unable to send funding request message: %w",
×
5136
                        err)
×
5137
                log.Errorf(e.Error())
×
5138

×
5139
                // Since we were unable to send the initial message to the peer
×
5140
                // and start the funding flow, we'll cancel this reservation.
×
5141
                _, err := f.cancelReservationCtx(peerKey, chanID, false)
×
5142
                if err != nil {
×
5143
                        log.Errorf("unable to cancel reservation: %v", err)
×
5144
                }
×
5145

5146
                msg.Err <- e
×
5147
                return
×
5148
        }
5149
}
5150

5151
// handleWarningMsg processes the warning which was received from remote peer.
5152
func (f *Manager) handleWarningMsg(peer lnpeer.Peer, msg *lnwire.Warning) {
44✔
5153
        log.Warnf("received warning message from peer %x: %v",
44✔
5154
                peer.IdentityKey().SerializeCompressed(), msg.Warning())
44✔
5155
}
44✔
5156

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

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

5174
        // If we did indeed find the funding workflow, then we'll return the
5175
        // error back to the caller (if any), and cancel the workflow itself.
5176
        fundingErr := fmt.Errorf("received funding error from %x: %v",
3✔
5177
                peerKey.SerializeCompressed(), msg.Error(),
3✔
5178
        )
3✔
5179
        log.Errorf(fundingErr.Error())
3✔
5180

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

5189
        resCtx.err <- fundingErr
3✔
5190
}
5191

5192
// pruneZombieReservations loops through all pending reservations and fails the
5193
// funding flow for any reservations that have not been updated since the
5194
// ReservationTimeout and are not locked waiting for the funding transaction.
5195
func (f *Manager) pruneZombieReservations() {
6✔
5196
        zombieReservations := make(pendingChannels)
6✔
5197

6✔
5198
        f.resMtx.RLock()
6✔
5199
        for _, pendingReservations := range f.activeReservations {
12✔
5200
                for pendingChanID, resCtx := range pendingReservations {
12✔
5201
                        if resCtx.isLocked() {
6✔
5202
                                continue
×
5203
                        }
5204

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

6✔
5219
        for pendingChanID, resCtx := range zombieReservations {
12✔
5220
                err := fmt.Errorf("reservation timed out waiting for peer "+
6✔
5221
                        "(peer_id:%x, chan_id:%x)",
6✔
5222
                        resCtx.peer.IdentityKey().SerializeCompressed(),
6✔
5223
                        pendingChanID[:])
6✔
5224
                log.Warnf(err.Error())
6✔
5225

6✔
5226
                chanID := lnwire.NewChanIDFromOutPoint(
6✔
5227
                        *resCtx.reservation.FundingOutpoint(),
6✔
5228
                )
6✔
5229

6✔
5230
                // Create channel identifier and set the channel ID.
6✔
5231
                cid := newChanIdentifier(pendingChanID)
6✔
5232
                cid.setChanID(chanID)
6✔
5233

6✔
5234
                f.failFundingFlow(resCtx.peer, cid, err)
6✔
5235
        }
6✔
5236
}
5237

5238
// cancelReservationCtx does all needed work in order to securely cancel the
5239
// reservation.
5240
func (f *Manager) cancelReservationCtx(peerKey *btcec.PublicKey,
5241
        pendingChanID PendingChanID,
5242
        byRemote bool) (*reservationWithCtx, error) {
27✔
5243

27✔
5244
        log.Infof("Cancelling funding reservation for node_key=%x, "+
27✔
5245
                "chan_id=%x", peerKey.SerializeCompressed(), pendingChanID[:])
27✔
5246

27✔
5247
        peerIDKey := newSerializedKey(peerKey)
27✔
5248
        f.resMtx.Lock()
27✔
5249
        defer f.resMtx.Unlock()
27✔
5250

27✔
5251
        nodeReservations, ok := f.activeReservations[peerIDKey]
27✔
5252
        if !ok {
38✔
5253
                // No reservations for this node.
11✔
5254
                return nil, fmt.Errorf("no active reservations for peer(%x)",
11✔
5255
                        peerIDKey[:])
11✔
5256
        }
11✔
5257

5258
        ctx, ok := nodeReservations[pendingChanID]
19✔
5259
        if !ok {
21✔
5260
                return nil, fmt.Errorf("unknown channel (id: %x) for "+
2✔
5261
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
2✔
5262
        }
2✔
5263

5264
        // If the reservation was a PSBT funding flow and it was canceled by the
5265
        // remote peer, then we need to thread through a different error message
5266
        // to the subroutine that's waiting for the user input so it can return
5267
        // a nice error message to the user.
5268
        if ctx.reservation.IsPsbt() && byRemote {
20✔
5269
                ctx.reservation.RemoteCanceled()
3✔
5270
        }
3✔
5271

5272
        if err := ctx.reservation.Cancel(); err != nil {
17✔
5273
                return nil, fmt.Errorf("unable to cancel reservation: %w", err)
×
5274
        }
×
5275

5276
        delete(nodeReservations, pendingChanID)
17✔
5277

17✔
5278
        // If this was the last active reservation for this peer, delete the
17✔
5279
        // peer's entry altogether.
17✔
5280
        if len(nodeReservations) == 0 {
34✔
5281
                delete(f.activeReservations, peerIDKey)
17✔
5282
        }
17✔
5283
        return ctx, nil
17✔
5284
}
5285

5286
// deleteReservationCtx deletes the reservation uniquely identified by the
5287
// target public key of the peer, and the specified pending channel ID.
5288
func (f *Manager) deleteReservationCtx(peerKey *btcec.PublicKey,
5289
        pendingChanID PendingChanID) {
59✔
5290

59✔
5291
        peerIDKey := newSerializedKey(peerKey)
59✔
5292
        f.resMtx.Lock()
59✔
5293
        defer f.resMtx.Unlock()
59✔
5294

59✔
5295
        nodeReservations, ok := f.activeReservations[peerIDKey]
59✔
5296
        if !ok {
59✔
5297
                // No reservations for this node.
×
5298
                return
×
5299
        }
×
5300
        delete(nodeReservations, pendingChanID)
59✔
5301

59✔
5302
        // If this was the last active reservation for this peer, delete the
59✔
5303
        // peer's entry altogether.
59✔
5304
        if len(nodeReservations) == 0 {
111✔
5305
                delete(f.activeReservations, peerIDKey)
52✔
5306
        }
52✔
5307
}
5308

5309
// getReservationCtx returns the reservation context for a particular pending
5310
// channel ID for a target peer.
5311
func (f *Manager) getReservationCtx(peerKey *btcec.PublicKey,
5312
        pendingChanID PendingChanID) (*reservationWithCtx, error) {
94✔
5313

94✔
5314
        peerIDKey := newSerializedKey(peerKey)
94✔
5315
        f.resMtx.RLock()
94✔
5316
        resCtx, ok := f.activeReservations[peerIDKey][pendingChanID]
94✔
5317
        f.resMtx.RUnlock()
94✔
5318

94✔
5319
        if !ok {
97✔
5320
                return nil, fmt.Errorf("unknown channel (id: %x) for "+
3✔
5321
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
3✔
5322
        }
3✔
5323

5324
        return resCtx, nil
94✔
5325
}
5326

5327
// IsPendingChannel returns a boolean indicating whether the channel identified
5328
// by the pendingChanID and given peer is pending, meaning it is in the process
5329
// of being funded. After the funding transaction has been confirmed, the
5330
// channel will receive a new, permanent channel ID, and will no longer be
5331
// considered pending.
5332
func (f *Manager) IsPendingChannel(pendingChanID PendingChanID,
5333
        peer lnpeer.Peer) bool {
3✔
5334

3✔
5335
        peerIDKey := newSerializedKey(peer.IdentityKey())
3✔
5336
        f.resMtx.RLock()
3✔
5337
        _, ok := f.activeReservations[peerIDKey][pendingChanID]
3✔
5338
        f.resMtx.RUnlock()
3✔
5339

3✔
5340
        return ok
3✔
5341
}
3✔
5342

5343
func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
388✔
5344
        var tmp btcec.JacobianPoint
388✔
5345
        pub.AsJacobian(&tmp)
388✔
5346
        tmp.ToAffine()
388✔
5347
        return btcec.NewPublicKey(&tmp.X, &tmp.Y)
388✔
5348
}
388✔
5349

5350
// defaultForwardingPolicy returns the default forwarding policy based on the
5351
// default routing policy and our local channel constraints.
5352
func (f *Manager) defaultForwardingPolicy(
5353
        bounds channeldb.ChannelStateBounds) *models.ForwardingPolicy {
107✔
5354

107✔
5355
        return &models.ForwardingPolicy{
107✔
5356
                MinHTLCOut:    bounds.MinHTLC,
107✔
5357
                MaxHTLC:       bounds.MaxPendingAmount,
107✔
5358
                BaseFee:       f.cfg.DefaultRoutingPolicy.BaseFee,
107✔
5359
                FeeRate:       f.cfg.DefaultRoutingPolicy.FeeRate,
107✔
5360
                TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
107✔
5361
        }
107✔
5362
}
107✔
5363

5364
// saveInitialForwardingPolicy saves the forwarding policy for the provided
5365
// chanPoint in the channelOpeningStateBucket.
5366
func (f *Manager) saveInitialForwardingPolicy(chanID lnwire.ChannelID,
5367
        forwardingPolicy *models.ForwardingPolicy) error {
72✔
5368

72✔
5369
        return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
72✔
5370
                chanID, forwardingPolicy,
72✔
5371
        )
72✔
5372
}
72✔
5373

5374
// getInitialForwardingPolicy fetches the initial forwarding policy for a given
5375
// channel id from the database which will be applied during the channel
5376
// announcement phase.
5377
func (f *Manager) getInitialForwardingPolicy(
5378
        chanID lnwire.ChannelID) (*models.ForwardingPolicy, error) {
97✔
5379

97✔
5380
        return f.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
97✔
5381
}
97✔
5382

5383
// deleteInitialForwardingPolicy removes channel fees for this chanID from
5384
// the database.
5385
func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
27✔
5386
        return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
27✔
5387
}
27✔
5388

5389
// saveChannelOpeningState saves the channelOpeningState for the provided
5390
// chanPoint to the channelOpeningStateBucket.
5391
func (f *Manager) saveChannelOpeningState(chanPoint *wire.OutPoint,
5392
        state channelOpeningState, shortChanID *lnwire.ShortChannelID) error {
95✔
5393

95✔
5394
        var outpointBytes bytes.Buffer
95✔
5395
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
95✔
5396
                return err
×
5397
        }
×
5398

5399
        // Save state and the uint64 representation of the shortChanID
5400
        // for later use.
5401
        scratch := make([]byte, 10)
95✔
5402
        byteOrder.PutUint16(scratch[:2], uint16(state))
95✔
5403
        byteOrder.PutUint64(scratch[2:], shortChanID.ToUint64())
95✔
5404

95✔
5405
        return f.cfg.ChannelDB.SaveChannelOpeningState(
95✔
5406
                outpointBytes.Bytes(), scratch,
95✔
5407
        )
95✔
5408
}
5409

5410
// getChannelOpeningState fetches the channelOpeningState for the provided
5411
// chanPoint from the database, or returns ErrChannelNotFound if the channel
5412
// is not found.
5413
func (f *Manager) getChannelOpeningState(chanPoint *wire.OutPoint) (
5414
        channelOpeningState, *lnwire.ShortChannelID, error) {
255✔
5415

255✔
5416
        var outpointBytes bytes.Buffer
255✔
5417
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
255✔
5418
                return 0, nil, err
×
5419
        }
×
5420

5421
        value, err := f.cfg.ChannelDB.GetChannelOpeningState(
255✔
5422
                outpointBytes.Bytes(),
255✔
5423
        )
255✔
5424
        if err != nil {
307✔
5425
                return 0, nil, err
52✔
5426
        }
52✔
5427

5428
        state := channelOpeningState(byteOrder.Uint16(value[:2]))
206✔
5429
        shortChanID := lnwire.NewShortChanIDFromInt(byteOrder.Uint64(value[2:]))
206✔
5430
        return state, &shortChanID, nil
206✔
5431
}
5432

5433
// deleteChannelOpeningState removes any state for chanPoint from the database.
5434
func (f *Manager) deleteChannelOpeningState(chanPoint *wire.OutPoint) error {
27✔
5435
        var outpointBytes bytes.Buffer
27✔
5436
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
27✔
5437
                return err
×
5438
        }
×
5439

5440
        return f.cfg.ChannelDB.DeleteChannelOpeningState(
27✔
5441
                outpointBytes.Bytes(),
27✔
5442
        )
27✔
5443
}
5444

5445
// selectShutdownScript selects the shutdown script we should send to the peer.
5446
// If we can use taproot, then we prefer that, otherwise we'll use a p2wkh
5447
// script.
5448
func (f *Manager) selectShutdownScript(taprootOK bool,
5449
) (lnwire.DeliveryAddress, error) {
×
5450

×
5451
        addrType := lnwallet.WitnessPubKey
×
5452
        if taprootOK {
×
5453
                addrType = lnwallet.TaprootPubkey
×
5454
        }
×
5455

5456
        addr, err := f.cfg.Wallet.NewAddress(
×
5457
                addrType, false, lnwallet.DefaultAccountName,
×
5458
        )
×
5459
        if err != nil {
×
5460
                return nil, err
×
5461
        }
×
5462

5463
        return txscript.PayToAddrScript(addr)
×
5464
}
5465

5466
// waitForPeerOnline blocks until the peer specified by peerPubkey comes online
5467
// and then returns the online peer.
5468
func (f *Manager) waitForPeerOnline(peerPubkey *btcec.PublicKey) (lnpeer.Peer,
5469
        error) {
108✔
5470

108✔
5471
        peerChan := make(chan lnpeer.Peer, 1)
108✔
5472

108✔
5473
        var peerKey [33]byte
108✔
5474
        copy(peerKey[:], peerPubkey.SerializeCompressed())
108✔
5475

108✔
5476
        f.cfg.NotifyWhenOnline(peerKey, peerChan)
108✔
5477

108✔
5478
        var peer lnpeer.Peer
108✔
5479
        select {
108✔
5480
        case peer = <-peerChan:
107✔
5481
        case <-f.quit:
1✔
5482
                return peer, ErrFundingManagerShuttingDown
1✔
5483
        }
5484
        return peer, nil
107✔
5485
}
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