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

lightningnetwork / lnd / 14954529010

11 May 2025 09:40AM UTC coverage: 69.023% (+10.4%) from 58.59%
14954529010

Pull #9677

github

web-flow
Merge 675a70980 into ee25c228e
Pull Request #9677: Expose confirmation count for pending 'channel open' transactions

124 of 170 new or added lines in 5 files covered. (72.94%)

31 existing lines in 6 files now uncovered.

134062 of 194227 relevant lines covered (69.02%)

22131.88 hits per line

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

73.23
/funding/manager.go
1
package funding
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

103
        msgBufferSize = 50
104

105
        // 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() {
137✔
184
        r.updateMtx.Lock()
137✔
185
        defer r.updateMtx.Unlock()
137✔
186

137✔
187
        r.lastUpdated = time.Now()
137✔
188
}
137✔
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 {
381✔
327
        var s serializedPubKey
381✔
328
        copy(s[:], pubKey.SerializeCompressed())
381✔
329
        return s
381✔
330
}
381✔
331

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

339
        // MaxWaitNumBlocksFundingConf is the maximum number of blocks to wait
340
        // for the funding transaction to be confirmed before forgetting
341
        // channels that aren't initiated by us.
342
        MaxWaitNumBlocksFundingConf uint32
343
}
344

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

110✔
782
        return nil
110✔
783
}
784

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

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

796
        return nil
107✔
797
}
798

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

37✔
1196
                return nil
37✔
1197

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

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

1221
                        return nil
27✔
1222
                }
1223

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

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

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

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

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

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

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

27✔
1277
                return nil
27✔
1278
        }
1279

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

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

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

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

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

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

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

1338
                return nil
7✔
1339
        }
1340

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

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

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

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

×
1368
                        return err
×
1369
                }
×
1370

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

×
1380
                        return err
×
1381
                }
×
1382

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

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

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

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

1409
        return nil
33✔
1410
}
1411

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

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

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

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

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

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

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

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

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

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

7✔
1485
                return
7✔
1486
        }
7✔
1487

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1648
                return
×
1649

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

×
1658
                return
×
1659
        }
1660

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

×
1675
                return
×
1676
        }
×
1677

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

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

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

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

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

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

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

1738
        reservation.SetNumConfsRequired(numConfsReq)
49✔
1739

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1927
                        return
×
1928
                }
×
1929

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2116
                minDepth = 1
×
2117
        }
×
2118

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

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

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

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

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

×
2187
                        return
×
2188
                }
×
2189

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2427
                        return
×
2428
                }
×
2429

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

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

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

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

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

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

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

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

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

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

×
2495
                        return
×
2496
                }
×
2497

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

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

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

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

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

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

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

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

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

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

×
2602
                        return
×
2603
                }
×
2604

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

×
2615
                        return
×
2616
                }
×
2617
        }
2618

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2752
                return
×
2753
        }
×
2754

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

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

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

×
2781
                        return
×
2782
                }
×
2783

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3001
        return timeoutErr
5✔
3002
}
3003

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

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

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

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

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

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

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

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

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

3064
                return pkScript, nil
8✔
3065
        }
3066

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

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

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

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

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

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

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

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

60✔
3127
        // Wait until the specified number of confirmations has been reached,
60✔
3128
        // we get a cancel signal, or the wallet signals a shutdown.
60✔
3129
        for {
120✔
3130
                select {
60✔
3131
                case updDetails := <-confNtfn.Updates:
3✔
3132
                        log.Debugf("funding tx %s received confirmation in "+
3✔
3133
                                "block %d", txid, updDetails.BlockHeight)
3✔
3134

3✔
3135
                        // Only update the ConfirmationHeight the first time a
3✔
3136
                        // confirmation is received, since on subsequent
3✔
3137
                        // confirmations the block height will remain the same.
3✔
3138
                        if completeChan.ConfirmationHeight == 0 {
6✔
3139
                                err := completeChan.MarkConfirmationHeight(
3✔
3140
                                        updDetails.BlockHeight,
3✔
3141
                                )
3✔
3142
                                if err != nil {
3✔
NEW
3143
                                        log.Errorf("failed to update "+
×
NEW
3144
                                                "confirmed state for "+
×
NEW
3145
                                                "ChannelPoint(%v): %v",
×
NEW
3146
                                                completeChan.FundingOutpoint,
×
NEW
3147
                                                err)
×
UNCOV
3148

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

NEW
3153
                case <-confNtfn.NegativeConf:
×
NEW
3154
                        log.Warnf("funding tx %s was reorged out; channel "+
×
NEW
3155
                                "point: %s", txid, completeChan.FundingOutpoint)
×
UNCOV
3156

×
NEW
3157
                        // Reset the confirmation height to 0 because the
×
NEW
3158
                        // funding transaction was reorged out.
×
NEW
3159
                        err := completeChan.MarkConfirmationHeight(uint32(0))
×
NEW
3160
                        if err != nil {
×
NEW
3161
                                log.Errorf("failed to update state for "+
×
NEW
3162
                                        "ChannelPoint(%v): %v",
×
NEW
3163
                                        completeChan.FundingOutpoint, err)
×
NEW
3164

×
NEW
3165
                                return
×
NEW
3166
                        }
×
3167

3168
                case confDetails, ok := <-confNtfn.Confirmed:
37✔
3169
                        if !ok {
37✔
NEW
3170
                                log.Warnf("ChainNotifier shutting down, "+
×
NEW
3171
                                        "cannot complete funding flow for "+
×
NEW
3172
                                        "ChannelPoint(%v)",
×
NEW
3173
                                        completeChan.FundingOutpoint)
×
NEW
3174

×
NEW
3175
                                return
×
NEW
3176
                        }
×
3177

3178
                        // Handle the case where numConfs is 1 and the Confirmed
3179
                        // channel fires before Updates. When multiple cases in
3180
                        // a select are ready, Go makes a uniform pseudo-random
3181
                        // choice between them.
3182
                        if completeChan.ConfirmationHeight == 0 {
71✔
3183
                                err := completeChan.MarkConfirmationHeight(
34✔
3184
                                        confDetails.BlockHeight,
34✔
3185
                                )
34✔
3186
                                if err != nil {
34✔
NEW
3187
                                        log.Errorf("failed to update "+
×
NEW
3188
                                                "confirmed state for "+
×
NEW
3189
                                                "ChannelPoint(%v): %v",
×
NEW
3190
                                                completeChan.FundingOutpoint,
×
NEW
3191
                                                err)
×
NEW
3192

×
NEW
3193
                                        return
×
NEW
3194
                                }
×
3195
                        }
3196

3197
                        err := f.handleConfirmation(
37✔
3198
                                confDetails, completeChan, confChan,
37✔
3199
                        )
37✔
3200
                        if err != nil {
37✔
NEW
3201
                                log.Errorf("Error handling confirmation for "+
×
NEW
3202
                                        "ChannelPoint(%v), txid=%v: %v",
×
NEW
3203
                                        completeChan.FundingOutpoint, txid, err)
×
NEW
3204
                        }
×
3205

3206
                        return
37✔
3207

3208
                case <-cancelChan:
7✔
3209
                        log.Warnf("canceled waiting for funding confirmation, "+
7✔
3210
                                "stopping funding flow for ChannelPoint(%v)",
7✔
3211
                                completeChan.FundingOutpoint)
7✔
3212

7✔
3213
                        return
7✔
3214

3215
                case <-f.quit:
22✔
3216
                        log.Warnf("fundingManager shutting down, stopping "+
22✔
3217
                                "funding flow for ChannelPoint(%v)",
22✔
3218
                                completeChan.FundingOutpoint)
22✔
3219

22✔
3220
                        return
22✔
3221
                }
3222
        }
3223
}
3224

3225
// handleConfirmation is a helper function that constructs a ShortChannelID
3226
// based on the confirmation details and sends this information, along with the
3227
// funding transaction, to the provided confirmation channel.
3228
func (f *Manager) handleConfirmation(confDetails *chainntnfs.TxConfirmation,
3229
        completeChan *channeldb.OpenChannel,
3230
        confChan chan<- *confirmedChannel) error {
37✔
3231

37✔
3232
        fundingPoint := completeChan.FundingOutpoint
37✔
3233
        log.Infof("ChannelPoint(%v) is now active: ChannelID(%v)",
37✔
3234
                fundingPoint, lnwire.NewChanIDFromOutPoint(fundingPoint))
37✔
3235

37✔
3236
        // With the block height and the transaction index known, we can
37✔
3237
        // construct the compact chanID which is used on the network to unique
37✔
3238
        // identify channels.
37✔
3239
        shortChanID := lnwire.ShortChannelID{
37✔
3240
                BlockHeight: confDetails.BlockHeight,
37✔
3241
                TxIndex:     confDetails.TxIndex,
37✔
3242
                TxPosition:  uint16(fundingPoint.Index),
37✔
3243
        }
37✔
3244

37✔
3245
        select {
37✔
3246
        case confChan <- &confirmedChannel{
3247
                shortChanID: shortChanID,
3248
                fundingTx:   confDetails.Tx,
3249
        }:
37✔
3250
        case <-f.quit:
×
NEW
3251
                return fmt.Errorf("manager shutting down")
×
3252
        }
3253

3254
        return nil
37✔
3255
}
3256

3257
// waitForTimeout will close the timeout channel if MaxWaitNumBlocksFundingConf
3258
// has passed from the broadcast height of the given channel. In case of error,
3259
// the error is sent on timeoutChan. The wait can be canceled by closing the
3260
// cancelChan.
3261
//
3262
// NOTE: timeoutChan MUST be buffered.
3263
// NOTE: This MUST be run as a goroutine.
3264
func (f *Manager) waitForTimeout(completeChan *channeldb.OpenChannel,
3265
        cancelChan <-chan struct{}, timeoutChan chan<- error) {
28✔
3266

28✔
3267
        defer f.wg.Done()
28✔
3268

28✔
3269
        epochClient, err := f.cfg.Notifier.RegisterBlockEpochNtfn(nil)
28✔
3270
        if err != nil {
28✔
3271
                timeoutChan <- fmt.Errorf("unable to register for epoch "+
×
3272
                        "notification: %v", err)
×
3273
                return
×
3274
        }
×
3275

3276
        defer epochClient.Cancel()
28✔
3277

28✔
3278
        // The value of waitBlocksForFundingConf is adjusted in a development
28✔
3279
        // environment to enhance test capabilities. Otherwise, it is set to
28✔
3280
        // DefaultMaxWaitNumBlocksFundingConf.
28✔
3281
        waitBlocksForFundingConf := uint32(
28✔
3282
                lncfg.DefaultMaxWaitNumBlocksFundingConf,
28✔
3283
        )
28✔
3284

28✔
3285
        if lncfg.IsDevBuild() {
31✔
3286
                waitBlocksForFundingConf =
3✔
3287
                        f.cfg.Dev.MaxWaitNumBlocksFundingConf
3✔
3288
        }
3✔
3289

3290
        // On block maxHeight we will cancel the funding confirmation wait.
3291
        broadcastHeight := completeChan.BroadcastHeight()
28✔
3292
        maxHeight := broadcastHeight + waitBlocksForFundingConf
28✔
3293
        for {
58✔
3294
                select {
30✔
3295
                case epoch, ok := <-epochClient.Epochs:
7✔
3296
                        if !ok {
7✔
3297
                                timeoutChan <- fmt.Errorf("epoch client " +
×
3298
                                        "shutting down")
×
3299
                                return
×
3300
                        }
×
3301

3302
                        // Close the timeout channel and exit if the block is
3303
                        // above the max height.
3304
                        if uint32(epoch.Height) >= maxHeight {
12✔
3305
                                log.Warnf("Waited for %v blocks without "+
5✔
3306
                                        "seeing funding transaction confirmed,"+
5✔
3307
                                        " cancelling.",
5✔
3308
                                        waitBlocksForFundingConf)
5✔
3309

5✔
3310
                                // Notify the caller of the timeout.
5✔
3311
                                close(timeoutChan)
5✔
3312
                                return
5✔
3313
                        }
5✔
3314

3315
                        // TODO: If we are the channel initiator implement
3316
                        // a method for recovering the funds from the funding
3317
                        // transaction
3318

3319
                case <-cancelChan:
18✔
3320
                        return
18✔
3321

3322
                case <-f.quit:
11✔
3323
                        // The fundingManager is shutting down, will resume
11✔
3324
                        // waiting for the funding transaction on startup.
11✔
3325
                        return
11✔
3326
                }
3327
        }
3328
}
3329

3330
// makeLabelForTx updates the label for the confirmed funding transaction. If
3331
// we opened the channel, and lnd's wallet published our funding tx (which is
3332
// not the case for some channels) then we update our transaction label with
3333
// our short channel ID, which is known now that our funding transaction has
3334
// confirmed. We do not label transactions we did not publish, because our
3335
// wallet has no knowledge of them.
3336
func (f *Manager) makeLabelForTx(c *channeldb.OpenChannel) {
37✔
3337
        if c.IsInitiator && c.ChanType.HasFundingTx() {
56✔
3338
                shortChanID := c.ShortChanID()
19✔
3339

19✔
3340
                // For zero-conf channels, we'll use the actually-confirmed
19✔
3341
                // short channel id.
19✔
3342
                if c.IsZeroConf() {
24✔
3343
                        shortChanID = c.ZeroConfRealScid()
5✔
3344
                }
5✔
3345

3346
                label := labels.MakeLabel(
19✔
3347
                        labels.LabelTypeChannelOpen, &shortChanID,
19✔
3348
                )
19✔
3349

19✔
3350
                err := f.cfg.UpdateLabel(c.FundingOutpoint.Hash, label)
19✔
3351
                if err != nil {
19✔
3352
                        log.Errorf("unable to update label: %v", err)
×
3353
                }
×
3354
        }
3355
}
3356

3357
// handleFundingConfirmation marks a channel as open in the database, and set
3358
// the channelOpeningState markedOpen. In addition it will report the now
3359
// decided short channel ID to the switch, and close the local discovery signal
3360
// for this channel.
3361
func (f *Manager) handleFundingConfirmation(
3362
        completeChan *channeldb.OpenChannel,
3363
        confChannel *confirmedChannel) error {
33✔
3364

33✔
3365
        fundingPoint := completeChan.FundingOutpoint
33✔
3366
        chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
33✔
3367

33✔
3368
        // TODO(roasbeef): ideally persistent state update for chan above
33✔
3369
        // should be abstracted
33✔
3370

33✔
3371
        // Now that that the channel has been fully confirmed, we'll request
33✔
3372
        // that the wallet fully verify this channel to ensure that it can be
33✔
3373
        // used.
33✔
3374
        err := f.cfg.Wallet.ValidateChannel(completeChan, confChannel.fundingTx)
33✔
3375
        if err != nil {
33✔
3376
                // TODO(roasbeef): delete chan state?
×
3377
                return fmt.Errorf("unable to validate channel: %w", err)
×
3378
        }
×
3379

3380
        // Now that the channel has been validated, we'll persist an alias for
3381
        // this channel if the option-scid-alias feature-bit was negotiated.
3382
        if completeChan.NegotiatedAliasFeature() {
38✔
3383
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
5✔
3384
                if err != nil {
5✔
3385
                        return fmt.Errorf("unable to request alias: %w", err)
×
3386
                }
×
3387

3388
                err = f.cfg.AliasManager.AddLocalAlias(
5✔
3389
                        aliasScid, confChannel.shortChanID, true, false,
5✔
3390
                )
5✔
3391
                if err != nil {
5✔
3392
                        return fmt.Errorf("unable to request alias: %w", err)
×
3393
                }
×
3394
        }
3395

3396
        // The funding transaction now being confirmed, we add this channel to
3397
        // the fundingManager's internal persistent state machine that we use
3398
        // to track the remaining process of the channel opening. This is
3399
        // useful to resume the opening process in case of restarts. We set the
3400
        // opening state before we mark the channel opened in the database,
3401
        // such that we can receover from one of the db writes failing.
3402
        err = f.saveChannelOpeningState(
33✔
3403
                &fundingPoint, markedOpen, &confChannel.shortChanID,
33✔
3404
        )
33✔
3405
        if err != nil {
33✔
3406
                return fmt.Errorf("error setting channel state to "+
×
3407
                        "markedOpen: %v", err)
×
3408
        }
×
3409

3410
        // Now that the channel has been fully confirmed and we successfully
3411
        // saved the opening state, we'll mark it as open within the database.
3412
        err = completeChan.MarkAsOpen(confChannel.shortChanID)
33✔
3413
        if err != nil {
33✔
3414
                return fmt.Errorf("error setting channel pending flag to "+
×
3415
                        "false:        %v", err)
×
3416
        }
×
3417

3418
        // Update the confirmed funding transaction label.
3419
        f.makeLabelForTx(completeChan)
33✔
3420

33✔
3421
        // Inform the ChannelNotifier that the channel has transitioned from
33✔
3422
        // pending open to open.
33✔
3423
        if err := f.cfg.NotifyOpenChannelEvent(
33✔
3424
                completeChan.FundingOutpoint, completeChan.IdentityPub,
33✔
3425
        ); err != nil {
36✔
3426
                log.Errorf("Unable to notify open channel event for "+
3✔
3427
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
3✔
3428
                        err)
3✔
3429
        }
3✔
3430

3431
        // Close the discoverySignal channel, indicating to a separate
3432
        // goroutine that the channel now is marked as open in the database
3433
        // and that it is acceptable to process channel_ready messages
3434
        // from the peer.
3435
        if discoverySignal, ok := f.localDiscoverySignals.Load(chanID); ok {
66✔
3436
                close(discoverySignal)
33✔
3437
        }
33✔
3438

3439
        return nil
33✔
3440
}
3441

3442
// sendChannelReady creates and sends the channelReady message.
3443
// This should be called after the funding transaction has been confirmed,
3444
// and the channelState is 'markedOpen'.
3445
func (f *Manager) sendChannelReady(completeChan *channeldb.OpenChannel,
3446
        channel *lnwallet.LightningChannel) error {
38✔
3447

38✔
3448
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
38✔
3449

38✔
3450
        var peerKey [33]byte
38✔
3451
        copy(peerKey[:], completeChan.IdentityPub.SerializeCompressed())
38✔
3452

38✔
3453
        // Next, we'll send over the channel_ready message which marks that we
38✔
3454
        // consider the channel open by presenting the remote party with our
38✔
3455
        // next revocation key. Without the revocation key, the remote party
38✔
3456
        // will be unable to propose state transitions.
38✔
3457
        nextRevocation, err := channel.NextRevocationKey()
38✔
3458
        if err != nil {
38✔
3459
                return fmt.Errorf("unable to create next revocation: %w", err)
×
3460
        }
×
3461
        channelReadyMsg := lnwire.NewChannelReady(chanID, nextRevocation)
38✔
3462

38✔
3463
        // If this is a taproot channel, then we also need to send along our
38✔
3464
        // set of musig2 nonces as well.
38✔
3465
        if completeChan.ChanType.IsTaproot() {
45✔
3466
                log.Infof("ChanID(%v): generating musig2 nonces...",
7✔
3467
                        chanID)
7✔
3468

7✔
3469
                f.nonceMtx.Lock()
7✔
3470
                localNonce, ok := f.pendingMusigNonces[chanID]
7✔
3471
                if !ok {
14✔
3472
                        // If we don't have any nonces generated yet for this
7✔
3473
                        // first state, then we'll generate them now and stow
7✔
3474
                        // them away.  When we receive the funding locked
7✔
3475
                        // message, we'll then pass along this same set of
7✔
3476
                        // nonces.
7✔
3477
                        newNonce, err := channel.GenMusigNonces()
7✔
3478
                        if err != nil {
7✔
3479
                                f.nonceMtx.Unlock()
×
3480
                                return err
×
3481
                        }
×
3482

3483
                        // Now that we've generated the nonce for this channel,
3484
                        // we'll store it in the set of pending nonces.
3485
                        localNonce = newNonce
7✔
3486
                        f.pendingMusigNonces[chanID] = localNonce
7✔
3487
                }
3488
                f.nonceMtx.Unlock()
7✔
3489

7✔
3490
                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
7✔
3491
                        localNonce.PubNonce,
7✔
3492
                )
7✔
3493
        }
3494

3495
        // If the channel negotiated the option-scid-alias feature bit, we'll
3496
        // send a TLV segment that includes an alias the peer can use in their
3497
        // invoice hop hints. We'll send the first alias we find for the
3498
        // channel since it does not matter which alias we send. We'll error
3499
        // out in the odd case that no aliases are found.
3500
        if completeChan.NegotiatedAliasFeature() {
47✔
3501
                aliases := f.cfg.AliasManager.GetAliases(
9✔
3502
                        completeChan.ShortChanID(),
9✔
3503
                )
9✔
3504
                if len(aliases) == 0 {
9✔
3505
                        return fmt.Errorf("no aliases found")
×
3506
                }
×
3507

3508
                // We can use a pointer to aliases since GetAliases returns a
3509
                // copy of the alias slice.
3510
                channelReadyMsg.AliasScid = &aliases[0]
9✔
3511
        }
3512

3513
        // If the peer has disconnected before we reach this point, we will need
3514
        // to wait for him to come back online before sending the channelReady
3515
        // message. This is special for channelReady, since failing to send any
3516
        // of the previous messages in the funding flow just cancels the flow.
3517
        // But now the funding transaction is confirmed, the channel is open
3518
        // and we have to make sure the peer gets the channelReady message when
3519
        // it comes back online. This is also crucial during restart of lnd,
3520
        // where we might try to resend the channelReady message before the
3521
        // server has had the time to connect to the peer. We keep trying to
3522
        // send channelReady until we succeed, or the fundingManager is shut
3523
        // down.
3524
        for {
76✔
3525
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
38✔
3526
                if err != nil {
39✔
3527
                        return err
1✔
3528
                }
1✔
3529

3530
                localAlias := peer.LocalFeatures().HasFeature(
37✔
3531
                        lnwire.ScidAliasOptional,
37✔
3532
                )
37✔
3533
                remoteAlias := peer.RemoteFeatures().HasFeature(
37✔
3534
                        lnwire.ScidAliasOptional,
37✔
3535
                )
37✔
3536

37✔
3537
                // We could also refresh the channel state instead of checking
37✔
3538
                // whether the feature was negotiated, but this saves us a
37✔
3539
                // database read.
37✔
3540
                if channelReadyMsg.AliasScid == nil && localAlias &&
37✔
3541
                        remoteAlias {
37✔
3542

×
3543
                        // If an alias was not assigned above and the scid
×
3544
                        // alias feature was negotiated, check if we already
×
3545
                        // have an alias stored in case handleChannelReady was
×
3546
                        // called before this. If an alias exists, use that in
×
3547
                        // channel_ready. Otherwise, request and store an
×
3548
                        // alias and use that.
×
3549
                        aliases := f.cfg.AliasManager.GetAliases(
×
3550
                                completeChan.ShortChannelID,
×
3551
                        )
×
3552
                        if len(aliases) == 0 {
×
3553
                                // No aliases were found.
×
3554
                                alias, err := f.cfg.AliasManager.RequestAlias()
×
3555
                                if err != nil {
×
3556
                                        return err
×
3557
                                }
×
3558

3559
                                err = f.cfg.AliasManager.AddLocalAlias(
×
3560
                                        alias, completeChan.ShortChannelID,
×
3561
                                        false, false,
×
3562
                                )
×
3563
                                if err != nil {
×
3564
                                        return err
×
3565
                                }
×
3566

3567
                                channelReadyMsg.AliasScid = &alias
×
3568
                        } else {
×
3569
                                channelReadyMsg.AliasScid = &aliases[0]
×
3570
                        }
×
3571
                }
3572

3573
                log.Infof("Peer(%x) is online, sending ChannelReady "+
37✔
3574
                        "for ChannelID(%v)", peerKey, chanID)
37✔
3575

37✔
3576
                if err := peer.SendMessage(true, channelReadyMsg); err == nil {
74✔
3577
                        // Sending succeeded, we can break out and continue the
37✔
3578
                        // funding flow.
37✔
3579
                        break
37✔
3580
                }
3581

3582
                log.Warnf("Unable to send channelReady to peer %x: %v. "+
×
3583
                        "Will retry when online", peerKey, err)
×
3584
        }
3585

3586
        return nil
37✔
3587
}
3588

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

