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

lightningnetwork / lnd / 17691910871

13 Sep 2025 04:44AM UTC coverage: 66.635% (-0.02%) from 66.651%
17691910871

Pull #9432

github

web-flow
Merge 1d80f3d14 into 5082566ed
Pull Request #9432: multi: add upfront-shutdown-address to lnd.conf.

10 of 13 new or added lines in 2 files covered. (76.92%)

103 existing lines in 22 files now uncovered.

136265 of 204496 relevant lines covered (66.63%)

21401.6 hits per line

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

73.78
/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/lightningnetwork/lnd/chainntnfs"
22
        "github.com/lightningnetwork/lnd/chanacceptor"
23
        "github.com/lightningnetwork/lnd/channeldb"
24
        "github.com/lightningnetwork/lnd/discovery"
25
        "github.com/lightningnetwork/lnd/fn/v2"
26
        "github.com/lightningnetwork/lnd/graph"
27
        "github.com/lightningnetwork/lnd/graph/db/models"
28
        "github.com/lightningnetwork/lnd/input"
29
        "github.com/lightningnetwork/lnd/keychain"
30
        "github.com/lightningnetwork/lnd/labels"
31
        "github.com/lightningnetwork/lnd/lncfg"
32
        "github.com/lightningnetwork/lnd/lnpeer"
33
        "github.com/lightningnetwork/lnd/lnrpc"
34
        "github.com/lightningnetwork/lnd/lnutils"
35
        "github.com/lightningnetwork/lnd/lnwallet"
36
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
37
        "github.com/lightningnetwork/lnd/lnwallet/chanfunding"
38
        "github.com/lightningnetwork/lnd/lnwire"
39
        "golang.org/x/crypto/salsa20"
40
)
41

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

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

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

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

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

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

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

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

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

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

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

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

102
        msgBufferSize = 50
103

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

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

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

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

129
        zeroID [32]byte
130
)
131

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

145
        chanAmt btcutil.Amount
146

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

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

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

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

164
        updateMtx   sync.RWMutex
165
        lastUpdated time.Time
166

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

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

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

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

140✔
186
        r.lastUpdated = time.Now()
140✔
187
}
140✔
188

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

572
        // ShutdownScript is an optional upfront-shutdown script to which our
573
        // funds should be paid on a cooperative close.
574
        ShutdownScript lnwire.DeliveryAddress
575
}
576

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

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

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

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

602
        // nonceMtx is a mutex that guards the pendingMusigNonces.
603
        nonceMtx sync.RWMutex
604

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

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

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

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

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

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

639
        localDiscoverySignals *lnutils.SyncMap[lnwire.ChannelID, chan struct{}]
640

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

643
        quit chan struct{}
644
        wg   sync.WaitGroup
645
}
646

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

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

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

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

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

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

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

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

737
        for _, channel := range allChannels {
124✔
738
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
12✔
739

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

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

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

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

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

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

782
        f.wg.Add(1) // TODO(roasbeef): tune
112✔
783
        go f.reservationCoordinator()
112✔
784

112✔
785
        return nil
112✔
786
}
787

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

108✔
795
                close(f.quit)
108✔
796
                f.wg.Wait()
108✔
797
        })
108✔
798

799
        return nil
109✔
800
}
801

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

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

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

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

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

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

60✔
842
        var nonceBytes [8]byte
60✔
843
        binary.LittleEndian.PutUint64(nonceBytes[:], nextNonce)
60✔
844

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

60✔
855
        return nextChanID
60✔
856
}
60✔
857

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

3✔
864
        f.resMtx.Lock()
3✔
865
        defer f.resMtx.Unlock()
3✔
866

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

24✔
997
        log.Debugf("Sending funding error to peer (%x): %v",
24✔
998
                peer.IdentityKey().SerializeCompressed(),
24✔
999
                lnutils.SpewLogClosure(errMsg))
24✔
1000

