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

lightningnetwork / lnd / 17381199536

01 Sep 2025 02:59PM UTC coverage: 66.638% (-0.02%) from 66.658%
17381199536

Pull #10182

github

web-flow
Merge e24e285e3 into 84b2c20ea
Pull Request #10182: Aux feature bits

52 of 119 new or added lines in 6 files covered. (43.7%)

86 existing lines in 20 files now uncovered.

136005 of 204094 relevant lines covered (66.64%)

21453.0 hits per line

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

74.09
/funding/manager.go
1
package funding
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

103
        msgBufferSize = 50
104

105
        // pendingChansLimit is the maximum number of pending channels that we
106
        // can have. After this point, pending channel opens will start to be
107
        // rejected.
108
        pendingChansLimit = 50
109
)
110

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

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

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

130
        zeroID [32]byte
131
)
132

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

146
        chanAmt btcutil.Amount
147

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

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

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

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

165
        updateMtx   sync.RWMutex
166
        lastUpdated time.Time
167

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

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

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

182
// updateTimestamp updates the reservation's timestamp with the current time.
183
func (r *reservationWithCtx) updateTimestamp() {
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)
515

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

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

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

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

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

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

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

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

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

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

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

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

573
        // AuxChannelNegotiator is an optional interface that allows aux channel
574
        // implementations to inject and process feature bits during init and
575
        // channel_reestablish messages.
576
        AuxChannelNegotiator fn.Option[lnwallet.AuxChannelNegotiator]
577
}
578

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

592
        // cfg is a copy of the configuration struct that the FundingManager
593
        // was initialized with.
594
        cfg *Config
595

596
        // chanIDKey is a cryptographically random key that's used to generate
597
        // temporary channel ID's.
598
        chanIDKey [32]byte
599

600
        // chanIDNonce is a nonce that's incremented for each new funding
601
        // reservation created.
602
        chanIDNonce atomic.Uint64
603

604
        // nonceMtx is a mutex that guards the pendingMusigNonces.
605
        nonceMtx sync.RWMutex
606

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

618
        // activeReservations is a map which houses the state of all pending
619
        // funding workflows.
620
        activeReservations map[serializedPubKey]pendingChannels
621

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

629
        // resMtx guards both of the maps above to ensure that all access is
630
        // goroutine safe.
631
        resMtx sync.RWMutex
632

633
        // fundingMsgs is a channel that relays fundingMsg structs from
634
        // external sub-systems using the ProcessFundingMsg call.
635
        fundingMsgs chan *fundingMsg
636

637
        // fundingRequests is a channel used to receive channel initiation
638
        // requests from a local subsystem within the daemon.
639
        fundingRequests chan *InitFundingMsg
640

641
        localDiscoverySignals *lnutils.SyncMap[lnwire.ChannelID, chan struct{}]
642

643
        handleChannelReadyBarriers *lnutils.SyncMap[lnwire.ChannelID, struct{}]
644

645
        quit chan struct{}
646
        wg   sync.WaitGroup
647
}
648

649
// channelOpeningState represents the different states a channel can be in
650
// between the funding transaction has been confirmed and the channel is
651
// announced to the network and ready to be used.
652
type channelOpeningState uint8
653

654
const (
655
        // markedOpen is the opening state of a channel if the funding
656
        // transaction is confirmed on-chain, but channelReady is not yet
657
        // successfully sent to the other peer.
658
        markedOpen channelOpeningState = iota
659

660
        // channelReadySent is the opening state of a channel if the
661
        // channelReady message has successfully been sent to the other peer,
662
        // but we still haven't announced the channel to the network.
663
        channelReadySent
664

665
        // addedToGraph is the opening state of a channel if the channel has
666
        // been successfully added to the graph immediately after the
667
        // channelReady message has been sent, but we still haven't announced
668
        // the channel to the network.
669
        addedToGraph
670
)
671

672
func (c channelOpeningState) String() string {
3✔
673
        switch c {
3✔
674
        case markedOpen:
3✔
675
                return "markedOpen"
3✔
676
        case channelReadySent:
3✔
677
                return "channelReadySent"
3✔
678
        case addedToGraph:
3✔
679
                return "addedToGraph"
3✔
680
        default:
×
681
                return "unknown"
×
682
        }
683
}
684

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

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

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

739
        for _, channel := range allChannels {
122✔
740
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
12✔
741

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

4✔
751
                        f.localDiscoverySignals.Store(
4✔
752
                                chanID, make(chan struct{}),
4✔
753
                        )
4✔
754

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

4✔
763
                                f.rebroadcastFundingTx(channel)
4✔
764
                        }
4✔
765
                } else if channel.ChanType.IsSingleFunder() &&
11✔
766
                        channel.ChanType.HasFundingTx() &&
11✔
767
                        channel.IsZeroConf() && channel.IsInitiator &&
11✔
768
                        !channel.ZeroConfConfirmed() {
13✔
769

2✔
770
                        // Rebroadcast the funding transaction for unconfirmed
2✔
771
                        // zero-conf channels if we have the funding tx and are
2✔
772
                        // also the initiator.
2✔
773
                        f.rebroadcastFundingTx(channel)
2✔
774
                }
2✔
775

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