63✔
3594
        // If the funding manager has exited, return an error to stop looping.
63✔
3595
        // Note that the peer may appear as online while the funding manager
63✔
3596
        // has stopped due to the shutdown order in the server.
63✔
3597
        select {
63✔
3598
        case <-f.quit:
1✔
3599
                return false, ErrFundingManagerShuttingDown
1✔
3600
        default:
62✔
3601
        }
3602

3603
        // Avoid a tight loop if peer is offline.
3604
        if _, err := f.waitForPeerOnline(node); err != nil {
62✔
UNCOV
3605
                log.Errorf("Wait for peer online failed: %v", err)
×
UNCOV
3606
                return false, err
×
UNCOV
3607
        }
×
3608

3609
        // If we cannot find the channel, then we haven't processed the
3610
        // remote's channelReady message.
3611
        channel, err := f.cfg.FindChannel(node, chanID)
62✔
3612
        if err != nil {
62✔
3613
                log.Errorf("Unable to locate ChannelID(%v) to determine if "+
×
3614
                        "ChannelReady was received", chanID)
×
3615
                return false, err
×
3616
        }
×
3617

3618
        // If we haven't insert the next revocation point, we haven't finished
3619
        // processing the channel ready message.
3620
        if channel.RemoteNextRevocation == nil {
100✔
3621
                return false, nil
38✔
3622
        }
38✔
3623

3624
        // Finally, the barrier signal is removed once we finish
3625
        // `handleChannelReady`. If we can still find the signal, we haven't
3626
        // finished processing it yet.
3627
        _, loaded := f.handleChannelReadyBarriers.Load(chanID)
27✔
3628

27✔
3629
        return !loaded, nil
27✔
3630
}
3631

3632
// extractAnnounceParams extracts the various channel announcement and update
3633
// parameters that will be needed to construct a ChannelAnnouncement and a
3634
// ChannelUpdate.
3635
func (f *Manager) extractAnnounceParams(c *channeldb.OpenChannel) (
3636
        lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
29✔
3637

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

29✔
3644
        // We don't necessarily want to go as low as the remote party allows.
29✔
3645
        // Check it against our default forwarding policy.
29✔
3646
        if fwdMinHTLC < f.cfg.DefaultRoutingPolicy.MinHTLCOut {
32✔
3647
                fwdMinHTLC = f.cfg.DefaultRoutingPolicy.MinHTLCOut
3✔
3648
        }
3✔
3649

3650
        // We'll obtain the max HTLC value we can forward in our direction, as
3651
        // we'll use this value within our ChannelUpdate. This value must be <=
3652
        // channel capacity and <= the maximum in-flight msats set by the peer.
3653
        fwdMaxHTLC := c.LocalChanCfg.MaxPendingAmount
29✔
3654
        capacityMSat := lnwire.NewMSatFromSatoshis(c.Capacity)
29✔
3655
        if fwdMaxHTLC > capacityMSat {
29✔
3656
                fwdMaxHTLC = capacityMSat
×
3657
        }
×
3658

3659
        return fwdMinHTLC, fwdMaxHTLC
29✔
3660
}
3661