24✔
1001
        if err := peer.SendMessage(false, errMsg); err != nil {
24✔
1002
                log.Errorf("unable to send error message to peer %v", err)
×
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
                lnutils.SpewLogClosure(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() {
112✔
1033
        defer f.wg.Done()
112✔
1034

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

112✔
1038
        for {
496✔
1039
                select {
384✔
1040
                case fmsg := <-f.fundingMsgs:
218✔
1041
                        switch msg := fmsg.msg.(type) {
218✔
1042
                        case *lnwire.OpenChannel:
57✔
1043
                                f.fundeeProcessOpenChannel(fmsg.peer, msg)
57✔
1044

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

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

1051
                        case *lnwire.FundingSigned:
31✔
1052
                                f.funderProcessFundingSigned(fmsg.peer, msg)
31✔
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:
44✔
1059
                                f.handleWarningMsg(fmsg.peer, msg)
44✔
1060

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

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

1070
                case <-f.quit:
108✔
1071
                        return
108✔
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) {
68✔
1087

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

68✔
1090
        // If the channel is still pending we must wait for the funding
68✔
1091
        // transaction to confirm.
68✔
1092
        if channel.IsPending {
128✔
1093
                err := f.advancePendingChannelState(channel, pendingChanID)
60✔
1094
                if err != nil {
86✔
1095
                        log.Errorf("Unable to advance pending state of "+
26✔
1096
                                "ChannelPoint(%v): %v",
26✔
1097
                                channel.FundingOutpoint, err)
26✔
1098
                        return
26✔
1099
                }
26✔
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 {
195✔
1124
                channelState, shortChanID, err := f.getChannelOpeningState(
150✔
1125
                        &channel.FundingOutpoint,
150✔
1126
                )
150✔
1127
                if err == channeldb.ErrChannelNotFound {
178✔
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 {
153✔
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(
125✔
1150
                        channel, lnChannel, shortChanID, pendingChanID,
125✔
1151
                        channelState, updateChan,
125✔
1152
                )
125✔
1153
                if err != nil {
145✔
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 {
125✔
1170

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

125✔
1175
        switch channelState {
125✔
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:
62✔
1206
                // We must wait until we've received the peer's channel_ready
62✔
1207
                // before sending a channel_update according to BOLT#07.
62✔
1208
                received, err := f.receivedChannelReady(
62✔
1209
                        channel.IdentityPub, chanID,
62✔
1210
                )
62✔
1211
                if err != nil {
63✔
1212
                        return fmt.Errorf("failed to check if channel_ready "+
1✔
1213
                                "was received: %v", err)
1✔
1214
                }
1✔
1215

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

1226
                        return nil
26✔
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 {
60✔
1292

60✔
1293
        if channel.IsZeroConf() {
67✔
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)
56✔
1343
        if err == ErrConfirmationTimeout {
61✔
1344
                return f.fundingTimeout(channel, pendingChanID)
5✔
1345
        } else if err != nil {
83✔
1346
                return fmt.Errorf("error waiting for funding "+
24✔
1347
                        "confirmation for ChannelPoint(%v): %v",
24✔
1348
                        channel.FundingOutpoint, err)
24✔
1349
        }
24✔
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) {
219✔
1416
        select {
219✔
1417
        case f.fundingMsgs <- &fundingMsg{msg, peer}:
219✔
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) {
57✔
1433

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

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

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

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

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

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

1469
        for _, c := range channels {
72✔
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 {
64✔
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()
53✔
1491
        if err != nil {
53✔
1492
                f.failFundingFlow(peer, cid, err)
×
1493
                return
×
1494
        }
×
1495

1496
        if len(pendingChans) > pendingChansLimit {
53✔
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()
53✔
1505
        if err != nil || !isSynced {
53✔
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 {
58✔
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 {
54✔
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 {
52✔
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{
50✔
1543
                Node:        peer.IdentityKey(),
50✔
1544
                OpenChanMsg: msg,
50✔
1545
        }
50✔
1546

50✔
1547
        // Query our channel acceptor to determine whether we should reject
50✔
1548
        // the channel.
50✔
1549
        acceptorResp := f.cfg.OpenChannelPredicate.Accept(chanReq)
50✔
1550
        if acceptorResp.RejectChannel() {
53✔
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, "+
50✔
1556
                "pendingId=%x) from peer(%x)", amt, msg.PushAmount,
50✔
1557
                msg.CsvDelay, msg.PendingChannelID,
50✔
1558
                peer.IdentityKey().SerializeCompressed())
50✔
1559

50✔
1560
        // Attempt to initialize a reservation within the wallet. If the wallet
50✔
1561
        // has insufficient resources to create the channel, then the
50✔
1562
        // reservation attempt may be rejected. Note that since we're on the
50✔
1563
        // responding side of a single funder workflow, we don't commit any
50✔
1564
        // funds to the channel ourselves.
50✔
1565
        //
50✔
1566
        // Before we init the channel, we'll also check to see what commitment
50✔
1567
        // format we can use with this peer. This is dependent on *both* us and
50✔
1568
        // the remote peer are signaling the proper feature bit if we're using
50✔
1569
        // implicit negotiation, and simply the channel type sent over if we're
50✔
1570
        // using explicit negotiation.
50✔
1571
        chanType, commitType, err := negotiateCommitmentType(
50✔
1572
                msg.ChannelType, peer.LocalFeatures(), peer.RemoteFeatures(),
50✔
1573
        )
50✔
1574
        if err != nil {
50✔
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
50✔
1582
        if hasFeatures(
50✔
1583
                peer.LocalFeatures(), peer.RemoteFeatures(),
50✔
1584
                lnwire.ScidAliasOptional,
50✔
1585
        ) {
56✔
1586

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

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

50✔
1595
        // Only echo back a channel type in AcceptChannel if we actually used
50✔
1596
        // explicit negotiation above.
50✔
1597
        if chanType != nil {
57✔
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
50✔
1639
        switch {
50✔
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(
50✔
1666
                f.cfg.AuxFundingController,
50✔
1667
                func(c AuxFundingController) AuxTapscriptResult {
50✔
1668
                        return c.DeriveTapscriptRoot(msg.PendingChannelID)
×
1669
                },
×
1670
        ).Unpack()
1671
        if err != nil {
50✔
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{
50✔
1680
                ChainHash:        &msg.ChainHash,
50✔
1681
                PendingChanID:    msg.PendingChannelID,
50✔
1682
                NodeID:           peer.IdentityKey(),
50✔
1683
                NodeAddr:         peer.Address(),
50✔
1684
                LocalFundingAmt:  0,
50✔
1685
                RemoteFundingAmt: amt,
50✔
1686
                CommitFeePerKw:   chainfee.SatPerKWeight(msg.FeePerKiloWeight),
50✔
1687
                FundingFeePerKw:  0,
50✔
1688
                PushMSat:         msg.PushAmount,
50✔
1689
                Flags:            msg.ChannelFlags,
50✔
1690
                MinConfs:         1,
50✔
1691
                CommitType:       commitType,
50✔
1692
                ZeroConf:         zeroConf,
50✔
1693
                OptionScidAlias:  scid,
50✔
1694
                ScidAliasFeature: scidFeatureVal,
50✔
1695
                TapscriptRoot:    tapscriptRoot,
50✔
1696
        }
50✔
1697

50✔
1698
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
50✔
1699
        if err != nil {
50✔
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, "+
50✔
1706
                "cannedShim=%v", reservation.IsZeroConf(),
50✔
1707
                reservation.IsPsbt(), reservation.IsCannedShim())
50✔
1708

50✔
1709
        if zeroConf {
55✔
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)
50✔
1729
        if acceptorResp.MinAcceptDepth != 0 {
50✔
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 {
55✔
1736
                numConfsReq = 0
5✔
1737
        }
5✔
1738

1739
        reservation.SetNumConfsRequired(numConfsReq)
50✔
1740

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

1762
        // If the fundee didn't provide an upfront-shutdown address via
1763
        // the channel acceptor, fall back to the configured shutdown
1764
        // script (if any).
1765
        if len(acceptorResp.UpfrontShutdown) == 0 {
100✔
1766
                acceptorResp.UpfrontShutdown = f.cfg.ShutdownScript
50✔
1767
        }
50✔
1768

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

50✔
1786
        // If a script enforced channel lease is being proposed, we'll need to
50✔
1787
        // validate its custom TLV records.
50✔
1788
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
53✔
1789
                if msg.LeaseExpiry == nil {
3✔
1790
                        err := errors.New("missing lease expiry")
×
1791
                        f.failFundingFlow(peer, cid, err)
×
1792
                        return
×
1793
                }
×
1794

1795
                // If we had a shim registered for this channel prior to
1796
                // receiving its corresponding OpenChannel message, then we'll
1797
                // validate the proposed LeaseExpiry against what was registered
1798
                // in our shim.
1799
                if reservation.LeaseExpiry() != 0 {
6✔
1800
                        if uint32(*msg.LeaseExpiry) !=
3✔
1801
                                reservation.LeaseExpiry() {
3✔
1802

×
1803
                                err := errors.New("lease expiry mismatch")
×
1804
                                f.failFundingFlow(peer, cid, err)
×
1805
                                return
×
1806
                        }
×
1807
                }
1808
        }
1809

1810
        log.Infof("Requiring %v confirmations for pendingChan(%x): "+
50✔
1811
                "amt=%v, push_amt=%v, committype=%v, upfrontShutdown=%x",
50✔
1812
                numConfsReq, msg.PendingChannelID, amt, msg.PushAmount,
50✔
1813
                commitType, msg.UpfrontShutdownScript)
50✔
1814

50✔
1815
        // Generate our required constraints for the remote party, using the
50✔
1816
        // values provided by the channel acceptor if they are non-zero.
50✔
1817
        remoteCsvDelay := f.cfg.RequiredRemoteDelay(amt)
50✔
1818
        if acceptorResp.CSVDelay != 0 {
50✔
1819
                remoteCsvDelay = acceptorResp.CSVDelay
×
1820
        }
×
1821

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

1834
        chanReserve := f.cfg.RequiredRemoteChanReserve(amt, maxDustLimit)
50✔
1835
        if acceptorResp.Reserve != 0 {
50✔
1836
                chanReserve = acceptorResp.Reserve
×
1837
        }
×
1838

1839
        remoteMaxValue := f.cfg.RequiredRemoteMaxValue(amt)
50✔
1840
        if acceptorResp.InFlightTotal != 0 {
50✔
1841
                remoteMaxValue = acceptorResp.InFlightTotal
×
1842
        }
×
1843

1844
        maxHtlcs := f.cfg.RequiredRemoteMaxHTLCs(amt)
50✔
1845
        if acceptorResp.HtlcLimit != 0 {
50✔
1846
                maxHtlcs = acceptorResp.HtlcLimit
×
1847
        }
×
1848

1849
        // Default to our default minimum hltc value, replacing it with the
1850
        // channel acceptor's value if it is set.
1851
        minHtlc := f.cfg.DefaultMinHtlcIn
50✔
1852
        if acceptorResp.MinHtlcIn != 0 {
50✔
1853
                minHtlc = acceptorResp.MinHtlcIn
×
1854
        }
×
1855

1856
        // If we are handling a FundingOpen request then we need to specify the
1857
        // default channel fees since they are not provided by the responder
1858
        // interactively.
1859
        ourContribution := reservation.OurContribution()
50✔
1860
        forwardingPolicy := f.defaultForwardingPolicy(
50✔
1861
                ourContribution.ChannelStateBounds,
50✔
1862
        )
50✔
1863

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

50✔
1888
        // Update the timestamp once the fundingOpenMsg has been handled.
50✔
1889
        defer resCtx.updateTimestamp()
50✔
1890

50✔
1891
        cfg := channeldb.ChannelConfig{
50✔
1892
                ChannelStateBounds: channeldb.ChannelStateBounds{
50✔
1893
                        MaxPendingAmount: remoteMaxValue,
50✔
1894
                        ChanReserve:      chanReserve,
50✔
1895
                        MinHTLC:          minHtlc,
50✔
1896
                        MaxAcceptedHtlcs: maxHtlcs,
50✔
1897
                },
50✔
1898
                CommitmentParams: channeldb.CommitmentParams{
50✔
1899
                        DustLimit: msg.DustLimit,
50✔
1900
                        CsvDelay:  remoteCsvDelay,
50✔
1901
                },
50✔
1902
                MultiSigKey: keychain.KeyDescriptor{
50✔
1903
                        PubKey: copyPubKey(msg.FundingKey),
50✔
1904
                },
50✔
1905
                RevocationBasePoint: keychain.KeyDescriptor{
50✔
1906
                        PubKey: copyPubKey(msg.RevocationPoint),
50✔
1907
                },
50✔
1908
                PaymentBasePoint: keychain.KeyDescriptor{
50✔
1909
                        PubKey: copyPubKey(msg.PaymentPoint),
50✔
1910
                },
50✔
1911
                DelayBasePoint: keychain.KeyDescriptor{
50✔
1912
                        PubKey: copyPubKey(msg.DelayedPaymentPoint),
50✔
1913
                },
50✔
1914
                HtlcBasePoint: keychain.KeyDescriptor{
50✔
1915
                        PubKey: copyPubKey(msg.HtlcPoint),
50✔
1916
                },
50✔
1917
        }
50✔
1918

50✔
1919
        // With our parameters set, we'll now process their contribution so we
50✔
1920
        // can move the funding workflow ahead.
50✔
1921
        remoteContribution := &lnwallet.ChannelContribution{
50✔
1922
                FundingAmount:        amt,
50✔
1923
                FirstCommitmentPoint: msg.FirstCommitmentPoint,
50✔
1924
                ChannelConfig:        &cfg,
50✔
1925
                UpfrontShutdown:      msg.UpfrontShutdownScript,
50✔
1926
        }
50✔
1927

50✔
1928
        if resCtx.reservation.IsTaproot() {
55✔
1929
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
5✔
1930
                if err != nil {
5✔
1931
                        log.Error(errNoLocalNonce)
×
1932

×
1933
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
1934

×
1935
                        return
×
1936
                }
×
1937

1938
                remoteContribution.LocalNonce = &musig2.Nonces{
5✔
1939
                        PubNonce: localNonce,
5✔
1940
                }
5✔
1941
        }
1942

1943
        err = reservation.ProcessSingleContribution(remoteContribution)
50✔
1944
        if err != nil {
56✔
1945
                log.Errorf("unable to add contribution reservation: %v", err)
6✔
1946
                f.failFundingFlow(peer, cid, err)
6✔
1947
                return
6✔
1948
        }
6✔
1949

1950
        log.Infof("Sending fundingResp for pending_id(%x)",
44✔
1951
                msg.PendingChannelID)
44✔
1952
        bounds := remoteContribution.ChannelConfig.ChannelStateBounds
44✔
1953
        log.Debugf("Remote party accepted channel state space bounds: %v",
44✔
1954
                lnutils.SpewLogClosure(bounds))
44✔
1955
        params := remoteContribution.ChannelConfig.CommitmentParams
44✔
1956
        log.Debugf("Remote party accepted commitment rendering params: %v",
44✔
1957
                lnutils.SpewLogClosure(params))
44✔
1958

44✔
1959
        reservation.SetState(lnwallet.SentAcceptChannel)
44✔
1960

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

44✔
1983
        if commitType.IsTaproot() {
49✔
1984
                fundingAccept.LocalNonce = lnwire.SomeMusig2Nonce(
5✔
1985
                        ourContribution.LocalNonce.PubNonce,
5✔
1986
                )
5✔
1987
        }
5✔
1988

1989
        if err := peer.SendMessage(true, &fundingAccept); err != nil {
44✔
1990
                log.Errorf("unable to send funding response to peer: %v", err)
×
1991
                f.failFundingFlow(peer, cid, err)
×
1992
                return
×
1993
        }
×
1994
}
1995

1996
// funderProcessAcceptChannel processes a response to the workflow initiation
1997
// sent by the remote peer. This message then queues a message with the funding
1998
// outpoint, and a commitment signature to the remote peer.
1999
//
2000
//nolint:funlen
2001
func (f *Manager) funderProcessAcceptChannel(peer lnpeer.Peer,
2002
        msg *lnwire.AcceptChannel) {
36✔
2003

36✔
2004
        pendingChanID := msg.PendingChannelID
36✔
2005
        peerKey := peer.IdentityKey()
36✔
2006
        var peerKeyBytes []byte
36✔
2007
        if peerKey != nil {
72✔
2008
                peerKeyBytes = peerKey.SerializeCompressed()
36✔
2009
        }
36✔
2010

2011
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
36✔
2012
        if err != nil {
36✔
2013
                log.Warnf("Can't find reservation (peerKey:%x, chan_id:%v)",
×
2014
                        peerKeyBytes, pendingChanID)
×
2015
                return
×
2016
        }
×
2017

2018
        // Update the timestamp once the fundingAcceptMsg has been handled.
2019
        defer resCtx.updateTimestamp()
36✔
2020

36✔
2021
        if resCtx.reservation.State() != lnwallet.SentOpenChannel {
36✔
2022
                return
×
2023
        }
×
2024

2025
        log.Infof("Recv'd fundingResponse for pending_id(%x)",
36✔
2026
                pendingChanID[:])
36✔
2027

36✔
2028
        // Create the channel identifier.
36✔
2029
        cid := newChanIdentifier(msg.PendingChannelID)
36✔
2030

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

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

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

×
2078
                _, negotiatedCommitType, err := negotiateCommitmentType(
×
2079
                        msg.ChannelType, peer.LocalFeatures(),
×
2080
                        peer.RemoteFeatures(),
×
2081
                )
×
2082
                if err != nil {
×
2083
                        err := errors.New("received unexpected channel type")
×
2084
                        f.failFundingFlow(peer, cid, err)
×
2085
                        return
×
2086
                }
×
2087

2088
                if implicitCommitType != negotiatedCommitType {
×
2089
                        err := errors.New("negotiated unexpected channel type")
×
2090
                        f.failFundingFlow(peer, cid, err)
×
2091
                        return
×
2092
                }
×
2093
        }
2094

2095
        // The required number of confirmations should not be greater than the
2096
        // maximum number of confirmations required by the ChainNotifier to
2097
        // properly dispatch confirmations.
2098
        if msg.MinAcceptDepth > chainntnfs.MaxNumConfs {
36✔
2099
                err := lnwallet.ErrNumConfsTooLarge(
1✔
2100
                        msg.MinAcceptDepth, chainntnfs.MaxNumConfs,
1✔
2101
                )
1✔
2102
                log.Warnf("Unacceptable channel constraints: %v", err)
1✔
2103
                f.failFundingFlow(peer, cid, err)
1✔
2104
                return
1✔
2105
        }
1✔
2106

2107
        // Check that zero-conf channels have minimum depth set to 0.
2108
        if resCtx.reservation.IsZeroConf() && msg.MinAcceptDepth != 0 {
34✔
2109
                err = fmt.Errorf("zero-conf channel has min_depth non-zero")
×
2110
                log.Warn(err)
×
2111
                f.failFundingFlow(peer, cid, err)
×
2112
                return
×
2113
        }
×
2114

2115
        // If this is not a zero-conf channel but the peer responded with a
2116
        // min-depth of zero, we will use our minimum of 1 instead.
2117
        minDepth := msg.MinAcceptDepth
34✔
2118
        if !resCtx.reservation.IsZeroConf() && minDepth == 0 {
34✔
2119
                log.Infof("Responder to pending_id=%v sent a minimum "+
×
2120
                        "confirmation depth of 0 for non-zero-conf channel. "+
×
2121
                        "We will use a minimum depth of 1 instead.",
×
2122
                        cid.tempChanID)
×
2123

×
2124
                minDepth = 1
×
2125
        }
×
2126

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

2150
        cfg := channeldb.ChannelConfig{
33✔
2151
                ChannelStateBounds: channeldb.ChannelStateBounds{
33✔
2152
                        MaxPendingAmount: resCtx.remoteMaxValue,
33✔
2153
                        ChanReserve:      resCtx.remoteChanReserve,
33✔
2154
                        MinHTLC:          resCtx.remoteMinHtlc,
33✔
2155
                        MaxAcceptedHtlcs: resCtx.remoteMaxHtlcs,
33✔
2156
                },
33✔
2157
                CommitmentParams: channeldb.CommitmentParams{
33✔
2158
                        DustLimit: msg.DustLimit,
33✔
2159
                        CsvDelay:  resCtx.remoteCsvDelay,
33✔
2160
                },
33✔
2161
                MultiSigKey: keychain.KeyDescriptor{
33✔
2162
                        PubKey: copyPubKey(msg.FundingKey),
33✔
2163
                },
33✔
2164
                RevocationBasePoint: keychain.KeyDescriptor{
33✔
2165
                        PubKey: copyPubKey(msg.RevocationPoint),
33✔
2166
                },
33✔
2167
                PaymentBasePoint: keychain.KeyDescriptor{
33✔
2168
                        PubKey: copyPubKey(msg.PaymentPoint),
33✔
2169
                },
33✔
2170
                DelayBasePoint: keychain.KeyDescriptor{
33✔
2171
                        PubKey: copyPubKey(msg.DelayedPaymentPoint),
33✔
2172
                },
33✔
2173
                HtlcBasePoint: keychain.KeyDescriptor{
33✔
2174
                        PubKey: copyPubKey(msg.HtlcPoint),
33✔
2175
                },
33✔
2176
        }
33✔
2177

33✔
2178
        // The remote node has responded with their portion of the channel
33✔
2179
        // contribution. At this point, we can process their contribution which
33✔
2180
        // allows us to construct and sign both the commitment transaction, and
33✔
2181
        // the funding transaction.
33✔
2182
        remoteContribution := &lnwallet.ChannelContribution{
33✔
2183
                FirstCommitmentPoint: msg.FirstCommitmentPoint,
33✔
2184
                ChannelConfig:        &cfg,
33✔
2185
                UpfrontShutdown:      msg.UpfrontShutdownScript,
33✔
2186
        }
33✔
2187

33✔
2188
        if resCtx.reservation.IsTaproot() {
38✔
2189
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
5✔
2190
                if err != nil {
5✔
2191
                        log.Error(errNoLocalNonce)
×
2192

×
2193
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
2194

×
2195
                        return
×
2196
                }
×
2197

2198
                remoteContribution.LocalNonce = &musig2.Nonces{
5✔
2199
                        PubNonce: localNonce,
5✔
2200
                }
5✔
2201
        }
2202

2203
        err = resCtx.reservation.ProcessContribution(remoteContribution)
33✔
2204

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

2247
        log.Infof("pendingChan(%x): remote party proposes num_confs=%v, "+
33✔
2248
                "csv_delay=%v", pendingChanID[:], msg.MinAcceptDepth,
33✔
2249
                msg.CsvDelay)
33✔
2250
        bounds = remoteContribution.ChannelConfig.ChannelStateBounds
33✔
2251
        log.Debugf("Remote party accepted channel state space bounds: %v",
33✔
2252
                lnutils.SpewLogClosure(bounds))
33✔
2253
        commitParams = remoteContribution.ChannelConfig.CommitmentParams
33✔
2254
        log.Debugf("Remote party accepted commitment rendering params: %v",
33✔
2255
                lnutils.SpewLogClosure(commitParams))
33✔
2256

33✔
2257
        // If the user requested funding through a PSBT, we cannot directly
33✔
2258
        // continue now and need to wait for the fully funded and signed PSBT
33✔
2259
        // to arrive. To not block any other channels from opening, we wait in
33✔
2260
        // a separate goroutine.
33✔
2261
        if psbtIntent != nil {
36✔
2262
                f.wg.Add(1)
3✔
2263
                go func() {
6✔
2264
                        defer f.wg.Done()
3✔
2265

3✔
2266
                        f.waitForPsbt(psbtIntent, resCtx, cid)
3✔
2267
                }()
3✔
2268

2269
                // With the new goroutine spawned, we can now exit to unblock
2270
                // the main event loop.
2271
                return
3✔
2272
        }
2273

2274
        // In a normal, non-PSBT funding flow, we can jump directly to the next
2275
        // step where we expect our contribution to be finalized.
2276
        f.continueFundingAccept(resCtx, cid)
33✔
2277
}
2278

2279
// waitForPsbt blocks until either a signed PSBT arrives, an error occurs or
2280
// the funding manager shuts down. In the case of a valid PSBT, the funding flow
2281
// is continued.
2282
//
2283
// NOTE: This method must be called as a goroutine.
2284
func (f *Manager) waitForPsbt(intent *chanfunding.PsbtIntent,
2285
        resCtx *reservationWithCtx, cid *chanIdentifier) {
3✔
2286

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

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

2310
                // If the remote canceled the funding reservation, we don't need
2311
                // to send another fail message. But we want to inform the user
2312
                // about what happened.
2313
                case chanfunding.ErrRemoteCanceled:
3✔
2314
                        log.Infof("Remote canceled, aborting PSBT flow "+
3✔
2315
                                "for peer_key=%x, pending_chan_id=%x",
3✔
2316
                                peerKey.SerializeCompressed(), cid.tempChanID)
3✔
2317
                        return
3✔
2318

2319
                // Nil error means the flow continues normally now.
2320
                case nil:
3✔
2321

2322
                // For any other error, we'll fail the funding flow.
2323
                default:
×
2324
                        failFlow("error waiting for PSBT flow", err)
×
2325
                        return
×
2326
                }
2327

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

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

2361
                // We are now ready to continue the funding flow.
2362
                f.continueFundingAccept(resCtx, cid)
3✔
2363

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

2375
// continueFundingAccept continues the channel funding flow once our
2376
// contribution is finalized, the channel output is known and the funding
2377
// transaction is signed.
2378
func (f *Manager) continueFundingAccept(resCtx *reservationWithCtx,
2379
        cid *chanIdentifier) {
33✔
2380

33✔
2381
        // Now that we have their contribution, we can extract, then send over
33✔
2382
        // both the funding out point and our signature for their version of
33✔
2383
        // the commitment transaction to the remote peer.
33✔
2384
        outPoint := resCtx.reservation.FundingOutpoint()
33✔
2385
        _, sig := resCtx.reservation.OurSignatures()
33✔
2386

33✔
2387
        // A new channel has almost finished the funding process. In order to
33✔
2388
        // properly synchronize with the writeHandler goroutine, we add a new
33✔
2389
        // channel to the barriers map which will be closed once the channel is
33✔
2390
        // fully open.
33✔
2391
        channelID := lnwire.NewChanIDFromOutPoint(*outPoint)
33✔
2392
        log.Debugf("Creating chan barrier for ChanID(%v)", channelID)
33✔
2393

33✔
2394
        // The next message that advances the funding flow will reference the
33✔
2395
        // channel via its permanent channel ID, so we'll set up this mapping
33✔
2396
        // so we can retrieve the reservation context once we get the
33✔
2397
        // FundingSigned message.
33✔
2398
        f.resMtx.Lock()
33✔
2399
        f.signedReservations[channelID] = cid.tempChanID
33✔
2400
        f.resMtx.Unlock()
33✔
2401

33✔
2402
        log.Infof("Generated ChannelPoint(%v) for pending_id(%x)", outPoint,
33✔
2403
                cid.tempChanID[:])
33✔
2404

33✔
2405
        // Before sending FundingCreated sent, we notify Brontide to keep track
33✔
2406
        // of this pending open channel.
33✔
2407
        err := resCtx.peer.AddPendingChannel(channelID, f.quit)
33✔
2408
        if err != nil {
33✔
2409
                pubKey := resCtx.peer.IdentityKey().SerializeCompressed()
×
2410
                log.Errorf("Unable to add pending channel %v with peer %x: %v",
×
2411
                        channelID, pubKey, err)
×
2412
        }
×
2413

2414
        // Once Brontide is aware of this channel, we need to set it in
2415
        // chanIdentifier so this channel will be removed from Brontide if the
2416
        // funding flow fails.
2417
        cid.setChanID(channelID)
33✔
2418

33✔
2419
        // Send the FundingCreated msg.
33✔
2420
        fundingCreated := &lnwire.FundingCreated{
33✔
2421
                PendingChannelID: cid.tempChanID,
33✔
2422
                FundingPoint:     *outPoint,
33✔
2423
        }
33✔
2424

33✔
2425
        // If this is a taproot channel, then we'll need to populate the musig2
33✔
2426
        // partial sig field instead of the regular commit sig field.
33✔
2427
        if resCtx.reservation.IsTaproot() {
38✔
2428
                partialSig, ok := sig.(*lnwallet.MusigPartialSig)
5✔
2429
                if !ok {
5✔
2430
                        err := fmt.Errorf("expected musig partial sig, got %T",
×
2431
                                sig)
×
2432
                        log.Error(err)
×
2433
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2434

×
2435
                        return
×
2436
                }
×
2437

2438
                fundingCreated.PartialSig = lnwire.MaybePartialSigWithNonce(
5✔
2439
                        partialSig.ToWireSig(),
5✔
2440
                )
5✔
2441
        } else {
31✔
2442
                fundingCreated.CommitSig, err = lnwire.NewSigFromSignature(sig)
31✔
2443
                if err != nil {
31✔
2444
                        log.Errorf("Unable to parse signature: %v", err)
×
2445
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2446
                        return
×
2447
                }
×
2448
        }
2449

2450
        resCtx.reservation.SetState(lnwallet.SentFundingCreated)
33✔
2451

33✔
2452
        if err := resCtx.peer.SendMessage(true, fundingCreated); err != nil {
33✔
2453
                log.Errorf("Unable to send funding complete message: %v", err)
×
2454
                f.failFundingFlow(resCtx.peer, cid, err)
×
2455
                return
×
2456
        }
×
2457
}
2458

2459
// fundeeProcessFundingCreated progresses the funding workflow when the daemon
2460
// is on the responding side of a single funder workflow. Once this message has
2461
// been processed, a signature is sent to the remote peer allowing it to
2462
// broadcast the funding transaction, progressing the workflow into the final
2463
// stage.
2464
//
2465
//nolint:funlen
2466
func (f *Manager) fundeeProcessFundingCreated(peer lnpeer.Peer,
2467
        msg *lnwire.FundingCreated) {
31✔
2468

31✔
2469
        peerKey := peer.IdentityKey()
31✔
2470
        pendingChanID := msg.PendingChannelID
31✔
2471

31✔
2472
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
31✔
2473
        if err != nil {
31✔
2474
                log.Warnf("can't find reservation (peer_id:%v, chan_id:%x)",
×
2475
                        peerKey, pendingChanID[:])
×
2476
                return
×
2477
        }
×
2478

2479
        // The channel initiator has responded with the funding outpoint of the
2480
        // final funding transaction, as well as a signature for our version of
2481
        // the commitment transaction. So at this point, we can validate the
2482
        // initiator's commitment transaction, then send our own if it's valid.
2483
        fundingOut := msg.FundingPoint
31✔
2484
        log.Infof("completing pending_id(%x) with ChannelPoint(%v)",
31✔
2485
                pendingChanID[:], fundingOut)
31✔
2486

31✔
2487
        if resCtx.reservation.State() != lnwallet.SentAcceptChannel {
31✔
2488
                return
×
2489
        }
×
2490

2491
        // Create the channel identifier without setting the active channel ID.
2492
        cid := newChanIdentifier(pendingChanID)
31✔
2493

31✔
2494
        // For taproot channels, the commit signature is actually the partial
31✔
2495
        // signature. Otherwise, we can convert the ECDSA commit signature into
31✔
2496
        // our internal input.Signature type.
31✔
2497
        var commitSig input.Signature
31✔
2498
        if resCtx.reservation.IsTaproot() {
36✔
2499
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
5✔
2500
                if err != nil {
5✔
2501
                        f.failFundingFlow(peer, cid, err)
×
2502

×
2503
                        return
×
2504
                }
×
2505

2506
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
5✔
2507
                        &partialSig,
5✔
2508
                )
5✔
2509
        } else {
29✔
2510
                commitSig, err = msg.CommitSig.ToSignature()
29✔
2511
                if err != nil {
29✔
2512
                        log.Errorf("unable to parse signature: %v", err)
×
2513
                        f.failFundingFlow(peer, cid, err)
×
2514
                        return
×
2515
                }
×
2516
        }
2517

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

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

2555
        // Get forwarding policy before deleting the reservation context.
2556
        forwardingPolicy := resCtx.forwardingPolicy
31✔
2557

31✔
2558
        // The channel is marked IsPending in the database, and can be removed
31✔
2559
        // from the set of active reservations.
31✔
2560
        f.deleteReservationCtx(peerKey, cid.tempChanID)
31✔
2561

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

×
2579
                // Close the channel with us as the initiator because we are
×
2580
                // deciding to exit the funding flow due to an internal error.
×
2581
                if err := completeChan.CloseChannel(
×
2582
                        closeInfo, channeldb.ChanStatusLocalCloseInitiator,
×
2583
                ); err != nil {
×
2584
                        log.Errorf("Failed closing channel %v: %v",
×
2585
                                completeChan.FundingOutpoint, err)
×
2586
                }
×
2587
        }
2588

2589
        // A new channel has almost finished the funding process. In order to
2590
        // properly synchronize with the writeHandler goroutine, we add a new
2591
        // channel to the barriers map which will be closed once the channel is
2592
        // fully open.
2593
        channelID := lnwire.NewChanIDFromOutPoint(fundingOut)
31✔
2594
        log.Debugf("Creating chan barrier for ChanID(%v)", channelID)
31✔
2595

31✔
2596
        fundingSigned := &lnwire.FundingSigned{}
31✔
2597

31✔
2598
        // For taproot channels, we'll need to send over a partial signature
31✔
2599
        // that includes the nonce along side the signature.
31✔
2600
        _, sig := resCtx.reservation.OurSignatures()
31✔
2601
        if resCtx.reservation.IsTaproot() {
36✔
2602
                partialSig, ok := sig.(*lnwallet.MusigPartialSig)
5✔
2603
                if !ok {
5✔
2604
                        err := fmt.Errorf("expected musig partial sig, got %T",
×
2605
                                sig)
×
2606
                        log.Error(err)
×
2607
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2608
                        deleteFromDatabase()
×
2609

×
2610
                        return
×
2611
                }
×
2612

2613
                fundingSigned.PartialSig = lnwire.MaybePartialSigWithNonce(
5✔
2614
                        partialSig.ToWireSig(),
5✔
2615
                )
5✔
2616
        } else {
29✔
2617
                fundingSigned.CommitSig, err = lnwire.NewSigFromSignature(sig)
29✔
2618
                if err != nil {
29✔
2619
                        log.Errorf("unable to parse signature: %v", err)
×
2620
                        f.failFundingFlow(peer, cid, err)
×
2621
                        deleteFromDatabase()
×
2622

×
2623
                        return
×
2624
                }
×
2625
        }
2626

2627
        // Before sending FundingSigned, we notify Brontide first to keep track
2628
        // of this pending open channel.
2629
        if err := peer.AddPendingChannel(channelID, f.quit); err != nil {
31✔
2630
                pubKey := peer.IdentityKey().SerializeCompressed()
×
2631
                log.Errorf("Unable to add pending channel %v with peer %x: %v",
×
2632
                        cid.chanID, pubKey, err)
×
2633
        }
×
2634

2635
        // Once Brontide is aware of this channel, we need to set it in
2636
        // chanIdentifier so this channel will be removed from Brontide if the
2637
        // funding flow fails.
2638
        cid.setChanID(channelID)
31✔
2639

31✔
2640
        fundingSigned.ChanID = cid.chanID
31✔
2641

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

31✔
2645
        // With their signature for our version of the commitment transaction
31✔
2646
        // verified, we can now send over our signature to the remote peer.
31✔
2647
        if err := peer.SendMessage(true, fundingSigned); err != nil {
31✔
2648
                log.Errorf("unable to send FundingSigned message: %v", err)
×
2649
                f.failFundingFlow(peer, cid, err)
×
2650
                deleteFromDatabase()
×
2651
                return
×
2652
        }
×
2653

2654
        // With a permanent channel id established we can save the respective
2655
        // forwarding policy in the database. In the channel announcement phase
2656
        // this forwarding policy is retrieved and applied.
2657
        err = f.saveInitialForwardingPolicy(cid.chanID, &forwardingPolicy)
31✔
2658
        if err != nil {
31✔
2659
                log.Errorf("Unable to store the forwarding policy: %v", err)
×
2660
        }
×
2661

2662
        // Now that we've sent over our final signature for this channel, we'll
2663
        // send it to the ChainArbitrator so it can watch for any on-chain
2664
        // actions during this final confirmation stage.
2665
        if err := f.cfg.WatchNewChannel(completeChan, peerKey); err != nil {
31✔
2666
                log.Errorf("Unable to send new ChannelPoint(%v) for "+
×
2667
                        "arbitration: %v", fundingOut, err)
×
2668
        }
×
2669

2670
        // Create an entry in the local discovery map so we can ensure that we
2671
        // process the channel confirmation fully before we receive a
2672
        // channel_ready message.
2673
        f.localDiscoverySignals.Store(cid.chanID, make(chan struct{}))
31✔
2674

31✔
2675
        // Inform the ChannelNotifier that the channel has entered
31✔
2676
        // pending open state.
31✔
2677
        f.cfg.NotifyPendingOpenChannelEvent(
31✔
2678
                fundingOut, completeChan, completeChan.IdentityPub,
31✔
2679
        )
31✔
2680

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

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

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

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

31✔
2728
        // If the pending channel ID is not found, fail the funding flow.
31✔
2729
        if !ok {
31✔
2730
                // NOTE: we directly overwrite the pending channel ID here for
×
2731
                // this rare case since we don't have a valid pending channel
×
2732
                // ID.
×
2733
                cid.tempChanID = msg.ChanID
×
2734

×
2735
                err := fmt.Errorf("unable to find signed reservation for "+
×
2736
                        "chan_id=%x", msg.ChanID)
×
2737
                log.Warnf(err.Error())
×
2738
                f.failFundingFlow(peer, cid, err)
×
2739
                return
×
2740
        }
×
2741

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

2752
        if resCtx.reservation.State() != lnwallet.SentFundingCreated {
31✔
2753
                err := fmt.Errorf("unable to find reservation for chan_id=%x",
×
2754
                        msg.ChanID)
×
2755
                f.failFundingFlow(peer, cid, err)
×
2756

×
2757
                return
×
2758
        }
×
2759

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

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

2777
        // For taproot channels, the commit signature is actually the partial
2778
        // signature. Otherwise, we can convert the ECDSA commit signature into
2779
        // our internal input.Signature type.
2780
        var commitSig input.Signature
31✔
2781
        if resCtx.reservation.IsTaproot() {
36✔
2782
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
5✔
2783
                if err != nil {
5✔
2784
                        f.failFundingFlow(peer, cid, err)
×
2785

×
2786
                        return
×
2787
                }
×
2788

2789
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
5✔
2790
                        &partialSig,
5✔
2791
                )
5✔
2792
        } else {
29✔
2793
                commitSig, err = msg.CommitSig.ToSignature()
29✔
2794
                if err != nil {
29✔
2795
                        log.Errorf("unable to parse signature: %v", err)
×
2796
                        f.failFundingFlow(peer, cid, err)
×
2797
                        return
×
2798
                }
×
2799
        }
2800

2801
        completeChan, err := resCtx.reservation.CompleteReservation(
31✔
2802
                nil, commitSig,
31✔
2803
        )
31✔
2804
        if err != nil {
31✔
2805
                log.Errorf("Unable to complete reservation sign "+
×
2806
                        "complete: %v", err)
×
2807
                f.failFundingFlow(peer, cid, err)
×
2808
                return
×
2809
        }
×
2810

2811
        // The channel is now marked IsPending in the database, and we can
2812
        // delete it from our set of active reservations.
2813
        f.deleteReservationCtx(peerKey, pendingChanID)
31✔
2814

31✔
2815
        // Broadcast the finalized funding transaction to the network, but only
31✔
2816
        // if we actually have the funding transaction.
31✔
2817
        if completeChan.ChanType.HasFundingTx() {
61✔
2818
                fundingTx := completeChan.FundingTxn
30✔
2819
                var fundingTxBuf bytes.Buffer
30✔
2820
                if err := fundingTx.Serialize(&fundingTxBuf); err != nil {
30✔
2821
                        log.Errorf("Unable to serialize funding "+
×
2822
                                "transaction %v: %v", fundingTx.TxHash(), err)
×
2823

×
2824
                        // Clear the buffer of any bytes that were written
×
2825
                        // before the serialization error to prevent logging an
×
2826
                        // incomplete transaction.
×
2827
                        fundingTxBuf.Reset()
×
2828
                }
×
2829

2830
                log.Infof("Broadcasting funding tx for ChannelPoint(%v): %x",
30✔
2831
                        completeChan.FundingOutpoint, fundingTxBuf.Bytes())
30✔
2832

30✔
2833
                // Set a nil short channel ID at this stage because we do not
30✔
2834
                // know it until our funding tx confirms.
30✔
2835
                label := labels.MakeLabel(
30✔
2836
                        labels.LabelTypeChannelOpen, nil,
30✔
2837
                )
30✔
2838

30✔
2839
                err = f.cfg.PublishTransaction(fundingTx, label)
30✔
2840
                if err != nil {
30✔
2841
                        log.Errorf("Unable to broadcast funding tx %x for "+
×
2842
                                "ChannelPoint(%v): %v", fundingTxBuf.Bytes(),
×
2843
                                completeChan.FundingOutpoint, err)
×
2844

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

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

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

2879
        log.Infof("Finalizing pending_id(%x) over ChannelPoint(%v), "+
31✔
2880
                "waiting for channel open on-chain", pendingChanID[:],
31✔
2881
                fundingPoint)
31✔
2882

31✔
2883
        // Send an update to the upstream client that the negotiation process
31✔
2884
        // is over.
31✔
2885
        upd := &lnrpc.OpenStatusUpdate{
31✔
2886
                Update: &lnrpc.OpenStatusUpdate_ChanPending{
31✔
2887
                        ChanPending: &lnrpc.PendingUpdate{
31✔
2888
                                Txid:        fundingPoint.Hash[:],
31✔
2889
                                OutputIndex: fundingPoint.Index,
31✔
2890
                        },
31✔
2891
                },
31✔
2892
                PendingChanId: pendingChanID[:],
31✔
2893
        }
31✔
2894

31✔
2895
        select {
31✔
2896
        case resCtx.updates <- upd:
31✔
2897
                // Inform the ChannelNotifier that the channel has entered
31✔
2898
                // pending open state.
31✔
2899
                f.cfg.NotifyPendingOpenChannelEvent(
31✔
2900
                        *fundingPoint, completeChan, completeChan.IdentityPub,
31✔
2901
                )
31✔
2902

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

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

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

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

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

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

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

2958
        // Notify other subsystems about the funding timeout.
2959
        f.cfg.NotifyFundingTimeout(c.FundingOutpoint, c.IdentityPub)
5✔
2960

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

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

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

2976
                // nil error means we continue on.
2977
                case nil:
5✔
2978

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

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

5✔
2990
                // TODO(halseth): should this send be made
5✔
2991
                // reliable?
5✔
2992

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

2998
        return timeoutErr
5✔
2999
}
3000

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

62✔
3009
        confChan := make(chan *confirmedChannel)
62✔
3010
        timeoutChan := make(chan error, 1)
62✔
3011
        cancelChan := make(chan struct{})
62✔
3012

62✔
3013
        f.wg.Add(1)
62✔
3014
        go f.waitForFundingConfirmation(ch, cancelChan, confChan)
62✔
3015

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

62✔
3025
        select {
62✔
3026
        case err := <-timeoutChan:
5✔
3027
                if err != nil {
5✔
3028
                        return nil, err
×
3029
                }
×
3030
                return nil, ErrConfirmationTimeout
5✔
3031

3032
        case <-f.quit:
26✔
3033
                // The fundingManager is shutting down, and will resume wait on
26✔
3034
                // startup.
26✔
3035
                return nil, ErrFundingManagerShuttingDown
26✔
3036

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

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

82✔
3052
        if channel.ChanType.IsTaproot() {
90✔
3053
                pkScript, _, err := input.GenTaprootFundingScript(
8✔
3054
                        localKey, remoteKey, int64(channel.Capacity),
8✔
3055
                        channel.TapscriptRoot,
8✔
3056
                )
8✔
3057
                if err != nil {
8✔
3058
                        return nil, err
×
3059
                }
×
3060

3061
                return pkScript, nil
8✔
3062
        }
3063

3064
        multiSigScript, err := input.GenMultiSigScript(
77✔
3065
                localKey.SerializeCompressed(),
77✔
3066
                remoteKey.SerializeCompressed(),
77✔
3067
        )
77✔
3068
        if err != nil {
77✔
3069
                return nil, err
×
3070
        }
×
3071

3072
        return input.WitnessScriptHash(multiSigScript)
77✔
3073
}
3074

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

62✔
3089
        defer f.wg.Done()
62✔
3090
        defer close(confChan)
62✔
3091

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

62✔
3104
        // If the underlying channel is a zero-conf channel, we'll set numConfs
62✔
3105
        // to 6, since it will be zero here.
62✔
3106
        if completeChan.IsZeroConf() {
71✔
3107
                numConfs = 6
9✔
3108
        }
9✔
3109

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

3121
        log.Infof("Waiting for funding tx (%v) to reach %v confirmations",
62✔
3122
                txid, numConfs)
62✔
3123

62✔
3124
        // Wait until the specified number of confirmations has been reached,
62✔
3125
        // we get a cancel signal, or the wallet signals a shutdown.
62✔
3126
        for {
152✔
3127
                select {
90✔
3128
                case updDetails, ok := <-confNtfn.Updates:
29✔
3129
                        if !ok {
29✔
3130
                                log.Warnf("ChainNotifier shutting down, "+
×
3131
                                        "cannot process updates for "+
×
3132
                                        "ChannelPoint(%v)",
×
3133
                                        completeChan.FundingOutpoint)
×
3134

×
3135
                                return
×
3136
                        }
×
3137

3138
                        log.Debugf("funding tx %s received confirmation in "+
29✔
3139
                                "block %d, %d confirmations left", txid,
29✔
3140
                                updDetails.BlockHeight, updDetails.NumConfsLeft)
29✔
3141

29✔
3142
                        // Only update the ConfirmationHeight the first time a
29✔
3143
                        // confirmation is received, since on subsequent
29✔
3144
                        // confirmations the block height will remain the same.
29✔
3145
                        if completeChan.ConfirmationHeight == 0 {
58✔
3146
                                err := completeChan.MarkConfirmationHeight(
29✔
3147
                                        updDetails.BlockHeight,
29✔
3148
                                )
29✔
3149
                                if err != nil {
29✔
3150
                                        log.Errorf("failed to update "+
×
3151
                                                "confirmed state for "+
×
3152
                                                "ChannelPoint(%v): %v",
×
3153
                                                completeChan.FundingOutpoint,
×
3154
                                                err)
×
3155

×
3156
                                        return
×
3157
                                }
×
3158
                        }
3159

3160
                case _, ok := <-confNtfn.NegativeConf:
4✔
3161
                        if !ok {
4✔
3162
                                log.Warnf("ChainNotifier shutting down, "+
×
3163
                                        "cannot track negative confirmations "+
×
3164
                                        "for ChannelPoint(%v)",
×
3165
                                        completeChan.FundingOutpoint)
×
3166

×
3167
                                return
×
3168
                        }
×
3169

3170
                        log.Warnf("funding tx %s was reorged out; channel "+
4✔
3171
                                "point: %s", txid, completeChan.FundingOutpoint)
4✔
3172

4✔
3173
                        // Reset the confirmation height to 0 because the
4✔
3174
                        // funding transaction was reorged out.
4✔
3175
                        err := completeChan.MarkConfirmationHeight(uint32(0))
4✔
3176
                        if err != nil {
4✔
3177
                                log.Errorf("failed to update state for "+
×
3178
                                        "ChannelPoint(%v): %v",
×
3179
                                        completeChan.FundingOutpoint, err)
×
3180

×
3181
                                return
×
3182
                        }
×
3183

3184
                case confDetails, ok := <-confNtfn.Confirmed:
37✔
3185
                        if !ok {
37✔
3186
                                log.Warnf("ChainNotifier shutting down, "+
×
3187
                                        "cannot complete funding flow for "+
×
3188
                                        "ChannelPoint(%v)",
×
3189
                                        completeChan.FundingOutpoint)
×
3190

×
3191
                                return
×
3192
                        }
×
3193

3194
                        log.Debugf("funding tx %s for ChannelPoint(%v) "+
37✔
3195
                                "confirmed in block %d", txid,
37✔
3196
                                completeChan.FundingOutpoint,
37✔
3197
                                confDetails.BlockHeight)
37✔
3198

37✔
3199
                        // In the case of requiring a single confirmation, it
37✔
3200
                        // can happen that the `Confirmed` channel is read
37✔
3201
                        // from first, in which case the confirmation height
37✔
3202
                        // will not be set. If this happens, we take the
37✔
3203
                        // confirmation height from the `Confirmed` channel.
37✔
3204
                        if completeChan.ConfirmationHeight == 0 {
49✔
3205
                                err := completeChan.MarkConfirmationHeight(
12✔
3206
                                        confDetails.BlockHeight,
12✔
3207
                                )
12✔
3208
                                if err != nil {
12✔
3209
                                        log.Errorf("failed to update "+
×
3210
                                                "confirmed state for "+
×
3211
                                                "ChannelPoint(%v): %v",
×
3212
                                                completeChan.FundingOutpoint,
×
3213
                                                err)
×
3214

×
3215
                                        return
×
3216
                                }
×
3217
                        }
3218

3219
                        err := f.handleConfirmation(
37✔
3220
                                confDetails, completeChan, confChan,
37✔
3221
                        )
37✔
3222
                        if err != nil {
37✔
3223
                                log.Errorf("Error handling confirmation for "+
×
3224
                                        "ChannelPoint(%v), txid=%v: %v",
×
3225
                                        completeChan.FundingOutpoint, txid, err)
×
3226
                        }
×
3227

3228
                        return
37✔
3229

3230
                case <-cancelChan:
6✔
3231
                        log.Warnf("canceled waiting for funding confirmation, "+
6✔
3232
                                "stopping funding flow for ChannelPoint(%v)",
6✔
3233
                                completeChan.FundingOutpoint)
6✔
3234

6✔
3235
                        return
6✔
3236

3237
                case <-f.quit:
25✔
3238
                        log.Warnf("fundingManager shutting down, stopping "+
25✔
3239
                                "funding flow for ChannelPoint(%v)",
25✔
3240
                                completeChan.FundingOutpoint)
25✔
3241

25✔
3242
                        return
25✔
3243
                }
3244
        }
3245
}
3246

3247
// handleConfirmation is a helper function that constructs a ShortChannelID
3248
// based on the confirmation details and sends this information, along with the
3249
// funding transaction, to the provided confirmation channel.
3250
func (f *Manager) handleConfirmation(confDetails *chainntnfs.TxConfirmation,
3251
        completeChan *channeldb.OpenChannel,
3252
        confChan chan<- *confirmedChannel) error {
37✔
3253

37✔
3254
        fundingPoint := completeChan.FundingOutpoint
37✔
3255
        log.Infof("ChannelPoint(%v) is now active: ChannelID(%v)",
37✔
3256
                fundingPoint, lnwire.NewChanIDFromOutPoint(fundingPoint))
37✔
3257

37✔
3258
        // With the block height and the transaction index known, we can
37✔
3259
        // construct the compact chanID which is used on the network to unique
37✔
3260
        // identify channels.
37✔
3261
        shortChanID := lnwire.ShortChannelID{
37✔
3262
                BlockHeight: confDetails.BlockHeight,
37✔
3263
                TxIndex:     confDetails.TxIndex,
37✔
3264
                TxPosition:  uint16(fundingPoint.Index),
37✔
3265
        }
37✔
3266

37✔
3267
        select {
37✔
3268
        case confChan <- &confirmedChannel{
3269
                shortChanID: shortChanID,
3270
                fundingTx:   confDetails.Tx,
3271
        }:
37✔
3272
        case <-f.quit:
×
3273
                return fmt.Errorf("manager shutting down")
×
3274
        }
3275

3276
        return nil
37✔
3277
}
3278

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

29✔
3289
        defer f.wg.Done()
29✔
3290

29✔
3291
        epochClient, err := f.cfg.Notifier.RegisterBlockEpochNtfn(nil)
29✔
3292
        if err != nil {
29✔
3293
                timeoutChan <- fmt.Errorf("unable to register for epoch "+
×
3294
                        "notification: %v", err)
×
3295
                return
×
3296
        }
×
3297

3298
        defer epochClient.Cancel()
29✔
3299

29✔
3300
        // The value of waitBlocksForFundingConf is adjusted in a development
29✔
3301
        // environment to enhance test capabilities. Otherwise, it is set to
29✔
3302
        // DefaultMaxWaitNumBlocksFundingConf.
29✔
3303
        waitBlocksForFundingConf := uint32(
29✔
3304
                lncfg.DefaultMaxWaitNumBlocksFundingConf,
29✔
3305
        )
29✔
3306

29✔
3307
        if lncfg.IsDevBuild() {
32✔
3308
                waitBlocksForFundingConf =
3✔
3309
                        f.cfg.Dev.MaxWaitNumBlocksFundingConf
3✔
3310
        }
3✔
3311

3312
        // On block maxHeight we will cancel the funding confirmation wait.
3313
        broadcastHeight := completeChan.BroadcastHeight()
29✔
3314
        maxHeight := broadcastHeight + waitBlocksForFundingConf
29✔
3315
        for {
60✔
3316
                select {
31✔
3317
                case epoch, ok := <-epochClient.Epochs:
7✔
3318
                        if !ok {
7✔
3319
                                timeoutChan <- fmt.Errorf("epoch client " +
×
3320
                                        "shutting down")
×
3321
                                return
×
3322
                        }
×
3323

3324
                        // Close the timeout channel and exit if the block is
3325
                        // above the max height.
3326
                        if uint32(epoch.Height) >= maxHeight {
12✔
3327
                                log.Warnf("Waited for %v blocks without "+
5✔
3328
                                        "seeing funding transaction confirmed,"+
5✔
3329
                                        " cancelling.",
5✔
3330
                                        waitBlocksForFundingConf)
5✔
3331

5✔
3332
                                // Notify the caller of the timeout.
5✔
3333
                                close(timeoutChan)
5✔
3334
                                return
5✔
3335
                        }
5✔
3336

3337
                        // TODO: If we are the channel initiator implement
3338
                        // a method for recovering the funds from the funding
3339
                        // transaction
3340

3341
                case <-cancelChan:
18✔
3342
                        return
18✔
3343

3344
                case <-f.quit:
12✔
3345
                        // The fundingManager is shutting down, will resume
12✔
3346
                        // waiting for the funding transaction on startup.
12✔
3347
                        return
12✔
3348
                }
3349
        }
3350
}
3351

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

19✔
3362
                // For zero-conf channels, we'll use the actually-confirmed
19✔
3363
                // short channel id.
19✔
3364
                if c.IsZeroConf() {
24✔
3365
                        shortChanID = c.ZeroConfRealScid()
5✔
3366
                }
5✔
3367

3368
                label := labels.MakeLabel(
19✔
3369
                        labels.LabelTypeChannelOpen, &shortChanID,
19✔
3370
                )
19✔
3371

19✔
3372
                err := f.cfg.UpdateLabel(c.FundingOutpoint.Hash, label)
19✔
3373
                if err != nil {
19✔
3374
                        log.Errorf("unable to update label: %v", err)
×
3375
                }
×
3376
        }
3377
}
3378

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

33✔
3387
        fundingPoint := completeChan.FundingOutpoint
33✔
3388
        chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
33✔
3389

33✔
3390
        // TODO(roasbeef): ideally persistent state update for chan above
33✔
3391
        // should be abstracted
33✔
3392

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

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

3410
                err = f.cfg.AliasManager.AddLocalAlias(
5✔
3411
                        aliasScid, confChannel.shortChanID, true, false,
5✔
3412
                )
5✔
3413
                if err != nil {
5✔
3414
                        return fmt.Errorf("unable to request alias: %w", err)
×
3415
                }
×
3416
        }
3417

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

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

3440
        // Update the confirmed funding transaction label.
3441
        f.makeLabelForTx(completeChan)
33✔
3442

33✔
3443
        // Inform the ChannelNotifier that the channel has transitioned from
33✔
3444
        // pending open to open.
33✔
3445
        f.cfg.NotifyOpenChannelEvent(
33✔
3446
                completeChan.FundingOutpoint, completeChan.IdentityPub,
33✔
3447
        )
33✔
3448

33✔
3449
        // Close the discoverySignal channel, indicating to a separate
33✔
3450
        // goroutine that the channel now is marked as open in the database
33✔
3451
        // and that it is acceptable to process channel_ready messages
33✔
3452
        // from the peer.
33✔
3453
        if discoverySignal, ok := f.localDiscoverySignals.Load(chanID); ok {
66✔
3454
                close(discoverySignal)
33✔
3455
        }
33✔
3456

3457
        return nil
33✔
3458
}
3459

3460
// sendChannelReady creates and sends the channelReady message.
3461
// This should be called after the funding transaction has been confirmed,
3462
// and the channelState is 'markedOpen'.
3463
func (f *Manager) sendChannelReady(completeChan *channeldb.OpenChannel,
3464
        channel *lnwallet.LightningChannel) error {
38✔
3465

38✔
3466
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
38✔
3467

38✔
3468
        var peerKey [33]byte
38✔
3469
        copy(peerKey[:], completeChan.IdentityPub.SerializeCompressed())
38✔
3470

38✔
3471
        // Next, we'll send over the channel_ready message which marks that we
38✔
3472
        // consider the channel open by presenting the remote party with our
38✔
3473
        // next revocation key. Without the revocation key, the remote party
38✔
3474
        // will be unable to propose state transitions.
38✔
3475
        nextRevocation, err := channel.NextRevocationKey()
38✔
3476
        if err != nil {
38✔
3477
                return fmt.Errorf("unable to create next revocation: %w", err)
×
3478
        }
×
3479
        channelReadyMsg := lnwire.NewChannelReady(chanID, nextRevocation)
38✔
3480

38✔
3481
        // If this is a taproot channel, then we also need to send along our
38✔
3482
        // set of musig2 nonces as well.
38✔
3483
        if completeChan.ChanType.IsTaproot() {
45✔
3484
                log.Infof("ChanID(%v): generating musig2 nonces...",
7✔
3485
                        chanID)
7✔
3486

7✔
3487
                f.nonceMtx.Lock()
7✔
3488
                localNonce, ok := f.pendingMusigNonces[chanID]
7✔
3489
                if !ok {
14✔
3490
                        // If we don't have any nonces generated yet for this
7✔
3491
                        // first state, then we'll generate them now and stow
7✔
3492
                        // them away.  When we receive the funding locked
7✔
3493
                        // message, we'll then pass along this same set of
7✔
3494
                        // nonces.
7✔
3495
                        newNonce, err := channel.GenMusigNonces()
7✔
3496
                        if err != nil {
7✔
3497
                                f.nonceMtx.Unlock()
×
3498
                                return err
×
3499
                        }
×
3500

3501
                        // Now that we've generated the nonce for this channel,
3502
                        // we'll store it in the set of pending nonces.
3503
                        localNonce = newNonce
7✔
3504
                        f.pendingMusigNonces[chanID] = localNonce
7✔
3505
                }
3506
                f.nonceMtx.Unlock()
7✔
3507

7✔
3508
                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
7✔
3509
                        localNonce.PubNonce,
7✔
3510
                )
7✔
3511
        }
3512

3513
        // If the channel negotiated the option-scid-alias feature bit, we'll
3514
        // send a TLV segment that includes an alias the peer can use in their
3515
        // invoice hop hints. We'll send the first alias we find for the
3516
        // channel since it does not matter which alias we send. We'll error
3517
        // out in the odd case that no aliases are found.
3518
        if completeChan.NegotiatedAliasFeature() {
47✔
3519
                aliases := f.cfg.AliasManager.GetAliases(
9✔
3520
                        completeChan.ShortChanID(),
9✔
3521
                )
9✔
3522
                if len(aliases) == 0 {
9✔
3523
                        return fmt.Errorf("no aliases found")
×
3524
                }
×
3525

3526
                // We can use a pointer to aliases since GetAliases returns a
3527
                // copy of the alias slice.
3528
                channelReadyMsg.AliasScid = &aliases[0]
9✔
3529
        }
3530

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

3548
                localAlias := peer.LocalFeatures().HasFeature(
37✔
3549
                        lnwire.ScidAliasOptional,
37✔
3550
                )
37✔
3551
                remoteAlias := peer.RemoteFeatures().HasFeature(
37✔
3552
                        lnwire.ScidAliasOptional,
37✔
3553
                )
37✔
3554

37✔
3555
                // We could also refresh the channel state instead of checking
37✔
3556
                // whether the feature was negotiated, but this saves us a
37✔
3557
                // database read.
37✔
3558
                if channelReadyMsg.AliasScid == nil && localAlias &&
37✔
3559
                        remoteAlias {
37✔
3560

×
3561
                        // If an alias was not assigned above and the scid
×
3562
                        // alias feature was negotiated, check if we already
×
3563
                        // have an alias stored in case handleChannelReady was
×
3564
                        // called before this. If an alias exists, use that in
×
3565
                        // channel_ready. Otherwise, request and store an
×
3566
                        // alias and use that.
×
3567
                        aliases := f.cfg.AliasManager.GetAliases(
×
3568
                                completeChan.ShortChannelID,
×
3569
                        )
×
3570
                        if len(aliases) == 0 {
×
3571
                                // No aliases were found.
×
3572
                                alias, err := f.cfg.AliasManager.RequestAlias()
×
3573
                                if err != nil {
×
3574
                                        return err
×
3575
                                }
×
3576

3577
                                err = f.cfg.AliasManager.AddLocalAlias(
×
3578
                                        alias, completeChan.ShortChannelID,
×
3579
                                        false, false,
×
3580
                                )
×
3581
                                if err != nil {
×
3582
                                        return err
×
3583
                                }
×
3584

3585
                                channelReadyMsg.AliasScid = &alias
×
3586
                        } else {
×
3587
                                channelReadyMsg.AliasScid = &aliases[0]
×
3588
                        }
×
3589
                }
3590

3591
                log.Infof("Peer(%x) is online, sending ChannelReady "+
37✔
3592
                        "for ChannelID(%v)", peerKey, chanID)
37✔
3593

37✔
3594
                if err := peer.SendMessage(true, channelReadyMsg); err == nil {
74✔
3595
                        // Sending succeeded, we can break out and continue the
37✔
3596
                        // funding flow.
37✔
3597
                        break
37✔
3598
                }
3599

3600
                log.Warnf("Unable to send channelReady to peer %x: %v. "+
×
3601
                        "Will retry when online", peerKey, err)
×
3602
        }
3603

3604
        return nil
37✔
3605
}
3606

3607
// receivedChannelReady checks whether or not we've received a ChannelReady
3608
// from the remote peer. If we have, RemoteNextRevocation will be set.
3609
func (f *Manager) receivedChannelReady(node *btcec.PublicKey,
3610
        chanID lnwire.ChannelID) (bool, error) {
62✔
3611

62✔
3612
        // If the funding manager has exited, return an error to stop looping.
62✔
3613
        // Note that the peer may appear as online while the funding manager
62✔
3614
        // has stopped due to the shutdown order in the server.
62✔
3615
        select {
62✔
3616
        case <-f.quit:
1✔
3617
                return false, ErrFundingManagerShuttingDown
1✔
3618
        default:
61✔
3619
        }
3620

3621
        // Avoid a tight loop if peer is offline.
3622
        if _, err := f.waitForPeerOnline(node); err != nil {
61✔
UNCOV
3623
                log.Errorf("Wait for peer online failed: %v", err)
×
UNCOV
3624
                return false, err
×
UNCOV
3625
        }
×
3626

3627
        // If we cannot find the channel, then we haven't processed the
3628
        // remote's channelReady message.
3629
        channel, err := f.cfg.FindChannel(node, chanID)
61✔
3630
        if err != nil {
61✔
3631
                log.Errorf("Unable to locate ChannelID(%v) to determine if "+
×
3632
                        "ChannelReady was received", chanID)
×
3633
                return false, err
×
3634
        }
×
3635

3636
        // If we haven't insert the next revocation point, we haven't finished
3637
        // processing the channel ready message.
3638
        if channel.RemoteNextRevocation == nil {
98✔
3639
                return false, nil
37✔
3640
        }
37✔
3641

3642
        // Finally, the barrier signal is removed once we finish
3643
        // `handleChannelReady`. If we can still find the signal, we haven't
3644
        // finished processing it yet.
3645
        _, loaded := f.handleChannelReadyBarriers.Load(chanID)
27✔
3646

27✔
3647
        return !loaded, nil
27✔
3648
}
3649

3650
// extractAnnounceParams extracts the various channel announcement and update
3651
// parameters that will be needed to construct a ChannelAnnouncement and a
3652
// ChannelUpdate.
3653
func (f *Manager) extractAnnounceParams(c *channeldb.OpenChannel) (
3654
        lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
29✔
3655

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

29✔
3662
        // We don't necessarily want to go as low as the remote party allows.
29✔
3663
        // Check it against our default forwarding policy.
29✔
3664
        if fwdMinHTLC < f.cfg.DefaultRoutingPolicy.MinHTLCOut {
32✔
3665
                fwdMinHTLC = f.cfg.DefaultRoutingPolicy.MinHTLCOut
3✔
3666
        }
3✔
3667

3668
        // We'll obtain the max HTLC value we can forward in our direction, as
3669
        // we'll use this value within our ChannelUpdate. This value must be <=
3670
        // channel capacity and <= the maximum in-flight msats set by the peer.
3671
        fwdMaxHTLC := c.LocalChanCfg.MaxPendingAmount
29✔
3672
        capacityMSat := lnwire.NewMSatFromSatoshis(c.Capacity)
29✔
3673
        if fwdMaxHTLC > capacityMSat {
29✔
3674
                fwdMaxHTLC = capacityMSat
×
3675
        }
×
3676

3677
        return fwdMinHTLC, fwdMaxHTLC
29✔
3678
}
3679

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

29✔
3693
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
29✔
3694

29✔
3695
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
29✔
3696

29✔
3697
        ann, err := f.newChanAnnouncement(
29✔
3698
                f.cfg.IDKey, completeChan.IdentityPub,
29✔
3699
                &completeChan.LocalChanCfg.MultiSigKey,
29✔
3700
                completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
29✔
3701
                chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
29✔
3702
                completeChan.ChanType,
29✔
3703
        )
29✔
3704
        if err != nil {
29✔
3705
                return fmt.Errorf("error generating channel "+
×
3706
                        "announcement: %v", err)
×
3707
        }
×
3708

3709
        // Send ChannelAnnouncement and ChannelUpdate to the gossiper to add
3710
        // to the Router's topology.
3711
        errChan := f.cfg.SendAnnouncement(
29✔
3712
                ann.chanAnn, discovery.ChannelCapacity(completeChan.Capacity),
29✔
3713
                discovery.ChannelPoint(completeChan.FundingOutpoint),
29✔
3714
                discovery.TapscriptRoot(completeChan.TapscriptRoot),
29✔
3715
        )
29✔
3716
        select {
29✔
3717
        case err := <-errChan:
29✔
3718
                if err != nil {
29✔
3719
                        if graph.IsError(err, graph.ErrOutdated,
×
3720
                                graph.ErrIgnored) {
×
3721

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

3733
        errChan = f.cfg.SendAnnouncement(
29✔
3734
                ann.chanUpdateAnn, discovery.RemoteAlias(peerAlias),
29✔
3735
        )
29✔
3736
        select {
29✔
3737
        case err := <-errChan:
29✔
3738
                if err != nil {
29✔
3739
                        if graph.IsError(err, graph.ErrOutdated,
×
3740
                                graph.ErrIgnored) {
×
3741

×
3742
                                log.Debugf("Graph rejected "+
×
3743
                                        "ChannelUpdate: %v", err)
×
3744
                        } else {
×
3745
                                return fmt.Errorf("error sending channel "+
×
3746
                                        "update: %v", err)
×
3747
                        }
×
3748
                }
3749
        case <-f.quit:
×
3750
                return ErrFundingManagerShuttingDown
×
3751
        }
3752

3753
        return nil
29✔
3754
}
3755

3756
// annAfterSixConfs broadcasts the necessary channel announcement messages to
3757
// the network after 6 confs. Should be called after the channelReady message
3758
// is sent and the channel is added to the graph (channelState is
3759
// 'addedToGraph') and the channel is ready to be used. This is the last
3760
// step in the channel opening process, and the opening state will be deleted
3761
// from the database if successful.
3762
func (f *Manager) annAfterSixConfs(completeChan *channeldb.OpenChannel,
3763
        shortChanID *lnwire.ShortChannelID) error {
29✔
3764

29✔
3765
        // If this channel is not meant to be announced to the greater network,
29✔
3766
        // we'll only send our NodeAnnouncement to our counterparty to ensure we
29✔
3767
        // don't leak any of our information.
29✔
3768
        announceChan := completeChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
29✔
3769
        if !announceChan {
40✔
3770
                log.Debugf("Will not announce private channel %v.",
11✔
3771
                        shortChanID.ToUint64())
11✔
3772

11✔
3773
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
11✔
3774
                if err != nil {
11✔
3775
                        return err
×
3776
                }
×
3777

3778
                nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
11✔
3779
                if err != nil {
11✔
3780
                        return fmt.Errorf("unable to retrieve current node "+
×
3781
                                "announcement: %v", err)
×
3782
                }
×
3783

3784
                chanID := lnwire.NewChanIDFromOutPoint(
11✔
3785
                        completeChan.FundingOutpoint,
11✔
3786
                )
11✔
3787
                pubKey := peer.PubKey()
11✔
3788
                log.Debugf("Sending our NodeAnnouncement for "+
11✔
3789
                        "ChannelID(%v) to %x", chanID, pubKey)
11✔
3790

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

21✔
3811
                fundingScript, err := makeFundingScript(completeChan)
21✔
3812
                if err != nil {
21✔
3813
                        return fmt.Errorf("unable to create funding script "+
×
3814
                                "for ChannelPoint(%v): %v",
×
3815
                                completeChan.FundingOutpoint, err)
×
3816
                }
×
3817

3818
                // Register with the ChainNotifier for a notification once the
3819
                // funding transaction reaches at least 6 confirmations.
3820
                confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
21✔
3821
                        &txid, fundingScript, numConfs,
21✔
3822
                        completeChan.BroadcastHeight(),
21✔
3823
                )
21✔
3824
                if err != nil {
21✔
3825
                        return fmt.Errorf("unable to register for "+
×
3826
                                "confirmation of ChannelPoint(%v): %v",
×
3827
                                completeChan.FundingOutpoint, err)
×
3828
                }
×
3829

3830
                // Wait until 6 confirmations has been reached or the wallet
3831
                // signals a shutdown.
3832
                select {
21✔
3833
                case _, ok := <-confNtfn.Confirmed:
19✔
3834
                        if !ok {
19✔
3835
                                return fmt.Errorf("ChainNotifier shutting "+
×
3836
                                        "down, cannot complete funding flow "+
×
3837
                                        "for ChannelPoint(%v)",
×
3838
                                        completeChan.FundingOutpoint)
×
3839
                        }
×
3840
                        // Fallthrough.
3841

3842
                case <-f.quit:
5✔
3843
                        return fmt.Errorf("%v, stopping funding flow for "+
5✔
3844
                                "ChannelPoint(%v)",
5✔
3845
                                ErrFundingManagerShuttingDown,
5✔
3846
                                completeChan.FundingOutpoint)
5✔
3847
                }
3848

3849
                fundingPoint := completeChan.FundingOutpoint
19✔
3850
                chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
19✔
3851

19✔
3852
                log.Infof("Announcing ChannelPoint(%v), short_chan_id=%v",
19✔
3853
                        &fundingPoint, shortChanID)
19✔
3854

19✔
3855
                // If this is a non-zero-conf option-scid-alias channel, we'll
19✔
3856
                // delete the mappings the gossiper uses so that ChannelUpdates
19✔
3857
                // with aliases won't be accepted. This is done elsewhere for
19✔
3858
                // zero-conf channels.
19✔
3859
                isScidFeature := completeChan.NegotiatedAliasFeature()
19✔
3860
                isZeroConf := completeChan.IsZeroConf()
19✔
3861
                if isScidFeature && !isZeroConf {
22✔
3862
                        baseScid := completeChan.ShortChanID()
3✔
3863
                        err := f.cfg.AliasManager.DeleteSixConfs(baseScid)
3✔
3864
                        if err != nil {
3✔
3865
                                return fmt.Errorf("failed deleting six confs "+
×
3866
                                        "maps: %v", err)
×
3867
                        }
×
3868

3869
                        // We'll delete the edge and add it again via
3870
                        // addToGraph. This is because the peer may have
3871
                        // sent us a ChannelUpdate with an alias and we don't
3872
                        // want to relay this.
3873
                        ourPolicy, err := f.cfg.DeleteAliasEdge(baseScid)
3✔
3874
                        if err != nil {
3✔
3875
                                return fmt.Errorf("failed deleting real edge "+
×
3876
                                        "for alias channel from graph: %v",
×
3877
                                        err)
×
3878
                        }
×
3879

3880
                        err = f.addToGraph(
3✔
3881
                                completeChan, &baseScid, nil, ourPolicy,
3✔
3882
                        )
3✔
3883
                        if err != nil {
3✔
3884
                                return fmt.Errorf("failed to re-add to "+
×
3885
                                        "graph: %v", err)
×
3886
                        }
×
3887
                }
3888

3889
                // Create and broadcast the proofs required to make this channel
3890
                // public and usable for other nodes for routing.
3891
                err = f.announceChannel(
19✔
3892
                        f.cfg.IDKey, completeChan.IdentityPub,
19✔
3893
                        &completeChan.LocalChanCfg.MultiSigKey,
19✔
3894
                        completeChan.RemoteChanCfg.MultiSigKey.PubKey,
19✔
3895
                        *shortChanID, chanID, completeChan.ChanType,
19✔
3896
                )
19✔
3897
                if err != nil {
22✔
3898
                        return fmt.Errorf("channel announcement failed: %w",
3✔
3899
                                err)
3✔
3900
                }
3✔
3901

3902
                log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+
19✔
3903
                        "sent to gossiper", &fundingPoint, shortChanID)
19✔
3904
        }
3905

3906
        return nil
27✔
3907
}
3908

3909
// waitForZeroConfChannel is called when the state is addedToGraph with
3910
// a zero-conf channel. This will wait for the real confirmation, add the
3911
// confirmed SCID to the router graph, and then announce after six confs.
3912
func (f *Manager) waitForZeroConfChannel(c *channeldb.OpenChannel) error {
9✔
3913
        // First we'll check whether the channel is confirmed on-chain. If it
9✔
3914
        // is already confirmed, the chainntnfs subsystem will return with the
9✔
3915
        // confirmed tx. Otherwise, we'll wait here until confirmation occurs.
9✔
3916
        confChan, err := f.waitForFundingWithTimeout(c)
9✔
3917
        if err != nil {
14✔
3918
                return fmt.Errorf("error waiting for zero-conf funding "+
5✔
3919
                        "confirmation for ChannelPoint(%v): %v",
5✔
3920
                        c.FundingOutpoint, err)
5✔
3921
        }
5✔
3922

3923
        // We'll need to refresh the channel state so that things are properly
3924
        // populated when validating the channel state. Otherwise, a panic may
3925
        // occur due to inconsistency in the OpenChannel struct.
3926
        err = c.Refresh()
7✔
3927
        if err != nil {
10✔
3928
                return fmt.Errorf("unable to refresh channel state: %w", err)
3✔
3929
        }
3✔
3930

3931
        // Now that we have the confirmed transaction and the proper SCID,
3932
        // we'll call ValidateChannel to ensure the confirmed tx is properly
3933
        // formatted.
3934
        err = f.cfg.Wallet.ValidateChannel(c, confChan.fundingTx)
7✔
3935
        if err != nil {
7✔
3936
                return fmt.Errorf("unable to validate zero-conf channel: "+
×
3937
                        "%v", err)
×
3938
        }
×
3939

3940
        // Once we know the confirmed ShortChannelID, we'll need to save it to
3941
        // the database and refresh the OpenChannel struct with it.
3942
        err = c.MarkRealScid(confChan.shortChanID)
7✔
3943
        if err != nil {
7✔
3944
                return fmt.Errorf("unable to set confirmed SCID for zero "+
×
3945
                        "channel: %v", err)
×
3946
        }
×
3947

3948
        // Six confirmations have been reached. If this channel is public,
3949
        // we'll delete some of the alias mappings the gossiper uses.
3950
        isPublic := c.ChannelFlags&lnwire.FFAnnounceChannel != 0
7✔
3951
        if isPublic {
12✔
3952
                err = f.cfg.AliasManager.DeleteSixConfs(c.ShortChannelID)
5✔
3953
                if err != nil {
5✔
3954
                        return fmt.Errorf("unable to delete base alias after "+
×
3955
                                "six confirmations: %v", err)
×
3956
                }
×
3957

3958
                // TODO: Make this atomic!
3959
                ourPolicy, err := f.cfg.DeleteAliasEdge(c.ShortChanID())
5✔
3960
                if err != nil {
5✔
3961
                        return fmt.Errorf("unable to delete alias edge from "+
×
3962
                                "graph: %v", err)
×
3963
                }
×
3964

3965
                // We'll need to update the graph with the new ShortChannelID
3966
                // via an addToGraph call. We don't pass in the peer's
3967
                // alias since we'll be using the confirmed SCID from now on
3968
                // regardless if it's public or not.
3969
                err = f.addToGraph(
5✔
3970
                        c, &confChan.shortChanID, nil, ourPolicy,
5✔
3971
                )
5✔
3972
                if err != nil {
5✔
3973
                        return fmt.Errorf("failed adding confirmed zero-conf "+
×
3974
                                "SCID to graph: %v", err)
×
3975
                }
×
3976
        }
3977

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

3991
        // Update the confirmed transaction's label.
3992
        f.makeLabelForTx(c)
7✔
3993

7✔
3994
        return nil
7✔
3995
}
3996

3997
// genFirstStateMusigNonce generates a nonces for the "first" local state. This
3998
// is the verification nonce for the state created for us after the initial
3999
// commitment transaction signed as part of the funding flow.
4000
func genFirstStateMusigNonce(channel *channeldb.OpenChannel,
4001
) (*musig2.Nonces, error) {
7✔
4002

7✔
4003
        musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
7✔
4004
                channel.RevocationProducer,
7✔
4005
        )
7✔
4006
        if err != nil {
7✔
4007
                return nil, fmt.Errorf("unable to generate musig channel "+
×
4008
                        "nonces: %v", err)
×
4009
        }
×
4010

4011
        // We use the _next_ commitment height here as we need to generate the
4012
        // nonce for the next state the remote party will sign for us.
4013
        verNonce, err := channeldb.NewMusigVerificationNonce(
7✔
4014
                channel.LocalChanCfg.MultiSigKey.PubKey,
7✔
4015
                channel.LocalCommitment.CommitHeight+1,
7✔
4016
                musig2ShaChain,
7✔
4017
        )
7✔
4018
        if err != nil {
7✔
4019
                return nil, fmt.Errorf("unable to generate musig channel "+
×
4020
                        "nonces: %v", err)
×
4021
        }
×
4022

4023
        return verNonce, nil
7✔
4024
}
4025

4026
// handleChannelReady finalizes the channel funding process and enables the
4027
// channel to enter normal operating mode.
4028
func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen
4029
        msg *lnwire.ChannelReady) {
31✔
4030

31✔
4031
        defer f.wg.Done()
31✔
4032

31✔
4033
        // If we are in development mode, we'll wait for specified duration
31✔
4034
        // before processing the channel ready message.
31✔
4035
        if f.cfg.Dev != nil {
34✔
4036
                duration := f.cfg.Dev.ProcessChannelReadyWait
3✔
4037
                log.Warnf("Channel(%v): sleeping %v before processing "+
3✔
4038
                        "channel_ready", msg.ChanID, duration)
3✔
4039

3✔
4040
                select {
3✔
4041
                case <-time.After(duration):
3✔
4042
                        log.Warnf("Channel(%v): slept %v before processing "+
3✔
4043
                                "channel_ready", msg.ChanID, duration)
3✔
4044
                case <-f.quit:
×
4045
                        log.Warnf("Channel(%v): quit sleeping", msg.ChanID)
×
4046
                        return
×
4047
                }
4048
        }
4049

4050
        log.Debugf("Received ChannelReady for ChannelID(%v) from "+
31✔
4051
                "peer %x", msg.ChanID,
31✔
4052
                peer.IdentityKey().SerializeCompressed())
31✔
4053

31✔
4054
        // We now load or create a new channel barrier for this channel.
31✔
4055
        _, loaded := f.handleChannelReadyBarriers.LoadOrStore(
31✔
4056
                msg.ChanID, struct{}{},
31✔
4057
        )
31✔
4058

31✔
4059
        // If we are currently in the process of handling a channel_ready
31✔
4060
        // message for this channel, ignore.
31✔
4061
        if loaded {
35✔
4062
                log.Infof("Already handling channelReady for "+
4✔
4063
                        "ChannelID(%v), ignoring.", msg.ChanID)
4✔
4064
                return
4✔
4065
        }
4✔
4066

4067
        // If not already handling channelReady for this channel, then the
4068
        // `LoadOrStore` has set up a barrier, and it will be removed once this
4069
        // function exits.
4070
        defer f.handleChannelReadyBarriers.Delete(msg.ChanID)
30✔
4071

30✔
4072
        localDiscoverySignal, ok := f.localDiscoverySignals.Load(msg.ChanID)
30✔
4073
        if ok {
58✔
4074
                // Before we proceed with processing the channel_ready
28✔
4075
                // message, we'll wait for the local waitForFundingConfirmation
28✔
4076
                // goroutine to signal that it has the necessary state in
28✔
4077
                // place. Otherwise, we may be missing critical information
28✔
4078
                // required to handle forwarded HTLC's.
28✔
4079
                select {
28✔
4080
                case <-localDiscoverySignal:
28✔
4081
                        // Fallthrough
4082
                case <-f.quit:
3✔
4083
                        return
3✔
4084
                }
4085

4086
                // With the signal received, we can now safely delete the entry
4087
                // from the map.
4088
                f.localDiscoverySignals.Delete(msg.ChanID)
28✔
4089
        }
4090

4091
        // First, we'll attempt to locate the channel whose funding workflow is
4092
        // being finalized by this message. We go to the database rather than
4093
        // our reservation map as we may have restarted, mid funding flow. Also
4094
        // provide the node's public key to make the search faster.
4095
        chanID := msg.ChanID
30✔
4096
        channel, err := f.cfg.FindChannel(peer.IdentityKey(), chanID)
30✔
4097
        if err != nil {
30✔
4098
                log.Errorf("Unable to locate ChannelID(%v), cannot complete "+
×
4099
                        "funding", chanID)
×
4100
                return
×
4101
        }
×
4102

4103
        // If this is a taproot channel, then we can generate the set of nonces
4104
        // the remote party needs to send the next remote commitment here.
4105
        var firstVerNonce *musig2.Nonces
30✔
4106
        if channel.ChanType.IsTaproot() {
37✔
4107
                firstVerNonce, err = genFirstStateMusigNonce(channel)
7✔
4108
                if err != nil {
7✔
4109
                        log.Error(err)
×
4110
                        return
×
4111
                }
×
4112
        }
4113

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

4131
                // We'll store the AliasScid so that invoice creation can use
4132
                // it.
4133
                err = f.cfg.AliasManager.PutPeerAlias(chanID, *msg.AliasScid)
9✔
4134
                if err != nil {
9✔
4135
                        log.Errorf("unable to store peer's alias: %v", err)
×
4136
                        return
×
4137
                }
×
4138

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

4156
                        err = f.cfg.AliasManager.AddLocalAlias(
×
4157
                                alias, channel.ShortChannelID, false, false,
×
4158
                        )
×
4159
                        if err != nil {
×
4160
                                log.Errorf("unable to add local alias: %v",
×
4161
                                        err)
×
4162
                                return
×
4163
                        }
×
4164

4165
                        secondPoint, err := channel.SecondCommitmentPoint()
×
4166
                        if err != nil {
×
4167
                                log.Errorf("unable to fetch second "+
×
4168
                                        "commitment point: %v", err)
×
4169
                                return
×
4170
                        }
×
4171

4172
                        channelReadyMsg := lnwire.NewChannelReady(
×
4173
                                chanID, secondPoint,
×
4174
                        )
×
4175
                        channelReadyMsg.AliasScid = &alias
×
4176

×
4177
                        if firstVerNonce != nil {
×
4178
                                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:ll
×
4179
                                        firstVerNonce.PubNonce,
×
4180
                                )
×
4181
                        }
×
4182

4183
                        err = peer.SendMessage(true, channelReadyMsg)
×
4184
                        if err != nil {
×
4185
                                log.Errorf("unable to send channel_ready: %v",
×
4186
                                        err)
×
4187
                                return
×
4188
                        }
×
4189
                }
4190
        }
4191

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

4207
        // If this is a taproot channel, then we'll need to map the received
4208
        // nonces to a nonce pair, and also fetch our pending nonces, which are
4209
        // required in order to make the channel whole.
4210
        var chanOpts []lnwallet.ChannelOpt
29✔
4211
        if channel.ChanType.IsTaproot() {
36✔
4212
                f.nonceMtx.Lock()
7✔
4213
                localNonce, ok := f.pendingMusigNonces[chanID]
7✔
4214
                if !ok {
10✔
4215
                        // If there's no pending nonce for this channel ID,
3✔
4216
                        // we'll use the one generated above.
3✔
4217
                        localNonce = firstVerNonce
3✔
4218
                        f.pendingMusigNonces[chanID] = firstVerNonce
3✔
4219
                }
3✔
4220
                f.nonceMtx.Unlock()
7✔
4221

7✔
4222
                log.Infof("ChanID(%v): applying local+remote musig2 nonces",
7✔
4223
                        chanID)
7✔
4224

7✔
4225
                remoteNonce, err := msg.NextLocalNonce.UnwrapOrErrV(
7✔
4226
                        errNoLocalNonce,
7✔
4227
                )
7✔
4228
                if err != nil {
7✔
4229
                        cid := newChanIdentifier(msg.ChanID)
×
4230
                        f.sendWarning(peer, cid, err)
×
4231

×
4232
                        return
×
4233
                }
×
4234

4235
                chanOpts = append(
7✔
4236
                        chanOpts,
7✔
4237
                        lnwallet.WithLocalMusigNonces(localNonce),
7✔
4238
                        lnwallet.WithRemoteMusigNonces(&musig2.Nonces{
7✔
4239
                                PubNonce: remoteNonce,
7✔
4240
                        }),
7✔
4241
                )
7✔
4242

7✔
4243
                // Inform the aux funding controller that the liquidity in the
7✔
4244
                // custom channel is now ready to be advertised. We potentially
7✔
4245
                // haven't sent our own channel ready message yet, but other
7✔
4246
                // than that the channel is ready to count toward available
7✔
4247
                // liquidity.
7✔
4248
                err = fn.MapOptionZ(
7✔
4249
                        f.cfg.AuxFundingController,
7✔
4250
                        func(controller AuxFundingController) error {
7✔
4251
                                return controller.ChannelReady(
×
4252
                                        lnwallet.NewAuxChanState(channel),
×
4253
                                )
×
4254
                        },
×
4255
                )
4256
                if err != nil {
7✔
4257
                        cid := newChanIdentifier(msg.ChanID)
×
4258
                        f.sendWarning(peer, cid, err)
×
4259

×
4260
                        return
×
4261
                }
×
4262
        }
4263

4264
        // The channel_ready message contains the next commitment point we'll
4265
        // need to create the next commitment state for the remote party. So
4266
        // we'll insert that into the channel now before passing it along to
4267
        // other sub-systems.
4268
        err = channel.InsertNextRevocation(msg.NextPerCommitmentPoint)
29✔
4269
        if err != nil {
29✔
4270
                log.Errorf("unable to insert next commitment point: %v", err)
×
4271
                return
×
4272
        }
×
4273

4274
        // Before we can add the channel to the peer, we'll need to ensure that
4275
        // we have an initial forwarding policy set.
4276
        if err := f.ensureInitialForwardingPolicy(chanID, channel); err != nil {
29✔
4277
                log.Errorf("Unable to ensure initial forwarding policy: %v",
×
4278
                        err)
×
4279
        }
×
4280

4281
        err = peer.AddNewChannel(&lnpeer.NewChannel{
29✔
4282
                OpenChannel: channel,
29✔
4283
                ChanOpts:    chanOpts,
29✔
4284
        }, f.quit)
29✔
4285
        if err != nil {
29✔
4286
                log.Errorf("Unable to add new channel %v with peer %x: %v",
×
4287
                        channel.FundingOutpoint,
×
4288
                        peer.IdentityKey().SerializeCompressed(), err,
×
4289
                )
×
4290
        }
×
4291
}
4292

4293
// handleChannelReadyReceived is called once the remote's channelReady message
4294
// is received and processed. At this stage, we must have sent out our
4295
// channelReady message, once the remote's channelReady is processed, the
4296
// channel is now active, thus we change its state to `addedToGraph` to
4297
// let the channel start handling routing.
4298
func (f *Manager) handleChannelReadyReceived(channel *channeldb.OpenChannel,
4299
        scid *lnwire.ShortChannelID, pendingChanID PendingChanID,
4300
        updateChan chan<- *lnrpc.OpenStatusUpdate) error {
27✔
4301

27✔
4302
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
27✔
4303

27✔
4304
        // Since we've sent+received funding locked at this point, we
27✔
4305
        // can clean up the pending musig2 nonce state.
27✔
4306
        f.nonceMtx.Lock()
27✔
4307
        delete(f.pendingMusigNonces, chanID)
27✔
4308
        f.nonceMtx.Unlock()
27✔
4309

27✔
4310
        var peerAlias *lnwire.ShortChannelID
27✔
4311
        if channel.IsZeroConf() {
34✔
4312
                // We'll need to wait until channel_ready has been received and
7✔
4313
                // the peer lets us know the alias they want to use for the
7✔
4314
                // channel. With this information, we can then construct a
7✔
4315
                // ChannelUpdate for them.  If an alias does not yet exist,
7✔
4316
                // we'll just return, letting the next iteration of the loop
7✔
4317
                // check again.
7✔
4318
                var defaultAlias lnwire.ShortChannelID
7✔
4319
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
7✔
4320
                foundAlias, _ := f.cfg.AliasManager.GetPeerAlias(chanID)
7✔
4321
                if foundAlias == defaultAlias {
7✔
4322
                        return nil
×
4323
                }
×
4324

4325
                peerAlias = &foundAlias
7✔
4326
        }
4327

4328
        err := f.addToGraph(channel, scid, peerAlias, nil)
27✔
4329
        if err != nil {
27✔
4330
                return fmt.Errorf("failed adding to graph: %w", err)
×
4331
        }
×
4332

4333
        // As the channel is now added to the ChannelRouter's topology, the
4334
        // channel is moved to the next state of the state machine. It will be
4335
        // moved to the last state (actually deleted from the database) after
4336
        // the channel is finally announced.
4337
        err = f.saveChannelOpeningState(
27✔
4338
                &channel.FundingOutpoint, addedToGraph, scid,
27✔
4339
        )
27✔
4340
        if err != nil {
27✔
4341
                return fmt.Errorf("error setting channel state to"+
×
4342
                        " addedToGraph: %w", err)
×
4343
        }
×
4344

4345
        log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
27✔
4346
                "added to graph", chanID, scid)
27✔
4347

27✔
4348
        err = fn.MapOptionZ(
27✔
4349
                f.cfg.AuxFundingController,
27✔
4350
                func(controller AuxFundingController) error {
27✔
4351
                        return controller.ChannelReady(
×
4352
                                lnwallet.NewAuxChanState(channel),
×
4353
                        )
×
4354
                },
×
4355
        )
4356
        if err != nil {
27✔
4357
                return fmt.Errorf("failed notifying aux funding controller "+
×
4358
                        "about channel ready: %w", err)
×
4359
        }
×
4360

4361
        // Give the caller a final update notifying them that the channel is
4362
        fundingPoint := channel.FundingOutpoint
27✔
4363
        cp := &lnrpc.ChannelPoint{
27✔
4364
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
27✔
4365
                        FundingTxidBytes: fundingPoint.Hash[:],
27✔
4366
                },
27✔
4367
                OutputIndex: fundingPoint.Index,
27✔
4368
        }
27✔
4369

27✔
4370
        if updateChan != nil {
40✔
4371
                upd := &lnrpc.OpenStatusUpdate{
13✔
4372
                        Update: &lnrpc.OpenStatusUpdate_ChanOpen{
13✔
4373
                                ChanOpen: &lnrpc.ChannelOpenUpdate{
13✔
4374
                                        ChannelPoint: cp,
13✔
4375
                                },
13✔
4376
                        },
13✔
4377
                        PendingChanId: pendingChanID[:],
13✔
4378
                }
13✔
4379

13✔
4380
                select {
13✔
4381
                case updateChan <- upd:
13✔
4382
                case <-f.quit:
×
4383
                        return ErrFundingManagerShuttingDown
×
4384
                }
4385
        }
4386

4387
        return nil
27✔
4388
}
4389

4390
// ensureInitialForwardingPolicy ensures that we have an initial forwarding
4391
// policy set for the given channel. If we don't, we'll fall back to the default
4392
// values.
4393
func (f *Manager) ensureInitialForwardingPolicy(chanID lnwire.ChannelID,
4394
        channel *channeldb.OpenChannel) error {
29✔
4395

29✔
4396
        // Before we can add the channel to the peer, we'll need to ensure that
29✔
4397
        // we have an initial forwarding policy set. This should always be the
29✔
4398
        // case except for a channel that was created with lnd <= 0.15.5 and
29✔
4399
        // is still pending while updating to this version.
29✔
4400
        var needDBUpdate bool
29✔
4401
        forwardingPolicy, err := f.getInitialForwardingPolicy(chanID)
29✔
4402
        if err != nil {
29✔
4403
                log.Errorf("Unable to fetch initial forwarding policy, "+
×
4404
                        "falling back to default values: %v", err)
×
4405

×
4406
                forwardingPolicy = f.defaultForwardingPolicy(
×
4407
                        channel.LocalChanCfg.ChannelStateBounds,
×
4408
                )
×
4409
                needDBUpdate = true
×
4410
        }
×
4411

4412
        // We only started storing the actual values for MinHTLCOut and MaxHTLC
4413
        // after 0.16.x, so if a channel was opened with such a version and is
4414
        // still pending while updating to this version, we'll need to set the
4415
        // values to the default values.
4416
        if forwardingPolicy.MinHTLCOut == 0 {
45✔
4417
                forwardingPolicy.MinHTLCOut = channel.LocalChanCfg.MinHTLC
16✔
4418
                needDBUpdate = true
16✔
4419
        }
16✔
4420
        if forwardingPolicy.MaxHTLC == 0 {
45✔
4421
                forwardingPolicy.MaxHTLC = channel.LocalChanCfg.MaxPendingAmount
16✔
4422
                needDBUpdate = true
16✔
4423
        }
16✔
4424

4425
        // And finally, if we found that the values currently stored aren't
4426
        // sufficient for the link, we'll update the database.
4427
        if needDBUpdate {
45✔
4428
                err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
16✔
4429
                if err != nil {
16✔
4430
                        return fmt.Errorf("unable to update initial "+
×
4431
                                "forwarding policy: %v", err)
×
4432
                }
×
4433
        }
4434

4435
        return nil
29✔
4436
}
4437

4438
// chanAnnouncement encapsulates the two authenticated announcements that we
4439
// send out to the network after a new channel has been created locally.
4440
type chanAnnouncement struct {
4441
        chanAnn       *lnwire.ChannelAnnouncement1
4442
        chanUpdateAnn *lnwire.ChannelUpdate1
4443
        chanProof     *lnwire.AnnounceSignatures1
4444
}
4445

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

45✔
4461
        chainHash := *f.cfg.Wallet.Cfg.NetParams.GenesisHash
45✔
4462

45✔
4463
        // The unconditional section of the announcement is the ShortChannelID
45✔
4464
        // itself which compactly encodes the location of the funding output
45✔
4465
        // within the blockchain.
45✔
4466
        chanAnn := &lnwire.ChannelAnnouncement1{
45✔
4467
                ShortChannelID: shortChanID,
45✔
4468
                Features:       lnwire.NewRawFeatureVector(),
45✔
4469
                ChainHash:      chainHash,
45✔
4470
        }
45✔
4471

45✔
4472
        // If this is a taproot channel, then we'll set a special bit in the
45✔
4473
        // feature vector to indicate to the routing layer that this needs a
45✔
4474
        // slightly different type of validation.
45✔
4475
        //
45✔
4476
        // TODO(roasbeef): temp, remove after gossip 1.5
45✔
4477
        if chanType.IsTaproot() {
52✔
4478
                log.Debugf("Applying taproot feature bit to "+
7✔
4479
                        "ChannelAnnouncement for %v", chanID)
7✔
4480

7✔
4481
                chanAnn.Features.Set(
7✔
4482
                        lnwire.SimpleTaprootChannelsRequiredStaging,
7✔
4483
                )
7✔
4484
        }
7✔
4485

4486
        // The chanFlags field indicates which directed edge of the channel is
4487
        // being updated within the ChannelUpdateAnnouncement announcement
4488
        // below. A value of zero means it's the edge of the "first" node and 1
4489
        // being the other node.
4490
        var chanFlags lnwire.ChanUpdateChanFlags
45✔
4491

45✔
4492
        // The lexicographical ordering of the two identity public keys of the
45✔
4493
        // nodes indicates which of the nodes is "first". If our serialized
45✔
4494
        // identity key is lower than theirs then we're the "first" node and
45✔
4495
        // second otherwise.
45✔
4496
        selfBytes := localPubKey.SerializeCompressed()
45✔
4497
        remoteBytes := remotePubKey.SerializeCompressed()
45✔
4498
        if bytes.Compare(selfBytes, remoteBytes) == -1 {
69✔
4499
                copy(chanAnn.NodeID1[:], localPubKey.SerializeCompressed())
24✔
4500
                copy(chanAnn.NodeID2[:], remotePubKey.SerializeCompressed())
24✔
4501
                copy(
24✔
4502
                        chanAnn.BitcoinKey1[:],
24✔
4503
                        localFundingKey.PubKey.SerializeCompressed(),
24✔
4504
                )
24✔
4505
                copy(
24✔
4506
                        chanAnn.BitcoinKey2[:],
24✔
4507
                        remoteFundingKey.SerializeCompressed(),
24✔
4508
                )
24✔
4509

24✔
4510
                // If we're the first node then update the chanFlags to
24✔
4511
                // indicate the "direction" of the update.
24✔
4512
                chanFlags = 0
24✔
4513
        } else {
48✔
4514
                copy(chanAnn.NodeID1[:], remotePubKey.SerializeCompressed())
24✔
4515
                copy(chanAnn.NodeID2[:], localPubKey.SerializeCompressed())
24✔
4516
                copy(
24✔
4517
                        chanAnn.BitcoinKey1[:],
24✔
4518
                        remoteFundingKey.SerializeCompressed(),
24✔
4519
                )
24✔
4520
                copy(
24✔
4521
                        chanAnn.BitcoinKey2[:],
24✔
4522
                        localFundingKey.PubKey.SerializeCompressed(),
24✔
4523
                )
24✔
4524

24✔
4525
                // If we're the second node then update the chanFlags to
24✔
4526
                // indicate the "direction" of the update.
24✔
4527
                chanFlags = 1
24✔
4528
        }
24✔
4529

4530
        // Our channel update message flags will signal that we support the
4531
        // max_htlc field.
4532
        msgFlags := lnwire.ChanUpdateRequiredMaxHtlc
45✔
4533

45✔
4534
        // We announce the channel with the default values. Some of
45✔
4535
        // these values can later be changed by crafting a new ChannelUpdate.
45✔
4536
        chanUpdateAnn := &lnwire.ChannelUpdate1{
45✔
4537
                ShortChannelID: shortChanID,
45✔
4538
                ChainHash:      chainHash,
45✔
4539
                Timestamp:      uint32(time.Now().Unix()),
45✔
4540
                MessageFlags:   msgFlags,
45✔
4541
                ChannelFlags:   chanFlags,
45✔
4542
                TimeLockDelta: uint16(
45✔
4543
                        f.cfg.DefaultRoutingPolicy.TimeLockDelta,
45✔
4544
                ),
45✔
4545
                HtlcMinimumMsat: fwdMinHTLC,
45✔
4546
                HtlcMaximumMsat: fwdMaxHTLC,
45✔
4547
        }
45✔
4548

45✔
4549
        // The caller of newChanAnnouncement is expected to provide the initial
45✔
4550
        // forwarding policy to be announced. If no persisted initial policy
45✔
4551
        // values are found, then we will use the default policy values in the
45✔
4552
        // channel announcement.
45✔
4553
        storedFwdingPolicy, err := f.getInitialForwardingPolicy(chanID)
45✔
4554
        if err != nil && !errors.Is(err, channeldb.ErrChannelNotFound) {
45✔
4555
                return nil, fmt.Errorf("unable to generate channel "+
×
4556
                        "update announcement: %w", err)
×
4557
        }
×
4558

4559
        switch {
45✔
4560
        case ourPolicy != nil:
3✔
4561
                // If ourPolicy is non-nil, modify the default parameters of the
3✔
4562
                // ChannelUpdate.
3✔
4563
                chanUpdateAnn.MessageFlags = ourPolicy.MessageFlags
3✔
4564
                chanUpdateAnn.ChannelFlags = ourPolicy.ChannelFlags
3✔
4565
                chanUpdateAnn.TimeLockDelta = ourPolicy.TimeLockDelta
3✔
4566
                chanUpdateAnn.HtlcMinimumMsat = ourPolicy.MinHTLC
3✔
4567
                chanUpdateAnn.HtlcMaximumMsat = ourPolicy.MaxHTLC
3✔
4568
                chanUpdateAnn.BaseFee = uint32(ourPolicy.FeeBaseMSat)
3✔
4569
                chanUpdateAnn.FeeRate = uint32(
3✔
4570
                        ourPolicy.FeeProportionalMillionths,
3✔
4571
                )
3✔
4572

4573
        case storedFwdingPolicy != nil:
45✔
4574
                chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
45✔
4575
                chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
45✔
4576

4577
        default:
×
4578
                log.Infof("No channel forwarding policy specified for channel "+
×
4579
                        "announcement of ChannelID(%v). "+
×
4580
                        "Assuming default fee parameters.", chanID)
×
4581
                chanUpdateAnn.BaseFee = uint32(
×
4582
                        f.cfg.DefaultRoutingPolicy.BaseFee,
×
4583
                )
×
4584
                chanUpdateAnn.FeeRate = uint32(
×
4585
                        f.cfg.DefaultRoutingPolicy.FeeRate,
×
4586
                )
×
4587
        }
4588

4589
        // With the channel update announcement constructed, we'll generate a
4590
        // signature that signs a double-sha digest of the announcement.
4591
        // This'll serve to authenticate this announcement and any other future
4592
        // updates we may send.
4593
        chanUpdateMsg, err := chanUpdateAnn.DataToSign()
45✔
4594
        if err != nil {
45✔
4595
                return nil, err
×
4596
        }
×
4597
        sig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanUpdateMsg, true)
45✔
4598
        if err != nil {
45✔
4599
                return nil, fmt.Errorf("unable to generate channel "+
×
4600
                        "update announcement signature: %w", err)
×
4601
        }
×
4602
        chanUpdateAnn.Signature, err = lnwire.NewSigFromSignature(sig)
45✔
4603
        if err != nil {
45✔
4604
                return nil, fmt.Errorf("unable to generate channel "+
×
4605
                        "update announcement signature: %w", err)
×
4606
        }
×
4607

4608
        // The channel existence proofs itself is currently announced in
4609
        // distinct message. In order to properly authenticate this message, we
4610
        // need two signatures: one under the identity public key used which
4611
        // signs the message itself and another signature of the identity
4612
        // public key under the funding key itself.
4613
        //
4614
        // TODO(roasbeef): use SignAnnouncement here instead?
4615
        chanAnnMsg, err := chanAnn.DataToSign()
45✔
4616
        if err != nil {
45✔
4617
                return nil, err
×
4618
        }
×
4619
        nodeSig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanAnnMsg, true)
45✔
4620
        if err != nil {
45✔
4621
                return nil, fmt.Errorf("unable to generate node "+
×
4622
                        "signature for channel announcement: %w", err)
×
4623
        }
×
4624
        bitcoinSig, err := f.cfg.SignMessage(
45✔
4625
                localFundingKey.KeyLocator, chanAnnMsg, true,
45✔
4626
        )
45✔
4627
        if err != nil {
45✔
4628
                return nil, fmt.Errorf("unable to generate bitcoin "+
×
4629
                        "signature for node public key: %w", err)
×
4630
        }
×
4631

4632
        // Finally, we'll generate the announcement proof which we'll use to
4633
        // provide the other side with the necessary signatures required to
4634
        // allow them to reconstruct the full channel announcement.
4635
        proof := &lnwire.AnnounceSignatures1{
45✔
4636
                ChannelID:      chanID,
45✔
4637
                ShortChannelID: shortChanID,
45✔
4638
        }
45✔
4639
        proof.NodeSignature, err = lnwire.NewSigFromSignature(nodeSig)
45✔
4640
        if err != nil {
45✔
4641
                return nil, err
×
4642
        }
×
4643
        proof.BitcoinSignature, err = lnwire.NewSigFromSignature(bitcoinSig)
45✔
4644
        if err != nil {
45✔
4645
                return nil, err
×
4646
        }
×
4647

4648
        return &chanAnnouncement{
45✔
4649
                chanAnn:       chanAnn,
45✔
4650
                chanUpdateAnn: chanUpdateAnn,
45✔
4651
                chanProof:     proof,
45✔
4652
        }, nil
45✔
4653
}
4654

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

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

4683
        // We only send the channel proof announcement and the node announcement
4684
        // because addToGraph previously sent the ChannelAnnouncement and
4685
        // the ChannelUpdate announcement messages. The channel proof and node
4686
        // announcements are broadcast to the greater network.
4687
        errChan := f.cfg.SendAnnouncement(ann.chanProof)
19✔
4688
        select {
19✔
4689
        case err := <-errChan:
19✔
4690
                if err != nil {
22✔
4691
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4692
                                graph.ErrIgnored) {
3✔
4693

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

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

4707
        // Now that the channel is announced to the network, we will also
4708
        // obtain and send a node announcement. This is done since a node
4709
        // announcement is only accepted after a channel is known for that
4710
        // particular node, and this might be our first channel.
4711
        nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
19✔
4712
        if err != nil {
19✔
4713
                log.Errorf("can't generate node announcement: %v", err)
×
4714
                return err
×
4715
        }
×
4716

4717
        errChan = f.cfg.SendAnnouncement(&nodeAnn)
19✔
4718
        select {
19✔
4719
        case err := <-errChan:
19✔
4720
                if err != nil {
22✔
4721
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4722
                                graph.ErrIgnored) {
6✔
4723

3✔
4724
                                log.Debugf("Graph rejected "+
3✔
4725
                                        "NodeAnnouncement: %v", err)
3✔
4726
                        } else {
3✔
4727
                                log.Errorf("Unable to send node "+
×
4728
                                        "announcement: %v", err)
×
4729
                                return err
×
4730
                        }
×
4731
                }
4732

4733
        case <-f.quit:
×
4734
                return ErrFundingManagerShuttingDown
×
4735
        }
4736

4737
        return nil
19✔
4738
}
4739

4740
// InitFundingWorkflow sends a message to the funding manager instructing it
4741
// to initiate a single funder workflow with the source peer.
4742
func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg) {
60✔
4743
        f.fundingRequests <- msg
60✔
4744
}
60✔
4745

4746
// getUpfrontShutdownScript takes a user provided script and a getScript
4747
// function which can be used to generate an upfront shutdown script. If our
4748
// peer does not support the feature, this function will error if a non-zero
4749
// script was provided by the user, and return an empty script otherwise. If
4750
// our peer does support the feature, we will return the user provided script
4751
// if non-zero, or a freshly generated script if our node is configured to set
4752
// upfront shutdown scripts automatically.
4753
func getUpfrontShutdownScript(enableUpfrontShutdown bool, peer lnpeer.Peer,
4754
        script lnwire.DeliveryAddress,
4755
        getScript func(bool) (lnwire.DeliveryAddress, error)) (lnwire.DeliveryAddress,
4756
        error) {
113✔
4757

113✔
4758
        // Check whether the remote peer supports upfront shutdown scripts.
113✔
4759
        remoteUpfrontShutdown := peer.RemoteFeatures().HasFeature(
113✔
4760
                lnwire.UpfrontShutdownScriptOptional,
113✔
4761
        )
113✔
4762

113✔
4763
        // If the peer does not support upfront shutdown scripts, and one has been
113✔
4764
        // provided, return an error because the feature is not supported.
113✔
4765
        if !remoteUpfrontShutdown && len(script) != 0 {
114✔
4766
                return nil, errUpfrontShutdownScriptNotSupported
1✔
4767
        }
1✔
4768

4769
        // If the peer does not support upfront shutdown, return an empty address.
4770
        if !remoteUpfrontShutdown {
217✔
4771
                return nil, nil
105✔
4772
        }
105✔
4773

4774
        // If the user has provided an script and the peer supports the feature,
4775
        // return it. Note that user set scripts override the enable upfront
4776
        // shutdown flag.
4777
        if len(script) > 0 {
12✔
4778
                return script, nil
5✔
4779
        }
5✔
4780

4781
        // If we do not have setting of upfront shutdown script enabled, return
4782
        // an empty script.
4783
        if !enableUpfrontShutdown {
9✔
4784
                return nil, nil
4✔
4785
        }
4✔
4786

4787
        // We can safely send a taproot address iff, both sides have negotiated
4788
        // the shutdown-any-segwit feature.
4789
        taprootOK := peer.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
1✔
4790
                peer.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
1✔
4791

1✔
4792
        return getScript(taprootOK)
1✔
4793
}
4794

4795
// handleInitFundingMsg creates a channel reservation within the daemon's
4796
// wallet, then sends a funding request to the remote peer kicking off the
4797
// funding workflow.
4798
func (f *Manager) handleInitFundingMsg(msg *InitFundingMsg) {
60✔
4799
        var (
60✔
4800
                peerKey        = msg.Peer.IdentityKey()
60✔
4801
                localAmt       = msg.LocalFundingAmt
60✔
4802
                baseFee        = msg.BaseFee
60✔
4803
                feeRate        = msg.FeeRate
60✔
4804
                minHtlcIn      = msg.MinHtlcIn
60✔
4805
                remoteCsvDelay = msg.RemoteCsvDelay
60✔
4806
                maxValue       = msg.MaxValueInFlight
60✔
4807
                maxHtlcs       = msg.MaxHtlcs
60✔
4808
                maxCSV         = msg.MaxLocalCsv
60✔
4809
                chanReserve    = msg.RemoteChanReserve
60✔
4810
                outpoints      = msg.Outpoints
60✔
4811
        )
60✔
4812

60✔
4813
        // If no maximum CSV delay was set for this channel, we use our default
60✔
4814
        // value.
60✔
4815
        if maxCSV == 0 {
120✔
4816
                maxCSV = f.cfg.MaxLocalCSVDelay
60✔
4817
        }
60✔
4818

4819
        log.Infof("Initiating fundingRequest(local_amt=%v "+
60✔
4820
                "(subtract_fees=%v), push_amt=%v, chain_hash=%v, peer=%x, "+
60✔
4821
                "min_confs=%v)", localAmt, msg.SubtractFees, msg.PushAmt,
60✔
4822
                msg.ChainHash, peerKey.SerializeCompressed(), msg.MinConfs)
60✔
4823

60✔
4824
        // We set the channel flags to indicate whether we want this channel to
60✔
4825
        // be announced to the network.
60✔
4826
        var channelFlags lnwire.FundingFlag
60✔
4827
        if !msg.Private {
115✔
4828
                // This channel will be announced.
55✔
4829
                channelFlags = lnwire.FFAnnounceChannel
55✔
4830
        }
55✔
4831

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

4850
        // If the funder did not provide an upfront-shutdown address, fall back
4851
        // to the configured shutdown script (if any).
4852
        if len(msg.ShutdownScript) == 0 {
120✔
4853
                msg.ShutdownScript = f.cfg.ShutdownScript
60✔
4854
        }
60✔
4855

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

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

4886
        var (
60✔
4887
                zeroConf bool
60✔
4888
                scid     bool
60✔
4889
        )
60✔
4890

60✔
4891
        if chanType != nil {
67✔
4892
                // Check if the returned chanType includes either the zero-conf
7✔
4893
                // or scid-alias bits.
7✔
4894
                featureVec := lnwire.RawFeatureVector(*chanType)
7✔
4895
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
7✔
4896
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
7✔
4897

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

×
4906
                        return
×
4907
                }
×
4908
        }
4909

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

4920
        // For anchor channels cap the initial commit fee rate at our defined
4921
        // maximum.
4922
        if commitType.HasAnchors() &&
60✔
4923
                commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
67✔
4924

7✔
4925
                commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate
7✔
4926
        }
7✔
4927

4928
        var scidFeatureVal bool
60✔
4929
        if hasFeatures(
60✔
4930
                msg.Peer.LocalFeatures(), msg.Peer.RemoteFeatures(),
60✔
4931
                lnwire.ScidAliasOptional,
60✔
4932
        ) {
66✔
4933

6✔
4934
                scidFeatureVal = true
6✔
4935
        }
6✔
4936

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

×
4951
                return
×
4952
        }
×
4953

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

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

4996
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
60✔
4997
        if err != nil {
63✔
4998
                msg.Err <- err
3✔
4999
                return
3✔
5000
        }
3✔
5001

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

5011
                reservation.AddAlias(aliasScid)
5✔
5012
        }
5013

5014
        // Set our upfront shutdown address in the existing reservation.
5015
        reservation.SetOurUpfrontShutdown(shutdown)
60✔
5016

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

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

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

5033
        // If no minimum HTLC value was specified, use the default one.
5034
        if minHtlcIn == 0 {
119✔
5035
                minHtlcIn = f.cfg.DefaultMinHtlcIn
59✔
5036
        }
59✔
5037

5038
        // If no max value was specified, use the default one.
5039
        if maxValue == 0 {
119✔
5040
                maxValue = f.cfg.RequiredRemoteMaxValue(capacity)
59✔
5041
        }
59✔
5042

5043
        if maxHtlcs == 0 {
120✔
5044
                maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
60✔
5045
        }
60✔
5046

5047
        // Once the reservation has been created, and indexed, queue a funding
5048
        // request to the remote peer, kicking off the funding workflow.
5049
        ourContribution := reservation.OurContribution()
60✔
5050

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

5061
        if feeRate != nil {
64✔
5062
                forwardingPolicy.FeeRate = lnwire.MilliSatoshi(*feeRate)
4✔
5063
        }
4✔
5064

5065
        // Fetch our dust limit which is part of the default channel
5066
        // constraints, and log it.
5067
        ourDustLimit := ourContribution.DustLimit
60✔
5068

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

60✔
5071
        // If the channel reserve is not specified, then we calculate an
60✔
5072
        // appropriate amount here.
60✔
5073
        if chanReserve == 0 {
116✔
5074
                chanReserve = f.cfg.RequiredRemoteChanReserve(
56✔
5075
                        capacity, ourDustLimit,
56✔
5076
                )
56✔
5077
        }
56✔
5078

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

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

60✔
5106
        // Update the timestamp once the InitFundingMsg has been handled.
60✔
5107
        defer resCtx.updateTimestamp()
60✔
5108

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

5130
                msg.Err <- err
2✔
5131
                return
2✔
5132
        }
5133

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

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

58✔
5145
        reservation.SetState(lnwallet.SentOpenChannel)
58✔
5146

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

58✔
5171
        if commitType.IsTaproot() {
63✔
5172
                fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
5✔
5173
                        ourContribution.LocalNonce.PubNonce,
5✔
5174
                )
5✔
5175
        }
5✔
5176

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

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

5189
                msg.Err <- e
×
5190
                return
×
5191
        }