784
        f.wg.Add(1) // TODO(roasbeef): tune
110✔
785
        go f.reservationCoordinator()
110✔
786

110✔
787
        return nil
110✔
788
}
789

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

106✔
797
                close(f.quit)
106✔
798
                f.wg.Wait()
106✔
799
        })
106✔
800

801
        return nil
107✔
802
}
803

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

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

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

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

834
// PendingChanID is a type that represents a pending channel ID. This might be
835
// selected by the caller, but if not, will be automatically selected.
836
type PendingChanID = [32]byte
837

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

59✔
844
        var nonceBytes [8]byte
59✔
845
        binary.LittleEndian.PutUint64(nonceBytes[:], nextNonce)
59✔
846

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

59✔
857
        return nextChanID
59✔
858
}
59✔
859

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

3✔
866
        f.resMtx.Lock()
3✔
867
        defer f.resMtx.Unlock()
3✔
868

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

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

887
                resCtx.err <- fmt.Errorf("peer disconnected")
×
888
                delete(nodeReservations, pendingID)
×
889
        }
890

891
        // Finally, we'll delete the node itself from the set of reservations.
892
        delete(f.activeReservations, nodePub)
×
893
}
894

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

906
        // chanID is the channel ID created by the funder once the
907
        // `accept_channel` message is received. For fundee, it's received from
908
        // the `funding_created` message.
909
        chanID lnwire.ChannelID
910

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

919
// newChanIdentifier creates a new chanIdentifier.
920
func newChanIdentifier(tempChanID lnwire.ChannelID) *chanIdentifier {
147✔
921
        return &chanIdentifier{
147✔
922
                tempChanID: tempChanID,
147✔
923
        }
147✔
924
}
147✔
925

926
// setChanID updates the `chanIdentifier` with the active channel ID.
927
func (c *chanIdentifier) setChanID(chanID lnwire.ChannelID) {
91✔
928
        c.chanID = chanID
91✔
929
        c.chanIDSet = true
91✔
930
}
91✔
931

932
// hasChanID returns true if the active channel ID has been set.
933
func (c *chanIdentifier) hasChanID() bool {
24✔
934
        return c.chanIDSet
24✔
935
}
24✔
936

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

24✔
947
        log.Debugf("Failing funding flow for pending_id=%v: %v",
24✔
948
                cid.tempChanID, fundingErr)
24✔
949

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

963
        ctx, err := f.cancelReservationCtx(
24✔
964
                peer.IdentityKey(), cid.tempChanID, false,
24✔
965
        )
24✔
966
        if err != nil {
36✔
967
                log.Errorf("unable to cancel reservation: %v", err)
12✔
968
        }
12✔
969

970
        // In case the case where the reservation existed, send the funding
971
        // error on the error channel.
972
        if ctx != nil {
39✔
973
                ctx.err <- fundingErr
15✔
974
        }
15✔
975

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

989
        // For all other error types we just send a generic error.
990
        default:
15✔
991
                msg = lnwire.ErrorData("funding failed due to internal error")
15✔
992
        }
993

994
        errMsg := &lnwire.Error{
24✔
995
                ChanID: cid.tempChanID,
24✔
996
                Data:   msg,
24✔
997
        }
24✔
998

24✔
999
        log.Debugf("Sending funding error to peer (%x): %v",
24✔
1000
                peer.IdentityKey().SerializeCompressed(), spew.Sdump(errMsg))
24✔
1001
        if err := peer.SendMessage(false, errMsg); err != nil {
24✔
UNCOV
1002
                log.Errorf("unable to send error message to peer %v", err)
×
UNCOV
1003
        }
×
1004
}
1005

1006
// sendWarning sends a new warning message to the target peer, targeting the
1007
// specified cid with the passed funding error.
1008
func (f *Manager) sendWarning(peer lnpeer.Peer, cid *chanIdentifier,
1009
        fundingErr error) {
×
1010

×
1011
        msg := fundingErr.Error()
×
1012

×
1013
        errMsg := &lnwire.Warning{
×
1014
                ChanID: cid.tempChanID,
×
1015
                Data:   lnwire.WarningData(msg),
×
1016
        }
×
1017

×
1018
        log.Debugf("Sending funding warning to peer (%x): %v",
×
1019
                peer.IdentityKey().SerializeCompressed(),
×
1020
                spew.Sdump(errMsg),
×
1021
        )
×
1022

×
1023
        if err := peer.SendMessage(false, errMsg); err != nil {
×
1024
                log.Errorf("unable to send error message to peer %v", err)
×
1025
        }
×
1026
}
1027

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

110✔
1035
        zombieSweepTicker := time.NewTicker(f.cfg.ZombieSweeperInterval)
110✔
1036
        defer zombieSweepTicker.Stop()
110✔
1037