3662
// addToGraph sends a ChannelAnnouncement and a ChannelUpdate to the
3663
// gossiper so that the channel is added to the graph builder's internal graph.
3664
// These announcement messages are NOT broadcasted to the greater network,
3665
// only to the channel counter party. The proofs required to announce the
3666
// channel to the greater network will be created and sent in annAfterSixConfs.
3667
// The peerAlias is used for zero-conf channels to give the counter-party a
3668
// ChannelUpdate they understand. ourPolicy may be set for various
3669
// option-scid-alias channels to re-use the same policy.
3670
func (f *Manager) addToGraph(completeChan *channeldb.OpenChannel,
3671
        shortChanID *lnwire.ShortChannelID,
3672
        peerAlias *lnwire.ShortChannelID,
3673
        ourPolicy *models.ChannelEdgePolicy) error {
29✔
3674

29✔
3675
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
29✔
3676

29✔
3677
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
29✔
3678

29✔
3679
        ann, err := f.newChanAnnouncement(
29✔
3680
                f.cfg.IDKey, completeChan.IdentityPub,
29✔
3681
                &completeChan.LocalChanCfg.MultiSigKey,
29✔
3682
                completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
29✔
3683
                chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
29✔
3684
                completeChan.ChanType,
29✔
3685
        )
29✔
3686
        if err != nil {
29✔
3687
                return fmt.Errorf("error generating channel "+
×
3688
                        "announcement: %v", err)
×
3689
        }
×
3690

3691
        // Send ChannelAnnouncement and ChannelUpdate to the gossiper to add
3692
        // to the Router's topology.
3693
        errChan := f.cfg.SendAnnouncement(
29✔
3694
                ann.chanAnn, discovery.ChannelCapacity(completeChan.Capacity),
29✔
3695
                discovery.ChannelPoint(completeChan.FundingOutpoint),
29✔
3696
                discovery.TapscriptRoot(completeChan.TapscriptRoot),
29✔
3697
        )
29✔
3698
        select {
29✔
3699
        case err := <-errChan:
29✔
3700
                if err != nil {
29✔
3701
                        if graph.IsError(err, graph.ErrOutdated,
×
3702
                                graph.ErrIgnored) {
×
3703

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

3715
        errChan = f.cfg.SendAnnouncement(
29✔
3716
                ann.chanUpdateAnn, discovery.RemoteAlias(peerAlias),
29✔
3717
        )
29✔
3718
        select {
29✔
3719
        case err := <-errChan:
29✔
3720
                if err != nil {
29✔
3721
                        if graph.IsError(err, graph.ErrOutdated,
×
3722
                                graph.ErrIgnored) {
×
3723

×
3724
                                log.Debugf("Graph rejected "+
×
3725
                                        "ChannelUpdate: %v", err)
×
3726
                        } else {
×
3727
                                return fmt.Errorf("error sending channel "+
×
3728
                                        "update: %v", err)
×
3729
                        }
×
3730
                }
3731
        case <-f.quit:
×
3732
                return ErrFundingManagerShuttingDown
×
3733
        }
3734

3735
        return nil
29✔
3736
}
3737

3738
// annAfterSixConfs broadcasts the necessary channel announcement messages to
3739
// the network after 6 confs. Should be called after the channelReady message
3740
// is sent and the channel is added to the graph (channelState is
3741
// 'addedToGraph') and the channel is ready to be used. This is the last
3742
// step in the channel opening process, and the opening state will be deleted
3743
// from the database if successful.
3744
func (f *Manager) annAfterSixConfs(completeChan *channeldb.OpenChannel,
3745
        shortChanID *lnwire.ShortChannelID) error {
29✔
3746

29✔
3747
        // If this channel is not meant to be announced to the greater network,
29✔
3748
        // we'll only send our NodeAnnouncement to our counterparty to ensure we
29✔
3749
        // don't leak any of our information.
29✔
3750
        announceChan := completeChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
29✔
3751
        if !announceChan {
40✔
3752
                log.Debugf("Will not announce private channel %v.",
11✔
3753
                        shortChanID.ToUint64())
11✔
3754

11✔
3755
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
11✔
3756
                if err != nil {
11✔
3757
                        return err
×
3758
                }
×
3759

3760
                nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
11✔
3761
                if err != nil {
11✔
3762
                        return fmt.Errorf("unable to retrieve current node "+
×
3763
                                "announcement: %v", err)
×
3764
                }
×
3765

3766
                chanID := lnwire.NewChanIDFromOutPoint(
11✔
3767
                        completeChan.FundingOutpoint,
11✔
3768
                )
11✔
3769
                pubKey := peer.PubKey()
11✔
3770
                log.Debugf("Sending our NodeAnnouncement for "+
11✔
3771
                        "ChannelID(%v) to %x", chanID, pubKey)
11✔
3772

11✔
3773
                // TODO(halseth): make reliable. If the peer is not online this
11✔
3774
                // will fail, and the opening process will stop. Should instead
11✔
3775
                // block here, waiting for the peer to come online.
11✔
3776
                if err := peer.SendMessage(true, &nodeAnn); err != nil {
11✔
3777
                        return fmt.Errorf("unable to send node announcement "+
×
3778
                                "to peer %x: %v", pubKey, err)
×
3779
                }
×
3780
        } else {
21✔
3781
                // Otherwise, we'll wait until the funding transaction has
21✔
3782
                // reached 6 confirmations before announcing it.
21✔
3783
                numConfs := uint32(completeChan.NumConfsRequired)
21✔
3784
                if numConfs < 6 {
42✔
3785
                        numConfs = 6
21✔
3786
                }
21✔
3787
                txid := completeChan.FundingOutpoint.Hash
21✔
3788
                log.Debugf("Will announce channel %v after ChannelPoint"+
21✔
3789
                        "(%v) has gotten %d confirmations",
21✔
3790
                        shortChanID.ToUint64(), completeChan.FundingOutpoint,
21✔
3791
                        numConfs)
21✔
3792

21✔
3793
                fundingScript, err := makeFundingScript(completeChan)
21✔
3794
                if err != nil {
21✔
3795
                        return fmt.Errorf("unable to create funding script "+
×
3796
                                "for ChannelPoint(%v): %v",
×
3797
                                completeChan.FundingOutpoint, err)
×
3798
                }
×
3799

3800
                // Register with the ChainNotifier for a notification once the
3801
                // funding transaction reaches at least 6 confirmations.
3802
                confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
21✔
3803
                        &txid, fundingScript, numConfs,
21✔
3804
                        completeChan.BroadcastHeight(),
21✔
3805
                )
21✔
3806
                if err != nil {
21✔
3807
                        return fmt.Errorf("unable to register for "+
×
3808
                                "confirmation of ChannelPoint(%v): %v",
×
3809
                                completeChan.FundingOutpoint, err)
×
3810
                }
×
3811

3812
                // Wait until 6 confirmations has been reached or the wallet
3813
                // signals a shutdown.
3814
                select {
21✔
3815
                case _, ok := <-confNtfn.Confirmed:
19✔
3816
                        if !ok {
19✔
3817
                                return fmt.Errorf("ChainNotifier shutting "+
×
3818
                                        "down, cannot complete funding flow "+
×
3819
                                        "for ChannelPoint(%v)",
×
3820
                                        completeChan.FundingOutpoint)
×
3821
                        }
×
3822
                        // Fallthrough.
3823

3824
                case <-f.quit:
5✔
3825
                        return fmt.Errorf("%v, stopping funding flow for "+
5✔
3826
                                "ChannelPoint(%v)",
5✔
3827
                                ErrFundingManagerShuttingDown,
5✔
3828
                                completeChan.FundingOutpoint)
5✔
3829
                }
3830

3831
                fundingPoint := completeChan.FundingOutpoint
19✔
3832
                chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
19✔
3833

19✔
3834
                log.Infof("Announcing ChannelPoint(%v), short_chan_id=%v",
19✔
3835
                        &fundingPoint, shortChanID)
19✔
3836

19✔
3837
                // If this is a non-zero-conf option-scid-alias channel, we'll
19✔
3838
                // delete the mappings the gossiper uses so that ChannelUpdates
19✔
3839
                // with aliases won't be accepted. This is done elsewhere for
19✔
3840
                // zero-conf channels.
19✔
3841
                isScidFeature := completeChan.NegotiatedAliasFeature()
19✔
3842
                isZeroConf := completeChan.IsZeroConf()
19✔
3843
                if isScidFeature && !isZeroConf {
22✔
3844
                        baseScid := completeChan.ShortChanID()
3✔
3845
                        err := f.cfg.AliasManager.DeleteSixConfs(baseScid)
3✔
3846
                        if err != nil {
3✔
3847
                                return fmt.Errorf("failed deleting six confs "+
×
3848
                                        "maps: %v", err)
×
3849
                        }
×
3850

3851
                        // We'll delete the edge and add it again via
3852
                        // addToGraph. This is because the peer may have
3853
                        // sent us a ChannelUpdate with an alias and we don't
3854
                        // want to relay this.
3855
                        ourPolicy, err := f.cfg.DeleteAliasEdge(baseScid)
3✔
3856
                        if err != nil {
3✔
3857
                                return fmt.Errorf("failed deleting real edge "+
×
3858
                                        "for alias channel from graph: %v",
×
3859
                                        err)
×
3860
                        }
×
3861

3862
                        err = f.addToGraph(
3✔
3863
                                completeChan, &baseScid, nil, ourPolicy,
3✔
3864
                        )
3✔
3865
                        if err != nil {
3✔
3866
                                return fmt.Errorf("failed to re-add to "+
×
3867
                                        "graph: %v", err)
×
3868
                        }
×
3869
                }
3870

3871
                // Create and broadcast the proofs required to make this channel
3872
                // public and usable for other nodes for routing.
3873
                err = f.announceChannel(
19✔
3874
                        f.cfg.IDKey, completeChan.IdentityPub,
19✔
3875
                        &completeChan.LocalChanCfg.MultiSigKey,
19✔
3876
                        completeChan.RemoteChanCfg.MultiSigKey.PubKey,
19✔
3877
                        *shortChanID, chanID, completeChan.ChanType,
19✔
3878
                )
19✔
3879
                if err != nil {
22✔
3880
                        return fmt.Errorf("channel announcement failed: %w",
3✔
3881
                                err)
3✔
3882
                }
3✔
3883

3884
                log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+
19✔
3885
                        "sent to gossiper", &fundingPoint, shortChanID)
19✔
3886
        }
3887

3888
        return nil
27✔
3889
}
3890

3891
// waitForZeroConfChannel is called when the state is addedToGraph with
3892
// a zero-conf channel. This will wait for the real confirmation, add the
3893
// confirmed SCID to the router graph, and then announce after six confs.
3894
func (f *Manager) waitForZeroConfChannel(c *channeldb.OpenChannel) error {
9✔
3895
        // First we'll check whether the channel is confirmed on-chain. If it
9✔
3896
        // is already confirmed, the chainntnfs subsystem will return with the
9✔
3897
        // confirmed tx. Otherwise, we'll wait here until confirmation occurs.
9✔
3898
        confChan, err := f.waitForFundingWithTimeout(c)
9✔
3899
        if err != nil {
14✔
3900
                return fmt.Errorf("error waiting for zero-conf funding "+
5✔
3901
                        "confirmation for ChannelPoint(%v): %v",
5✔
3902
                        c.FundingOutpoint, err)
5✔
3903
        }
5✔
3904

3905
        // We'll need to refresh the channel state so that things are properly
3906
        // populated when validating the channel state. Otherwise, a panic may
3907
        // occur due to inconsistency in the OpenChannel struct.
3908
        err = c.Refresh()
7✔
3909
        if err != nil {
10✔
3910
                return fmt.Errorf("unable to refresh channel state: %w", err)
3✔
3911
        }
3✔
3912

3913
        // Now that we have the confirmed transaction and the proper SCID,
3914
        // we'll call ValidateChannel to ensure the confirmed tx is properly
3915
        // formatted.
3916
        err = f.cfg.Wallet.ValidateChannel(c, confChan.fundingTx)
7✔
3917
        if err != nil {
7✔
3918
                return fmt.Errorf("unable to validate zero-conf channel: "+
×
3919
                        "%v", err)
×
3920
        }
×
3921

3922
        // Once we know the confirmed ShortChannelID, we'll need to save it to
3923
        // the database and refresh the OpenChannel struct with it.
3924
        err = c.MarkRealScid(confChan.shortChanID)
7✔
3925
        if err != nil {
7✔
3926
                return fmt.Errorf("unable to set confirmed SCID for zero "+
×
3927
                        "channel: %v", err)
×
3928
        }
×
3929

3930
        // Six confirmations have been reached. If this channel is public,
3931
        // we'll delete some of the alias mappings the gossiper uses.
3932
        isPublic := c.ChannelFlags&lnwire.FFAnnounceChannel != 0
7✔
3933
        if isPublic {
12✔
3934
                err = f.cfg.AliasManager.DeleteSixConfs(c.ShortChannelID)
5✔
3935
                if err != nil {
5✔
3936
                        return fmt.Errorf("unable to delete base alias after "+
×
3937
                                "six confirmations: %v", err)
×
3938
                }
×
3939

3940
                // TODO: Make this atomic!
3941
                ourPolicy, err := f.cfg.DeleteAliasEdge(c.ShortChanID())
5✔
3942
                if err != nil {
5✔
3943
                        return fmt.Errorf("unable to delete alias edge from "+
×
3944
                                "graph: %v", err)
×
3945
                }
×
3946

3947
                // We'll need to update the graph with the new ShortChannelID
3948
                // via an addToGraph call. We don't pass in the peer's
3949
                // alias since we'll be using the confirmed SCID from now on
3950
                // regardless if it's public or not.
3951
                err = f.addToGraph(
5✔
3952
                        c, &confChan.shortChanID, nil, ourPolicy,
5✔
3953
                )
5✔
3954
                if err != nil {
5✔
3955
                        return fmt.Errorf("failed adding confirmed zero-conf "+
×
3956
                                "SCID to graph: %v", err)
×
3957
                }
×
3958
        }
3959

3960
        // Since we have now marked down the confirmed SCID, we'll also need to
3961
        // tell the Switch to refresh the relevant ChannelLink so that forwards
3962
        // under the confirmed SCID are possible if this is a public channel.
3963
        err = f.cfg.ReportShortChanID(c.FundingOutpoint)
7✔
3964
        if err != nil {
7✔
3965
                // This should only fail if the link is not found in the
×
3966
                // Switch's linkIndex map. If this is the case, then the peer
×
3967
                // has gone offline and the next time the link is loaded, it
×
3968
                // will have a refreshed state. Just log an error here.
×
3969
                log.Errorf("unable to report scid for zero-conf channel "+
×
3970
                        "channel: %v", err)
×
3971
        }
×
3972

3973
        // Update the confirmed transaction's label.
3974
        f.makeLabelForTx(c)
7✔
3975

7✔
3976
        return nil
7✔
3977
}
3978

3979
// genFirstStateMusigNonce generates a nonces for the "first" local state. This
3980
// is the verification nonce for the state created for us after the initial
3981
// commitment transaction signed as part of the funding flow.
3982
func genFirstStateMusigNonce(channel *channeldb.OpenChannel,
3983
) (*musig2.Nonces, error) {
7✔
3984

7✔
3985
        musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
7✔
3986
                channel.RevocationProducer,
7✔
3987
        )
7✔
3988
        if err != nil {
7✔
3989
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3990
                        "nonces: %v", err)
×
3991
        }
×
3992

3993
        // We use the _next_ commitment height here as we need to generate the
3994
        // nonce for the next state the remote party will sign for us.