5192
}
5193

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

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

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

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

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

5232
        resCtx.err <- fundingErr
3✔
5233
}
5234

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

6✔
5241
        f.resMtx.RLock()
6✔
5242
        for _, pendingReservations := range f.activeReservations {
12✔
5243
                for pendingChanID, resCtx := range pendingReservations {
12✔
5244
                        if resCtx.isLocked() {
6✔
5245
                                continue
×
5246
                        }
5247

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

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

6✔
5269
                chanID := lnwire.NewChanIDFromOutPoint(
6✔
5270
                        *resCtx.reservation.FundingOutpoint(),
6✔
5271
                )
6✔
5272

6✔
5273
                // Create channel identifier and set the channel ID.
6✔
5274
                cid := newChanIdentifier(pendingChanID)
6✔
5275
                cid.setChanID(chanID)
6✔
5276

6✔
5277
                f.failFundingFlow(resCtx.peer, cid, err)
6✔
5278
        }
6✔
5279
}
5280

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

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

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

26✔
5294
        nodeReservations, ok := f.activeReservations[peerIDKey]
26✔
5295
        if !ok {
36✔
5296
                // No reservations for this node.
10✔
5297
                return nil, fmt.Errorf("no active reservations for peer(%x)",
10✔
5298
                        peerIDKey[:])
10✔
5299
        }