110✔
1038
        for {
485✔
1039
                select {
375✔
1040
                case fmsg := <-f.fundingMsgs:
212✔
1041
                        switch msg := fmsg.msg.(type) {
212✔
1042
                        case *lnwire.OpenChannel:
56✔
1043
                                f.fundeeProcessOpenChannel(fmsg.peer, msg)
56✔
1044

1045
                        case *lnwire.AcceptChannel:
35✔
1046
                                f.funderProcessAcceptChannel(fmsg.peer, msg)
35✔
1047

1048
                        case *lnwire.FundingCreated:
30✔
1049
                                f.fundeeProcessFundingCreated(fmsg.peer, msg)
30✔
1050

1051
                        case *lnwire.FundingSigned:
30✔
1052
                                f.funderProcessFundingSigned(fmsg.peer, msg)
30✔
1053

1054
                        case *lnwire.ChannelReady:
31✔
1055
                                f.wg.Add(1)
31✔
1056
                                go f.handleChannelReady(fmsg.peer, msg)
31✔
1057

1058
                        case *lnwire.Warning:
42✔
1059
                                f.handleWarningMsg(fmsg.peer, msg)
42✔
1060

1061
                        case *lnwire.Error:
3✔
1062
                                f.handleErrorMsg(fmsg.peer, msg)
3✔
1063
                        }
1064
                case req := <-f.fundingRequests:
59✔
1065
                        f.handleInitFundingMsg(req)
59✔
1066

1067
                case <-zombieSweepTicker.C:
3✔
1068
                        f.pruneZombieReservations()
3✔
1069

1070
                case <-f.quit:
106✔
1071
                        return
106✔
1072
                }
1073
        }
1074
}
1075

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

66✔
1088
        defer f.wg.Done()
66✔
1089

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

1102
        var chanOpts []lnwallet.ChannelOpt
45✔
1103
        f.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
87✔
1104
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
42✔
1105
        })
42✔
1106
        f.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
87✔
1107
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
42✔
1108
        })
42✔
1109
        f.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
45✔
1110
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
1111
        })
×
1112

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

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

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

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

126✔
1171
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
126✔
1172
        log.Debugf("Channel(%v) with ShortChanID %v has opening state %v",
126✔
1173
                chanID, shortChanID, channelState)
126✔
1174

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

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

1198
                log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
37✔
1199
                        "sent ChannelReady", chanID, shortChanID)
37✔
1200

37✔
1201
                return nil
37✔
1202

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

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

1226
                        return nil
27✔
1227
                }
1228

1229
                return f.handleChannelReadyReceived(
27✔
1230
                        channel, shortChanID, pendingChanID, updateChan,
27✔
1231
                )
27✔
1232

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

1246
                        // Update the local shortChanID variable such that
1247
                        // annAfterSixConfs uses the confirmed SCID.
1248
                        confirmedScid := channel.ZeroConfRealScid()
7✔
1249
                        shortChanID = &confirmedScid
7✔
1250
                }
1251

1252
                err := f.annAfterSixConfs(channel, shortChanID)
29✔
1253
                if err != nil {
34✔
1254
                        return fmt.Errorf("error sending channel "+
5✔
1255
                                "announcement: %v", err)
5✔
1256
                }
5✔
1257

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

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

1279
                log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
27✔
1280
                        "announced", chanID, shortChanID)
27✔
1281

27✔
1282
                return nil
27✔
1283
        }
1284

1285
        return fmt.Errorf("undefined channelState: %v", channelState)
×
1286
}
1287

1288
// advancePendingChannelState waits for a pending channel's funding tx to
1289
// confirm, and marks it open in the database when that happens.
1290
func (f *Manager) advancePendingChannelState(channel *channeldb.OpenChannel,
1291
        pendingChanID PendingChanID) error {
58✔
1292

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

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

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

1325
                // Inform the ChannelNotifier that the channel has transitioned
1326
                // from pending open to open.
1327
                f.cfg.NotifyOpenChannelEvent(
7✔
1328
                        channel.FundingOutpoint, channel.IdentityPub,
7✔
1329
                )
7✔
1330

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

1339
                return nil
7✔
1340
        }
1341

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

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

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

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

×
1369
                        return err
×
1370
                }
×
1371

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

×
1381
                        return err
×
1382
                }
×
1383

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

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

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

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

1410
        return nil
33✔
1411
}
1412

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

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

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

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

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

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

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

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

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

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

7✔
1486
                return
7✔
1487
        }
7✔
1488

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1649
                return
×
1650

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

×
1659
                return
×
1660
        }
1661

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

×
1676
                return
×
1677
        }
×
1678

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

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

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

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

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

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

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

1739
        reservation.SetNumConfsRequired(numConfsReq)
49✔
1740

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1928
                        return
×
1929
                }
×
1930

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2117
                minDepth = 1
×
2118
        }
×
2119

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

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

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

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

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

×
2188
                        return
×
2189
                }
×
2190

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2428
                        return
×
2429
                }
×
2430

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

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

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

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

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

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

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

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

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

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

×
2496
                        return
×
2497
                }
×
2498

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

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

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

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

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

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

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

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

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

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

×
2603
                        return
×
2604
                }
×
2605

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

×
2616
                        return
×
2617
                }
×
2618
        }
2619

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

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

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

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

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

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

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

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

30✔
2668
        // Inform the ChannelNotifier that the channel has entered
30✔
2669
        // pending open state.
30✔
2670
        f.cfg.NotifyPendingOpenChannelEvent(
30✔
2671
                fundingOut, completeChan, completeChan.IdentityPub,
30✔
2672
        )