3995
        verNonce, err := channeldb.NewMusigVerificationNonce(
7✔
3996
                channel.LocalChanCfg.MultiSigKey.PubKey,
7✔
3997
                channel.LocalCommitment.CommitHeight+1,
7✔
3998
                musig2ShaChain,
7✔
3999
        )
7✔
4000
        if err != nil {
7✔
4001
                return nil, fmt.Errorf("unable to generate musig channel "+
×
4002
                        "nonces: %v", err)
×
4003
        }
×
4004

4005
        return verNonce, nil
7✔
4006
}
4007

4008
// handleChannelReady finalizes the channel funding process and enables the
4009
// channel to enter normal operating mode.
4010
func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen
4011
        msg *lnwire.ChannelReady) {
31✔
4012

31✔
4013
        defer f.wg.Done()
31✔
4014

31✔
4015
        // If we are in development mode, we'll wait for specified duration
31✔
4016
        // before processing the channel ready message.
31✔
4017
        if f.cfg.Dev != nil {
34✔
4018
                duration := f.cfg.Dev.ProcessChannelReadyWait
3✔
4019
                log.Warnf("Channel(%v): sleeping %v before processing "+
3✔
4020
                        "channel_ready", msg.ChanID, duration)
3✔
4021

3✔
4022
                select {
3✔
4023
                case <-time.After(duration):
3✔
4024
                        log.Warnf("Channel(%v): slept %v before processing "+
3✔
4025
                                "channel_ready", msg.ChanID, duration)
3✔
4026
                case <-f.quit:
×
4027
                        log.Warnf("Channel(%v): quit sleeping", msg.ChanID)
×
4028
                        return
×
4029
                }
4030
        }
4031

4032
        log.Debugf("Received ChannelReady for ChannelID(%v) from "+
31✔
4033
                "peer %x", msg.ChanID,
31✔
4034
                peer.IdentityKey().SerializeCompressed())
31✔
4035

31✔
4036
        // We now load or create a new channel barrier for this channel.
31✔
4037
        _, loaded := f.handleChannelReadyBarriers.LoadOrStore(
31✔
4038
                msg.ChanID, struct{}{},
31✔
4039
        )
31✔
4040

31✔
4041
        // If we are currently in the process of handling a channel_ready
31✔
4042
        // message for this channel, ignore.
31✔
4043
        if loaded {
34✔
4044
                log.Infof("Already handling channelReady for "+
3✔
4045
                        "ChannelID(%v), ignoring.", msg.ChanID)
3✔
4046
                return
3✔
4047
        }
3✔
4048

4049
        // If not already handling channelReady for this channel, then the
4050
        // `LoadOrStore` has set up a barrier, and it will be removed once this
4051
        // function exits.
4052
        defer f.handleChannelReadyBarriers.Delete(msg.ChanID)
30✔
4053

30✔
4054
        localDiscoverySignal, ok := f.localDiscoverySignals.Load(msg.ChanID)
30✔
4055
        if ok {
58✔
4056
                // Before we proceed with processing the channel_ready
28✔
4057
                // message, we'll wait for the local waitForFundingConfirmation
28✔
4058
                // goroutine to signal that it has the necessary state in
28✔
4059
                // place. Otherwise, we may be missing critical information
28✔
4060
                // required to handle forwarded HTLC's.
28✔
4061
                select {
28✔
4062
                case <-localDiscoverySignal:
28✔
4063
                        // Fallthrough
4064
                case <-f.quit:
3✔
4065
                        return
3✔
4066
                }
4067

4068
                // With the signal received, we can now safely delete the entry
4069
                // from the map.
4070
                f.localDiscoverySignals.Delete(msg.ChanID)
28✔
4071
        }
4072

4073
        // First, we'll attempt to locate the channel whose funding workflow is
4074
        // being finalized by this message. We go to the database rather than
4075
        // our reservation map as we may have restarted, mid funding flow. Also
4076
        // provide the node's public key to make the search faster.
4077
        chanID := msg.ChanID
30✔
4078
        channel, err := f.cfg.FindChannel(peer.IdentityKey(), chanID)
30✔
4079
        if err != nil {
30✔
4080
                log.Errorf("Unable to locate ChannelID(%v), cannot complete "+
×
4081
                        "funding", chanID)
×
4082
                return
×
4083
        }
×
4084

4085
        // If this is a taproot channel, then we can generate the set of nonces
4086
        // the remote party needs to send the next remote commitment here.
4087
        var firstVerNonce *musig2.Nonces
30✔
4088
        if channel.ChanType.IsTaproot() {
37✔
4089
                firstVerNonce, err = genFirstStateMusigNonce(channel)
7✔
4090
                if err != nil {
7✔
4091
                        log.Error(err)
×
4092
                        return
×
4093
                }
×
4094
        }
4095

4096
        // We'll need to store the received TLV alias if the option_scid_alias
4097
        // feature was negotiated. This will be used to provide route hints
4098
        // during invoice creation. In the zero-conf case, it is also used to
4099
        // provide a ChannelUpdate to the remote peer. This is done before the
4100
        // call to InsertNextRevocation in case the call to PutPeerAlias fails.
4101
        // If it were to fail on the first call to handleChannelReady, we
4102
        // wouldn't want the channel to be usable yet.
4103
        if channel.NegotiatedAliasFeature() {
39✔
4104
                // If the AliasScid field is nil, we must fail out. We will
9✔
4105
                // most likely not be able to route through the peer.
9✔
4106
                if msg.AliasScid == nil {
9✔
4107
                        log.Debugf("Consider closing ChannelID(%v), peer "+
×
4108
                                "does not implement the option-scid-alias "+
×
4109
                                "feature properly", chanID)
×
4110
                        return
×
4111
                }
×
4112

4113
                // We'll store the AliasScid so that invoice creation can use
4114
                // it.
4115
                err = f.cfg.AliasManager.PutPeerAlias(chanID, *msg.AliasScid)
9✔
4116
                if err != nil {
9✔
4117
                        log.Errorf("unable to store peer's alias: %v", err)
×
4118
                        return
×
4119
                }
×
4120

4121
                // If we do not have an alias stored, we'll create one now.
4122
                // This is only used in the upgrade case where a user toggles
4123
                // the option-scid-alias feature-bit to on. We'll also send the
4124
                // channel_ready message here in case the link is created
4125
                // before sendChannelReady is called.
4126
                aliases := f.cfg.AliasManager.GetAliases(
9✔
4127
                        channel.ShortChannelID,
9✔
4128
                )
9✔
4129
                if len(aliases) == 0 {
9✔
4130
                        // No aliases were found so we'll request and store an
×
4131
                        // alias and use it in the channel_ready message.
×
4132
                        alias, err := f.cfg.AliasManager.RequestAlias()
×
4133
                        if err != nil {
×
4134
                                log.Errorf("unable to request alias: %v", err)
×
4135
                                return
×
4136
                        }
×
4137

4138
                        err = f.cfg.AliasManager.AddLocalAlias(
×
4139
                                alias, channel.ShortChannelID, false, false,
×
4140
                        )
×
4141
                        if err != nil {
×
4142
                                log.Errorf("unable to add local alias: %v",
×
4143
                                        err)
×
4144
                                return
×
4145
                        }
×
4146

4147
                        secondPoint, err := channel.SecondCommitmentPoint()
×
4148
                        if err != nil {
×
4149
                                log.Errorf("unable to fetch second "+
×
4150
                                        "commitment point: %v", err)
×
4151
                                return
×
4152
                        }
×
4153

4154
                        channelReadyMsg := lnwire.NewChannelReady(
×
4155
                                chanID, secondPoint,
×
4156
                        )
×
4157
                        channelReadyMsg.AliasScid = &alias
×
4158

×
4159
                        if firstVerNonce != nil {
×
4160
                                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:ll
×
4161
                                        firstVerNonce.PubNonce,
×
4162
                                )
×
4163
                        }
×
4164

4165
                        err = peer.SendMessage(true, channelReadyMsg)
×
4166
                        if err != nil {
×
4167
                                log.Errorf("unable to send channel_ready: %v",
×
4168
                                        err)
×
4169
                                return
×
4170
                        }
×
4171
                }
4172
        }
4173

4174
        // If the RemoteNextRevocation is non-nil, it means that we have
4175
        // already processed channelReady for this channel, so ignore. This
4176
        // check is after the alias logic so we store the peer's most recent
4177
        // alias. The spec requires us to validate that subsequent
4178
        // channel_ready messages use the same per commitment point (the
4179
        // second), but it is not actually necessary since we'll just end up
4180
        // ignoring it. We are, however, required to *send* the same per
4181
        // commitment point, since another pedantic implementation might
4182
        // verify it.
4183
        if channel.RemoteNextRevocation != nil {
34✔
4184
                log.Infof("Received duplicate channelReady for "+
4✔
4185
                        "ChannelID(%v), ignoring.", chanID)
4✔
4186
                return
4✔
4187
        }
4✔
4188

4189
        // If this is a taproot channel, then we'll need to map the received
4190
        // nonces to a nonce pair, and also fetch our pending nonces, which are
4191
        // required in order to make the channel whole.
4192
        var chanOpts []lnwallet.ChannelOpt
29✔
4193
        if channel.ChanType.IsTaproot() {
36✔
4194
                f.nonceMtx.Lock()
7✔
4195
                localNonce, ok := f.pendingMusigNonces[chanID]
7✔
4196
                if !ok {
10✔
4197
                        // If there's no pending nonce for this channel ID,
3✔
4198
                        // we'll use the one generated above.
3✔
4199
                        localNonce = firstVerNonce
3✔
4200
                        f.pendingMusigNonces[chanID] = firstVerNonce
3✔
4201
                }
3✔
4202
                f.nonceMtx.Unlock()
7✔
4203

7✔
4204
                log.Infof("ChanID(%v): applying local+remote musig2 nonces",
7✔
4205
                        chanID)
7✔
4206

7✔
4207
                remoteNonce, err := msg.NextLocalNonce.UnwrapOrErrV(
7✔
4208
                        errNoLocalNonce,
7✔
4209
                )
7✔
4210
                if err != nil {
7✔
4211
                        cid := newChanIdentifier(msg.ChanID)
×
4212
                        f.sendWarning(peer, cid, err)
×
4213

×
4214
                        return
×
4215
                }
×
4216

4217
                chanOpts = append(
7✔
4218
                        chanOpts,
7✔
4219
                        lnwallet.WithLocalMusigNonces(localNonce),
7✔
4220
                        lnwallet.WithRemoteMusigNonces(&musig2.Nonces{
7✔
4221
                                PubNonce: remoteNonce,
7✔
4222
                        }),
7✔
4223
                )
7✔
4224

7✔
4225
                // Inform the aux funding controller that the liquidity in the
7✔
4226
                // custom channel is now ready to be advertised. We potentially
7✔
4227
                // haven't sent our own channel ready message yet, but other
7✔
4228
                // than that the channel is ready to count toward available
7✔
4229
                // liquidity.
7✔
4230
                err = fn.MapOptionZ(
7✔
4231
                        f.cfg.AuxFundingController,
7✔
4232
                        func(controller AuxFundingController) error {
7✔
4233
                                return controller.ChannelReady(
×
4234
                                        lnwallet.NewAuxChanState(channel),
×
4235
                                )
×
4236
                        },
×
4237
                )
4238
                if err != nil {
7✔
4239
                        cid := newChanIdentifier(msg.ChanID)
×
4240
                        f.sendWarning(peer, cid, err)
×
4241

×
4242
                        return
×
4243
                }
×
4244
        }
4245

4246
        // The channel_ready message contains the next commitment point we'll
4247
        // need to create the next commitment state for the remote party. So
4248
        // we'll insert that into the channel now before passing it along to
4249
        // other sub-systems.
4250
        err = channel.InsertNextRevocation(msg.NextPerCommitmentPoint)
29✔
4251
        if err != nil {
29✔
4252
                log.Errorf("unable to insert next commitment point: %v", err)
×
4253
                return
×
4254
        }
×
4255

4256
        // Before we can add the channel to the peer, we'll need to ensure that
4257
        // we have an initial forwarding policy set.
4258
        if err := f.ensureInitialForwardingPolicy(chanID, channel); err != nil {
29✔
4259
                log.Errorf("Unable to ensure initial forwarding policy: %v",
×
4260
                        err)
×
4261
        }
×
4262

4263
        err = peer.AddNewChannel(&lnpeer.NewChannel{
29✔
4264
                OpenChannel: channel,
29✔
4265
                ChanOpts:    chanOpts,
29✔
4266
        }, f.quit)
29✔
4267
        if err != nil {
29✔
4268
                log.Errorf("Unable to add new channel %v with peer %x: %v",
×
4269
                        channel.FundingOutpoint,
×
4270
                        peer.IdentityKey().SerializeCompressed(), err,
×
4271
                )
×
4272
        }
×
4273
}
4274

4275
// handleChannelReadyReceived is called once the remote's channelReady message
4276
// is received and processed. At this stage, we must have sent out our
4277
// channelReady message, once the remote's channelReady is processed, the
4278
// channel is now active, thus we change its state to `addedToGraph` to
4279
// let the channel start handling routing.
4280
func (f *Manager) handleChannelReadyReceived(channel *channeldb.OpenChannel,
4281
        scid *lnwire.ShortChannelID, pendingChanID PendingChanID,
4282
        updateChan chan<- *lnrpc.OpenStatusUpdate) error {
27✔
4283

27✔
4284
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
27✔
4285

27✔
4286
        // Since we've sent+received funding locked at this point, we
27✔
4287
        // can clean up the pending musig2 nonce state.
27✔
4288
        f.nonceMtx.Lock()
27✔
4289
        delete(f.pendingMusigNonces, chanID)
27✔
4290
        f.nonceMtx.Unlock()
27✔
4291

27✔
4292
        var peerAlias *lnwire.ShortChannelID
27✔
4293
        if channel.IsZeroConf() {
34✔
4294
                // We'll need to wait until channel_ready has been received and
7✔
4295
                // the peer lets us know the alias they want to use for the
7✔
4296
                // channel. With this information, we can then construct a
7✔
4297
                // ChannelUpdate for them.  If an alias does not yet exist,
7✔
4298
                // we'll just return, letting the next iteration of the loop
7✔
4299
                // check again.
7✔
4300
                var defaultAlias lnwire.ShortChannelID
7✔
4301
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
7✔
4302
                foundAlias, _ := f.cfg.AliasManager.GetPeerAlias(chanID)
7✔
4303
                if foundAlias == defaultAlias {
7✔
4304
                        return nil
×
4305
                }
×
4306

4307
                peerAlias = &foundAlias
7✔
4308
        }
4309

4310
        err := f.addToGraph(channel, scid, peerAlias, nil)
27✔
4311
        if err != nil {
27✔
4312
                return fmt.Errorf("failed adding to graph: %w", err)
×
4313
        }
×
4314

4315
        // As the channel is now added to the ChannelRouter's topology, the
4316
        // channel is moved to the next state of the state machine. It will be
4317
        // moved to the last state (actually deleted from the database) after
4318
        // the channel is finally announced.
4319
        err = f.saveChannelOpeningState(
27✔
4320
                &channel.FundingOutpoint, addedToGraph, scid,
27✔
4321
        )
27✔
4322
        if err != nil {
27✔
4323
                return fmt.Errorf("error setting channel state to"+
×
4324
                        " addedToGraph: %w", err)
×
4325
        }
×
4326

4327
        log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
27✔
4328
                "added to graph", chanID, scid)