10✔
5300

5301
        ctx, ok := nodeReservations[pendingChanID]
19✔
5302
        if !ok {
21✔
5303
                return nil, fmt.Errorf("unknown channel (id: %x) for "+
2✔
5304
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
2✔
5305
        }
2✔
5306

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

5315
        if err := ctx.reservation.Cancel(); err != nil {
17✔
5316
                return nil, fmt.Errorf("unable to cancel reservation: %w", err)
×
5317
        }
×
5318

5319
        delete(nodeReservations, pendingChanID)
17✔
5320

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

5329
// deleteReservationCtx deletes the reservation uniquely identified by the
5330
// target public key of the peer, and the specified pending channel ID.
5331
func (f *Manager) deleteReservationCtx(peerKey *btcec.PublicKey,
5332
        pendingChanID PendingChanID) {
59✔
5333

59✔
5334
        peerIDKey := newSerializedKey(peerKey)
59✔
5335
        f.resMtx.Lock()
59✔
5336
        defer f.resMtx.Unlock()
59✔
5337

59✔
5338
        nodeReservations, ok := f.activeReservations[peerIDKey]
59✔
5339
        if !ok {
59✔
5340
                // No reservations for this node.
×
5341
                return
×
5342
        }
×
5343
        delete(nodeReservations, pendingChanID)
59✔
5344

59✔
5345
        // If this was the last active reservation for this peer, delete the
59✔
5346
        // peer's entry altogether.
59✔
5347
        if len(nodeReservations) == 0 {
111✔
5348
                delete(f.activeReservations, peerIDKey)
52✔
5349
        }
52✔
5350
}
5351

5352
// getReservationCtx returns the reservation context for a particular pending
5353
// channel ID for a target peer.
5354
func (f *Manager) getReservationCtx(peerKey *btcec.PublicKey,
5355
        pendingChanID PendingChanID) (*reservationWithCtx, error) {
94✔
5356

94✔
5357
        peerIDKey := newSerializedKey(peerKey)
94✔
5358
        f.resMtx.RLock()
94✔
5359
        resCtx, ok := f.activeReservations[peerIDKey][pendingChanID]
94✔
5360
        f.resMtx.RUnlock()
94✔
5361

94✔
5362
        if !ok {
97✔
5363
                return nil, fmt.Errorf("unknown channel (id: %x) for "+
3✔
5364
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
3✔
5365
        }
3✔
5366

5367
        return resCtx, nil
94✔
5368
}
5369

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

3✔
5378
        peerIDKey := newSerializedKey(peer.IdentityKey())
3✔
5379
        f.resMtx.RLock()
3✔
5380
        _, ok := f.activeReservations[peerIDKey][pendingChanID]
3✔
5381
        f.resMtx.RUnlock()
3✔
5382

3✔
5383
        return ok
3✔
5384
}
3✔
5385

5386
func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
388✔
5387
        var tmp btcec.JacobianPoint
388✔
5388
        pub.AsJacobian(&tmp)
388✔
5389
        tmp.ToAffine()
388✔
5390
        return btcec.NewPublicKey(&tmp.X, &tmp.Y)
388✔
5391
}
388✔
5392