30✔
2673

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

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

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

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

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

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

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

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

×
2750
                return
×
2751
        }
×
2752

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

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

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

×
2779
                        return
×
2780
                }
×
2781

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

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

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

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

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

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

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

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

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

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

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

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

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

30✔
2888
        select {
30✔
2889
        case resCtx.updates <- upd:
30✔
2890
                // Inform the ChannelNotifier that the channel has entered
30✔
2891
                // pending open state.
30✔
2892
                f.cfg.NotifyPendingOpenChannelEvent(
30✔
2893
                        *fundingPoint, completeChan, completeChan.IdentityPub,
30✔
2894
                )
30✔
2895

2896
        case <-f.quit:
×
2897
                return
×
2898
        }
2899

2900
        // At this point we have broadcast the funding transaction and done all
2901
        // necessary processing.
2902
        f.wg.Add(1)
30✔
2903
        go f.advanceFundingState(completeChan, pendingChanID, resCtx.updates)
30✔
2904
}
2905

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

2915
        // fundingTx is the funding transaction that created the channel.
2916
        fundingTx *wire.MsgTx
2917
}
2918

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

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

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

2951
        // Notify other subsystems about the funding timeout.
2952
        f.cfg.NotifyFundingTimeout(c.FundingOutpoint, c.IdentityPub)
5✔
2953

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

5✔
2957
        // When the peer comes online, we'll notify it that we are now
5✔
2958
        // considering the channel flow canceled.
5✔
2959
        f.wg.Add(1)
5✔
2960
        go func() {
10✔
2961
                defer f.wg.Done()
5✔
2962

5✔
2963
                peer, err := f.waitForPeerOnline(c.IdentityPub)
5✔
2964
                switch err {
5✔
2965
                // We're already shutting down, so we can just return.
2966
                case ErrFundingManagerShuttingDown:
×
2967
                        return
×
2968

2969
                // nil error means we continue on.
2970
                case nil:
5✔
2971

2972
                // For unexpected errors, we print the error and still try to
2973
                // fail the funding flow.
2974
                default:
×
2975
                        log.Errorf("Unexpected error while waiting for peer "+
×
2976
                                "to come online: %v", err)
×
2977
                }
2978

2979
                // Create channel identifier and set the channel ID.
2980
                cid := newChanIdentifier(pendingID)
5✔
2981
                cid.setChanID(lnwire.NewChanIDFromOutPoint(c.FundingOutpoint))
5✔
2982

5✔
2983
                // TODO(halseth): should this send be made
5✔
2984
                // reliable?
5✔
2985

5✔
2986
                // The reservation won't exist at this point, but we'll send an
5✔
2987
                // Error message over anyways with ChanID set to pendingID.
5✔
2988
                f.failFundingFlow(peer, cid, timeoutErr)
5✔
2989
        }()
2990

2991
        return timeoutErr
5✔
2992
}
2993

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

60✔
3002
        confChan := make(chan *confirmedChannel)
60✔
3003
        timeoutChan := make(chan error, 1)
60✔
3004
        cancelChan := make(chan struct{})
60✔
3005

60✔
3006
        f.wg.Add(1)
60✔
3007
        go f.waitForFundingConfirmation(ch, cancelChan, confChan)
60✔
3008

60✔
3009
        // If we are not the initiator, we have no money at stake and will
60✔
3010
        // timeout waiting for the funding transaction to confirm after a
60✔
3011
        // while.
60✔
3012
        if !ch.IsInitiator && !ch.IsZeroConf() {
88✔
3013
                f.wg.Add(1)
28✔
3014
                go f.waitForTimeout(ch, cancelChan, timeoutChan)
28✔
3015
        }
28✔
3016
        defer close(cancelChan)
60✔
3017

60✔
3018
        select {
60✔
3019
        case err := <-timeoutChan:
5✔
3020
                if err != nil {
5✔
3021
                        return nil, err
×
3022
                }
×
3023
                return nil, ErrConfirmationTimeout
5✔
3024

3025
        case <-f.quit:
24✔
3026
                // The fundingManager is shutting down, and will resume wait on
24✔
3027
                // startup.
24✔
3028
                return nil, ErrFundingManagerShuttingDown
24✔
3029

3030
        case confirmedChannel, ok := <-confChan:
37✔
3031
                if !ok {
37✔
3032
                        return nil, fmt.Errorf("waiting for funding" +
×
3033
                                "confirmation failed")
×
3034
                }
×
3035
                return confirmedChannel, nil
37✔
3036
        }
3037
}
3038

3039
// makeFundingScript re-creates the funding script for the funding transaction
3040
// of the target channel.
3041
func makeFundingScript(channel *channeldb.OpenChannel) ([]byte, error) {
80✔
3042
        localKey := channel.LocalChanCfg.MultiSigKey.PubKey
80✔
3043
        remoteKey := channel.RemoteChanCfg.MultiSigKey.PubKey
80✔
3044

80✔
3045
        if channel.ChanType.IsTaproot() {
88✔
3046
                pkScript, _, err := input.GenTaprootFundingScript(
8✔
3047
                        localKey, remoteKey, int64(channel.Capacity),
8✔
3048
                        channel.TapscriptRoot,
8✔
3049
                )
8✔
3050
                if err != nil {
8✔
3051
                        return nil, err
×
3052
                }
×
3053

3054
                return pkScript, nil
8✔
3055
        }
3056

3057
        multiSigScript, err := input.GenMultiSigScript(
75✔
3058
                localKey.SerializeCompressed(),
75✔
3059
                remoteKey.SerializeCompressed(),
75✔
3060
        )
75✔
3061
        if err != nil {
75✔
3062
                return nil, err
×
3063
        }
×
3064

3065
        return input.WitnessScriptHash(multiSigScript)
75✔
3066
}
3067

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