27✔
4329

27✔
4330
        err = fn.MapOptionZ(
27✔
4331
                f.cfg.AuxFundingController,
27✔
4332
                func(controller AuxFundingController) error {
27✔
4333
                        return controller.ChannelReady(
×
4334
                                lnwallet.NewAuxChanState(channel),
×
4335
                        )
×
4336
                },
×
4337
        )
4338
        if err != nil {
27✔
4339
                return fmt.Errorf("failed notifying aux funding controller "+
×
4340
                        "about channel ready: %w", err)
×
4341
        }
×
4342

4343
        // Give the caller a final update notifying them that the channel is
4344
        fundingPoint := channel.FundingOutpoint
27✔
4345
        cp := &lnrpc.ChannelPoint{
27✔
4346
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
27✔
4347
                        FundingTxidBytes: fundingPoint.Hash[:],
27✔
4348
                },
27✔
4349
                OutputIndex: fundingPoint.Index,
27✔
4350
        }
27✔
4351

27✔
4352
        if updateChan != nil {
40✔
4353
                upd := &lnrpc.OpenStatusUpdate{
13✔
4354
                        Update: &lnrpc.OpenStatusUpdate_ChanOpen{
13✔
4355
                                ChanOpen: &lnrpc.ChannelOpenUpdate{
13✔
4356
                                        ChannelPoint: cp,
13✔
4357
                                },
13✔
4358
                        },
13✔
4359
                        PendingChanId: pendingChanID[:],
13✔
4360
                }
13✔
4361

13✔
4362
                select {
13✔
4363
                case updateChan <- upd:
13✔
4364
                case <-f.quit:
×
4365
                        return ErrFundingManagerShuttingDown
×
4366
                }
4367
        }
4368

4369
        return nil
27✔
4370
}
4371

4372
// ensureInitialForwardingPolicy ensures that we have an initial forwarding
4373
// policy set for the given channel. If we don't, we'll fall back to the default
4374
// values.
4375
func (f *Manager) ensureInitialForwardingPolicy(chanID lnwire.ChannelID,
4376
        channel *channeldb.OpenChannel) error {
29✔
4377

29✔
4378
        // Before we can add the channel to the peer, we'll need to ensure that
29✔
4379
        // we have an initial forwarding policy set. This should always be the
29✔
4380
        // case except for a channel that was created with lnd <= 0.15.5 and
29✔
4381
        // is still pending while updating to this version.
29✔
4382
        var needDBUpdate bool
29✔
4383
        forwardingPolicy, err := f.getInitialForwardingPolicy(chanID)
29✔
4384
        if err != nil {
29✔
4385
                log.Errorf("Unable to fetch initial forwarding policy, "+
×
4386
                        "falling back to default values: %v", err)
×
4387

×
4388
                forwardingPolicy = f.defaultForwardingPolicy(
×
4389
                        channel.LocalChanCfg.ChannelStateBounds,
×
4390
                )
×
4391
                needDBUpdate = true
×
4392
        }
×
4393

4394
        // We only started storing the actual values for MinHTLCOut and MaxHTLC
4395
        // after 0.16.x, so if a channel was opened with such a version and is
4396
        // still pending while updating to this version, we'll need to set the
4397
        // values to the default values.
4398
        if forwardingPolicy.MinHTLCOut == 0 {
45✔
4399
                forwardingPolicy.MinHTLCOut = channel.LocalChanCfg.MinHTLC
16✔
4400
                needDBUpdate = true
16✔
4401
        }
16✔
4402
        if forwardingPolicy.MaxHTLC == 0 {
45✔
4403
                forwardingPolicy.MaxHTLC = channel.LocalChanCfg.MaxPendingAmount
16✔
4404
                needDBUpdate = true
16✔
4405
        }
16✔
4406

4407
        // And finally, if we found that the values currently stored aren't
4408
        // sufficient for the link, we'll update the database.
4409
        if needDBUpdate {
45✔
4410
                err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
16✔
4411
                if err != nil {
16✔
4412
                        return fmt.Errorf("unable to update initial "+
×
4413
                                "forwarding policy: %v", err)
×
4414
                }
×
4415
        }
4416

4417
        return nil
29✔
4418
}
4419

4420
// chanAnnouncement encapsulates the two authenticated announcements that we
4421
// send out to the network after a new channel has been created locally.
4422
type chanAnnouncement struct {
4423
        chanAnn       *lnwire.ChannelAnnouncement1
4424
        chanUpdateAnn *lnwire.ChannelUpdate1
4425
        chanProof     *lnwire.AnnounceSignatures1
4426
}
4427

4428
// newChanAnnouncement creates the authenticated channel announcement messages
4429
// required to broadcast a newly created channel to the network. The
4430
// announcement is two part: the first part authenticates the existence of the
4431
// channel and contains four signatures binding the funding pub keys and
4432
// identity pub keys of both parties to the channel, and the second segment is
4433
// authenticated only by us and contains our directional routing policy for the
4434
// channel. ourPolicy may be set in order to re-use an existing, non-default
4435
// policy.
4436
func (f *Manager) newChanAnnouncement(localPubKey,
4437
        remotePubKey *btcec.PublicKey, localFundingKey *keychain.KeyDescriptor,
4438
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4439
        chanID lnwire.ChannelID, fwdMinHTLC, fwdMaxHTLC lnwire.MilliSatoshi,
4440
        ourPolicy *models.ChannelEdgePolicy,
4441
        chanType channeldb.ChannelType) (*chanAnnouncement, error) {
45✔
4442

45✔
4443
        chainHash := *f.cfg.Wallet.Cfg.NetParams.GenesisHash
45✔
4444

45✔
4445
        // The unconditional section of the announcement is the ShortChannelID
45✔
4446
        // itself which compactly encodes the location of the funding output
45✔
4447
        // within the blockchain.
45✔
4448
        chanAnn := &lnwire.ChannelAnnouncement1{
45✔
4449
                ShortChannelID: shortChanID,
45✔
4450
                Features:       lnwire.NewRawFeatureVector(),
45✔
4451
                ChainHash:      chainHash,
45✔
4452
        }
45✔
4453

45✔
4454
        // If this is a taproot channel, then we'll set a special bit in the
45✔
4455
        // feature vector to indicate to the routing layer that this needs a
45✔
4456
        // slightly different type of validation.
45✔
4457
        //
45✔
4458
        // TODO(roasbeef): temp, remove after gossip 1.5
45✔
4459
        if chanType.IsTaproot() {
52✔
4460
                log.Debugf("Applying taproot feature bit to "+
7✔
4461
                        "ChannelAnnouncement for %v", chanID)
7✔
4462

7✔
4463
                chanAnn.Features.Set(
7✔
4464
                        lnwire.SimpleTaprootChannelsRequiredStaging,
7✔
4465
                )
7✔
4466
        }
7✔
4467

4468
        // The chanFlags field indicates which directed edge of the channel is
4469
        // being updated within the ChannelUpdateAnnouncement announcement
4470
        // below. A value of zero means it's the edge of the "first" node and 1
4471
        // being the other node.
4472
        var chanFlags lnwire.ChanUpdateChanFlags
45✔
4473

45✔
4474
        // The lexicographical ordering of the two identity public keys of the
45✔
4475
        // nodes indicates which of the nodes is "first". If our serialized
45✔
4476
        // identity key is lower than theirs then we're the "first" node and
45✔
4477
        // second otherwise.
45✔
4478
        selfBytes := localPubKey.SerializeCompressed()
45✔
4479
        remoteBytes := remotePubKey.SerializeCompressed()
45✔
4480
        if bytes.Compare(selfBytes, remoteBytes) == -1 {
69✔
4481
                copy(chanAnn.NodeID1[:], localPubKey.SerializeCompressed())
24✔
4482
                copy(chanAnn.NodeID2[:], remotePubKey.SerializeCompressed())
24✔
4483
                copy(
24✔
4484
                        chanAnn.BitcoinKey1[:],
24✔
4485
                        localFundingKey.PubKey.SerializeCompressed(),
24✔
4486
                )
24✔
4487
                copy(
24✔
4488
                        chanAnn.BitcoinKey2[:],
24✔
4489
                        remoteFundingKey.SerializeCompressed(),
24✔
4490
                )
24✔
4491

24✔
4492
                // If we're the first node then update the chanFlags to
24✔
4493
                // indicate the "direction" of the update.
24✔
4494
                chanFlags = 0
24✔
4495
        } else {
48✔
4496
                copy(chanAnn.NodeID1[:], remotePubKey.SerializeCompressed())
24✔
4497
                copy(chanAnn.NodeID2[:], localPubKey.SerializeCompressed())
24✔
4498
                copy(
24✔
4499
                        chanAnn.BitcoinKey1[:],
24✔
4500
                        remoteFundingKey.SerializeCompressed(),
24✔
4501
                )
24✔
4502
                copy(
24✔
4503
                        chanAnn.BitcoinKey2[:],
24✔
4504
                        localFundingKey.PubKey.SerializeCompressed(),
24✔
4505
                )
24✔
4506

24✔
4507
                // If we're the second node then update the chanFlags to
24✔
4508
                // indicate the "direction" of the update.
24✔
4509
                chanFlags = 1
24✔
4510
        }
24✔
4511

4512
        // Our channel update message flags will signal that we support the
4513
        // max_htlc field.
4514
        msgFlags := lnwire.ChanUpdateRequiredMaxHtlc
45✔
4515

45✔
4516
        // We announce the channel with the default values. Some of
45✔
4517
        // these values can later be changed by crafting a new ChannelUpdate.
45✔
4518
        chanUpdateAnn := &lnwire.ChannelUpdate1{
45✔
4519
                ShortChannelID: shortChanID,
45✔
4520
                ChainHash:      chainHash,
45✔
4521
                Timestamp:      uint32(time.Now().Unix()),
45✔
4522
                MessageFlags:   msgFlags,
45✔
4523
                ChannelFlags:   chanFlags,
45✔
4524
                TimeLockDelta: uint16(
45✔
4525
                        f.cfg.DefaultRoutingPolicy.TimeLockDelta,
45✔
4526
                ),
45✔
4527
                HtlcMinimumMsat: fwdMinHTLC,
45✔
4528
                HtlcMaximumMsat: fwdMaxHTLC,
45✔
4529
        }
45✔
4530

45✔
4531
        // The caller of newChanAnnouncement is expected to provide the initial
45✔
4532
        // forwarding policy to be announced. If no persisted initial policy
45✔
4533
        // values are found, then we will use the default policy values in the
45✔
4534
        // channel announcement.
45✔
4535
        storedFwdingPolicy, err := f.getInitialForwardingPolicy(chanID)
45✔
4536
        if err != nil && !errors.Is(err, channeldb.ErrChannelNotFound) {
45✔
4537
                return nil, errors.Errorf("unable to generate channel "+
×
4538
                        "update announcement: %v", err)
×
4539
        }
×
4540

4541
        switch {
45✔
4542
        case ourPolicy != nil:
3✔
4543
                // If ourPolicy is non-nil, modify the default parameters of the
3✔
4544
                // ChannelUpdate.
3✔
4545
                chanUpdateAnn.MessageFlags = ourPolicy.MessageFlags
3✔
4546
                chanUpdateAnn.ChannelFlags = ourPolicy.ChannelFlags
3✔
4547
                chanUpdateAnn.TimeLockDelta = ourPolicy.TimeLockDelta
3✔
4548
                chanUpdateAnn.HtlcMinimumMsat = ourPolicy.MinHTLC
3✔
4549
                chanUpdateAnn.HtlcMaximumMsat = ourPolicy.MaxHTLC
3✔
4550
                chanUpdateAnn.BaseFee = uint32(ourPolicy.FeeBaseMSat)
3✔
4551
                chanUpdateAnn.FeeRate = uint32(
3✔
4552
                        ourPolicy.FeeProportionalMillionths,
3✔
4553
                )
3✔
4554

4555
        case storedFwdingPolicy != nil:
45✔
4556
                chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
45✔
4557
                chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
45✔
4558

4559
        default:
×
4560
                log.Infof("No channel forwarding policy specified for channel "+
×
4561
                        "announcement of ChannelID(%v). "+
×
4562
                        "Assuming default fee parameters.", chanID)
×
4563
                chanUpdateAnn.BaseFee = uint32(
×
4564
                        f.cfg.DefaultRoutingPolicy.BaseFee,
×
4565
                )
×
4566
                chanUpdateAnn.FeeRate = uint32(
×
4567
                        f.cfg.DefaultRoutingPolicy.FeeRate,
×
4568
                )
×
4569
        }
4570

4571
        // With the channel update announcement constructed, we'll generate a
4572
        // signature that signs a double-sha digest of the announcement.
4573
        // This'll serve to authenticate this announcement and any other future
4574
        // updates we may send.
4575
        chanUpdateMsg, err := chanUpdateAnn.DataToSign()
45✔
4576
        if err != nil {
45✔
4577
                return nil, err
×
4578
        }
×
4579
        sig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanUpdateMsg, true)
45✔
4580
        if err != nil {
45✔
4581
                return nil, errors.Errorf("unable to generate channel "+
×
4582
                        "update announcement signature: %v", err)
×
4583
        }
×
4584
        chanUpdateAnn.Signature, err = lnwire.NewSigFromSignature(sig)