5393
// defaultForwardingPolicy returns the default forwarding policy based on the
5394
// default routing policy and our local channel constraints.
5395
func (f *Manager) defaultForwardingPolicy(
5396
        bounds channeldb.ChannelStateBounds) *models.ForwardingPolicy {
107✔
5397

107✔
5398
        return &models.ForwardingPolicy{
107✔
5399
                MinHTLCOut:    bounds.MinHTLC,
107✔
5400
                MaxHTLC:       bounds.MaxPendingAmount,
107✔
5401
                BaseFee:       f.cfg.DefaultRoutingPolicy.BaseFee,
107✔
5402
                FeeRate:       f.cfg.DefaultRoutingPolicy.FeeRate,
107✔
5403
                TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
107✔
5404
        }
107✔
5405
}
107✔
5406

5407
// saveInitialForwardingPolicy saves the forwarding policy for the provided
5408
// chanPoint in the channelOpeningStateBucket.
5409
func (f *Manager) saveInitialForwardingPolicy(chanID lnwire.ChannelID,
5410
        forwardingPolicy *models.ForwardingPolicy) error {
72✔
5411

72✔
5412
        return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
72✔
5413
                chanID, forwardingPolicy,
72✔
5414
        )
72✔
5415
}
72✔
5416

5417
// getInitialForwardingPolicy fetches the initial forwarding policy for a given
5418
// channel id from the database which will be applied during the channel
5419
// announcement phase.
5420
func (f *Manager) getInitialForwardingPolicy(
5421
        chanID lnwire.ChannelID) (*models.ForwardingPolicy, error) {
97✔
5422

97✔
5423
        return f.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
97✔
5424
}
97✔
5425