60✔
3081
        defer f.wg.Done()
60✔
3082
        defer close(confChan)
60✔
3083

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

60✔
3096
        // If the underlying channel is a zero-conf channel, we'll set numConfs
60✔
3097
        // to 6, since it will be zero here.
60✔
3098
        if completeChan.IsZeroConf() {
69✔
3099
                numConfs = 6
9✔
3100
        }
9✔
3101

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

3113
        log.Infof("Waiting for funding tx (%v) to reach %v confirmations",
60✔
3114
                txid, numConfs)
60✔
3115

60✔
3116
        var confDetails *chainntnfs.TxConfirmation
60✔
3117
        var ok bool
60✔
3118

60✔
3119
        // Wait until the specified number of confirmations has been reached,
60✔
3120
        // we get a cancel signal, or the wallet signals a shutdown.
60✔
3121
        select {
60✔
3122
        case confDetails, ok = <-confNtfn.Confirmed:
37✔
3123
                // fallthrough
3124

3125
        case <-cancelChan:
6✔
3126
                log.Warnf("canceled waiting for funding confirmation, "+
6✔
3127
                        "stopping funding flow for ChannelPoint(%v)",
6✔
3128
                        completeChan.FundingOutpoint)
6✔
3129
                return
6✔
3130

3131
        case <-f.quit:
23✔
3132
                log.Warnf("fundingManager shutting down, stopping funding "+
23✔
3133
                        "flow for ChannelPoint(%v)",
23✔
3134
                        completeChan.FundingOutpoint)
23✔
3135
                return
23✔
3136
        }
3137

3138
        if !ok {
37✔
3139
                log.Warnf("ChainNotifier shutting down, cannot complete "+
×
3140
                        "funding flow for ChannelPoint(%v)",
×
3141
                        completeChan.FundingOutpoint)
×
3142
                return
×
3143
        }
×
3144

3145
        fundingPoint := completeChan.FundingOutpoint
37✔
3146
        log.Infof("ChannelPoint(%v) is now active: ChannelID(%v)",
37✔
3147
                fundingPoint, lnwire.NewChanIDFromOutPoint(fundingPoint))
37✔
3148

37✔
3149
        // With the block height and the transaction index known, we can
37✔
3150
        // construct the compact chanID which is used on the network to unique
37✔
3151
        // identify channels.
37✔
3152
        shortChanID := lnwire.ShortChannelID{
37✔
3153
                BlockHeight: confDetails.BlockHeight,
37✔
3154
                TxIndex:     confDetails.TxIndex,
37✔
3155
                TxPosition:  uint16(fundingPoint.Index),
37✔
3156
        }
37✔
3157

37✔
3158
        select {
37✔
3159
        case confChan <- &confirmedChannel{
3160
                shortChanID: shortChanID,
3161
                fundingTx:   confDetails.Tx,
3162
        }:
37✔
3163
        case <-f.quit:
×
3164
                return
×
3165
        }
3166
}
3167

3168
// waitForTimeout will close the timeout channel if MaxWaitNumBlocksFundingConf
3169
// has passed from the broadcast height of the given channel. In case of error,
3170
// the error is sent on timeoutChan. The wait can be canceled by closing the
3171
// cancelChan.
3172
//
3173
// NOTE: timeoutChan MUST be buffered.
3174
// NOTE: This MUST be run as a goroutine.
3175
func (f *Manager) waitForTimeout(completeChan *channeldb.OpenChannel,
3176
        cancelChan <-chan struct{}, timeoutChan chan<- error) {
28✔
3177

28✔
3178
        defer f.wg.Done()
28✔
3179

28✔
3180
        epochClient, err := f.cfg.Notifier.RegisterBlockEpochNtfn(nil)
28✔
3181
        if err != nil {
28✔
3182
                timeoutChan <- fmt.Errorf("unable to register for epoch "+
×
3183
                        "notification: %v", err)
×
3184
                return
×
3185
        }
×
3186

3187
        defer epochClient.Cancel()
28✔
3188

28✔
3189
        // The value of waitBlocksForFundingConf is adjusted in a development
28✔
3190
        // environment to enhance test capabilities. Otherwise, it is set to
28✔
3191
        // DefaultMaxWaitNumBlocksFundingConf.
28✔
3192
        waitBlocksForFundingConf := uint32(
28✔
3193
                lncfg.DefaultMaxWaitNumBlocksFundingConf,
28✔
3194
        )
28✔
3195

28✔
3196
        if lncfg.IsDevBuild() {
31✔
3197
                waitBlocksForFundingConf =
3✔
3198
                        f.cfg.Dev.MaxWaitNumBlocksFundingConf
3✔
3199
        }
3✔
3200

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

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

5✔
3221
                                // Notify the caller of the timeout.
5✔
3222
                                close(timeoutChan)
5✔
3223
                                return
5✔
3224
                        }