45✔
4585
        if err != nil {
45✔
4586
                return nil, errors.Errorf("unable to generate channel "+
×
4587
                        "update announcement signature: %v", err)
×
4588
        }
×
4589

4590
        // The channel existence proofs itself is currently announced in
4591
        // distinct message. In order to properly authenticate this message, we
4592
        // need two signatures: one under the identity public key used which
4593
        // signs the message itself and another signature of the identity
4594
        // public key under the funding key itself.
4595
        //
4596
        // TODO(roasbeef): use SignAnnouncement here instead?
4597
        chanAnnMsg, err := chanAnn.DataToSign()
45✔
4598
        if err != nil {
45✔
4599
                return nil, err
×
4600
        }
×
4601
        nodeSig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanAnnMsg, true)
45✔
4602
        if err != nil {
45✔
4603
                return nil, errors.Errorf("unable to generate node "+
×
4604
                        "signature for channel announcement: %v", err)
×
4605
        }
×
4606
        bitcoinSig, err := f.cfg.SignMessage(
45✔
4607
                localFundingKey.KeyLocator, chanAnnMsg, true,
45✔
4608
        )
45✔
4609
        if err != nil {
45✔
4610
                return nil, errors.Errorf("unable to generate bitcoin "+
×
4611
                        "signature for node public key: %v", err)
×
4612
        }
×
4613

4614
        // Finally, we'll generate the announcement proof which we'll use to
4615
        // provide the other side with the necessary signatures required to
4616
        // allow them to reconstruct the full channel announcement.
4617
        proof := &lnwire.AnnounceSignatures1{
45✔
4618
                ChannelID:      chanID,
45✔
4619
                ShortChannelID: shortChanID,
45✔
4620
        }
45✔
4621
        proof.NodeSignature, err = lnwire.NewSigFromSignature(nodeSig)
45✔
4622
        if err != nil {
45✔
4623
                return nil, err
×
4624
        }
×
4625
        proof.BitcoinSignature, err = lnwire.NewSigFromSignature(bitcoinSig)
45✔
4626
        if err != nil {
45✔
4627
                return nil, err
×
4628
        }
×
4629

4630
        return &chanAnnouncement{
45✔
4631
                chanAnn:       chanAnn,
45✔
4632
                chanUpdateAnn: chanUpdateAnn,
45✔
4633
                chanProof:     proof,
45✔
4634
        }, nil
45✔
4635
}
4636

4637
// announceChannel announces a newly created channel to the rest of the network
4638
// by crafting the two authenticated announcements required for the peers on
4639
// the network to recognize the legitimacy of the channel. The crafted
4640
// announcements are then sent to the channel router to handle broadcasting to
4641
// the network during its next trickle.
4642
// This method is synchronous and will return when all the network requests
4643
// finish, either successfully or with an error.
4644
func (f *Manager) announceChannel(localIDKey, remoteIDKey *btcec.PublicKey,
4645
        localFundingKey *keychain.KeyDescriptor,
4646
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4647
        chanID lnwire.ChannelID, chanType channeldb.ChannelType) error {
19✔
4648

19✔
4649
        // First, we'll create the batch of announcements to be sent upon
19✔
4650
        // initial channel creation. This includes the channel announcement
19✔
4651
        // itself, the channel update announcement, and our half of the channel
19✔
4652
        // proof needed to fully authenticate the channel.
19✔
4653
        //
19✔
4654
        // We can pass in zeroes for the min and max htlc policy, because we
19✔
4655
        // only use the channel announcement message from the returned struct.
19✔
4656
        ann, err := f.newChanAnnouncement(
19✔
4657
                localIDKey, remoteIDKey, localFundingKey, remoteFundingKey,
19✔
4658
                shortChanID, chanID, 0, 0, nil, chanType,
19✔
4659
        )
19✔
4660
        if err != nil {
19✔
4661
                log.Errorf("can't generate channel announcement: %v", err)
×
4662
                return err
×
4663
        }
×
4664

4665
        // We only send the channel proof announcement and the node announcement
4666
        // because addToGraph previously sent the ChannelAnnouncement and
4667
        // the ChannelUpdate announcement messages. The channel proof and node
4668
        // announcements are broadcast to the greater network.
4669
        errChan := f.cfg.SendAnnouncement(ann.chanProof)
19✔
4670
        select {
19✔
4671
        case err := <-errChan:
19✔
4672
                if err != nil {
22✔
4673
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4674
                                graph.ErrIgnored) {
3✔
4675

×
4676
                                log.Debugf("Graph rejected "+
×
4677
                                        "AnnounceSignatures: %v", err)
×
4678
                        } else {
3✔
4679
                                log.Errorf("Unable to send channel "+
3✔
4680
                                        "proof: %v", err)
3✔
4681
                                return err
3✔
4682
                        }
3✔
4683
                }
4684

4685
        case <-f.quit:
×
4686
                return ErrFundingManagerShuttingDown
×
4687
        }
4688

4689
        // Now that the channel is announced to the network, we will also
4690
        // obtain and send a node announcement. This is done since a node
4691
        // announcement is only accepted after a channel is known for that
4692
        // particular node, and this might be our first channel.
4693
        nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
19✔
4694
        if err != nil {
19✔
4695
                log.Errorf("can't generate node announcement: %v", err)
×
4696
                return err
×
4697
        }
×
4698

4699
        errChan = f.cfg.SendAnnouncement(&nodeAnn)
19✔
4700
        select {
19✔
4701
        case err := <-errChan:
19✔
4702
                if err != nil {
22✔
4703
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4704
                                graph.ErrIgnored) {
6✔
4705

3✔
4706
                                log.Debugf("Graph rejected "+
3✔
4707
                                        "NodeAnnouncement: %v", err)
3✔
4708
                        } else {
3✔
4709
                                log.Errorf("Unable to send node "+
×
4710
                                        "announcement: %v", err)
×
4711
                                return err
×
4712
                        }
×
4713
                }
4714

4715
        case <-f.quit:
×
4716
                return ErrFundingManagerShuttingDown
×
4717
        }
4718

4719
        return nil
19✔
4720
}
4721

4722
// InitFundingWorkflow sends a message to the funding manager instructing it
4723
// to initiate a single funder workflow with the source peer.
4724
func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg) {
59✔
4725
        f.fundingRequests <- msg
59✔
4726
}
59✔
4727

4728
// getUpfrontShutdownScript takes a user provided script and a getScript
4729
// function which can be used to generate an upfront shutdown script. If our
4730
// peer does not support the feature, this function will error if a non-zero
4731
// script was provided by the user, and return an empty script otherwise. If
4732
// our peer does support the feature, we will return the user provided script
4733
// if non-zero, or a freshly generated script if our node is configured to set
4734
// upfront shutdown scripts automatically.
4735
func getUpfrontShutdownScript(enableUpfrontShutdown bool, peer lnpeer.Peer,
4736
        script lnwire.DeliveryAddress,
4737
        getScript func(bool) (lnwire.DeliveryAddress, error)) (lnwire.DeliveryAddress,
4738
        error) {
111✔
4739

111✔
4740
        // Check whether the remote peer supports upfront shutdown scripts.
111✔
4741
        remoteUpfrontShutdown := peer.RemoteFeatures().HasFeature(
111✔
4742
                lnwire.UpfrontShutdownScriptOptional,
111✔
4743
        )
111✔
4744

111✔
4745
        // If the peer does not support upfront shutdown scripts, and one has been
111✔
4746
        // provided, return an error because the feature is not supported.
111✔
4747
        if !remoteUpfrontShutdown && len(script) != 0 {
112✔
4748
                return nil, errUpfrontShutdownScriptNotSupported
1✔
4749
        }
1✔
4750

4751
        // If the peer does not support upfront shutdown, return an empty address.
4752
        if !remoteUpfrontShutdown {
213✔
4753
                return nil, nil
103✔
4754
        }
103✔
4755

4756
        // If the user has provided an script and the peer supports the feature,
4757
        // return it. Note that user set scripts override the enable upfront
4758
        // shutdown flag.
4759
        if len(script) > 0 {
12✔
4760
                return script, nil
5✔
4761
        }
5✔
4762

4763
        // If we do not have setting of upfront shutdown script enabled, return
4764
        // an empty script.
4765
        if !enableUpfrontShutdown {
9✔
4766
                return nil, nil
4✔
4767
        }
4✔
4768

4769
        // We can safely send a taproot address iff, both sides have negotiated
4770
        // the shutdown-any-segwit feature.
4771
        taprootOK := peer.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
1✔
4772
                peer.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
1✔
4773

1✔
4774
        return getScript(taprootOK)
1✔
4775
}
4776

4777
// handleInitFundingMsg creates a channel reservation within the daemon's
4778
// wallet, then sends a funding request to the remote peer kicking off the
4779
// funding workflow.
4780
func (f *Manager) handleInitFundingMsg(msg *InitFundingMsg) {
59✔
4781
        var (
59✔
4782
                peerKey        = msg.Peer.IdentityKey()
59✔
4783
                localAmt       = msg.LocalFundingAmt
59✔
4784
                baseFee        = msg.BaseFee
59✔
4785
                feeRate        = msg.FeeRate
59✔
4786
                minHtlcIn      = msg.MinHtlcIn
59✔
4787
                remoteCsvDelay = msg.RemoteCsvDelay
59✔
4788
                maxValue       = msg.MaxValueInFlight
59✔
4789
                maxHtlcs       = msg.MaxHtlcs
59✔
4790
                maxCSV         = msg.MaxLocalCsv
59✔
4791
                chanReserve    = msg.RemoteChanReserve
59✔
4792
                outpoints      = msg.Outpoints
59✔
4793
        )
59✔
4794

59✔
4795
        // If no maximum CSV delay was set for this channel, we use our default
59✔
4796
        // value.
59✔
4797
        if maxCSV == 0 {
118✔
4798
                maxCSV = f.cfg.MaxLocalCSVDelay
59✔
4799
        }
59✔
4800

4801
        log.Infof("Initiating fundingRequest(local_amt=%v "+
59✔
4802
                "(subtract_fees=%v), push_amt=%v, chain_hash=%v, peer=%x, "+
59✔
4803
                "min_confs=%v)", localAmt, msg.SubtractFees, msg.PushAmt,
59✔
4804
                msg.ChainHash, peerKey.SerializeCompressed(), msg.MinConfs)
59✔
4805

59✔
4806
        // We set the channel flags to indicate whether we want this channel to
59✔
4807
        // be announced to the network.
59✔
4808
        var channelFlags lnwire.FundingFlag
59✔
4809
        if !msg.Private {
113✔
4810
                // This channel will be announced.
54✔
4811
                channelFlags = lnwire.FFAnnounceChannel
54✔
4812
        }
54✔
4813

4814
        // If the caller specified their own channel ID, then we'll use that.
4815
        // Otherwise we'll generate a fresh one as normal.  This will be used
4816
        // to track this reservation throughout its lifetime.
4817
        var chanID PendingChanID
59✔
4818
        if msg.PendingChanID == zeroID {
118✔
4819
                chanID = f.nextPendingChanID()
59✔
4820
        } else {
62✔
4821
                // If the user specified their own pending channel ID, then
3✔
4822
                // we'll ensure it doesn't collide with any existing pending
3✔
4823
                // channel ID.
3✔
4824
                chanID = msg.PendingChanID
3✔
4825
                if _, err := f.getReservationCtx(peerKey, chanID); err == nil {
3✔
4826
                        msg.Err <- fmt.Errorf("pendingChannelID(%x) "+
×
4827
                                "already present", chanID[:])
×
4828
                        return
×
4829
                }
×
4830
        }
4831

4832
        // Check whether the peer supports upfront shutdown, and get an address
4833
        // which should be used (either a user specified address or a new
4834
        // address from the wallet if our node is configured to set shutdown
4835
        // address by default).
4836
        shutdown, err := getUpfrontShutdownScript(
59✔
4837
                f.cfg.EnableUpfrontShutdown, msg.Peer, msg.ShutdownScript,
59✔
4838
                f.selectShutdownScript,
59✔
4839
        )
59✔
4840
        if err != nil {
59✔
4841
                msg.Err <- err
×
4842
                return
×
4843
        }
×
4844

4845
        // Initialize a funding reservation with the local wallet. If the
4846
        // wallet doesn't have enough funds to commit to this channel, then the
4847
        // request will fail, and be aborted.
4848
        //
4849
        // Before we init the channel, we'll also check to see what commitment
4850
        // format we can use with this peer. This is dependent on *both* us and
4851
        // the remote peer are signaling the proper feature bit.
4852
        chanType, commitType, err := negotiateCommitmentType(
59✔
4853
                msg.ChannelType, msg.Peer.LocalFeatures(),
59✔
4854
                msg.Peer.RemoteFeatures(),
59✔
4855
        )
59✔
4856
        if err != nil {
62✔
4857
                log.Errorf("channel type negotiation failed: %v", err)
3✔
4858
                msg.Err <- err
3✔
4859
                return
3✔
4860
        }
3✔
4861

4862
        var (
59✔
4863
                zeroConf bool
59✔
4864
                scid     bool
59✔
4865
        )
59✔
4866

59✔
4867
        if chanType != nil {
66✔
4868
                // Check if the returned chanType includes either the zero-conf
7✔
4869
                // or scid-alias bits.
7✔
4870
                featureVec := lnwire.RawFeatureVector(*chanType)
7✔
4871
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
7✔
4872
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
7✔
4873

7✔
4874
                // The option-scid-alias channel type for a public channel is
7✔
4875
                // disallowed.
7✔
4876
                if scid && !msg.Private {
7✔
4877
                        err = fmt.Errorf("option-scid-alias chantype for " +
×
4878
                                "public channel")
×
4879
                        log.Error(err)
×
4880
                        msg.Err <- err
×
4881

×
4882
                        return
×
4883
                }
×
4884
        }
4885

4886
        // First, we'll query the fee estimator for a fee that should get the
4887
        // commitment transaction confirmed by the next few blocks (conf target
4888
        // of 3). We target the near blocks here to ensure that we'll be able
4889
        // to execute a timely unilateral channel closure if needed.
4890
        commitFeePerKw, err := f.cfg.FeeEstimator.EstimateFeePerKW(3)
59✔
4891
        if err != nil {
59✔
4892
                msg.Err <- err
×
4893
                return
×
4894
        }
×
4895

4896
        // For anchor channels cap the initial commit fee rate at our defined
4897
        // maximum.
4898
        if commitType.HasAnchors() &&
59✔
4899
                commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
66✔
4900

7✔
4901
                commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate
7✔
4902
        }