5426
// deleteInitialForwardingPolicy removes channel fees for this chanID from
5427
// the database.
5428
func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
27✔
5429
        return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
27✔
5430
}
27✔
5431

5432
// saveChannelOpeningState saves the channelOpeningState for the provided
5433
// chanPoint to the channelOpeningStateBucket.
5434
func (f *Manager) saveChannelOpeningState(chanPoint *wire.OutPoint,
5435
        state channelOpeningState, shortChanID *lnwire.ShortChannelID) error {
95✔
5436

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

5442
        // Save state and the uint64 representation of the shortChanID
5443
        // for later use.
5444
        scratch := make([]byte, 10)
95✔
5445
        byteOrder.PutUint16(scratch[:2], uint16(state))
95✔
5446
        byteOrder.PutUint64(scratch[2:], shortChanID.ToUint64())
95✔
5447

95✔
5448
        return f.cfg.ChannelDB.SaveChannelOpeningState(
95✔
5449
                outpointBytes.Bytes(), scratch,
95✔
5450
        )
95✔
5451
}
5452

5453
// getChannelOpeningState fetches the channelOpeningState for the provided
5454
// chanPoint from the database, or returns ErrChannelNotFound if the channel
5455
// is not found.
5456
func (f *Manager) getChannelOpeningState(chanPoint *wire.OutPoint) (
5457
        channelOpeningState, *lnwire.ShortChannelID, error) {
256✔
5458

256✔
5459
        var outpointBytes bytes.Buffer
256✔
5460
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
256✔
5461
                return 0, nil, err
×
5462
        }