5✔
3225

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

3230
                case <-cancelChan:
18✔
3231
                        return
18✔
3232

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

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

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

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

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

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

33✔
3276
        fundingPoint := completeChan.FundingOutpoint
33✔
3277
        chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
33✔
3278

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

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

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

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

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

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

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

33✔
3332
        // Inform the ChannelNotifier that the channel has transitioned from
33✔
3333
        // pending open to open.
33✔
3334
        f.cfg.NotifyOpenChannelEvent(
33✔
3335
                completeChan.FundingOutpoint, completeChan.IdentityPub,
33✔
3336
        )
33✔
3337

33✔
3338
        // Close the discoverySignal channel, indicating to a separate
33✔
3339
        // goroutine that the channel now is marked as open in the database
33✔
3340
        // and that it is acceptable to process channel_ready messages
33✔
3341
        // from the peer.
33✔
3342
        if discoverySignal, ok := f.localDiscoverySignals.Load(chanID); ok {
66✔
3343
                close(discoverySignal)
33✔
3344
        }
33✔
3345

3346
        return nil
33✔
3347
}
3348

3349
// sendChannelReady creates and sends the channelReady message.
3350
// This should be called after the funding transaction has been confirmed,
3351
// and the channelState is 'markedOpen'.
3352
func (f *Manager) sendChannelReady(completeChan *channeldb.OpenChannel,
3353
        channel *lnwallet.LightningChannel) error {
38✔
3354

38✔
3355
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
38✔
3356

38✔
3357
        var peerKey [33]byte
38✔
3358
        copy(peerKey[:], completeChan.IdentityPub.SerializeCompressed())
38✔
3359

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

38✔
3370
        // If this is a taproot channel, then we also need to send along our
38✔
3371
        // set of musig2 nonces as well.
38✔
3372
        if completeChan.ChanType.IsTaproot() {
45✔
3373
                log.Infof("ChanID(%v): generating musig2 nonces...",
7✔
3374
                        chanID)
7✔
3375

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

3390
                        // Now that we've generated the nonce for this channel,
3391
                        // we'll store it in the set of pending nonces.
3392
                        localNonce = newNonce
7✔
3393
                        f.pendingMusigNonces[chanID] = localNonce
7✔
3394
                }
3395
                f.nonceMtx.Unlock()
7✔
3396

7✔
3397
                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
7✔
3398
                        localNonce.PubNonce,
7✔
3399
                )
7✔
3400
        }
3401

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

3415
                // We can use a pointer to aliases since GetAliases returns a
3416
                // copy of the alias slice.
3417
                channelReadyMsg.AliasScid = &aliases[0]
9✔
3418
        }
3419

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

3437
                localAlias := peer.LocalFeatures().HasFeature(
37✔
3438
                        lnwire.ScidAliasOptional,
37✔
3439
                )
37✔
3440
                remoteAlias := peer.RemoteFeatures().HasFeature(
37✔
3441
                        lnwire.ScidAliasOptional,
37✔
3442
                )
37✔
3443

37✔
3444
                // We could also refresh the channel state instead of checking
37✔
3445
                // whether the feature was negotiated, but this saves us a
37✔
3446
                // database read.
37✔
3447
                if channelReadyMsg.AliasScid == nil && localAlias &&
37✔
3448
                        remoteAlias {
37✔
3449

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

3466
                                err = f.cfg.AliasManager.AddLocalAlias(
×
3467
                                        alias, completeChan.ShortChannelID,
×
3468
                                        false, false,
×
3469
                                )
×
3470
                                if err != nil {
×
3471
                                        return err
×
3472
                                }
×
3473

3474
                                channelReadyMsg.AliasScid = &alias
×
3475
                        } else {
×
3476
                                channelReadyMsg.AliasScid = &aliases[0]
×
3477
                        }
×
3478
                }
3479

3480
                log.Infof("Peer(%x) is online, sending ChannelReady "+
37✔
3481
                        "for ChannelID(%v)", peerKey, chanID)
37✔
3482

37✔
3483
                if err := peer.SendMessage(true, channelReadyMsg); err == nil {
74✔
3484
                        // Sending succeeded, we can break out and continue the
37✔
3485
                        // funding flow.
37✔
3486
                        break
37✔
3487
                }
3488

3489
                log.Warnf("Unable to send channelReady to peer %x: %v. "+
×
3490
                        "Will retry when online", peerKey, err)
×
3491
        }
3492

3493
        return nil
37✔
3494
}
3495

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

63✔
3501
        // If the funding manager has exited, return an error to stop looping.
63✔
3502
        // Note that the peer may appear as online while the funding manager
63✔
3503
        // has stopped due to the shutdown order in the server.
63✔
3504
        select {
63✔
3505
        case <-f.quit:
×
3506
                return false, ErrFundingManagerShuttingDown
×
3507
        default:
63✔
3508
        }
3509

3510
        // Avoid a tight loop if peer is offline.