7✔
4903

4904
        var scidFeatureVal bool
59✔
4905
        if hasFeatures(
59✔
4906
                msg.Peer.LocalFeatures(), msg.Peer.RemoteFeatures(),
59✔
4907
                lnwire.ScidAliasOptional,
59✔
4908
        ) {
65✔
4909

6✔
4910
                scidFeatureVal = true
6✔
4911
        }
6✔
4912

4913
        // At this point, if we have an AuxFundingController active, we'll check
4914
        // to see if we have a special tapscript root to use in our MuSig2
4915
        // funding output.
4916
        tapscriptRoot, err := fn.MapOptionZ(
59✔
4917
                f.cfg.AuxFundingController,
59✔
4918
                func(c AuxFundingController) AuxTapscriptResult {
59✔
4919
                        return c.DeriveTapscriptRoot(chanID)
×
4920
                },
×
4921
        ).Unpack()
4922
        if err != nil {
59✔
4923
                err = fmt.Errorf("error deriving tapscript root: %w", err)
×
4924
                log.Error(err)
×
4925
                msg.Err <- err
×
4926

×
4927
                return
×
4928
        }
×
4929

4930
        req := &lnwallet.InitFundingReserveMsg{
59✔
4931
                ChainHash:         &msg.ChainHash,
59✔
4932
                PendingChanID:     chanID,
59✔
4933
                NodeID:            peerKey,
59✔
4934
                NodeAddr:          msg.Peer.Address(),
59✔
4935
                SubtractFees:      msg.SubtractFees,
59✔
4936
                LocalFundingAmt:   localAmt,
59✔
4937
                RemoteFundingAmt:  0,
59✔
4938
                FundUpToMaxAmt:    msg.FundUpToMaxAmt,
59✔
4939
                MinFundAmt:        msg.MinFundAmt,
59✔
4940
                RemoteChanReserve: chanReserve,
59✔
4941
                Outpoints:         outpoints,
59✔
4942
                CommitFeePerKw:    commitFeePerKw,
59✔
4943
                FundingFeePerKw:   msg.FundingFeePerKw,
59✔
4944
                PushMSat:          msg.PushAmt,
59✔
4945
                Flags:             channelFlags,
59✔
4946
                MinConfs:          msg.MinConfs,
59✔
4947
                CommitType:        commitType,
59✔
4948
                ChanFunder:        msg.ChanFunder,
59✔
4949
                // Unconfirmed Utxos which are marked by the sweeper subsystem
59✔
4950
                // are excluded from the coin selection because they are not
59✔
4951
                // final and can be RBFed by the sweeper subsystem.
59✔
4952
                AllowUtxoForFunding: func(u lnwallet.Utxo) bool {
119✔
4953
                        // Utxos with at least 1 confirmation are safe to use
60✔
4954
                        // for channel openings because they don't bare the risk
60✔
4955
                        // of being replaced (BIP 125 RBF).
60✔
4956
                        if u.Confirmations > 0 {
63✔
4957
                                return true
3✔
4958
                        }
3✔
4959

4960
                        // Query the sweeper storage to make sure we don't use
4961
                        // an unconfirmed utxo still in use by the sweeper
4962
                        // subsystem.
4963
                        return !f.cfg.IsSweeperOutpoint(u.OutPoint)
60✔
4964
                },
4965
                ZeroConf:         zeroConf,
4966
                OptionScidAlias:  scid,
4967
                ScidAliasFeature: scidFeatureVal,
4968
                Memo:             msg.Memo,
4969
                TapscriptRoot:    tapscriptRoot,
4970
        }
4971

4972
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
59✔
4973
        if err != nil {
62✔
4974
                msg.Err <- err
3✔
4975
                return
3✔
4976
        }
3✔
4977

4978
        if zeroConf {
64✔
4979
                // Store the alias for zero-conf channels in the underlying
5✔
4980
                // partial channel state.
5✔
4981
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
5✔
4982
                if err != nil {
5✔
4983
                        msg.Err <- err
×
4984
                        return
×
4985
                }
×
4986

4987
                reservation.AddAlias(aliasScid)
5✔
4988
        }
4989

4990
        // Set our upfront shutdown address in the existing reservation.
4991
        reservation.SetOurUpfrontShutdown(shutdown)
59✔
4992

59✔
4993
        // Now that we have successfully reserved funds for this channel in the
59✔
4994
        // wallet, we can fetch the final channel capacity. This is done at
59✔
4995
        // this point since the final capacity might change in case of
59✔
4996
        // SubtractFees=true.
59✔
4997
        capacity := reservation.Capacity()
59✔
4998

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

59✔
5002
        // If the remote CSV delay was not set in the open channel request,
59✔
5003
        // we'll use the RequiredRemoteDelay closure to compute the delay we
59✔
5004
        // require given the total amount of funds within the channel.
59✔
5005
        if remoteCsvDelay == 0 {
117✔
5006
                remoteCsvDelay = f.cfg.RequiredRemoteDelay(capacity)
58✔
5007
        }
58✔
5008

5009
        // If no minimum HTLC value was specified, use the default one.
5010
        if minHtlcIn == 0 {
117✔
5011
                minHtlcIn = f.cfg.DefaultMinHtlcIn
58✔
5012
        }
58✔
5013

5014
        // If no max value was specified, use the default one.
5015
        if maxValue == 0 {
117✔
5016
                maxValue = f.cfg.RequiredRemoteMaxValue(capacity)
58✔
5017
        }
58✔
5018

5019
        if maxHtlcs == 0 {
118✔
5020
                maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
59✔
5021
        }
59✔
5022

5023
        // Once the reservation has been created, and indexed, queue a funding
5024
        // request to the remote peer, kicking off the funding workflow.
5025
        ourContribution := reservation.OurContribution()
59✔
5026

59✔
5027
        // Prepare the optional channel fee values from the initFundingMsg. If
59✔
5028
        // useBaseFee or useFeeRate are false the client did not provide fee
59✔
5029
        // values hence we assume default fee settings from the config.
59✔
5030
        forwardingPolicy := f.defaultForwardingPolicy(
59✔
5031
                ourContribution.ChannelStateBounds,
59✔
5032
        )
59✔
5033
        if baseFee != nil {
63✔
5034
                forwardingPolicy.BaseFee = lnwire.MilliSatoshi(*baseFee)
4✔
5035
        }
4✔
5036

5037
        if feeRate != nil {
63✔
5038
                forwardingPolicy.FeeRate = lnwire.MilliSatoshi(*feeRate)
4✔
5039
        }
4✔
5040

5041
        // Fetch our dust limit which is part of the default channel
5042
        // constraints, and log it.
5043
        ourDustLimit := ourContribution.DustLimit
59✔
5044

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

59✔
5047
        // If the channel reserve is not specified, then we calculate an
59✔
5048
        // appropriate amount here.
59✔
5049
        if chanReserve == 0 {
114✔
5050
                chanReserve = f.cfg.RequiredRemoteChanReserve(
55✔
5051
                        capacity, ourDustLimit,
55✔
5052
                )
55✔
5053
        }
55✔
5054

5055
        // If a pending channel map for this peer isn't already created, then
5056
        // we create one, ultimately allowing us to track this pending
5057
        // reservation within the target peer.
5058
        peerIDKey := newSerializedKey(peerKey)
59✔
5059
        f.resMtx.Lock()
59✔
5060
        if _, ok := f.activeReservations[peerIDKey]; !ok {
111✔
5061
                f.activeReservations[peerIDKey] = make(pendingChannels)
52✔
5062
        }
52✔
5063

5064
        resCtx := &reservationWithCtx{
59✔
5065
                chanAmt:           capacity,
59✔
5066
                forwardingPolicy:  *forwardingPolicy,
59✔
5067
                remoteCsvDelay:    remoteCsvDelay,
59✔
5068
                remoteMinHtlc:     minHtlcIn,
59✔
5069
                remoteMaxValue:    maxValue,
59✔
5070
                remoteMaxHtlcs:    maxHtlcs,
59✔
5071
                remoteChanReserve: chanReserve,
59✔
5072
                maxLocalCsv:       maxCSV,
59✔
5073
                channelType:       chanType,
59✔
5074
                reservation:       reservation,
59✔
5075
                peer:              msg.Peer,
59✔
5076
                updates:           msg.Updates,
59✔
5077
                err:               msg.Err,
59✔
5078
        }
59✔
5079
        f.activeReservations[peerIDKey][chanID] = resCtx
59✔
5080
        f.resMtx.Unlock()
59✔
5081

59✔
5082
        // Update the timestamp once the InitFundingMsg has been handled.
59✔
5083
        defer resCtx.updateTimestamp()
59✔
5084

59✔
5085
        // Check the sanity of the selected channel constraints.
59✔
5086
        bounds := &channeldb.ChannelStateBounds{
59✔
5087
                ChanReserve:      chanReserve,
59✔
5088
                MaxPendingAmount: maxValue,
59✔
5089
                MinHTLC:          minHtlcIn,
59✔
5090
                MaxAcceptedHtlcs: maxHtlcs,
59✔
5091
        }
59✔
5092
        commitParams := &channeldb.CommitmentParams{
59✔
5093
                DustLimit: ourDustLimit,
59✔
5094
                CsvDelay:  remoteCsvDelay,
59✔
5095
        }
59✔
5096
        err = lnwallet.VerifyConstraints(
59✔
5097
                bounds, commitParams, resCtx.maxLocalCsv, capacity,
59✔
5098
        )
59✔
5099
        if err != nil {
61✔
5100
                _, reserveErr := f.cancelReservationCtx(peerKey, chanID, false)
2✔
5101
                if reserveErr != nil {
2✔
5102
                        log.Errorf("unable to cancel reservation: %v",
×
5103
                                reserveErr)
×
5104
                }
×
5105

5106
                msg.Err <- err
2✔
5107
                return
2✔
5108
        }
5109

5110
        // When opening a script enforced channel lease, include the required
5111
        // expiry TLV record in our proposal.
5112
        var leaseExpiry *lnwire.LeaseExpiry
57✔
5113
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
60✔
5114
                leaseExpiry = new(lnwire.LeaseExpiry)
3✔
5115
                *leaseExpiry = lnwire.LeaseExpiry(reservation.LeaseExpiry())
3✔
5116
        }
3✔
5117

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

57✔
5121
        reservation.SetState(lnwallet.SentOpenChannel)
57✔
5122

57✔
5123
        fundingOpen := lnwire.OpenChannel{
57✔
5124
                ChainHash:             *f.cfg.Wallet.Cfg.NetParams.GenesisHash,
57✔
5125
                PendingChannelID:      chanID,
57✔
5126
                FundingAmount:         capacity,
57✔
5127
                PushAmount:            msg.PushAmt,
57✔
5128
                DustLimit:             ourDustLimit,
57✔
5129
                MaxValueInFlight:      maxValue,
57✔
5130
                ChannelReserve:        chanReserve,
57✔
5131
                HtlcMinimum:           minHtlcIn,
57✔
5132
                FeePerKiloWeight:      uint32(commitFeePerKw),
57✔
5133
                CsvDelay:              remoteCsvDelay,
57✔
5134
                MaxAcceptedHTLCs:      maxHtlcs,
57✔
5135
                FundingKey:            ourContribution.MultiSigKey.PubKey,
57✔
5136
                RevocationPoint:       ourContribution.RevocationBasePoint.PubKey,
57✔
5137
                PaymentPoint:          ourContribution.PaymentBasePoint.PubKey,
57✔
5138
                HtlcPoint:             ourContribution.HtlcBasePoint.PubKey,
57✔
5139
                DelayedPaymentPoint:   ourContribution.DelayBasePoint.PubKey,
57✔
5140
                FirstCommitmentPoint:  ourContribution.FirstCommitmentPoint,
57✔
5141
                ChannelFlags:          channelFlags,
57✔
5142
                UpfrontShutdownScript: shutdown,
57✔
5143
                ChannelType:           chanType,
57✔
5144
                LeaseExpiry:           leaseExpiry,
57✔
5145
        }
57✔
5146

57✔
5147
        if commitType.IsTaproot() {
62✔
5148
                fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
5✔
5149
                        ourContribution.LocalNonce.PubNonce,
5✔
5150
                )
5✔
5151
        }
5✔
5152

5153
        if err := msg.Peer.SendMessage(true, &fundingOpen); err != nil {
57✔
5154
                e := fmt.Errorf("unable to send funding request message: %w",
×
5155
                        err)
×
5156
                log.Errorf(e.Error())
×
5157

×
5158
                // Since we were unable to send the initial message to the peer
×
5159
                // and start the funding flow, we'll cancel this reservation.
×
5160
                _, err := f.cancelReservationCtx(peerKey, chanID, false)
×
5161
                if err != nil {
×
5162
                        log.Errorf("unable to cancel reservation: %v", err)
×
5163
                }
×
5164

5165
                msg.Err <- e
×
5166
                return
×
5167
        }
5168
}
5169

5170
// handleWarningMsg processes the warning which was received from remote peer.
5171
func (f *Manager) handleWarningMsg(peer lnpeer.Peer, msg *lnwire.Warning) {
42✔
5172
        log.Warnf("received warning message from peer %x: %v",
42✔
5173
                peer.IdentityKey().SerializeCompressed(), msg.Warning())
42✔
5174
}
42✔
5175

5176
// handleErrorMsg processes the error which was received from remote peer,
5177
// depending on the type of error we should do different clean up steps and
5178
// inform the user about it.
5179
func (f *Manager) handleErrorMsg(peer lnpeer.Peer, msg *lnwire.Error) {
3✔
5180
        chanID := msg.ChanID
3✔
5181
        peerKey := peer.IdentityKey()
3✔
5182

3✔
5183
        // First, we'll attempt to retrieve and cancel the funding workflow
3✔
5184
        // that this error was tied to. If we're unable to do so, then we'll
3✔
5185
        // exit early as this was an unwarranted error.
3✔
5186
        resCtx, err := f.cancelReservationCtx(peerKey, chanID, true)
3✔
5187
        if err != nil {
3✔
5188
                log.Warnf("Received error for non-existent funding "+
×
5189
                        "flow: %v (%v)", err, msg.Error())
×
5190
                return
×
5191
        }
×
5192

5193
        // If we did indeed find the funding workflow, then we'll return the
5194
        // error back to the caller (if any), and cancel the workflow itself.
5195
        fundingErr := fmt.Errorf("received funding error from %x: %v",
3✔
5196
                peerKey.SerializeCompressed(), msg.Error(),
3✔
5197
        )
3✔
5198
        log.Errorf(fundingErr.Error())
3✔
5199

3✔
5200
        // If this was a PSBT funding flow, the remote likely timed out because
3✔
5201
        // we waited too long. Return a nice error message to the user in that
3✔
5202
        // case so the user knows what's the problem.
3✔
5203
        if resCtx.reservation.IsPsbt() {
6✔
5204
                fundingErr = fmt.Errorf("%w: %v", chanfunding.ErrRemoteCanceled,
3✔
5205
                        fundingErr)
3✔
5206
        }
3✔
5207

5208
        resCtx.err <- fundingErr
3✔
5209
}
5210