×
5463

5464
        value, err := f.cfg.ChannelDB.GetChannelOpeningState(
256✔
5465
                outpointBytes.Bytes(),
256✔
5466
        )
256✔
5467
        if err != nil {
308✔
5468
                return 0, nil, err
52✔
5469
        }
52✔
5470

5471
        state := channelOpeningState(byteOrder.Uint16(value[:2]))
207✔
5472
        shortChanID := lnwire.NewShortChanIDFromInt(byteOrder.Uint64(value[2:]))
207✔
5473
        return state, &shortChanID, nil
207✔
5474
}
5475

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

5483
        return f.cfg.ChannelDB.DeleteChannelOpeningState(
27✔
5484
                outpointBytes.Bytes(),
27✔
5485
        )
27✔
5486
}
5487

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

×
5494
        addrType := lnwallet.WitnessPubKey
×
5495
        if taprootOK {
×
5496
                addrType = lnwallet.TaprootPubkey
×
5497
        }
×
5498

5499
        addr, err := f.cfg.Wallet.NewAddress(
×
5500
                addrType, false, lnwallet.DefaultAccountName,
×
5501
        )
×
5502
        if err != nil {
×
5503
                return nil, err
×
5504
        }
×
5505

5506
        return txscript.PayToAddrScript(addr)
×
5507
}
5508

5509
// waitForPeerOnline blocks until the peer specified by peerPubkey comes online
5510
// and then returns the online peer.
5511
func (f *Manager) waitForPeerOnline(peerPubkey *btcec.PublicKey) (lnpeer.Peer,
5512
        error) {
106✔
5513

106✔
5514
        peerChan := make(chan lnpeer.Peer, 1)
106✔
5515

106✔
5516
        var peerKey [33]byte
106✔
5517
        copy(peerKey[:], peerPubkey.SerializeCompressed())
106✔
5518

106✔
5519
        f.cfg.NotifyWhenOnline(peerKey, peerChan)
106✔
5520

106✔
5521
        var peer lnpeer.Peer
106✔
5522
        select {
106✔
5523
        case peer = <-peerChan:
105✔
5524
        case <-f.quit:
1✔
5525
                return peer, ErrFundingManagerShuttingDown
1✔
5526
        }
5527
        return peer, nil
105✔
5528
}
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