3511
        if _, err := f.waitForPeerOnline(node); err != nil {
63✔
3512
                log.Errorf("Wait for peer online failed: %v", err)
×
3513
                return false, err
×
3514
        }
×
3515

3516
        // If we cannot find the channel, then we haven't processed the
3517
        // remote's channelReady message.
3518
        channel, err := f.cfg.FindChannel(node, chanID)
63✔
3519
        if err != nil {
63✔
3520
                log.Errorf("Unable to locate ChannelID(%v) to determine if "+
×
3521
                        "ChannelReady was received", chanID)
×
3522
                return false, err
×
3523
        }
×
3524

3525
        // If we haven't insert the next revocation point, we haven't finished
3526
        // processing the channel ready message.
3527
        if channel.RemoteNextRevocation == nil {
101✔
3528
                return false, nil
38✔
3529
        }
38✔
3530

3531
        // Finally, the barrier signal is removed once we finish
3532
        // `handleChannelReady`. If we can still find the signal, we haven't
3533
        // finished processing it yet.
3534
        _, loaded := f.handleChannelReadyBarriers.Load(chanID)
28✔
3535

28✔
3536
        return !loaded, nil
28✔
3537
}
3538

3539
// extractAnnounceParams extracts the various channel announcement and update
3540
// parameters that will be needed to construct a ChannelAnnouncement and a
3541
// ChannelUpdate.
3542
func (f *Manager) extractAnnounceParams(c *channeldb.OpenChannel) (
3543
        lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
29✔
3544

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

29✔
3551
        // We don't necessarily want to go as low as the remote party allows.
29✔
3552
        // Check it against our default forwarding policy.
29✔
3553
        if fwdMinHTLC < f.cfg.DefaultRoutingPolicy.MinHTLCOut {
32✔
3554
                fwdMinHTLC = f.cfg.DefaultRoutingPolicy.MinHTLCOut
3✔
3555
        }
3✔
3556

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

3566
        return fwdMinHTLC, fwdMaxHTLC
29✔
3567
}
3568

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

29✔
3582
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
29✔
3583

29✔
3584
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
29✔
3585

29✔
3586
        ann, err := f.newChanAnnouncement(
29✔
3587
                f.cfg.IDKey, completeChan.IdentityPub,
29✔
3588
                &completeChan.LocalChanCfg.MultiSigKey,
29✔
3589
                completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
29✔
3590
                chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
29✔
3591
                completeChan.ChanType,
29✔
3592
        )
29✔
3593
        if err != nil {
29✔
3594
                return fmt.Errorf("error generating channel "+
×
3595
                        "announcement: %v", err)
×
3596
        }
×
3597

3598
        // Send ChannelAnnouncement and ChannelUpdate to the gossiper to add
3599
        // to the Router's topology.
3600
        errChan := f.cfg.SendAnnouncement(
29✔
3601
                ann.chanAnn, discovery.ChannelCapacity(completeChan.Capacity),
29✔
3602
                discovery.ChannelPoint(completeChan.FundingOutpoint),
29✔
3603
                discovery.TapscriptRoot(completeChan.TapscriptRoot),
29✔
3604
        )
29✔
3605
        select {
29✔
3606
        case err := <-errChan:
29✔
3607
                if err != nil {
29✔
3608
                        if graph.IsError(err, graph.ErrOutdated,
×
3609
                                graph.ErrIgnored) {
×
3610

×
3611
                                log.Debugf("Graph rejected "+
×
3612
                                        "ChannelAnnouncement: %v", err)
×
3613
                        } else {
×
3614
                                return fmt.Errorf("error sending channel "+
×
3615
                                        "announcement: %v", err)
×
3616
                        }
×
3617
                }
3618
        case <-f.quit:
×
3619
                return ErrFundingManagerShuttingDown
×
3620
        }
3621

3622
        errChan = f.cfg.SendAnnouncement(
29✔
3623
                ann.chanUpdateAnn, discovery.RemoteAlias(peerAlias),
29✔
3624
        )
29✔
3625
        select {
29✔
3626
        case err := <-errChan:
29✔
3627
                if err != nil {
29✔
3628
                        if graph.IsError(err, graph.ErrOutdated,
×
3629
                                graph.ErrIgnored) {
×
3630

×
3631
                                log.Debugf("Graph rejected "+
×
3632
                                        "ChannelUpdate: %v", err)
×
3633
                        } else {
×
3634
                                return fmt.Errorf("error sending channel "+
×
3635
                                        "update: %v", err)
×
3636
                        }
×
3637
                }
3638
        case <-f.quit:
×
3639
                return ErrFundingManagerShuttingDown
×
3640
        }
3641

3642
        return nil
29✔
3643
}
3644

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

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

11✔
3662
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
11✔
3663
                if err != nil {
11✔
3664
                        return err
×
3665
                }
×
3666

3667
                nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
11✔
3668
                if err != nil {
11✔
3669
                        return fmt.Errorf("unable to retrieve current node "+
×
3670
                                "announcement: %v", err)
×
3671
                }
×
3672

3673
                chanID := lnwire.NewChanIDFromOutPoint(
11✔
3674
                        completeChan.FundingOutpoint,
11✔
3675
                )
11✔
3676
                pubKey := peer.PubKey()