5211
// pruneZombieReservations loops through all pending reservations and fails the
5212
// funding flow for any reservations that have not been updated since the
5213
// ReservationTimeout and are not locked waiting for the funding transaction.
5214
func (f *Manager) pruneZombieReservations() {
6✔
5215
        zombieReservations := make(pendingChannels)
6✔
5216

6✔
5217
        f.resMtx.RLock()
6✔
5218
        for _, pendingReservations := range f.activeReservations {
12✔
5219
                for pendingChanID, resCtx := range pendingReservations {
12✔
5220
                        if resCtx.isLocked() {
6✔
5221
                                continue
×
5222
                        }
5223

5224
                        // We don't want to expire PSBT funding reservations.
5225
                        // These reservations are always initiated by us and the
5226
                        // remote peer is likely going to cancel them after some
5227
                        // idle time anyway. So no need for us to also prune
5228
                        // them.
5229
                        sinceLastUpdate := time.Since(resCtx.lastUpdated)
6✔
5230
                        isExpired := sinceLastUpdate > f.cfg.ReservationTimeout
6✔
5231
                        if !resCtx.reservation.IsPsbt() && isExpired {
12✔
5232
                                zombieReservations[pendingChanID] = resCtx
6✔
5233
                        }
6✔
5234
                }
5235
        }
5236
        f.resMtx.RUnlock()
6✔
5237

6✔
5238
        for pendingChanID, resCtx := range zombieReservations {
12✔
5239
                err := fmt.Errorf("reservation timed out waiting for peer "+
6✔
5240
                        "(peer_id:%x, chan_id:%x)",
6✔
5241
                        resCtx.peer.IdentityKey().SerializeCompressed(),
6✔
5242
                        pendingChanID[:])
6✔
5243
                log.Warnf(err.Error())
6✔
5244

6✔
5245
                chanID := lnwire.NewChanIDFromOutPoint(
6✔
5246
                        *resCtx.reservation.FundingOutpoint(),
6✔
5247
                )
6✔
5248

6✔
5249
                // Create channel identifier and set the channel ID.
6✔
5250
                cid := newChanIdentifier(pendingChanID)
6✔
5251
                cid.setChanID(chanID)
6✔
5252

6✔
5253
                f.failFundingFlow(resCtx.peer, cid, err)
6✔
5254
        }
6✔
5255
}
5256

5257
// cancelReservationCtx does all needed work in order to securely cancel the
5258
// reservation.
5259
func (f *Manager) cancelReservationCtx(peerKey *btcec.PublicKey,
5260
        pendingChanID PendingChanID,
5261
        byRemote bool) (*reservationWithCtx, error) {
26✔
5262

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

26✔
5266
        peerIDKey := newSerializedKey(peerKey)
26✔
5267
        f.resMtx.Lock()
26✔
5268
        defer f.resMtx.Unlock()
26✔
5269

26✔
5270
        nodeReservations, ok := f.activeReservations[peerIDKey]
26✔
5271
        if !ok {
36✔
5272
                // No reservations for this node.
10✔
5273
                return nil, errors.Errorf("no active reservations for peer(%x)",
10✔
5274
                        peerIDKey[:])
10✔
5275
        }
10✔
5276

5277
        ctx, ok := nodeReservations[pendingChanID]
19✔
5278
        if !ok {
21✔
5279
                return nil, errors.Errorf("unknown channel (id: %x) for "+
2✔
5280
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
2✔
5281
        }
2✔
5282

5283
        // If the reservation was a PSBT funding flow and it was canceled by the
5284
        // remote peer, then we need to thread through a different error message
5285
        // to the subroutine that's waiting for the user input so it can return
5286
        // a nice error message to the user.
5287
        if ctx.reservation.IsPsbt() && byRemote {
20✔
5288
                ctx.reservation.RemoteCanceled()
3✔
5289
        }
3✔
5290

5291
        if err := ctx.reservation.Cancel(); err != nil {
17✔
5292
                return nil, errors.Errorf("unable to cancel reservation: %v",
×
5293
                        err)
×
5294
        }
×
5295

5296
        delete(nodeReservations, pendingChanID)
17✔
5297

17✔
5298
        // If this was the last active reservation for this peer, delete the
17✔
5299
        // peer's entry altogether.
17✔
5300
        if len(nodeReservations) == 0 {
34✔
5301
                delete(f.activeReservations, peerIDKey)
17✔
5302
        }
17✔
5303
        return ctx, nil
17✔
5304
}
5305

5306
// deleteReservationCtx deletes the reservation uniquely identified by the
5307
// target public key of the peer, and the specified pending channel ID.
5308
func (f *Manager) deleteReservationCtx(peerKey *btcec.PublicKey,
5309
        pendingChanID PendingChanID) {
57✔
5310

57✔
5311
        peerIDKey := newSerializedKey(peerKey)
57✔
5312
        f.resMtx.Lock()
57✔
5313
        defer f.resMtx.Unlock()
57✔
5314

57✔
5315
        nodeReservations, ok := f.activeReservations[peerIDKey]
57✔
5316
        if !ok {
57✔
5317
                // No reservations for this node.
×
5318
                return
×
5319
        }
×
5320
        delete(nodeReservations, pendingChanID)
57✔
5321

57✔
5322
        // If this was the last active reservation for this peer, delete the
57✔
5323
        // peer's entry altogether.
57✔
5324
        if len(nodeReservations) == 0 {
107✔
5325
                delete(f.activeReservations, peerIDKey)
50✔
5326
        }
50✔
5327
}
5328

5329
// getReservationCtx returns the reservation context for a particular pending
5330
// channel ID for a target peer.
5331
func (f *Manager) getReservationCtx(peerKey *btcec.PublicKey,
5332
        pendingChanID PendingChanID) (*reservationWithCtx, error) {
91✔
5333

91✔
5334
        peerIDKey := newSerializedKey(peerKey)
91✔
5335
        f.resMtx.RLock()
91✔
5336
        resCtx, ok := f.activeReservations[peerIDKey][pendingChanID]
91✔
5337
        f.resMtx.RUnlock()
91✔
5338

91✔
5339
        if !ok {
94✔
5340
                return nil, errors.Errorf("unknown channel (id: %x) for "+
3✔
5341
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
3✔
5342
        }
3✔
5343

5344
        return resCtx, nil
91✔
5345
}
5346

5347
// IsPendingChannel returns a boolean indicating whether the channel identified
5348
// by the pendingChanID and given peer is pending, meaning it is in the process
5349
// of being funded. After the funding transaction has been confirmed, the
5350
// channel will receive a new, permanent channel ID, and will no longer be
5351
// considered pending.
5352
func (f *Manager) IsPendingChannel(pendingChanID PendingChanID,
5353
        peer lnpeer.Peer) bool {
3✔
5354

3✔
5355
        peerIDKey := newSerializedKey(peer.IdentityKey())
3✔
5356
        f.resMtx.RLock()
3✔
5357
        _, ok := f.activeReservations[peerIDKey][pendingChanID]
3✔
5358
        f.resMtx.RUnlock()
3✔
5359

3✔
5360
        return ok
3✔
5361
}
3✔
5362

5363
func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
378✔
5364
        var tmp btcec.JacobianPoint
378✔
5365
        pub.AsJacobian(&tmp)
378✔
5366
        tmp.ToAffine()
378✔
5367
        return btcec.NewPublicKey(&tmp.X, &tmp.Y)
378✔
5368
}
378✔
5369

5370
// defaultForwardingPolicy returns the default forwarding policy based on the
5371
// default routing policy and our local channel constraints.
5372
func (f *Manager) defaultForwardingPolicy(
5373
        bounds channeldb.ChannelStateBounds) *models.ForwardingPolicy {
105✔
5374

105✔
5375
        return &models.ForwardingPolicy{
105✔
5376
                MinHTLCOut:    bounds.MinHTLC,
105✔
5377
                MaxHTLC:       bounds.MaxPendingAmount,
105✔
5378
                BaseFee:       f.cfg.DefaultRoutingPolicy.BaseFee,
105✔
5379
                FeeRate:       f.cfg.DefaultRoutingPolicy.FeeRate,
105✔
5380
                TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
105✔
5381
        }
105✔
5382
}
105✔
5383

5384
// saveInitialForwardingPolicy saves the forwarding policy for the provided
5385
// chanPoint in the channelOpeningStateBucket.
5386
func (f *Manager) saveInitialForwardingPolicy(chanID lnwire.ChannelID,
5387
        forwardingPolicy *models.ForwardingPolicy) error {
70✔
5388

70✔
5389
        return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
70✔
5390
                chanID, forwardingPolicy,
70✔
5391
        )
70✔
5392
}
70✔
5393

5394
// getInitialForwardingPolicy fetches the initial forwarding policy for a given
5395
// channel id from the database which will be applied during the channel
5396
// announcement phase.
5397
func (f *Manager) getInitialForwardingPolicy(
5398
        chanID lnwire.ChannelID) (*models.ForwardingPolicy, error) {
97✔
5399

97✔
5400
        return f.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
97✔
5401
}
97✔
5402

5403
// deleteInitialForwardingPolicy removes channel fees for this chanID from
5404
// the database.
5405
func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
27✔
5406
        return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
27✔
5407
}
27✔
5408

5409
// saveChannelOpeningState saves the channelOpeningState for the provided
5410
// chanPoint to the channelOpeningStateBucket.
5411
func (f *Manager) saveChannelOpeningState(chanPoint *wire.OutPoint,
5412
        state channelOpeningState, shortChanID *lnwire.ShortChannelID) error {
95✔
5413

95✔
5414
        var outpointBytes bytes.Buffer
95✔
5415
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
95✔
5416
                return err
×
5417
        }
×
5418

5419
        // Save state and the uint64 representation of the shortChanID
5420
        // for later use.
5421
        scratch := make([]byte, 10)
95✔
5422
        byteOrder.PutUint16(scratch[:2], uint16(state))
95✔
5423
        byteOrder.PutUint64(scratch[2:], shortChanID.ToUint64())
95✔
5424

95✔
5425
        return f.cfg.ChannelDB.SaveChannelOpeningState(
95✔
5426
                outpointBytes.Bytes(), scratch,
95✔
5427
        )
95✔
5428
}
5429

5430
// getChannelOpeningState fetches the channelOpeningState for the provided
5431
// chanPoint from the database, or returns ErrChannelNotFound if the channel
5432
// is not found.
5433
func (f *Manager) getChannelOpeningState(chanPoint *wire.OutPoint) (
5434
        channelOpeningState, *lnwire.ShortChannelID, error) {
254✔
5435

254✔
5436
        var outpointBytes bytes.Buffer
254✔
5437
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
254✔
5438
                return 0, nil, err
×
5439
        }
×
5440

5441
        value, err := f.cfg.ChannelDB.GetChannelOpeningState(
254✔
5442
                outpointBytes.Bytes(),
254✔
5443
        )
254✔
5444
        if err != nil {
304✔
5445
                return 0, nil, err
50✔
5446
        }
50✔
5447

5448
        state := channelOpeningState(byteOrder.Uint16(value[:2]))
207✔
5449
        shortChanID := lnwire.NewShortChanIDFromInt(byteOrder.Uint64(value[2:]))
207✔
5450
        return state, &shortChanID, nil
207✔
5451
}
5452

5453
// deleteChannelOpeningState removes any state for chanPoint from the database.
5454
func (f *Manager) deleteChannelOpeningState(chanPoint *wire.OutPoint) error {
27✔
5455
        var outpointBytes bytes.Buffer
27✔
5456
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
27✔
5457
                return err
×
5458
        }
×
5459

5460
        return f.cfg.ChannelDB.DeleteChannelOpeningState(
27✔
5461
                outpointBytes.Bytes(),
27✔
5462
        )
27✔
5463
}
5464

5465
// selectShutdownScript selects the shutdown script we should send to the peer.
5466
// If we can use taproot, then we prefer that, otherwise we'll use a p2wkh
5467
// script.
5468
func (f *Manager) selectShutdownScript(taprootOK bool,
5469
) (lnwire.DeliveryAddress, error) {
×
5470

×
5471
        addrType := lnwallet.WitnessPubKey
×
5472
        if taprootOK {
×
5473
                addrType = lnwallet.TaprootPubkey
×
5474
        }
×
5475

5476
        addr, err := f.cfg.Wallet.NewAddress(
×
5477
                addrType, false, lnwallet.DefaultAccountName,
×
5478
        )
×
5479
        if err != nil {
×
5480
                return nil, err
×
5481
        }
×
5482

5483
        return txscript.PayToAddrScript(addr)
×
5484
}
5485

5486
// waitForPeerOnline blocks until the peer specified by peerPubkey comes online
5487
// and then returns the online peer.
5488
func (f *Manager) waitForPeerOnline(peerPubkey *btcec.PublicKey) (lnpeer.Peer,
5489
        error) {
107✔
5490

107✔
5491
        peerChan := make(chan lnpeer.Peer, 1)
107✔
5492

107✔
5493
        var peerKey [33]byte
107✔
5494
        copy(peerKey[:], peerPubkey.SerializeCompressed())
107✔
5495

107✔
5496
        f.cfg.NotifyWhenOnline(peerKey, peerChan)
107✔
5497

107✔
5498
        var peer lnpeer.Peer
107✔
5499
        select {
107✔
5500
        case peer = <-peerChan:
106✔
5501
        case <-f.quit:
1✔
5502
                return peer, ErrFundingManagerShuttingDown
1✔
5503
        }
5504
        return peer, nil
106✔
5505
}
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