11✔
3677
                log.Debugf("Sending our NodeAnnouncement for "+
11✔
3678
                        "ChannelID(%v) to %x", chanID, pubKey)
11✔
3679

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

21✔
3700
                fundingScript, err := makeFundingScript(completeChan)
21✔
3701
                if err != nil {
21✔
3702
                        return fmt.Errorf("unable to create funding script "+
×
3703
                                "for ChannelPoint(%v): %v",
×
3704
                                completeChan.FundingOutpoint, err)
×
3705
                }
×
3706

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

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

3731
                case <-f.quit:
5✔
3732
                        return fmt.Errorf("%v, stopping funding flow for "+
5✔
3733
                                "ChannelPoint(%v)",
5✔
3734
                                ErrFundingManagerShuttingDown,
5✔
3735
                                completeChan.FundingOutpoint)
5✔
3736
                }
3737

3738
                fundingPoint := completeChan.FundingOutpoint
19✔
3739
                chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
19✔
3740

19✔
3741
                log.Infof("Announcing ChannelPoint(%v), short_chan_id=%v",
19✔
3742
                        &fundingPoint, shortChanID)
19✔
3743

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

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

3769
                        err = f.addToGraph(
3✔
3770
                                completeChan, &baseScid, nil, ourPolicy,
3✔
3771
                        )
3✔
3772
                        if err != nil {
3✔
3773
                                return fmt.Errorf("failed to re-add to "+
×
3774
                                        "graph: %v", err)
×
3775
                        }
×
3776
                }
3777

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

3791
                log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+
19✔
3792
                        "sent to gossiper", &fundingPoint, shortChanID)
19✔
3793
        }
3794

3795
        return nil
27✔
3796
}
3797

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

3812
        // We'll need to refresh the channel state so that things are properly
3813
        // populated when validating the channel state. Otherwise, a panic may
3814
        // occur due to inconsistency in the OpenChannel struct.
3815
        err = c.Refresh()
7✔
3816
        if err != nil {
10✔
3817
                return fmt.Errorf("unable to refresh channel state: %w", err)
3✔
3818
        }
3✔
3819

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

3829
        // Once we know the confirmed ShortChannelID, we'll need to save it to
3830
        // the database and refresh the OpenChannel struct with it.
3831
        err = c.MarkRealScid(confChan.shortChanID)
7✔
3832
        if err != nil {
7✔
3833
                return fmt.Errorf("unable to set confirmed SCID for zero "+
×
3834
                        "channel: %v", err)
×
3835
        }
×
3836

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

3847
                // TODO: Make this atomic!
3848
                ourPolicy, err := f.cfg.DeleteAliasEdge(c.ShortChanID())
5✔
3849
                if err != nil {
5✔
3850
                        return fmt.Errorf("unable to delete alias edge from "+
×
3851
                                "graph: %v", err)
×
3852
                }
×
3853

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

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

3880
        // Update the confirmed transaction's label.
3881
        f.makeLabelForTx(c)
7✔
3882

7✔
3883
        return nil
7✔
3884
}
3885

3886
// genFirstStateMusigNonce generates a nonces for the "first" local state. This
3887
// is the verification nonce for the state created for us after the initial
3888
// commitment transaction signed as part of the funding flow.
3889
func genFirstStateMusigNonce(channel *channeldb.OpenChannel,
3890
) (*musig2.Nonces, error) {
7✔
3891

7✔
3892
        musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
7✔
3893
                channel.RevocationProducer,
7✔
3894
        )
7✔
3895
        if err != nil {
7✔
3896
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3897
                        "nonces: %v", err)
×
3898
        }
×
3899

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

3912
        return verNonce, nil
7✔
3913
}
3914

3915
// handleChannelReady finalizes the channel funding process and enables the
3916
// channel to enter normal operating mode.
3917
func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen
3918
        msg *lnwire.ChannelReady) {
31✔
3919

31✔
3920
        defer f.wg.Done()
31✔
3921

31✔
3922
        // Notify the aux hook that the specified peer just established a
31✔
3923
        // channel with us, identified by the given channel ID.
31✔
3924
        f.cfg.AuxChannelNegotiator.WhenSome(
31✔
3925
                func(acn lnwallet.AuxChannelNegotiator) {
31✔
NEW
3926
                        acn.ProcessChannelReady(msg.ChanID, peer.PubKey())
×
NEW
3927
                },
×
3928
        )
3929

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
4129
                        return
×
4130
                }
×
4131

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

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

×
4157
                        return
×
4158
                }
×
4159
        }
4160

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

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

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

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

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

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

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

4222
                peerAlias = &foundAlias
7✔
4223
        }
4224

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

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

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

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

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

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

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

4284
        return nil
27✔
4285
}
4286

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

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

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

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

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

4332
        return nil
29✔
4333
}
4334

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4634
        return nil
19✔
4635
}
4636

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
4797
                        return
×
4798
                }
×
4799
        }
4800

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

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

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

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

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

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

×
4842
                return
×
4843
        }
×
4844

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5210
        delete(nodeReservations, pendingChanID)
17✔
5211

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

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

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

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

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

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

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

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

5258
        return resCtx, nil
91✔
5259
}
5260

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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