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

lightningnetwork / lnd / 19924300449

04 Dec 2025 09:35AM UTC coverage: 53.479% (-1.9%) from 55.404%
19924300449

Pull #10419

github

web-flow
Merge f811805c6 into 20473482d
Pull Request #10419: [docs] Document use-native-sql=true for SQL migration step 2

110496 of 206616 relevant lines covered (53.48%)

21221.61 hits per line

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

67.8
/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 {
369✔
66
        scratch := make([]byte, 4)
369✔
67

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

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

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

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

137✔
186
        r.lastUpdated = time.Now()
137✔
187
}
137✔
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 {
389✔
326
        var s serializedPubKey
389✔
327
        copy(s[:], pubKey.SerializeCompressed())
389✔
328
        return s
389✔
329
}
389✔
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.NodeAnnouncement1, 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
        // AuxChannelNegotiator is an optional interface that allows aux channel
573
        // implementations to inject and process custom records over channel
574
        // related wire messages.
575
        AuxChannelNegotiator fn.Option[lnwallet.AuxChannelNegotiator]
576

577
        // ShutdownScript is an optional upfront-shutdown script to which our
578
        // funds should be paid on a cooperative close.
579
        ShutdownScript fn.Option[lnwire.DeliveryAddress]
580
}
581

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

595
        // cfg is a copy of the configuration struct that the FundingManager
596
        // was initialized with.
597
        cfg *Config
598

599
        // chanIDKey is a cryptographically random key that's used to generate
600
        // temporary channel ID's.
601
        chanIDKey [32]byte
602

603
        // chanIDNonce is a nonce that's incremented for each new funding
604
        // reservation created.
605
        chanIDNonce atomic.Uint64
606

607
        // nonceMtx is a mutex that guards the pendingMusigNonces.
608
        nonceMtx sync.RWMutex
609

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

621
        // activeReservations is a map which houses the state of all pending
622
        // funding workflows.
623
        activeReservations map[serializedPubKey]pendingChannels
624

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

632
        // resMtx guards both of the maps above to ensure that all access is
633
        // goroutine safe.
634
        resMtx sync.RWMutex
635

636
        // fundingMsgs is a channel that relays fundingMsg structs from
637
        // external sub-systems using the ProcessFundingMsg call.
638
        fundingMsgs chan *fundingMsg
639

640
        // fundingRequests is a channel used to receive channel initiation
641
        // requests from a local subsystem within the daemon.
642
        fundingRequests chan *InitFundingMsg
643

644
        localDiscoverySignals *lnutils.SyncMap[lnwire.ChannelID, chan struct{}]
645

646
        handleChannelReadyBarriers *lnutils.SyncMap[lnwire.ChannelID, struct{}]
647

648
        quit chan struct{}
649
        wg   sync.WaitGroup
650
}
651

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

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

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

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

675
func (c channelOpeningState) String() string {
×
676
        switch c {
×
677
        case markedOpen:
×
678
                return "markedOpen"
×
679
        case channelReadySent:
×
680
                return "channelReadySent"
×
681
        case addedToGraph:
×
682
                return "addedToGraph"
×
683
        default:
×
684
                return "unknown"
×
685
        }
686
}
687

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

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

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

742
        for _, channel := range allChannels {
118✔
743
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
9✔
744

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

1✔
754
                        f.localDiscoverySignals.Store(
1✔
755
                                chanID, make(chan struct{}),
1✔
756
                        )
1✔
757

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

1✔
766
                                f.rebroadcastFundingTx(channel)
1✔
767
                        }
1✔
768
                } else if channel.ChanType.IsSingleFunder() &&
8✔
769
                        channel.ChanType.HasFundingTx() &&
8✔
770
                        channel.IsZeroConf() && channel.IsInitiator &&
8✔
771
                        !channel.ZeroConfConfirmed() {
10✔
772

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

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

787
        f.wg.Add(1) // TODO(roasbeef): tune
109✔
788
        go f.reservationCoordinator()
109✔
789

109✔
790
        return nil
109✔
791
}
792

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

105✔
800
                close(f.quit)
105✔
801
                f.wg.Wait()
105✔
802
        })
105✔
803

804
        return nil
106✔
805
}
806

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

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

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

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

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

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

57✔
847
        var nonceBytes [8]byte
57✔
848
        binary.LittleEndian.PutUint64(nonceBytes[:], nextNonce)
57✔
849

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

57✔
860
        return nextChanID
57✔
861
}
57✔
862

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

×
869
        f.resMtx.Lock()
×
870
        defer f.resMtx.Unlock()
×
871

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

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

890
                resCtx.err <- fmt.Errorf("peer disconnected")
×
891
                delete(nodeReservations, pendingID)
×
892
        }
893

894
        // Finally, we'll delete the node itself from the set of reservations.
895
        delete(f.activeReservations, nodePub)
×
896
}
897

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

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

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

922
// newChanIdentifier creates a new chanIdentifier.
923
func newChanIdentifier(tempChanID lnwire.ChannelID) *chanIdentifier {
148✔
924
        return &chanIdentifier{
148✔
925
                tempChanID: tempChanID,
148✔
926
        }
148✔
927
}
148✔
928

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

935
// hasChanID returns true if the active channel ID has been set.
936
func (c *chanIdentifier) hasChanID() bool {
21✔
937
        return c.chanIDSet
21✔
938
}
21✔
939

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

21✔
950
        log.Debugf("Failing funding flow for pending_id=%v: %v",
21✔
951
                cid.tempChanID, fundingErr)
21✔
952

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

966
        ctx, err := f.cancelReservationCtx(
21✔
967
                peer.IdentityKey(), cid.tempChanID, false,
21✔
968
        )
21✔
969
        if err != nil {
30✔
970
                log.Errorf("unable to cancel reservation: %v", err)
9✔
971
        }
9✔
972

973
        // In case the case where the reservation existed, send the funding
974
        // error on the error channel.
975
        if ctx != nil {
33✔
976
                ctx.err <- fundingErr
12✔
977
        }
12✔
978

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

992
        // For all other error types we just send a generic error.
993
        default:
12✔
994
                msg = lnwire.ErrorData("funding failed due to internal error")
12✔
995
        }
996

997
        errMsg := &lnwire.Error{
21✔
998
                ChanID: cid.tempChanID,
21✔
999
                Data:   msg,
21✔
1000
        }
21✔
1001

21✔
1002
        log.Debugf("Sending funding error to peer (%x): %v",
21✔
1003
                peer.IdentityKey().SerializeCompressed(),
21✔
1004
                lnutils.SpewLogClosure(errMsg))
21✔
1005

21✔
1006
        if err := peer.SendMessage(false, errMsg); err != nil {
21✔
1007
                log.Errorf("unable to send error message to peer %v", err)
×
1008
        }
×
1009
}
1010

1011
// sendWarning sends a new warning message to the target peer, targeting the
1012
// specified cid with the passed funding error.
1013
func (f *Manager) sendWarning(peer lnpeer.Peer, cid *chanIdentifier,
1014
        fundingErr error) {
×
1015

×
1016
        msg := fundingErr.Error()
×
1017

×
1018
        errMsg := &lnwire.Warning{
×
1019
                ChanID: cid.tempChanID,
×
1020
                Data:   lnwire.WarningData(msg),
×
1021
        }
×
1022

×
1023
        log.Debugf("Sending funding warning to peer (%x): %v",
×
1024
                peer.IdentityKey().SerializeCompressed(),
×
1025
                lnutils.SpewLogClosure(errMsg),
×
1026
        )
×
1027

×
1028
        if err := peer.SendMessage(false, errMsg); err != nil {
×
1029
                log.Errorf("unable to send error message to peer %v", err)
×
1030
        }
×
1031
}
1032

1033
// reservationCoordinator is the primary goroutine tasked with progressing the
1034
// funding workflow between the wallet, and any outside peers or local callers.
1035
//
1036
// NOTE: This MUST be run as a goroutine.
1037
func (f *Manager) reservationCoordinator() {
109✔
1038
        defer f.wg.Done()
109✔
1039

109✔
1040
        zombieSweepTicker := time.NewTicker(f.cfg.ZombieSweeperInterval)
109✔
1041
        defer zombieSweepTicker.Stop()
109✔
1042

109✔
1043
        for {
490✔
1044
                select {
381✔
1045
                case fmsg := <-f.fundingMsgs:
215✔
1046
                        switch msg := fmsg.msg.(type) {
215✔
1047
                        case *lnwire.OpenChannel:
54✔
1048
                                f.fundeeProcessOpenChannel(fmsg.peer, msg)
54✔
1049

1050
                        case *lnwire.AcceptChannel:
33✔
1051
                                f.funderProcessAcceptChannel(fmsg.peer, msg)
33✔
1052

1053
                        case *lnwire.FundingCreated:
28✔
1054
                                f.fundeeProcessFundingCreated(fmsg.peer, msg)
28✔
1055

1056
                        case *lnwire.FundingSigned:
28✔
1057
                                f.funderProcessFundingSigned(fmsg.peer, msg)
28✔
1058

1059
                        case *lnwire.ChannelReady:
28✔
1060
                                f.wg.Add(1)
28✔
1061
                                go f.handleChannelReady(fmsg.peer, msg)
28✔
1062

1063
                        case *lnwire.Warning:
44✔
1064
                                f.handleWarningMsg(fmsg.peer, msg)
44✔
1065

1066
                        case *lnwire.Error:
×
1067
                                f.handleErrorMsg(fmsg.peer, msg)
×
1068
                        }
1069
                case req := <-f.fundingRequests:
57✔
1070
                        f.handleInitFundingMsg(req)
57✔
1071

1072
                case <-zombieSweepTicker.C:
×
1073
                        f.pruneZombieReservations()
×
1074

1075
                case <-f.quit:
105✔
1076
                        return
105✔
1077
                }
1078
        }
1079
}
1080

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

65✔
1093
        defer f.wg.Done()
65✔
1094

65✔
1095
        // If the channel is still pending we must wait for the funding
65✔
1096
        // transaction to confirm.
65✔
1097
        if channel.IsPending {
122✔
1098
                err := f.advancePendingChannelState(channel, pendingChanID)
57✔
1099
                if err != nil {
80✔
1100
                        log.Errorf("Unable to advance pending state of "+
23✔
1101
                                "ChannelPoint(%v): %v",
23✔
1102
                                channel.FundingOutpoint, err)
23✔
1103
                        return
23✔
1104
                }
23✔
1105
        }
1106

1107
        var chanOpts []lnwallet.ChannelOpt
42✔
1108
        f.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
84✔
1109
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
42✔
1110
        })
42✔
1111
        f.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
84✔
1112
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
42✔
1113
        })
42✔
1114
        f.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
42✔
1115
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
1116
        })
×
1117

1118
        // We create the state-machine object which wraps the database state.
1119
        lnChannel, err := lnwallet.NewLightningChannel(
42✔
1120
                nil, channel, nil, chanOpts...,
42✔
1121
        )
42✔
1122
        if err != nil {
42✔
1123
                log.Errorf("Unable to create LightningChannel(%v): %v",
×
1124
                        channel.FundingOutpoint, err)
×
1125
                return
×
1126
        }
×
1127

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

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

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

123✔
1176
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
123✔
1177
        log.Debugf("Channel(%v) with ShortChanID %v has opening state %v",
123✔
1178
                chanID, shortChanID, channelState)
123✔
1179

123✔
1180
        switch channelState {
123✔
1181
        // The funding transaction was confirmed, but we did not successfully
1182
        // send the channelReady message to the peer, so let's do that now.
1183
        case markedOpen:
35✔
1184
                err := f.sendChannelReady(channel, lnChannel)
35✔
1185
                if err != nil {
36✔
1186
                        return fmt.Errorf("failed sending channelReady: %w",
1✔
1187
                                err)
1✔
1188
                }
1✔
1189

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

1203
                log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
34✔
1204
                        "sent ChannelReady", chanID, shortChanID)
34✔
1205

34✔
1206
                return nil
34✔
1207

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

1221
                if !received {
94✔
1222
                        // We haven't received ChannelReady, so we'll continue
35✔
1223
                        // to the next iteration of the loop after sleeping for
35✔
1224
                        // checkPeerChannelReadyInterval.
35✔
1225
                        select {
35✔
1226
                        case <-time.After(checkPeerChannelReadyInterval):
24✔
1227
                        case <-f.quit:
11✔
1228
                                return ErrFundingManagerShuttingDown
11✔
1229
                        }
1230

1231
                        return nil
24✔
1232
                }
1233

1234
                return f.handleChannelReadyReceived(
24✔
1235
                        channel, shortChanID, pendingChanID, updateChan,
24✔
1236
                )
24✔
1237

1238
        // The channel was added to the Router's topology, but the channel
1239
        // announcement was not sent.
1240
        case addedToGraph:
28✔
1241
                if channel.IsZeroConf() {
34✔
1242
                        // If this is a zero-conf channel, then we will wait
6✔
1243
                        // for it to be confirmed before announcing it to the
6✔
1244
                        // greater network.
6✔
1245
                        err := f.waitForZeroConfChannel(channel)
6✔
1246
                        if err != nil {
8✔
1247
                                return fmt.Errorf("failed waiting for zero "+
2✔
1248
                                        "channel: %v", err)
2✔
1249
                        }
2✔
1250

1251
                        // Update the local shortChanID variable such that
1252
                        // annAfterSixConfs uses the confirmed SCID.
1253
                        confirmedScid := channel.ZeroConfRealScid()
4✔
1254
                        shortChanID = &confirmedScid
4✔
1255
                }
1256

1257
                err := f.annAfterSixConfs(channel, shortChanID)
26✔
1258
                if err != nil {
28✔
1259
                        return fmt.Errorf("error sending channel "+
2✔
1260
                                "announcement: %v", err)
2✔
1261
                }
2✔
1262

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

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

1284
                log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
24✔
1285
                        "announced", chanID, shortChanID)
24✔
1286

24✔
1287
                return nil
24✔
1288
        }
1289

1290
        return fmt.Errorf("undefined channelState: %v", channelState)
×
1291
}
1292

1293
// advancePendingChannelState waits for a pending channel's funding tx to
1294
// confirm, and marks it open in the database when that happens.
1295
func (f *Manager) advancePendingChannelState(channel *channeldb.OpenChannel,
1296
        pendingChanID PendingChanID) error {
57✔
1297

57✔
1298
        if channel.IsZeroConf() {
61✔
1299
                // Persist the alias to the alias database.
4✔
1300
                baseScid := channel.ShortChannelID
4✔
1301
                err := f.cfg.AliasManager.AddLocalAlias(
4✔
1302
                        baseScid, baseScid, true, false,
4✔
1303
                )
4✔
1304
                if err != nil {
4✔
1305
                        return fmt.Errorf("error adding local alias to "+
×
1306
                                "store: %v", err)
×
1307
                }
×
1308

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

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

1330
                // Inform the ChannelNotifier that the channel has transitioned
1331
                // from pending open to open.
1332
                f.cfg.NotifyOpenChannelEvent(
4✔
1333
                        channel.FundingOutpoint, channel.IdentityPub,
4✔
1334
                )
4✔
1335

4✔
1336
                // Find and close the discoverySignal for this channel such
4✔
1337
                // that ChannelReady messages will be processed.
4✔
1338
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
4✔
1339
                discoverySignal, ok := f.localDiscoverySignals.Load(chanID)
4✔
1340
                if ok {
8✔
1341
                        close(discoverySignal)
4✔
1342
                }
4✔
1343

1344
                return nil
4✔
1345
        }
1346

1347
        confChannel, err := f.waitForFundingWithTimeout(channel)
53✔
1348
        if err == ErrConfirmationTimeout {
55✔
1349
                return f.fundingTimeout(channel, pendingChanID)
2✔
1350
        } else if err != nil {
74✔
1351
                return fmt.Errorf("error waiting for funding "+
21✔
1352
                        "confirmation for ChannelPoint(%v): %v",
21✔
1353
                        channel.FundingOutpoint, err)
21✔
1354
        }
21✔
1355

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

2✔
1363
                if channel.NumConfsRequired > maturity {
2✔
1364
                        numCoinbaseConfs = uint32(channel.NumConfsRequired)
×
1365
                }
×
1366

1367
                txid := &channel.FundingOutpoint.Hash
2✔
1368
                fundingScript, err := makeFundingScript(channel)
2✔
1369
                if err != nil {
2✔
1370
                        log.Errorf("unable to create funding script for "+
×
1371
                                "ChannelPoint(%v): %v",
×
1372
                                channel.FundingOutpoint, err)
×
1373

×
1374
                        return err
×
1375
                }
×
1376

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

×
1386
                        return err
×
1387
                }
×
1388

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

1398
                case <-f.quit:
×
1399
                        return ErrFundingManagerShuttingDown
×
1400
                }
1401
        }
1402

1403
        // Success, funding transaction was confirmed.
1404
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
30✔
1405
        log.Debugf("ChannelID(%v) is now fully confirmed! "+
30✔
1406
                "(shortChanID=%v)", chanID, confChannel.shortChanID)
30✔
1407

30✔
1408
        err = f.handleFundingConfirmation(channel, confChannel)
30✔
1409
        if err != nil {
30✔
1410
                return fmt.Errorf("unable to handle funding "+
×
1411
                        "confirmation for ChannelPoint(%v): %v",
×
1412
                        channel.FundingOutpoint, err)
×
1413
        }
×
1414

1415
        return nil
30✔
1416
}
1417

1418
// ProcessFundingMsg sends a message to the internal fundingManager goroutine,
1419
// allowing it to handle the lnwire.Message.
1420
func (f *Manager) ProcessFundingMsg(msg lnwire.Message, peer lnpeer.Peer) {
216✔
1421
        select {
216✔
1422
        case f.fundingMsgs <- &fundingMsg{msg, peer}:
216✔
1423
        case <-f.quit:
×
1424
                return
×
1425
        }
1426
}
1427

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

54✔
1439
        // Check number of pending channels to be smaller than maximum allowed
54✔
1440
        // number and send ErrorGeneric to remote peer if condition is
54✔
1441
        // violated.
54✔
1442
        peerPubKey := peer.IdentityKey()
54✔
1443
        peerIDKey := newSerializedKey(peerPubKey)
54✔
1444

54✔
1445
        amt := msg.FundingAmount
54✔
1446

54✔
1447
        // We get all pending channels for this peer. This is the list of the
54✔
1448
        // active reservations and the channels pending open in the database.
54✔
1449
        f.resMtx.RLock()
54✔
1450
        reservations := f.activeReservations[peerIDKey]
54✔
1451

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

54✔
1463
        // Create the channel identifier.
54✔
1464
        cid := newChanIdentifier(msg.PendingChannelID)
54✔
1465

54✔
1466
        // Also count the channels that are already pending. There we don't know
54✔
1467
        // the underlying intent anymore, unfortunately.
54✔
1468
        channels, err := f.cfg.ChannelDB.FetchOpenChannels(peerPubKey)
54✔
1469
        if err != nil {
54✔
1470
                f.failFundingFlow(peer, cid, err)
×
1471
                return
×
1472
        }
×
1473

1474
        for _, c := range channels {
66✔
1475
                // Pending channels that have a non-zero thaw height were also
12✔
1476
                // created through a canned funding shim. Those also don't
12✔
1477
                // count towards the DoS protection limit.
12✔
1478
                //
12✔
1479
                // TODO(guggero): Properly store the funding type (wallet, shim,
12✔
1480
                // PSBT) on the channel so we don't need to use the thaw height.
12✔
1481
                if c.IsPending && c.ThawHeight == 0 {
20✔
1482
                        numPending++
8✔
1483
                }
8✔
1484
        }
1485

1486
        // TODO(roasbeef): modify to only accept a _single_ pending channel per
1487
        // block unless white listed
1488
        if numPending >= f.cfg.MaxPendingChannels {
58✔
1489
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
4✔
1490

4✔
1491
                return
4✔
1492
        }
4✔
1493

1494
        // Ensure that the pendingChansLimit is respected.
1495
        pendingChans, err := f.cfg.ChannelDB.FetchPendingChannels()
50✔
1496
        if err != nil {
50✔
1497
                f.failFundingFlow(peer, cid, err)
×
1498
                return
×
1499
        }
×
1500

1501
        if len(pendingChans) > pendingChansLimit {
50✔
1502
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
×
1503
                return
×
1504
        }
×
1505

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

1519
        // Ensure that the remote party respects our maximum channel size.
1520
        if amt > f.cfg.MaxChanSize {
52✔
1521
                f.failFundingFlow(
2✔
1522
                        peer, cid,
2✔
1523
                        lnwallet.ErrChanTooLarge(amt, f.cfg.MaxChanSize),
2✔
1524
                )
2✔
1525
                return
2✔
1526
        }
2✔
1527

1528
        // We'll, also ensure that the remote party isn't attempting to propose
1529
        // a channel that's below our current min channel size.
1530
        if amt < f.cfg.MinChanSize {
48✔
1531
                f.failFundingFlow(
×
1532
                        peer, cid,
×
1533
                        lnwallet.ErrChanTooSmall(amt, f.cfg.MinChanSize),
×
1534
                )
×
1535
                return
×
1536
        }
×
1537

1538
        // If request specifies non-zero push amount and 'rejectpush' is set,
1539
        // signal an error.
1540
        if f.cfg.RejectPush && msg.PushAmount > 0 {
49✔
1541
                f.failFundingFlow(peer, cid, lnwallet.ErrNonZeroPushAmount())
1✔
1542
                return
1✔
1543
        }
1✔
1544

1545
        // Send the OpenChannel request to the ChannelAcceptor to determine
1546
        // whether this node will accept the channel.
1547
        chanReq := &chanacceptor.ChannelAcceptRequest{
47✔
1548
                Node:        peer.IdentityKey(),
47✔
1549
                OpenChanMsg: msg,
47✔
1550
        }
47✔
1551

47✔
1552
        // Query our channel acceptor to determine whether we should reject
47✔
1553
        // the channel.
47✔
1554
        acceptorResp := f.cfg.OpenChannelPredicate.Accept(chanReq)
47✔
1555
        if acceptorResp.RejectChannel() {
47✔
1556
                f.failFundingFlow(peer, cid, acceptorResp.ChanAcceptError)
×
1557
                return
×
1558
        }
×
1559

1560
        log.Infof("Recv'd fundingRequest(amt=%v, push=%v, delay=%v, "+
47✔
1561
                "pendingId=%x) from peer(%x)", amt, msg.PushAmount,
47✔
1562
                msg.CsvDelay, msg.PendingChannelID,
47✔
1563
                peer.IdentityKey().SerializeCompressed())
47✔
1564

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

1586
        var scidFeatureVal bool
47✔
1587
        if hasFeatures(
47✔
1588
                peer.LocalFeatures(), peer.RemoteFeatures(),
47✔
1589
                lnwire.ScidAliasOptional,
47✔
1590
        ) {
50✔
1591

3✔
1592
                scidFeatureVal = true
3✔
1593
        }
3✔
1594

1595
        var (
47✔
1596
                zeroConf bool
47✔
1597
                scid     bool
47✔
1598
        )
47✔
1599

47✔
1600
        // Only echo back a channel type in AcceptChannel if we actually used
47✔
1601
        // explicit negotiation above.
47✔
1602
        if chanType != nil {
51✔
1603
                // Check if the channel type includes the zero-conf or
4✔
1604
                // scid-alias bits.
4✔
1605
                featureVec := lnwire.RawFeatureVector(*chanType)
4✔
1606
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
4✔
1607
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
4✔
1608

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

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

1638
                        // Set zeroConf to true to enable the zero-conf flow.
1639
                        zeroConf = true
×
1640
                }
1641
        }
1642

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

×
1654
                return
×
1655

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

×
1664
                return
×
1665
        }
1666

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

×
1681
                return
×
1682
        }
×
1683

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

47✔
1703
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
47✔
1704
        if err != nil {
47✔
1705
                log.Errorf("Unable to initialize reservation: %v", err)
×
1706
                f.failFundingFlow(peer, cid, err)
×
1707
                return
×
1708
        }
×
1709

1710
        log.Debugf("Initialized channel reservation: zeroConf=%v, psbt=%v, "+
47✔
1711
                "cannedShim=%v", reservation.IsZeroConf(),
47✔
1712
                reservation.IsPsbt(), reservation.IsCannedShim())
47✔
1713

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

1724
                reservation.AddAlias(aliasScid)
2✔
1725
        }
1726

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

1738
        // We'll ignore the min_depth calculated above if this is a zero-conf
1739
        // channel.
1740
        if zeroConf {
49✔
1741
                numConfsReq = 0
2✔
1742
        }
2✔
1743

1744
        reservation.SetNumConfsRequired(numConfsReq)
47✔
1745

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

1767
        // If the fundee didn't provide an upfront-shutdown address via
1768
        // the channel acceptor, fall back to the configured shutdown
1769
        // script (if any).
1770
        shutdownScript := acceptorResp.UpfrontShutdown
47✔
1771
        if len(shutdownScript) == 0 {
94✔
1772
                f.cfg.ShutdownScript.WhenSome(
47✔
1773
                        func(script lnwire.DeliveryAddress) {
47✔
1774
                                shutdownScript = script
×
1775
                        },
×
1776
                )
1777
        }
1778

1779
        // Check whether the peer supports upfront shutdown, and get a new
1780
        // wallet address if our node is configured to set shutdown addresses by
1781
        // default. We use the upfront shutdown script provided by our channel
1782
        // acceptor (if any) in lieu of user input.
1783
        shutdown, err := getUpfrontShutdownScript(
47✔
1784
                f.cfg.EnableUpfrontShutdown, peer, shutdownScript,
47✔
1785
                f.selectShutdownScript,
47✔
1786
        )
47✔
1787
        if err != nil {
47✔
1788
                f.failFundingFlow(
×
1789
                        peer, cid,
×
1790
                        fmt.Errorf("getUpfrontShutdownScript error: %w", err),
×
1791
                )
×
1792
                return
×
1793
        }
×
1794
        reservation.SetOurUpfrontShutdown(shutdown)
47✔
1795

47✔
1796
        // If a script enforced channel lease is being proposed, we'll need to
47✔
1797
        // validate its custom TLV records.
47✔
1798
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
47✔
1799
                if msg.LeaseExpiry == nil {
×
1800
                        err := errors.New("missing lease expiry")
×
1801
                        f.failFundingFlow(peer, cid, err)
×
1802
                        return
×
1803
                }
×
1804

1805
                // If we had a shim registered for this channel prior to
1806
                // receiving its corresponding OpenChannel message, then we'll
1807
                // validate the proposed LeaseExpiry against what was registered
1808
                // in our shim.
1809
                if reservation.LeaseExpiry() != 0 {
×
1810
                        if uint32(*msg.LeaseExpiry) !=
×
1811
                                reservation.LeaseExpiry() {
×
1812

×
1813
                                err := errors.New("lease expiry mismatch")
×
1814
                                f.failFundingFlow(peer, cid, err)
×
1815
                                return
×
1816
                        }
×
1817
                }
1818
        }
1819

1820
        log.Infof("Requiring %v confirmations for pendingChan(%x): "+
47✔
1821
                "amt=%v, push_amt=%v, committype=%v, upfrontShutdown=%x",
47✔
1822
                numConfsReq, msg.PendingChannelID, amt, msg.PushAmount,
47✔
1823
                commitType, msg.UpfrontShutdownScript)
47✔
1824

47✔
1825
        // Generate our required constraints for the remote party, using the
47✔
1826
        // values provided by the channel acceptor if they are non-zero.
47✔
1827
        remoteCsvDelay := f.cfg.RequiredRemoteDelay(amt)
47✔
1828
        if acceptorResp.CSVDelay != 0 {
47✔
1829
                remoteCsvDelay = acceptorResp.CSVDelay
×
1830
        }
×
1831

1832
        // If our default dust limit was above their ChannelReserve, we change
1833
        // it to the ChannelReserve. We must make sure the ChannelReserve we
1834
        // send in the AcceptChannel message is above both dust limits.
1835
        // Therefore, take the maximum of msg.DustLimit and our dust limit.
1836
        //
1837
        // NOTE: Even with this bounding, the ChannelAcceptor may return an
1838
        // BOLT#02-invalid ChannelReserve.
1839
        maxDustLimit := reservation.OurContribution().DustLimit
47✔
1840
        if msg.DustLimit > maxDustLimit {
47✔
1841
                maxDustLimit = msg.DustLimit
×
1842
        }
×
1843

1844
        chanReserve := f.cfg.RequiredRemoteChanReserve(amt, maxDustLimit)
47✔
1845
        if acceptorResp.Reserve != 0 {
47✔
1846
                chanReserve = acceptorResp.Reserve
×
1847
        }
×
1848

1849
        remoteMaxValue := f.cfg.RequiredRemoteMaxValue(amt)
47✔
1850
        if acceptorResp.InFlightTotal != 0 {
47✔
1851
                remoteMaxValue = acceptorResp.InFlightTotal
×
1852
        }
×
1853

1854
        maxHtlcs := f.cfg.RequiredRemoteMaxHTLCs(amt)
47✔
1855
        if acceptorResp.HtlcLimit != 0 {
47✔
1856
                maxHtlcs = acceptorResp.HtlcLimit
×
1857
        }
×
1858

1859
        // Default to our default minimum hltc value, replacing it with the
1860
        // channel acceptor's value if it is set.
1861
        minHtlc := f.cfg.DefaultMinHtlcIn
47✔
1862
        if acceptorResp.MinHtlcIn != 0 {
47✔
1863
                minHtlc = acceptorResp.MinHtlcIn
×
1864
        }
×
1865

1866
        // If we are handling a FundingOpen request then we need to specify the
1867
        // default channel fees since they are not provided by the responder
1868
        // interactively.
1869
        ourContribution := reservation.OurContribution()
47✔
1870
        forwardingPolicy := f.defaultForwardingPolicy(
47✔
1871
                ourContribution.ChannelStateBounds,
47✔
1872
        )
47✔
1873

47✔
1874
        // Once the reservation has been created successfully, we add it to
47✔
1875
        // this peer's map of pending reservations to track this particular
47✔
1876
        // reservation until either abort or completion.
47✔
1877
        f.resMtx.Lock()
47✔
1878
        if _, ok := f.activeReservations[peerIDKey]; !ok {
90✔
1879
                f.activeReservations[peerIDKey] = make(pendingChannels)
43✔
1880
        }
43✔
1881
        resCtx := &reservationWithCtx{
47✔
1882
                reservation:       reservation,
47✔
1883
                chanAmt:           amt,
47✔
1884
                forwardingPolicy:  *forwardingPolicy,
47✔
1885
                remoteCsvDelay:    remoteCsvDelay,
47✔
1886
                remoteMinHtlc:     minHtlc,
47✔
1887
                remoteMaxValue:    remoteMaxValue,
47✔
1888
                remoteMaxHtlcs:    maxHtlcs,
47✔
1889
                remoteChanReserve: chanReserve,
47✔
1890
                maxLocalCsv:       f.cfg.MaxLocalCSVDelay,
47✔
1891
                channelType:       chanType,
47✔
1892
                err:               make(chan error, 1),
47✔
1893
                peer:              peer,
47✔
1894
        }
47✔
1895
        f.activeReservations[peerIDKey][msg.PendingChannelID] = resCtx
47✔
1896
        f.resMtx.Unlock()
47✔
1897

47✔
1898
        // Update the timestamp once the fundingOpenMsg has been handled.
47✔
1899
        defer resCtx.updateTimestamp()
47✔
1900

47✔
1901
        cfg := channeldb.ChannelConfig{
47✔
1902
                ChannelStateBounds: channeldb.ChannelStateBounds{
47✔
1903
                        MaxPendingAmount: remoteMaxValue,
47✔
1904
                        ChanReserve:      chanReserve,
47✔
1905
                        MinHTLC:          minHtlc,
47✔
1906
                        MaxAcceptedHtlcs: maxHtlcs,
47✔
1907
                },
47✔
1908
                CommitmentParams: channeldb.CommitmentParams{
47✔
1909
                        DustLimit: msg.DustLimit,
47✔
1910
                        CsvDelay:  remoteCsvDelay,
47✔
1911
                },
47✔
1912
                MultiSigKey: keychain.KeyDescriptor{
47✔
1913
                        PubKey: copyPubKey(msg.FundingKey),
47✔
1914
                },
47✔
1915
                RevocationBasePoint: keychain.KeyDescriptor{
47✔
1916
                        PubKey: copyPubKey(msg.RevocationPoint),
47✔
1917
                },
47✔
1918
                PaymentBasePoint: keychain.KeyDescriptor{
47✔
1919
                        PubKey: copyPubKey(msg.PaymentPoint),
47✔
1920
                },
47✔
1921
                DelayBasePoint: keychain.KeyDescriptor{
47✔
1922
                        PubKey: copyPubKey(msg.DelayedPaymentPoint),
47✔
1923
                },
47✔
1924
                HtlcBasePoint: keychain.KeyDescriptor{
47✔
1925
                        PubKey: copyPubKey(msg.HtlcPoint),
47✔
1926
                },
47✔
1927
        }
47✔
1928

47✔
1929
        // With our parameters set, we'll now process their contribution so we
47✔
1930
        // can move the funding workflow ahead.
47✔
1931
        remoteContribution := &lnwallet.ChannelContribution{
47✔
1932
                FundingAmount:        amt,
47✔
1933
                FirstCommitmentPoint: msg.FirstCommitmentPoint,
47✔
1934
                ChannelConfig:        &cfg,
47✔
1935
                UpfrontShutdown:      msg.UpfrontShutdownScript,
47✔
1936
        }
47✔
1937

47✔
1938
        if resCtx.reservation.IsTaproot() {
49✔
1939
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
2✔
1940
                if err != nil {
2✔
1941
                        log.Error(errNoLocalNonce)
×
1942

×
1943
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
1944

×
1945
                        return
×
1946
                }
×
1947

1948
                remoteContribution.LocalNonce = &musig2.Nonces{
2✔
1949
                        PubNonce: localNonce,
2✔
1950
                }
2✔
1951
        }
1952

1953
        err = reservation.ProcessSingleContribution(remoteContribution)
47✔
1954
        if err != nil {
53✔
1955
                log.Errorf("unable to add contribution reservation: %v", err)
6✔
1956
                f.failFundingFlow(peer, cid, err)
6✔
1957
                return
6✔
1958
        }
6✔
1959

1960
        log.Infof("Sending fundingResp for pending_id(%x)",
41✔
1961
                msg.PendingChannelID)
41✔
1962
        bounds := remoteContribution.ChannelConfig.ChannelStateBounds
41✔
1963
        log.Debugf("Remote party accepted channel state space bounds: %v",
41✔
1964
                lnutils.SpewLogClosure(bounds))
41✔
1965
        params := remoteContribution.ChannelConfig.CommitmentParams
41✔
1966
        log.Debugf("Remote party accepted commitment rendering params: %v",
41✔
1967
                lnutils.SpewLogClosure(params))
41✔
1968

41✔
1969
        reservation.SetState(lnwallet.SentAcceptChannel)
41✔
1970

41✔
1971
        // With the initiator's contribution recorded, respond with our
41✔
1972
        // contribution in the next message of the workflow.
41✔
1973
        fundingAccept := lnwire.AcceptChannel{
41✔
1974
                PendingChannelID:      msg.PendingChannelID,
41✔
1975
                DustLimit:             ourContribution.DustLimit,
41✔
1976
                MaxValueInFlight:      remoteMaxValue,
41✔
1977
                ChannelReserve:        chanReserve,
41✔
1978
                MinAcceptDepth:        uint32(numConfsReq),
41✔
1979
                HtlcMinimum:           minHtlc,
41✔
1980
                CsvDelay:              remoteCsvDelay,
41✔
1981
                MaxAcceptedHTLCs:      maxHtlcs,
41✔
1982
                FundingKey:            ourContribution.MultiSigKey.PubKey,
41✔
1983
                RevocationPoint:       ourContribution.RevocationBasePoint.PubKey,
41✔
1984
                PaymentPoint:          ourContribution.PaymentBasePoint.PubKey,
41✔
1985
                DelayedPaymentPoint:   ourContribution.DelayBasePoint.PubKey,
41✔
1986
                HtlcPoint:             ourContribution.HtlcBasePoint.PubKey,
41✔
1987
                FirstCommitmentPoint:  ourContribution.FirstCommitmentPoint,
41✔
1988
                UpfrontShutdownScript: ourContribution.UpfrontShutdown,
41✔
1989
                ChannelType:           chanType,
41✔
1990
                LeaseExpiry:           msg.LeaseExpiry,
41✔
1991
        }
41✔
1992

41✔
1993
        if commitType.IsTaproot() {
43✔
1994
                fundingAccept.LocalNonce = lnwire.SomeMusig2Nonce(
2✔
1995
                        ourContribution.LocalNonce.PubNonce,
2✔
1996
                )
2✔
1997
        }
2✔
1998

1999
        if err := peer.SendMessage(true, &fundingAccept); err != nil {
41✔
2000
                log.Errorf("unable to send funding response to peer: %v", err)
×
2001
                f.failFundingFlow(peer, cid, err)
×
2002
                return
×
2003
        }
×
2004
}
2005

2006
// funderProcessAcceptChannel processes a response to the workflow initiation
2007
// sent by the remote peer. This message then queues a message with the funding
2008
// outpoint, and a commitment signature to the remote peer.
2009
//
2010
//nolint:funlen
2011
func (f *Manager) funderProcessAcceptChannel(peer lnpeer.Peer,
2012
        msg *lnwire.AcceptChannel) {
33✔
2013

33✔
2014
        pendingChanID := msg.PendingChannelID
33✔
2015
        peerKey := peer.IdentityKey()
33✔
2016
        var peerKeyBytes []byte
33✔
2017
        if peerKey != nil {
66✔
2018
                peerKeyBytes = peerKey.SerializeCompressed()
33✔
2019
        }
33✔
2020

2021
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
33✔
2022
        if err != nil {
33✔
2023
                log.Warnf("Can't find reservation (peerKey:%x, chan_id:%v)",
×
2024
                        peerKeyBytes, pendingChanID)
×
2025
                return
×
2026
        }
×
2027

2028
        // Update the timestamp once the fundingAcceptMsg has been handled.
2029
        defer resCtx.updateTimestamp()
33✔
2030

33✔
2031
        if resCtx.reservation.State() != lnwallet.SentOpenChannel {
33✔
2032
                return
×
2033
        }
×
2034

2035
        log.Infof("Recv'd fundingResponse for pending_id(%x)",
33✔
2036
                pendingChanID[:])
33✔
2037

33✔
2038
        // Create the channel identifier.
33✔
2039
        cid := newChanIdentifier(msg.PendingChannelID)
33✔
2040

33✔
2041
        // Perform some basic validation of any custom TLV records included.
33✔
2042
        //
33✔
2043
        // TODO: Return errors as funding.Error to give context to remote peer?
33✔
2044
        if resCtx.channelType != nil {
37✔
2045
                // We'll want to quickly check that the ChannelType echoed by
4✔
2046
                // the channel request recipient matches what we proposed.
4✔
2047
                if msg.ChannelType == nil {
5✔
2048
                        err := errors.New("explicit channel type not echoed " +
1✔
2049
                                "back")
1✔
2050
                        f.failFundingFlow(peer, cid, err)
1✔
2051
                        return
1✔
2052
                }
1✔
2053
                proposedFeatures := lnwire.RawFeatureVector(*resCtx.channelType)
3✔
2054
                ackedFeatures := lnwire.RawFeatureVector(*msg.ChannelType)
3✔
2055
                if !proposedFeatures.Equals(&ackedFeatures) {
3✔
2056
                        err := errors.New("channel type mismatch")
×
2057
                        f.failFundingFlow(peer, cid, err)
×
2058
                        return
×
2059
                }
×
2060

2061
                // We'll want to do the same with the LeaseExpiry if one should
2062
                // be set.
2063
                if resCtx.reservation.LeaseExpiry() != 0 {
3✔
2064
                        if msg.LeaseExpiry == nil {
×
2065
                                err := errors.New("lease expiry not echoed " +
×
2066
                                        "back")
×
2067
                                f.failFundingFlow(peer, cid, err)
×
2068
                                return
×
2069
                        }
×
2070
                        if uint32(*msg.LeaseExpiry) !=
×
2071
                                resCtx.reservation.LeaseExpiry() {
×
2072

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

×
2088
                _, negotiatedCommitType, err := negotiateCommitmentType(
×
2089
                        msg.ChannelType, peer.LocalFeatures(),
×
2090
                        peer.RemoteFeatures(),
×
2091
                )
×
2092
                if err != nil {
×
2093
                        err := errors.New("received unexpected channel type")
×
2094
                        f.failFundingFlow(peer, cid, err)
×
2095
                        return
×
2096
                }
×
2097

2098
                if implicitCommitType != negotiatedCommitType {
×
2099
                        err := errors.New("negotiated unexpected channel type")
×
2100
                        f.failFundingFlow(peer, cid, err)
×
2101
                        return
×
2102
                }
×
2103
        }
2104

2105
        // The required number of confirmations should not be greater than the
2106
        // maximum number of confirmations required by the ChainNotifier to
2107
        // properly dispatch confirmations.
2108
        if msg.MinAcceptDepth > chainntnfs.MaxNumConfs {
33✔
2109
                err := lnwallet.ErrNumConfsTooLarge(
1✔
2110
                        msg.MinAcceptDepth, chainntnfs.MaxNumConfs,
1✔
2111
                )
1✔
2112
                log.Warnf("Unacceptable channel constraints: %v", err)
1✔
2113
                f.failFundingFlow(peer, cid, err)
1✔
2114
                return
1✔
2115
        }
1✔
2116

2117
        // Check that zero-conf channels have minimum depth set to 0.
2118
        if resCtx.reservation.IsZeroConf() && msg.MinAcceptDepth != 0 {
31✔
2119
                err = fmt.Errorf("zero-conf channel has min_depth non-zero")
×
2120
                log.Warn(err)
×
2121
                f.failFundingFlow(peer, cid, err)
×
2122
                return
×
2123
        }
×
2124

2125
        // If this is not a zero-conf channel but the peer responded with a
2126
        // min-depth of zero, we will use our minimum of 1 instead.
2127
        minDepth := msg.MinAcceptDepth
31✔
2128
        if !resCtx.reservation.IsZeroConf() && minDepth == 0 {
31✔
2129
                log.Infof("Responder to pending_id=%v sent a minimum "+
×
2130
                        "confirmation depth of 0 for non-zero-conf channel. "+
×
2131
                        "We will use a minimum depth of 1 instead.",
×
2132
                        cid.tempChanID)
×
2133

×
2134
                minDepth = 1
×
2135
        }
×
2136

2137
        // We'll also specify the responder's preference for the number of
2138
        // required confirmations, and also the set of channel constraints
2139
        // they've specified for commitment states we can create.
2140
        resCtx.reservation.SetNumConfsRequired(uint16(minDepth))
31✔
2141
        bounds := channeldb.ChannelStateBounds{
31✔
2142
                ChanReserve:      msg.ChannelReserve,
31✔
2143
                MaxPendingAmount: msg.MaxValueInFlight,
31✔
2144
                MinHTLC:          msg.HtlcMinimum,
31✔
2145
                MaxAcceptedHtlcs: msg.MaxAcceptedHTLCs,
31✔
2146
        }
31✔
2147
        commitParams := channeldb.CommitmentParams{
31✔
2148
                DustLimit: msg.DustLimit,
31✔
2149
                CsvDelay:  msg.CsvDelay,
31✔
2150
        }
31✔
2151
        err = resCtx.reservation.CommitConstraints(
31✔
2152
                &bounds, &commitParams, resCtx.maxLocalCsv, false,
31✔
2153
        )
31✔
2154
        if err != nil {
32✔
2155
                log.Warnf("Unacceptable channel constraints: %v", err)
1✔
2156
                f.failFundingFlow(peer, cid, err)
1✔
2157
                return
1✔
2158
        }
1✔
2159

2160
        cfg := channeldb.ChannelConfig{
30✔
2161
                ChannelStateBounds: channeldb.ChannelStateBounds{
30✔
2162
                        MaxPendingAmount: resCtx.remoteMaxValue,
30✔
2163
                        ChanReserve:      resCtx.remoteChanReserve,
30✔
2164
                        MinHTLC:          resCtx.remoteMinHtlc,
30✔
2165
                        MaxAcceptedHtlcs: resCtx.remoteMaxHtlcs,
30✔
2166
                },
30✔
2167
                CommitmentParams: channeldb.CommitmentParams{
30✔
2168
                        DustLimit: msg.DustLimit,
30✔
2169
                        CsvDelay:  resCtx.remoteCsvDelay,
30✔
2170
                },
30✔
2171
                MultiSigKey: keychain.KeyDescriptor{
30✔
2172
                        PubKey: copyPubKey(msg.FundingKey),
30✔
2173
                },
30✔
2174
                RevocationBasePoint: keychain.KeyDescriptor{
30✔
2175
                        PubKey: copyPubKey(msg.RevocationPoint),
30✔
2176
                },
30✔
2177
                PaymentBasePoint: keychain.KeyDescriptor{
30✔
2178
                        PubKey: copyPubKey(msg.PaymentPoint),
30✔
2179
                },
30✔
2180
                DelayBasePoint: keychain.KeyDescriptor{
30✔
2181
                        PubKey: copyPubKey(msg.DelayedPaymentPoint),
30✔
2182
                },
30✔
2183
                HtlcBasePoint: keychain.KeyDescriptor{
30✔
2184
                        PubKey: copyPubKey(msg.HtlcPoint),
30✔
2185
                },
30✔
2186
        }
30✔
2187

30✔
2188
        // The remote node has responded with their portion of the channel
30✔
2189
        // contribution. At this point, we can process their contribution which
30✔
2190
        // allows us to construct and sign both the commitment transaction, and
30✔
2191
        // the funding transaction.
30✔
2192
        remoteContribution := &lnwallet.ChannelContribution{
30✔
2193
                FirstCommitmentPoint: msg.FirstCommitmentPoint,
30✔
2194
                ChannelConfig:        &cfg,
30✔
2195
                UpfrontShutdown:      msg.UpfrontShutdownScript,
30✔
2196
        }
30✔
2197

30✔
2198
        if resCtx.reservation.IsTaproot() {
32✔
2199
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
2✔
2200
                if err != nil {
2✔
2201
                        log.Error(errNoLocalNonce)
×
2202

×
2203
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
2204

×
2205
                        return
×
2206
                }
×
2207

2208
                remoteContribution.LocalNonce = &musig2.Nonces{
2✔
2209
                        PubNonce: localNonce,
2✔
2210
                }
2✔
2211
        }
2212

2213
        err = resCtx.reservation.ProcessContribution(remoteContribution)
30✔
2214

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

2257
        log.Infof("pendingChan(%x): remote party proposes num_confs=%v, "+
30✔
2258
                "csv_delay=%v", pendingChanID[:], msg.MinAcceptDepth,
30✔
2259
                msg.CsvDelay)
30✔
2260
        bounds = remoteContribution.ChannelConfig.ChannelStateBounds
30✔
2261
        log.Debugf("Remote party accepted channel state space bounds: %v",
30✔
2262
                lnutils.SpewLogClosure(bounds))
30✔
2263
        commitParams = remoteContribution.ChannelConfig.CommitmentParams
30✔
2264
        log.Debugf("Remote party accepted commitment rendering params: %v",
30✔
2265
                lnutils.SpewLogClosure(commitParams))
30✔
2266

30✔
2267
        // If the user requested funding through a PSBT, we cannot directly
30✔
2268
        // continue now and need to wait for the fully funded and signed PSBT
30✔
2269
        // to arrive. To not block any other channels from opening, we wait in
30✔
2270
        // a separate goroutine.
30✔
2271
        if psbtIntent != nil {
30✔
2272
                f.wg.Add(1)
×
2273
                go func() {
×
2274
                        defer f.wg.Done()
×
2275

×
2276
                        f.waitForPsbt(psbtIntent, resCtx, cid)
×
2277
                }()
×
2278

2279
                // With the new goroutine spawned, we can now exit to unblock
2280
                // the main event loop.
2281
                return
×
2282
        }
2283

2284
        // In a normal, non-PSBT funding flow, we can jump directly to the next
2285
        // step where we expect our contribution to be finalized.
2286
        f.continueFundingAccept(resCtx, cid)
30✔
2287
}
2288

2289
// waitForPsbt blocks until either a signed PSBT arrives, an error occurs or
2290
// the funding manager shuts down. In the case of a valid PSBT, the funding flow
2291
// is continued.
2292
//
2293
// NOTE: This method must be called as a goroutine.
2294
func (f *Manager) waitForPsbt(intent *chanfunding.PsbtIntent,
2295
        resCtx *reservationWithCtx, cid *chanIdentifier) {
×
2296

×
2297
        // failFlow is a helper that logs an error message with the current
×
2298
        // context and then fails the funding flow.
×
2299
        peerKey := resCtx.peer.IdentityKey()
×
2300
        failFlow := func(errMsg string, cause error) {
×
2301
                log.Errorf("Unable to handle funding accept message "+
×
2302
                        "for peer_key=%x, pending_chan_id=%x: %s: %v",
×
2303
                        peerKey.SerializeCompressed(), cid.tempChanID, errMsg,
×
2304
                        cause)
×
2305
                f.failFundingFlow(resCtx.peer, cid, cause)
×
2306
        }
×
2307

2308
        // We'll now wait until the intent has received the final and complete
2309
        // funding transaction. If the channel is closed without any error being
2310
        // sent, we know everything's going as expected.
2311
        select {
×
2312
        case err := <-intent.PsbtReady:
×
2313
                switch err {
×
2314
                // If the user canceled the funding reservation, we need to
2315
                // inform the other peer about us canceling the reservation.
2316
                case chanfunding.ErrUserCanceled:
×
2317
                        failFlow("aborting PSBT flow", err)
×
2318
                        return
×
2319

2320
                // If the remote canceled the funding reservation, we don't need
2321
                // to send another fail message. But we want to inform the user
2322
                // about what happened.
2323
                case chanfunding.ErrRemoteCanceled:
×
2324
                        log.Infof("Remote canceled, aborting PSBT flow "+
×
2325
                                "for peer_key=%x, pending_chan_id=%x",
×
2326
                                peerKey.SerializeCompressed(), cid.tempChanID)
×
2327
                        return
×
2328

2329
                // Nil error means the flow continues normally now.
2330
                case nil:
×
2331

2332
                // For any other error, we'll fail the funding flow.
2333
                default:
×
2334
                        failFlow("error waiting for PSBT flow", err)
×
2335
                        return
×
2336
                }
2337

2338
                // At this point, we'll see if there's an AuxFundingDesc we
2339
                // need to deliver so the funding process can continue
2340
                // properly.
2341
                auxFundingDesc, err := fn.MapOptionZ(
×
2342
                        f.cfg.AuxFundingController,
×
2343
                        func(c AuxFundingController) AuxFundingDescResult {
×
2344
                                return c.DescFromPendingChanID(
×
2345
                                        cid.tempChanID,
×
2346
                                        lnwallet.NewAuxChanState(
×
2347
                                                resCtx.reservation.ChanState(),
×
2348
                                        ),
×
2349
                                        resCtx.reservation.CommitmentKeyRings(),
×
2350
                                        true,
×
2351
                                )
×
2352
                        },
×
2353
                ).Unpack()
2354
                if err != nil {
×
2355
                        failFlow("error continuing PSBT flow", err)
×
2356
                        return
×
2357
                }
×
2358

2359
                // A non-nil error means we can continue the funding flow.
2360
                // Notify the wallet so it can prepare everything we need to
2361
                // continue.
2362
                //
2363
                // We'll also pass along the aux funding controller as well,
2364
                // which may be used to help process the finalized PSBT.
2365
                err = resCtx.reservation.ProcessPsbt(auxFundingDesc)
×
2366
                if err != nil {
×
2367
                        failFlow("error continuing PSBT flow", err)
×
2368
                        return
×
2369
                }
×
2370

2371
                // We are now ready to continue the funding flow.
2372
                f.continueFundingAccept(resCtx, cid)
×
2373

2374
        // Handle a server shutdown as well because the reservation won't
2375
        // survive a restart as it's in memory only.
2376
        case <-f.quit:
×
2377
                log.Errorf("Unable to handle funding accept message "+
×
2378
                        "for peer_key=%x, pending_chan_id=%x: funding manager "+
×
2379
                        "shutting down", peerKey.SerializeCompressed(),
×
2380
                        cid.tempChanID)
×
2381
                return
×
2382
        }
2383
}
2384

2385
// continueFundingAccept continues the channel funding flow once our
2386
// contribution is finalized, the channel output is known and the funding
2387
// transaction is signed.
2388
func (f *Manager) continueFundingAccept(resCtx *reservationWithCtx,
2389
        cid *chanIdentifier) {
30✔
2390

30✔
2391
        // Now that we have their contribution, we can extract, then send over
30✔
2392
        // both the funding out point and our signature for their version of
30✔
2393
        // the commitment transaction to the remote peer.
30✔
2394
        outPoint := resCtx.reservation.FundingOutpoint()
30✔
2395
        _, sig := resCtx.reservation.OurSignatures()
30✔
2396

30✔
2397
        // A new channel has almost finished the funding process. In order to
30✔
2398
        // properly synchronize with the writeHandler goroutine, we add a new
30✔
2399
        // channel to the barriers map which will be closed once the channel is
30✔
2400
        // fully open.
30✔
2401
        channelID := lnwire.NewChanIDFromOutPoint(*outPoint)
30✔
2402
        log.Debugf("Creating chan barrier for ChanID(%v)", channelID)
30✔
2403

30✔
2404
        // The next message that advances the funding flow will reference the
30✔
2405
        // channel via its permanent channel ID, so we'll set up this mapping
30✔
2406
        // so we can retrieve the reservation context once we get the
30✔
2407
        // FundingSigned message.
30✔
2408
        f.resMtx.Lock()
30✔
2409
        f.signedReservations[channelID] = cid.tempChanID
30✔
2410
        f.resMtx.Unlock()
30✔
2411

30✔
2412
        log.Infof("Generated ChannelPoint(%v) for pending_id(%x)", outPoint,
30✔
2413
                cid.tempChanID[:])
30✔
2414

30✔
2415
        // Before sending FundingCreated sent, we notify Brontide to keep track
30✔
2416
        // of this pending open channel.
30✔
2417
        err := resCtx.peer.AddPendingChannel(channelID, f.quit)
30✔
2418
        if err != nil {
30✔
2419
                pubKey := resCtx.peer.IdentityKey().SerializeCompressed()
×
2420
                log.Errorf("Unable to add pending channel %v with peer %x: %v",
×
2421
                        channelID, pubKey, err)
×
2422
        }
×
2423

2424
        // Once Brontide is aware of this channel, we need to set it in
2425
        // chanIdentifier so this channel will be removed from Brontide if the
2426
        // funding flow fails.
2427
        cid.setChanID(channelID)
30✔
2428

30✔
2429
        // Send the FundingCreated msg.
30✔
2430
        fundingCreated := &lnwire.FundingCreated{
30✔
2431
                PendingChannelID: cid.tempChanID,
30✔
2432
                FundingPoint:     *outPoint,
30✔
2433
        }
30✔
2434

30✔
2435
        // If this is a taproot channel, then we'll need to populate the musig2
30✔
2436
        // partial sig field instead of the regular commit sig field.
30✔
2437
        if resCtx.reservation.IsTaproot() {
32✔
2438
                partialSig, ok := sig.(*lnwallet.MusigPartialSig)
2✔
2439
                if !ok {
2✔
2440
                        err := fmt.Errorf("expected musig partial sig, got %T",
×
2441
                                sig)
×
2442
                        log.Error(err)
×
2443
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2444

×
2445
                        return
×
2446
                }
×
2447

2448
                fundingCreated.PartialSig = lnwire.MaybePartialSigWithNonce(
2✔
2449
                        partialSig.ToWireSig(),
2✔
2450
                )
2✔
2451
        } else {
28✔
2452
                fundingCreated.CommitSig, err = lnwire.NewSigFromSignature(sig)
28✔
2453
                if err != nil {
28✔
2454
                        log.Errorf("Unable to parse signature: %v", err)
×
2455
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2456
                        return
×
2457
                }
×
2458
        }
2459

2460
        resCtx.reservation.SetState(lnwallet.SentFundingCreated)
30✔
2461

30✔
2462
        if err := resCtx.peer.SendMessage(true, fundingCreated); err != nil {
30✔
2463
                log.Errorf("Unable to send funding complete message: %v", err)
×
2464
                f.failFundingFlow(resCtx.peer, cid, err)
×
2465
                return
×
2466
        }
×
2467
}
2468

2469
// fundeeProcessFundingCreated progresses the funding workflow when the daemon
2470
// is on the responding side of a single funder workflow. Once this message has
2471
// been processed, a signature is sent to the remote peer allowing it to
2472
// broadcast the funding transaction, progressing the workflow into the final
2473
// stage.
2474
//
2475
//nolint:funlen
2476
func (f *Manager) fundeeProcessFundingCreated(peer lnpeer.Peer,
2477
        msg *lnwire.FundingCreated) {
28✔
2478

28✔
2479
        peerKey := peer.IdentityKey()
28✔
2480
        pendingChanID := msg.PendingChannelID
28✔
2481

28✔
2482
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
28✔
2483
        if err != nil {
28✔
2484
                log.Warnf("can't find reservation (peer_id:%v, chan_id:%x)",
×
2485
                        peerKey, pendingChanID[:])
×
2486
                return
×
2487
        }
×
2488

2489
        // The channel initiator has responded with the funding outpoint of the
2490
        // final funding transaction, as well as a signature for our version of
2491
        // the commitment transaction. So at this point, we can validate the
2492
        // initiator's commitment transaction, then send our own if it's valid.
2493
        fundingOut := msg.FundingPoint
28✔
2494
        log.Infof("completing pending_id(%x) with ChannelPoint(%v)",
28✔
2495
                pendingChanID[:], fundingOut)
28✔
2496

28✔
2497
        if resCtx.reservation.State() != lnwallet.SentAcceptChannel {
28✔
2498
                return
×
2499
        }
×
2500

2501
        // Create the channel identifier without setting the active channel ID.
2502
        cid := newChanIdentifier(pendingChanID)
28✔
2503

28✔
2504
        // For taproot channels, the commit signature is actually the partial
28✔
2505
        // signature. Otherwise, we can convert the ECDSA commit signature into
28✔
2506
        // our internal input.Signature type.
28✔
2507
        var commitSig input.Signature
28✔
2508
        if resCtx.reservation.IsTaproot() {
30✔
2509
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
2✔
2510
                if err != nil {
2✔
2511
                        f.failFundingFlow(peer, cid, err)
×
2512

×
2513
                        return
×
2514
                }
×
2515

2516
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
2✔
2517
                        &partialSig,
2✔
2518
                )
2✔
2519
        } else {
26✔
2520
                commitSig, err = msg.CommitSig.ToSignature()
26✔
2521
                if err != nil {
26✔
2522
                        log.Errorf("unable to parse signature: %v", err)
×
2523
                        f.failFundingFlow(peer, cid, err)
×
2524
                        return
×
2525
                }
×
2526
        }
2527

2528
        // At this point, we'll see if there's an AuxFundingDesc we need to
2529
        // deliver so the funding process can continue properly.
2530
        auxFundingDesc, err := fn.MapOptionZ(
28✔
2531
                f.cfg.AuxFundingController,
28✔
2532
                func(c AuxFundingController) AuxFundingDescResult {
28✔
2533
                        return c.DescFromPendingChanID(
×
2534
                                cid.tempChanID, lnwallet.NewAuxChanState(
×
2535
                                        resCtx.reservation.ChanState(),
×
2536
                                ), resCtx.reservation.CommitmentKeyRings(),
×
2537
                                true,
×
2538
                        )
×
2539
                },
×
2540
        ).Unpack()
2541
        if err != nil {
28✔
2542
                log.Errorf("error continuing PSBT flow: %v", err)
×
2543
                f.failFundingFlow(peer, cid, err)
×
2544
                return
×
2545
        }
×
2546

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

2565
        // Get forwarding policy before deleting the reservation context.
2566
        forwardingPolicy := resCtx.forwardingPolicy
28✔
2567

28✔
2568
        // The channel is marked IsPending in the database, and can be removed
28✔
2569
        // from the set of active reservations.
28✔
2570
        f.deleteReservationCtx(peerKey, cid.tempChanID)
28✔
2571

28✔
2572
        // If something goes wrong before the funding transaction is confirmed,
28✔
2573
        // we use this convenience method to delete the pending OpenChannel
28✔
2574
        // from the database.
28✔
2575
        deleteFromDatabase := func() {
28✔
2576
                localBalance := completeChan.LocalCommitment.LocalBalance.ToSatoshis()
×
2577
                closeInfo := &channeldb.ChannelCloseSummary{
×
2578
                        ChanPoint:               completeChan.FundingOutpoint,
×
2579
                        ChainHash:               completeChan.ChainHash,
×
2580
                        RemotePub:               completeChan.IdentityPub,
×
2581
                        CloseType:               channeldb.FundingCanceled,
×
2582
                        Capacity:                completeChan.Capacity,
×
2583
                        SettledBalance:          localBalance,
×
2584
                        RemoteCurrentRevocation: completeChan.RemoteCurrentRevocation,
×
2585
                        RemoteNextRevocation:    completeChan.RemoteNextRevocation,
×
2586
                        LocalChanConfig:         completeChan.LocalChanCfg,
×
2587
                }
×
2588

×
2589
                // Close the channel with us as the initiator because we are
×
2590
                // deciding to exit the funding flow due to an internal error.
×
2591
                if err := completeChan.CloseChannel(
×
2592
                        closeInfo, channeldb.ChanStatusLocalCloseInitiator,
×
2593
                ); err != nil {
×
2594
                        log.Errorf("Failed closing channel %v: %v",
×
2595
                                completeChan.FundingOutpoint, err)
×
2596
                }
×
2597
        }
2598

2599
        // A new channel has almost finished the funding process. In order to
2600
        // properly synchronize with the writeHandler goroutine, we add a new
2601
        // channel to the barriers map which will be closed once the channel is
2602
        // fully open.
2603
        channelID := lnwire.NewChanIDFromOutPoint(fundingOut)
28✔
2604
        log.Debugf("Creating chan barrier for ChanID(%v)", channelID)
28✔
2605

28✔
2606
        fundingSigned := &lnwire.FundingSigned{}
28✔
2607

28✔
2608
        // For taproot channels, we'll need to send over a partial signature
28✔
2609
        // that includes the nonce along side the signature.
28✔
2610
        _, sig := resCtx.reservation.OurSignatures()
28✔
2611
        if resCtx.reservation.IsTaproot() {
30✔
2612
                partialSig, ok := sig.(*lnwallet.MusigPartialSig)
2✔
2613
                if !ok {
2✔
2614
                        err := fmt.Errorf("expected musig partial sig, got %T",
×
2615
                                sig)
×
2616
                        log.Error(err)
×
2617
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2618
                        deleteFromDatabase()
×
2619

×
2620
                        return
×
2621
                }
×
2622

2623
                fundingSigned.PartialSig = lnwire.MaybePartialSigWithNonce(
2✔
2624
                        partialSig.ToWireSig(),
2✔
2625
                )
2✔
2626
        } else {
26✔
2627
                fundingSigned.CommitSig, err = lnwire.NewSigFromSignature(sig)
26✔
2628
                if err != nil {
26✔
2629
                        log.Errorf("unable to parse signature: %v", err)
×
2630
                        f.failFundingFlow(peer, cid, err)
×
2631
                        deleteFromDatabase()
×
2632

×
2633
                        return
×
2634
                }
×
2635
        }
2636

2637
        // Before sending FundingSigned, we notify Brontide first to keep track
2638
        // of this pending open channel.
2639
        if err := peer.AddPendingChannel(channelID, f.quit); err != nil {
28✔
2640
                pubKey := peer.IdentityKey().SerializeCompressed()
×
2641
                log.Errorf("Unable to add pending channel %v with peer %x: %v",
×
2642
                        cid.chanID, pubKey, err)
×
2643
        }
×
2644

2645
        // Once Brontide is aware of this channel, we need to set it in
2646
        // chanIdentifier so this channel will be removed from Brontide if the
2647
        // funding flow fails.
2648
        cid.setChanID(channelID)
28✔
2649

28✔
2650
        fundingSigned.ChanID = cid.chanID
28✔
2651

28✔
2652
        log.Infof("sending FundingSigned for pending_id(%x) over "+
28✔
2653
                "ChannelPoint(%v)", pendingChanID[:], fundingOut)
28✔
2654

28✔
2655
        // With their signature for our version of the commitment transaction
28✔
2656
        // verified, we can now send over our signature to the remote peer.
28✔
2657
        if err := peer.SendMessage(true, fundingSigned); err != nil {
28✔
2658
                log.Errorf("unable to send FundingSigned message: %v", err)
×
2659
                f.failFundingFlow(peer, cid, err)
×
2660
                deleteFromDatabase()
×
2661
                return
×
2662
        }
×
2663

2664
        // With a permanent channel id established we can save the respective
2665
        // forwarding policy in the database. In the channel announcement phase
2666
        // this forwarding policy is retrieved and applied.
2667
        err = f.saveInitialForwardingPolicy(cid.chanID, &forwardingPolicy)
28✔
2668
        if err != nil {
28✔
2669
                log.Errorf("Unable to store the forwarding policy: %v", err)
×
2670
        }
×
2671

2672
        // Now that we've sent over our final signature for this channel, we'll
2673
        // send it to the ChainArbitrator so it can watch for any on-chain
2674
        // actions during this final confirmation stage.
2675
        if err := f.cfg.WatchNewChannel(completeChan, peerKey); err != nil {
28✔
2676
                log.Errorf("Unable to send new ChannelPoint(%v) for "+
×
2677
                        "arbitration: %v", fundingOut, err)
×
2678
        }
×
2679

2680
        // Create an entry in the local discovery map so we can ensure that we
2681
        // process the channel confirmation fully before we receive a
2682
        // channel_ready message.
2683
        f.localDiscoverySignals.Store(cid.chanID, make(chan struct{}))
28✔
2684

28✔
2685
        // Inform the ChannelNotifier that the channel has entered
28✔
2686
        // pending open state.
28✔
2687
        f.cfg.NotifyPendingOpenChannelEvent(
28✔
2688
                fundingOut, completeChan, completeChan.IdentityPub,
28✔
2689
        )
28✔
2690

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

2711
// funderProcessFundingSigned processes the final message received in a single
2712
// funder workflow. Once this message is processed, the funding transaction is
2713
// broadcast. Once the funding transaction reaches a sufficient number of
2714
// confirmations, a message is sent to the responding peer along with a compact
2715
// encoding of the location of the channel within the blockchain.
2716
func (f *Manager) funderProcessFundingSigned(peer lnpeer.Peer,
2717
        msg *lnwire.FundingSigned) {
28✔
2718

28✔
2719
        // As the funding signed message will reference the reservation by its
28✔
2720
        // permanent channel ID, we'll need to perform an intermediate look up
28✔
2721
        // before we can obtain the reservation.
28✔
2722
        f.resMtx.Lock()
28✔
2723
        pendingChanID, ok := f.signedReservations[msg.ChanID]
28✔
2724
        delete(f.signedReservations, msg.ChanID)
28✔
2725
        f.resMtx.Unlock()
28✔
2726

28✔
2727
        // Create the channel identifier and set the channel ID.
28✔
2728
        //
28✔
2729
        // NOTE: we may get an empty pending channel ID here if the key cannot
28✔
2730
        // be found, which means when we cancel the reservation context in
28✔
2731
        // `failFundingFlow`, we will get an error. In this case, we will send
28✔
2732
        // an error msg to our peer using the active channel ID.
28✔
2733
        //
28✔
2734
        // TODO(yy): refactor the funding flow to fix this case.
28✔
2735
        cid := newChanIdentifier(pendingChanID)
28✔
2736
        cid.setChanID(msg.ChanID)
28✔
2737

28✔
2738
        // If the pending channel ID is not found, fail the funding flow.
28✔
2739
        if !ok {
28✔
2740
                // NOTE: we directly overwrite the pending channel ID here for
×
2741
                // this rare case since we don't have a valid pending channel
×
2742
                // ID.
×
2743
                cid.tempChanID = msg.ChanID
×
2744

×
2745
                err := fmt.Errorf("unable to find signed reservation for "+
×
2746
                        "chan_id=%x", msg.ChanID)
×
2747
                log.Warnf(err.Error())
×
2748
                f.failFundingFlow(peer, cid, err)
×
2749
                return
×
2750
        }
×
2751

2752
        peerKey := peer.IdentityKey()
28✔
2753
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
28✔
2754
        if err != nil {
28✔
2755
                log.Warnf("Unable to find reservation (peer_id:%v, "+
×
2756
                        "chan_id:%x)", peerKey, pendingChanID[:])
×
2757
                // TODO: add ErrChanNotFound?
×
2758
                f.failFundingFlow(peer, cid, err)
×
2759
                return
×
2760
        }
×
2761

2762
        if resCtx.reservation.State() != lnwallet.SentFundingCreated {
28✔
2763
                err := fmt.Errorf("unable to find reservation for chan_id=%x",
×
2764
                        msg.ChanID)
×
2765
                f.failFundingFlow(peer, cid, err)
×
2766

×
2767
                return
×
2768
        }
×
2769

2770
        // Create an entry in the local discovery map so we can ensure that we
2771
        // process the channel confirmation fully before we receive a
2772
        // channel_ready message.
2773
        fundingPoint := resCtx.reservation.FundingOutpoint()
28✔
2774
        permChanID := lnwire.NewChanIDFromOutPoint(*fundingPoint)
28✔
2775
        f.localDiscoverySignals.Store(permChanID, make(chan struct{}))
28✔
2776

28✔
2777
        // We have to store the forwardingPolicy before the reservation context
28✔
2778
        // is deleted. The policy will then be read and applied in
28✔
2779
        // newChanAnnouncement.
28✔
2780
        err = f.saveInitialForwardingPolicy(
28✔
2781
                permChanID, &resCtx.forwardingPolicy,
28✔
2782
        )
28✔
2783
        if err != nil {
28✔
2784
                log.Errorf("Unable to store the forwarding policy: %v", err)
×
2785
        }
×
2786

2787
        // For taproot channels, the commit signature is actually the partial
2788
        // signature. Otherwise, we can convert the ECDSA commit signature into
2789
        // our internal input.Signature type.
2790
        var commitSig input.Signature
28✔
2791
        if resCtx.reservation.IsTaproot() {
30✔
2792
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
2✔
2793
                if err != nil {
2✔
2794
                        f.failFundingFlow(peer, cid, err)
×
2795

×
2796
                        return
×
2797
                }
×
2798

2799
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
2✔
2800
                        &partialSig,
2✔
2801
                )
2✔
2802
        } else {
26✔
2803
                commitSig, err = msg.CommitSig.ToSignature()
26✔
2804
                if err != nil {
26✔
2805
                        log.Errorf("unable to parse signature: %v", err)
×
2806
                        f.failFundingFlow(peer, cid, err)
×
2807
                        return
×
2808
                }
×
2809
        }
2810

2811
        completeChan, err := resCtx.reservation.CompleteReservation(
28✔
2812
                nil, commitSig,
28✔
2813
        )
28✔
2814
        if err != nil {
28✔
2815
                log.Errorf("Unable to complete reservation sign "+
×
2816
                        "complete: %v", err)
×
2817
                f.failFundingFlow(peer, cid, err)
×
2818
                return
×
2819
        }
×
2820

2821
        // The channel is now marked IsPending in the database, and we can
2822
        // delete it from our set of active reservations.
2823
        f.deleteReservationCtx(peerKey, pendingChanID)
28✔
2824

28✔
2825
        // Broadcast the finalized funding transaction to the network, but only
28✔
2826
        // if we actually have the funding transaction.
28✔
2827
        if completeChan.ChanType.HasFundingTx() {
55✔
2828
                fundingTx := completeChan.FundingTxn
27✔
2829
                var fundingTxBuf bytes.Buffer
27✔
2830
                if err := fundingTx.Serialize(&fundingTxBuf); err != nil {
27✔
2831
                        log.Errorf("Unable to serialize funding "+
×
2832
                                "transaction %v: %v", fundingTx.TxHash(), err)
×
2833

×
2834
                        // Clear the buffer of any bytes that were written
×
2835
                        // before the serialization error to prevent logging an
×
2836
                        // incomplete transaction.
×
2837
                        fundingTxBuf.Reset()
×
2838
                }
×
2839

2840
                log.Infof("Broadcasting funding tx for ChannelPoint(%v): %x",
27✔
2841
                        completeChan.FundingOutpoint, fundingTxBuf.Bytes())
27✔
2842

27✔
2843
                // Set a nil short channel ID at this stage because we do not
27✔
2844
                // know it until our funding tx confirms.
27✔
2845
                label := labels.MakeLabel(
27✔
2846
                        labels.LabelTypeChannelOpen, nil,
27✔
2847
                )
27✔
2848

27✔
2849
                err = f.cfg.PublishTransaction(fundingTx, label)
27✔
2850
                if err != nil {
27✔
2851
                        log.Errorf("Unable to broadcast funding tx %x for "+
×
2852
                                "ChannelPoint(%v): %v", fundingTxBuf.Bytes(),
×
2853
                                completeChan.FundingOutpoint, err)
×
2854

×
2855
                        // We failed to broadcast the funding transaction, but
×
2856
                        // watch the channel regardless, in case the
×
2857
                        // transaction made it to the network. We will retry
×
2858
                        // broadcast at startup.
×
2859
                        //
×
2860
                        // TODO(halseth): retry more often? Handle with CPFP?
×
2861
                        // Just delete from the DB?
×
2862
                }
×
2863
        }
2864

2865
        // Before we proceed, if we have a funding hook that wants a
2866
        // notification that it's safe to broadcast the funding transaction,
2867
        // then we'll send that now.
2868
        err = fn.MapOptionZ(
28✔
2869
                f.cfg.AuxFundingController,
28✔
2870
                func(controller AuxFundingController) error {
28✔
2871
                        return controller.ChannelFinalized(cid.tempChanID)
×
2872
                },
×
2873
        )
2874
        if err != nil {
28✔
2875
                log.Errorf("Failed to inform aux funding controller about "+
×
2876
                        "ChannelPoint(%v) being finalized: %v", fundingPoint,
×
2877
                        err)
×
2878
        }
×
2879

2880
        // Now that we have a finalized reservation for this funding flow,
2881
        // we'll send the to be active channel to the ChainArbitrator so it can
2882
        // watch for any on-chain actions before the channel has fully
2883
        // confirmed.
2884
        if err := f.cfg.WatchNewChannel(completeChan, peerKey); err != nil {
28✔
2885
                log.Errorf("Unable to send new ChannelPoint(%v) for "+
×
2886
                        "arbitration: %v", fundingPoint, err)
×
2887
        }
×
2888

2889
        log.Infof("Finalizing pending_id(%x) over ChannelPoint(%v), "+
28✔
2890
                "waiting for channel open on-chain", pendingChanID[:],
28✔
2891
                fundingPoint)
28✔
2892

28✔
2893
        // Send an update to the upstream client that the negotiation process
28✔
2894
        // is over.
28✔
2895
        upd := &lnrpc.OpenStatusUpdate{
28✔
2896
                Update: &lnrpc.OpenStatusUpdate_ChanPending{
28✔
2897
                        ChanPending: &lnrpc.PendingUpdate{
28✔
2898
                                Txid:        fundingPoint.Hash[:],
28✔
2899
                                OutputIndex: fundingPoint.Index,
28✔
2900
                        },
28✔
2901
                },
28✔
2902
                PendingChanId: pendingChanID[:],
28✔
2903
        }
28✔
2904

28✔
2905
        select {
28✔
2906
        case resCtx.updates <- upd:
28✔
2907
                // Inform the ChannelNotifier that the channel has entered
28✔
2908
                // pending open state.
28✔
2909
                f.cfg.NotifyPendingOpenChannelEvent(
28✔
2910
                        *fundingPoint, completeChan, completeChan.IdentityPub,
28✔
2911
                )
28✔
2912

2913
        case <-f.quit:
×
2914
                return
×
2915
        }
2916

2917
        // At this point we have broadcast the funding transaction and done all
2918
        // necessary processing.
2919
        f.wg.Add(1)
28✔
2920
        go f.advanceFundingState(completeChan, pendingChanID, resCtx.updates)
28✔
2921
}
2922

2923
// confirmedChannel wraps a confirmed funding transaction, as well as the short
2924
// channel ID which identifies that channel into a single struct. We'll use
2925
// this to pass around the final state of a channel after it has been
2926
// confirmed.
2927
type confirmedChannel struct {
2928
        // shortChanID expresses where in the block the funding transaction was
2929
        // located.
2930
        shortChanID lnwire.ShortChannelID
2931

2932
        // fundingTx is the funding transaction that created the channel.
2933
        fundingTx *wire.MsgTx
2934
}
2935

2936
// fundingTimeout is called when callers of waitForFundingWithTimeout receive
2937
// an ErrConfirmationTimeout. It is used to clean-up channel state and mark the
2938
// channel as closed. The error is only returned for the responder of the
2939
// channel flow.
2940
func (f *Manager) fundingTimeout(c *channeldb.OpenChannel,
2941
        pendingID PendingChanID) error {
2✔
2942

2✔
2943
        // We'll get a timeout if the number of blocks mined since the channel
2✔
2944
        // was initiated reaches MaxWaitNumBlocksFundingConf and we are not the
2✔
2945
        // channel initiator.
2✔
2946
        localBalance := c.LocalCommitment.LocalBalance.ToSatoshis()
2✔
2947
        closeInfo := &channeldb.ChannelCloseSummary{
2✔
2948
                ChainHash:               c.ChainHash,
2✔
2949
                ChanPoint:               c.FundingOutpoint,
2✔
2950
                RemotePub:               c.IdentityPub,
2✔
2951
                Capacity:                c.Capacity,
2✔
2952
                SettledBalance:          localBalance,
2✔
2953
                CloseType:               channeldb.FundingCanceled,
2✔
2954
                RemoteCurrentRevocation: c.RemoteCurrentRevocation,
2✔
2955
                RemoteNextRevocation:    c.RemoteNextRevocation,
2✔
2956
                LocalChanConfig:         c.LocalChanCfg,
2✔
2957
        }
2✔
2958

2✔
2959
        // Close the channel with us as the initiator because we are timing the
2✔
2960
        // channel out.
2✔
2961
        if err := c.CloseChannel(
2✔
2962
                closeInfo, channeldb.ChanStatusLocalCloseInitiator,
2✔
2963
        ); err != nil {
2✔
2964
                return fmt.Errorf("failed closing channel %v: %w",
×
2965
                        c.FundingOutpoint, err)
×
2966
        }
×
2967

2968
        // Notify other subsystems about the funding timeout.
2969
        f.cfg.NotifyFundingTimeout(c.FundingOutpoint, c.IdentityPub)
2✔
2970

2✔
2971
        timeoutErr := fmt.Errorf("timeout waiting for funding tx (%v) to "+
2✔
2972
                "confirm", c.FundingOutpoint)
2✔
2973

2✔
2974
        // When the peer comes online, we'll notify it that we are now
2✔
2975
        // considering the channel flow canceled.
2✔
2976
        f.wg.Add(1)
2✔
2977
        go func() {
4✔
2978
                defer f.wg.Done()
2✔
2979

2✔
2980
                peer, err := f.waitForPeerOnline(c.IdentityPub)
2✔
2981
                switch err {
2✔
2982
                // We're already shutting down, so we can just return.
2983
                case ErrFundingManagerShuttingDown:
×
2984
                        return
×
2985

2986
                // nil error means we continue on.
2987
                case nil:
2✔
2988

2989
                // For unexpected errors, we print the error and still try to
2990
                // fail the funding flow.
2991
                default:
×
2992
                        log.Errorf("Unexpected error while waiting for peer "+
×
2993
                                "to come online: %v", err)
×
2994
                }
2995

2996
                // Create channel identifier and set the channel ID.
2997
                cid := newChanIdentifier(pendingID)
2✔
2998
                cid.setChanID(lnwire.NewChanIDFromOutPoint(c.FundingOutpoint))
2✔
2999

2✔
3000
                // TODO(halseth): should this send be made
2✔
3001
                // reliable?
2✔
3002

2✔
3003
                // The reservation won't exist at this point, but we'll send an
2✔
3004
                // Error message over anyways with ChanID set to pendingID.
2✔
3005
                f.failFundingFlow(peer, cid, timeoutErr)
2✔
3006
        }()
3007

3008
        return timeoutErr
2✔
3009
}
3010

3011
// waitForFundingWithTimeout is a wrapper around waitForFundingConfirmation and
3012
// waitForTimeout that will return ErrConfirmationTimeout if we are not the
3013
// channel initiator and the MaxWaitNumBlocksFundingConf has passed from the
3014
// funding broadcast height. In case of confirmation, the short channel ID of
3015
// the channel and the funding transaction will be returned.
3016
func (f *Manager) waitForFundingWithTimeout(
3017
        ch *channeldb.OpenChannel) (*confirmedChannel, error) {
59✔
3018

59✔
3019
        confChan := make(chan *confirmedChannel)
59✔
3020
        timeoutChan := make(chan error, 1)
59✔
3021
        cancelChan := make(chan struct{})
59✔
3022

59✔
3023
        f.wg.Add(1)
59✔
3024
        go f.waitForFundingConfirmation(ch, cancelChan, confChan)
59✔
3025

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

59✔
3035
        select {
59✔
3036
        case err := <-timeoutChan:
2✔
3037
                if err != nil {
2✔
3038
                        return nil, err
×
3039
                }
×
3040
                return nil, ErrConfirmationTimeout
2✔
3041

3042
        case <-f.quit:
23✔
3043
                // The fundingManager is shutting down, and will resume wait on
23✔
3044
                // startup.
23✔
3045
                return nil, ErrFundingManagerShuttingDown
23✔
3046

3047
        case confirmedChannel, ok := <-confChan:
34✔
3048
                if !ok {
34✔
3049
                        return nil, fmt.Errorf("waiting for funding" +
×
3050
                                "confirmation failed")
×
3051
                }
×
3052
                return confirmedChannel, nil
34✔
3053
        }
3054
}
3055

3056
// makeFundingScript re-creates the funding script for the funding transaction
3057
// of the target channel.
3058
func makeFundingScript(channel *channeldb.OpenChannel) ([]byte, error) {
79✔
3059
        localKey := channel.LocalChanCfg.MultiSigKey.PubKey
79✔
3060
        remoteKey := channel.RemoteChanCfg.MultiSigKey.PubKey
79✔
3061

79✔
3062
        if channel.ChanType.IsTaproot() {
84✔
3063
                pkScript, _, err := input.GenTaprootFundingScript(
5✔
3064
                        localKey, remoteKey, int64(channel.Capacity),
5✔
3065
                        channel.TapscriptRoot,
5✔
3066
                )
5✔
3067
                if err != nil {
5✔
3068
                        return nil, err
×
3069
                }
×
3070

3071
                return pkScript, nil
5✔
3072
        }
3073

3074
        multiSigScript, err := input.GenMultiSigScript(
74✔
3075
                localKey.SerializeCompressed(),
74✔
3076
                remoteKey.SerializeCompressed(),
74✔
3077
        )
74✔
3078
        if err != nil {
74✔
3079
                return nil, err
×
3080
        }
×
3081

3082
        return input.WitnessScriptHash(multiSigScript)
74✔
3083
}
3084

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

59✔
3099
        defer f.wg.Done()
59✔
3100
        defer close(confChan)
59✔
3101

59✔
3102
        // Register with the ChainNotifier for a notification once the funding
59✔
3103
        // transaction reaches `numConfs` confirmations.
59✔
3104
        txid := completeChan.FundingOutpoint.Hash
59✔
3105
        fundingScript, err := makeFundingScript(completeChan)
59✔
3106
        if err != nil {
59✔
3107
                log.Errorf("unable to create funding script for "+
×
3108
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3109
                        err)
×
3110
                return
×
3111
        }
×
3112
        numConfs := uint32(completeChan.NumConfsRequired)
59✔
3113

59✔
3114
        // If the underlying channel is a zero-conf channel, we'll set numConfs
59✔
3115
        // to 6, since it will be zero here.
59✔
3116
        if completeChan.IsZeroConf() {
65✔
3117
                numConfs = 6
6✔
3118
        }
6✔
3119

3120
        confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
59✔
3121
                &txid, fundingScript, numConfs,
59✔
3122
                completeChan.BroadcastHeight(),
59✔
3123
        )
59✔
3124
        if err != nil {
59✔
3125
                log.Errorf("Unable to register for confirmation of "+
×
3126
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3127
                        err)
×
3128
                return
×
3129
        }
×
3130

3131
        log.Infof("Waiting for funding tx (%v) to reach %v confirmations",
59✔
3132
                txid, numConfs)
59✔
3133

59✔
3134
        // Wait until the specified number of confirmations has been reached,
59✔
3135
        // we get a cancel signal, or the wallet signals a shutdown.
59✔
3136
        for {
146✔
3137
                select {
87✔
3138
                case updDetails, ok := <-confNtfn.Updates:
26✔
3139
                        if !ok {
26✔
3140
                                log.Warnf("ChainNotifier shutting down, "+
×
3141
                                        "cannot process updates for "+
×
3142
                                        "ChannelPoint(%v)",
×
3143
                                        completeChan.FundingOutpoint)
×
3144

×
3145
                                return
×
3146
                        }
×
3147

3148
                        log.Debugf("funding tx %s received confirmation in "+
26✔
3149
                                "block %d, %d confirmations left", txid,
26✔
3150
                                updDetails.BlockHeight, updDetails.NumConfsLeft)
26✔
3151

26✔
3152
                        // Only update the ConfirmationHeight the first time a
26✔
3153
                        // confirmation is received, since on subsequent
26✔
3154
                        // confirmations the block height will remain the same.
26✔
3155
                        if completeChan.ConfirmationHeight == 0 {
52✔
3156
                                err := completeChan.MarkConfirmationHeight(
26✔
3157
                                        updDetails.BlockHeight,
26✔
3158
                                )
26✔
3159
                                if err != nil {
26✔
3160
                                        log.Errorf("failed to update "+
×
3161
                                                "confirmed state for "+
×
3162
                                                "ChannelPoint(%v): %v",
×
3163
                                                completeChan.FundingOutpoint,
×
3164
                                                err)
×
3165

×
3166
                                        return
×
3167
                                }
×
3168
                        }
3169

3170
                case _, ok := <-confNtfn.NegativeConf:
2✔
3171
                        if !ok {
2✔
3172
                                log.Warnf("ChainNotifier shutting down, "+
×
3173
                                        "cannot track negative confirmations "+
×
3174
                                        "for ChannelPoint(%v)",
×
3175
                                        completeChan.FundingOutpoint)
×
3176

×
3177
                                return
×
3178
                        }
×
3179

3180
                        log.Warnf("funding tx %s was reorged out; channel "+
2✔
3181
                                "point: %s", txid, completeChan.FundingOutpoint)
2✔
3182

2✔
3183
                        // Reset the confirmation height to 0 because the
2✔
3184
                        // funding transaction was reorged out.
2✔
3185
                        err := completeChan.MarkConfirmationHeight(uint32(0))
2✔
3186
                        if err != nil {
2✔
3187
                                log.Errorf("failed to update state for "+
×
3188
                                        "ChannelPoint(%v): %v",
×
3189
                                        completeChan.FundingOutpoint, err)
×
3190

×
3191
                                return
×
3192
                        }
×
3193

3194
                case confDetails, ok := <-confNtfn.Confirmed:
34✔
3195
                        if !ok {
34✔
3196
                                log.Warnf("ChainNotifier shutting down, "+
×
3197
                                        "cannot complete funding flow for "+
×
3198
                                        "ChannelPoint(%v)",
×
3199
                                        completeChan.FundingOutpoint)
×
3200

×
3201
                                return
×
3202
                        }
×
3203

3204
                        log.Debugf("funding tx %s for ChannelPoint(%v) "+
34✔
3205
                                "confirmed in block %d", txid,
34✔
3206
                                completeChan.FundingOutpoint,
34✔
3207
                                confDetails.BlockHeight)
34✔
3208

34✔
3209
                        // In the case of requiring a single confirmation, it
34✔
3210
                        // can happen that the `Confirmed` channel is read
34✔
3211
                        // from first, in which case the confirmation height
34✔
3212
                        // will not be set. If this happens, we take the
34✔
3213
                        // confirmation height from the `Confirmed` channel.
34✔
3214
                        if completeChan.ConfirmationHeight == 0 {
46✔
3215
                                err := completeChan.MarkConfirmationHeight(
12✔
3216
                                        confDetails.BlockHeight,
12✔
3217
                                )
12✔
3218
                                if err != nil {
12✔
3219
                                        log.Errorf("failed to update "+
×
3220
                                                "confirmed state for "+
×
3221
                                                "ChannelPoint(%v): %v",
×
3222
                                                completeChan.FundingOutpoint,
×
3223
                                                err)
×
3224

×
3225
                                        return
×
3226
                                }
×
3227
                        }
3228

3229
                        err := f.handleConfirmation(
34✔
3230
                                confDetails, completeChan, confChan,
34✔
3231
                        )
34✔
3232
                        if err != nil {
34✔
3233
                                log.Errorf("Error handling confirmation for "+
×
3234
                                        "ChannelPoint(%v), txid=%v: %v",
×
3235
                                        completeChan.FundingOutpoint, txid, err)
×
3236
                        }
×
3237

3238
                        return
34✔
3239

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

2✔
3245
                        return
2✔
3246

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

23✔
3252
                        return
23✔
3253
                }
3254
        }
3255
}
3256

3257
// handleConfirmation is a helper function that constructs a ShortChannelID
3258
// based on the confirmation details and sends this information, along with the
3259
// funding transaction, to the provided confirmation channel.
3260
func (f *Manager) handleConfirmation(confDetails *chainntnfs.TxConfirmation,
3261
        completeChan *channeldb.OpenChannel,
3262
        confChan chan<- *confirmedChannel) error {
34✔
3263

34✔
3264
        fundingPoint := completeChan.FundingOutpoint
34✔
3265
        log.Infof("ChannelPoint(%v) is now active: ChannelID(%v)",
34✔
3266
                fundingPoint, lnwire.NewChanIDFromOutPoint(fundingPoint))
34✔
3267

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

34✔
3277
        select {
34✔
3278
        case confChan <- &confirmedChannel{
3279
                shortChanID: shortChanID,
3280
                fundingTx:   confDetails.Tx,
3281
        }:
34✔
3282
        case <-f.quit:
×
3283
                return fmt.Errorf("manager shutting down")
×
3284
        }
3285

3286
        return nil
34✔
3287
}
3288

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

26✔
3299
        defer f.wg.Done()
26✔
3300

26✔
3301
        epochClient, err := f.cfg.Notifier.RegisterBlockEpochNtfn(nil)
26✔
3302
        if err != nil {
26✔
3303
                timeoutChan <- fmt.Errorf("unable to register for epoch "+
×
3304
                        "notification: %v", err)
×
3305
                return
×
3306
        }
×
3307

3308
        defer epochClient.Cancel()
26✔
3309

26✔
3310
        // The value of waitBlocksForFundingConf is adjusted in a development
26✔
3311
        // environment to enhance test capabilities. Otherwise, it is set to
26✔
3312
        // DefaultMaxWaitNumBlocksFundingConf.
26✔
3313
        waitBlocksForFundingConf := uint32(
26✔
3314
                lncfg.DefaultMaxWaitNumBlocksFundingConf,
26✔
3315
        )
26✔
3316

26✔
3317
        if lncfg.IsDevBuild() {
26✔
3318
                waitBlocksForFundingConf =
×
3319
                        f.cfg.Dev.MaxWaitNumBlocksFundingConf
×
3320
        }
×
3321

3322
        // On block maxHeight we will cancel the funding confirmation wait.
3323
        broadcastHeight := completeChan.BroadcastHeight()
26✔
3324
        maxHeight := broadcastHeight + waitBlocksForFundingConf
26✔
3325
        for {
54✔
3326
                select {
28✔
3327
                case epoch, ok := <-epochClient.Epochs:
4✔
3328
                        if !ok {
4✔
3329
                                timeoutChan <- fmt.Errorf("epoch client " +
×
3330
                                        "shutting down")
×
3331
                                return
×
3332
                        }
×
3333

3334
                        // Close the timeout channel and exit if the block is
3335
                        // above the max height.
3336
                        if uint32(epoch.Height) >= maxHeight {
6✔
3337
                                log.Warnf("Waited for %v blocks without "+
2✔
3338
                                        "seeing funding transaction confirmed,"+
2✔
3339
                                        " cancelling.",
2✔
3340
                                        waitBlocksForFundingConf)
2✔
3341

2✔
3342
                                // Notify the caller of the timeout.
2✔
3343
                                close(timeoutChan)
2✔
3344
                                return
2✔
3345
                        }
2✔
3346

3347
                        // TODO: If we are the channel initiator implement
3348
                        // a method for recovering the funds from the funding
3349
                        // transaction
3350

3351
                case <-cancelChan:
15✔
3352
                        return
15✔
3353

3354
                case <-f.quit:
9✔
3355
                        // The fundingManager is shutting down, will resume
9✔
3356
                        // waiting for the funding transaction on startup.
9✔
3357
                        return
9✔
3358
                }
3359
        }
3360
}
3361

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

16✔
3372
                // For zero-conf channels, we'll use the actually-confirmed
16✔
3373
                // short channel id.
16✔
3374
                if c.IsZeroConf() {
18✔
3375
                        shortChanID = c.ZeroConfRealScid()
2✔
3376
                }
2✔
3377

3378
                label := labels.MakeLabel(
16✔
3379
                        labels.LabelTypeChannelOpen, &shortChanID,
16✔
3380
                )
16✔
3381

16✔
3382
                err := f.cfg.UpdateLabel(c.FundingOutpoint.Hash, label)
16✔
3383
                if err != nil {
16✔
3384
                        log.Errorf("unable to update label: %v", err)
×
3385
                }
×
3386
        }
3387
}
3388

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

30✔
3397
        fundingPoint := completeChan.FundingOutpoint
30✔
3398
        chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
30✔
3399

30✔
3400
        // TODO(roasbeef): ideally persistent state update for chan above
30✔
3401
        // should be abstracted
30✔
3402

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

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

3420
                err = f.cfg.AliasManager.AddLocalAlias(
2✔
3421
                        aliasScid, confChannel.shortChanID, true, false,
2✔
3422
                )
2✔
3423
                if err != nil {
2✔
3424
                        return fmt.Errorf("unable to request alias: %w", err)
×
3425
                }
×
3426
        }
3427

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

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

3450
        // Update the confirmed funding transaction label.
3451
        f.makeLabelForTx(completeChan)
30✔
3452

30✔
3453
        // Inform the ChannelNotifier that the channel has transitioned from
30✔
3454
        // pending open to open.
30✔
3455
        f.cfg.NotifyOpenChannelEvent(
30✔
3456
                completeChan.FundingOutpoint, completeChan.IdentityPub,
30✔
3457
        )
30✔
3458

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

3467
        return nil
30✔
3468
}
3469

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

35✔
3476
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
35✔
3477

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3614
        return nil
34✔
3615
}
3616

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

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

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

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

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

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

26✔
3657
        return !loaded, nil
26✔
3658
}
3659

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

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

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

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

3687
        return fwdMinHTLC, fwdMaxHTLC
26✔
3688
}
3689

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

26✔
3703
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
26✔
3704

26✔
3705
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
26✔
3706

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

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

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

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

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

3763
        return nil
26✔
3764
}
3765

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

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

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

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

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

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

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

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

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

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

3859
                fundingPoint := completeChan.FundingOutpoint
16✔
3860
                chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
16✔
3861

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

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

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

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

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

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

3916
        return nil
24✔
3917
}
3918

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

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

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

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

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

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

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

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

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

4✔
4004
        return nil
4✔
4005
}
4006

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

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

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

4033
        return verNonce, nil
4✔
4034
}
4035

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

28✔
4041
        defer f.wg.Done()
28✔
4042

28✔
4043
        // Notify the aux hook that the specified peer just established a
28✔
4044
        // channel with us, identified by the given channel ID.
28✔
4045
        f.cfg.AuxChannelNegotiator.WhenSome(
28✔
4046
                func(acn lnwallet.AuxChannelNegotiator) {
28✔
4047
                        acn.ProcessChannelReady(msg.ChanID, peer.PubKey())
×
4048
                },
×
4049
        )
4050

4051
        // If we are in development mode, we'll wait for specified duration
4052
        // before processing the channel ready message.
4053
        if f.cfg.Dev != nil {
28✔
4054
                duration := f.cfg.Dev.ProcessChannelReadyWait
×
4055
                log.Warnf("Channel(%v): sleeping %v before processing "+
×
4056
                        "channel_ready", msg.ChanID, duration)
×
4057

×
4058
                select {
×
4059
                case <-time.After(duration):
×
4060
                        log.Warnf("Channel(%v): slept %v before processing "+
×
4061
                                "channel_ready", msg.ChanID, duration)
×
4062
                case <-f.quit:
×
4063
                        log.Warnf("Channel(%v): quit sleeping", msg.ChanID)
×
4064
                        return
×
4065
                }
4066
        }
4067

4068
        log.Debugf("Received ChannelReady for ChannelID(%v) from "+
28✔
4069
                "peer %x", msg.ChanID,
28✔
4070
                peer.IdentityKey().SerializeCompressed())
28✔
4071

28✔
4072
        // We now load or create a new channel barrier for this channel.
28✔
4073
        _, loaded := f.handleChannelReadyBarriers.LoadOrStore(
28✔
4074
                msg.ChanID, struct{}{},
28✔
4075
        )
28✔
4076

28✔
4077
        // If we are currently in the process of handling a channel_ready
28✔
4078
        // message for this channel, ignore.
28✔
4079
        if loaded {
29✔
4080
                log.Infof("Already handling channelReady for "+
1✔
4081
                        "ChannelID(%v), ignoring.", msg.ChanID)
1✔
4082
                return
1✔
4083
        }
1✔
4084

4085
        // If not already handling channelReady for this channel, then the
4086
        // `LoadOrStore` has set up a barrier, and it will be removed once this
4087
        // function exits.
4088
        defer f.handleChannelReadyBarriers.Delete(msg.ChanID)
27✔
4089

27✔
4090
        localDiscoverySignal, ok := f.localDiscoverySignals.Load(msg.ChanID)
27✔
4091
        if ok {
52✔
4092
                // Before we proceed with processing the channel_ready
25✔
4093
                // message, we'll wait for the local waitForFundingConfirmation
25✔
4094
                // goroutine to signal that it has the necessary state in
25✔
4095
                // place. Otherwise, we may be missing critical information
25✔
4096
                // required to handle forwarded HTLC's.
25✔
4097
                select {
25✔
4098
                case <-localDiscoverySignal:
25✔
4099
                        // Fallthrough
4100
                case <-f.quit:
×
4101
                        return
×
4102
                }
4103

4104
                // With the signal received, we can now safely delete the entry
4105
                // from the map.
4106
                f.localDiscoverySignals.Delete(msg.ChanID)
25✔
4107
        }
4108

4109
        // First, we'll attempt to locate the channel whose funding workflow is
4110
        // being finalized by this message. We go to the database rather than
4111
        // our reservation map as we may have restarted, mid funding flow. Also
4112
        // provide the node's public key to make the search faster.
4113
        chanID := msg.ChanID
27✔
4114
        channel, err := f.cfg.FindChannel(peer.IdentityKey(), chanID)
27✔
4115
        if err != nil {
27✔
4116
                log.Errorf("Unable to locate ChannelID(%v), cannot complete "+
×
4117
                        "funding", chanID)
×
4118
                return
×
4119
        }
×
4120

4121
        // If this is a taproot channel, then we can generate the set of nonces
4122
        // the remote party needs to send the next remote commitment here.
4123
        var firstVerNonce *musig2.Nonces
27✔
4124
        if channel.ChanType.IsTaproot() {
31✔
4125
                firstVerNonce, err = genFirstStateMusigNonce(channel)
4✔
4126
                if err != nil {
4✔
4127
                        log.Error(err)
×
4128
                        return
×
4129
                }
×
4130
        }
4131

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

4149
                // We'll store the AliasScid so that invoice creation can use
4150
                // it.
4151
                err = f.cfg.AliasManager.PutPeerAlias(chanID, *msg.AliasScid)
6✔
4152
                if err != nil {
6✔
4153
                        log.Errorf("unable to store peer's alias: %v", err)
×
4154
                        return
×
4155
                }
×
4156

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

4174
                        err = f.cfg.AliasManager.AddLocalAlias(
×
4175
                                alias, channel.ShortChannelID, false, false,
×
4176
                        )
×
4177
                        if err != nil {
×
4178
                                log.Errorf("unable to add local alias: %v",
×
4179
                                        err)
×
4180
                                return
×
4181
                        }
×
4182

4183
                        secondPoint, err := channel.SecondCommitmentPoint()
×
4184
                        if err != nil {
×
4185
                                log.Errorf("unable to fetch second "+
×
4186
                                        "commitment point: %v", err)
×
4187
                                return
×
4188
                        }
×
4189

4190
                        channelReadyMsg := lnwire.NewChannelReady(
×
4191
                                chanID, secondPoint,
×
4192
                        )
×
4193
                        channelReadyMsg.AliasScid = &alias
×
4194

×
4195
                        if firstVerNonce != nil {
×
4196
                                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:ll
×
4197
                                        firstVerNonce.PubNonce,
×
4198
                                )
×
4199
                        }
×
4200

4201
                        err = peer.SendMessage(true, channelReadyMsg)
×
4202
                        if err != nil {
×
4203
                                log.Errorf("unable to send channel_ready: %v",
×
4204
                                        err)
×
4205
                                return
×
4206
                        }
×
4207
                }
4208
        }
4209

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

4225
        // If this is a taproot channel, then we'll need to map the received
4226
        // nonces to a nonce pair, and also fetch our pending nonces, which are
4227
        // required in order to make the channel whole.
4228
        var chanOpts []lnwallet.ChannelOpt
26✔
4229
        if channel.ChanType.IsTaproot() {
30✔
4230
                f.nonceMtx.Lock()
4✔
4231
                localNonce, ok := f.pendingMusigNonces[chanID]
4✔
4232
                if !ok {
4✔
4233
                        // If there's no pending nonce for this channel ID,
×
4234
                        // we'll use the one generated above.
×
4235
                        localNonce = firstVerNonce
×
4236
                        f.pendingMusigNonces[chanID] = firstVerNonce
×
4237
                }
×
4238
                f.nonceMtx.Unlock()
4✔
4239

4✔
4240
                log.Infof("ChanID(%v): applying local+remote musig2 nonces",
4✔
4241
                        chanID)
4✔
4242

4✔
4243
                remoteNonce, err := msg.NextLocalNonce.UnwrapOrErrV(
4✔
4244
                        errNoLocalNonce,
4✔
4245
                )
4✔
4246
                if err != nil {
4✔
4247
                        cid := newChanIdentifier(msg.ChanID)
×
4248
                        f.sendWarning(peer, cid, err)
×
4249

×
4250
                        return
×
4251
                }
×
4252

4253
                chanOpts = append(
4✔
4254
                        chanOpts,
4✔
4255
                        lnwallet.WithLocalMusigNonces(localNonce),
4✔
4256
                        lnwallet.WithRemoteMusigNonces(&musig2.Nonces{
4✔
4257
                                PubNonce: remoteNonce,
4✔
4258
                        }),
4✔
4259
                )
4✔
4260

4✔
4261
                // Inform the aux funding controller that the liquidity in the
4✔
4262
                // custom channel is now ready to be advertised. We potentially
4✔
4263
                // haven't sent our own channel ready message yet, but other
4✔
4264
                // than that the channel is ready to count toward available
4✔
4265
                // liquidity.
4✔
4266
                err = fn.MapOptionZ(
4✔
4267
                        f.cfg.AuxFundingController,
4✔
4268
                        func(controller AuxFundingController) error {
4✔
4269
                                return controller.ChannelReady(
×
4270
                                        lnwallet.NewAuxChanState(channel),
×
4271
                                )
×
4272
                        },
×
4273
                )
4274
                if err != nil {
4✔
4275
                        cid := newChanIdentifier(msg.ChanID)
×
4276
                        f.sendWarning(peer, cid, err)
×
4277

×
4278
                        return
×
4279
                }
×
4280
        }
4281

4282
        // The channel_ready message contains the next commitment point we'll
4283
        // need to create the next commitment state for the remote party. So
4284
        // we'll insert that into the channel now before passing it along to
4285
        // other sub-systems.
4286
        err = channel.InsertNextRevocation(msg.NextPerCommitmentPoint)
26✔
4287
        if err != nil {
26✔
4288
                log.Errorf("unable to insert next commitment point: %v", err)
×
4289
                return
×
4290
        }
×
4291

4292
        // Before we can add the channel to the peer, we'll need to ensure that
4293
        // we have an initial forwarding policy set.
4294
        if err := f.ensureInitialForwardingPolicy(chanID, channel); err != nil {
26✔
4295
                log.Errorf("Unable to ensure initial forwarding policy: %v",
×
4296
                        err)
×
4297
        }
×
4298

4299
        err = peer.AddNewChannel(&lnpeer.NewChannel{
26✔
4300
                OpenChannel: channel,
26✔
4301
                ChanOpts:    chanOpts,
26✔
4302
        }, f.quit)
26✔
4303
        if err != nil {
26✔
4304
                log.Errorf("Unable to add new channel %v with peer %x: %v",
×
4305
                        channel.FundingOutpoint,
×
4306
                        peer.IdentityKey().SerializeCompressed(), err,
×
4307
                )
×
4308
        }
×
4309
}
4310

4311
// handleChannelReadyReceived is called once the remote's channelReady message
4312
// is received and processed. At this stage, we must have sent out our
4313
// channelReady message, once the remote's channelReady is processed, the
4314
// channel is now active, thus we change its state to `addedToGraph` to
4315
// let the channel start handling routing.
4316
func (f *Manager) handleChannelReadyReceived(channel *channeldb.OpenChannel,
4317
        scid *lnwire.ShortChannelID, pendingChanID PendingChanID,
4318
        updateChan chan<- *lnrpc.OpenStatusUpdate) error {
24✔
4319

24✔
4320
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
24✔
4321

24✔
4322
        // Since we've sent+received funding locked at this point, we
24✔
4323
        // can clean up the pending musig2 nonce state.
24✔
4324
        f.nonceMtx.Lock()
24✔
4325
        delete(f.pendingMusigNonces, chanID)
24✔
4326
        f.nonceMtx.Unlock()
24✔
4327

24✔
4328
        var peerAlias *lnwire.ShortChannelID
24✔
4329
        if channel.IsZeroConf() {
28✔
4330
                // We'll need to wait until channel_ready has been received and
4✔
4331
                // the peer lets us know the alias they want to use for the
4✔
4332
                // channel. With this information, we can then construct a
4✔
4333
                // ChannelUpdate for them.  If an alias does not yet exist,
4✔
4334
                // we'll just return, letting the next iteration of the loop
4✔
4335
                // check again.
4✔
4336
                var defaultAlias lnwire.ShortChannelID
4✔
4337
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
4✔
4338
                foundAlias, _ := f.cfg.AliasManager.GetPeerAlias(chanID)
4✔
4339
                if foundAlias == defaultAlias {
4✔
4340
                        return nil
×
4341
                }
×
4342

4343
                peerAlias = &foundAlias
4✔
4344
        }
4345

4346
        err := f.addToGraph(channel, scid, peerAlias, nil)
24✔
4347
        if err != nil {
24✔
4348
                return fmt.Errorf("failed adding to graph: %w", err)
×
4349
        }
×
4350

4351
        // As the channel is now added to the ChannelRouter's topology, the
4352
        // channel is moved to the next state of the state machine. It will be
4353
        // moved to the last state (actually deleted from the database) after
4354
        // the channel is finally announced.
4355
        err = f.saveChannelOpeningState(
24✔
4356
                &channel.FundingOutpoint, addedToGraph, scid,
24✔
4357
        )
24✔
4358
        if err != nil {
24✔
4359
                return fmt.Errorf("error setting channel state to"+
×
4360
                        " addedToGraph: %w", err)
×
4361
        }
×
4362

4363
        log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
24✔
4364
                "added to graph", chanID, scid)
24✔
4365

24✔
4366
        err = fn.MapOptionZ(
24✔
4367
                f.cfg.AuxFundingController,
24✔
4368
                func(controller AuxFundingController) error {
24✔
4369
                        return controller.ChannelReady(
×
4370
                                lnwallet.NewAuxChanState(channel),
×
4371
                        )
×
4372
                },
×
4373
        )
4374
        if err != nil {
24✔
4375
                return fmt.Errorf("failed notifying aux funding controller "+
×
4376
                        "about channel ready: %w", err)
×
4377
        }
×
4378

4379
        // Give the caller a final update notifying them that the channel is
4380
        fundingPoint := channel.FundingOutpoint
24✔
4381
        cp := &lnrpc.ChannelPoint{
24✔
4382
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
24✔
4383
                        FundingTxidBytes: fundingPoint.Hash[:],
24✔
4384
                },
24✔
4385
                OutputIndex: fundingPoint.Index,
24✔
4386
        }
24✔
4387

24✔
4388
        if updateChan != nil {
34✔
4389
                upd := &lnrpc.OpenStatusUpdate{
10✔
4390
                        Update: &lnrpc.OpenStatusUpdate_ChanOpen{
10✔
4391
                                ChanOpen: &lnrpc.ChannelOpenUpdate{
10✔
4392
                                        ChannelPoint: cp,
10✔
4393
                                },
10✔
4394
                        },
10✔
4395
                        PendingChanId: pendingChanID[:],
10✔
4396
                }
10✔
4397

10✔
4398
                select {
10✔
4399
                case updateChan <- upd:
10✔
4400
                case <-f.quit:
×
4401
                        return ErrFundingManagerShuttingDown
×
4402
                }
4403
        }
4404

4405
        return nil
24✔
4406
}
4407

4408
// ensureInitialForwardingPolicy ensures that we have an initial forwarding
4409
// policy set for the given channel. If we don't, we'll fall back to the default
4410
// values.
4411
func (f *Manager) ensureInitialForwardingPolicy(chanID lnwire.ChannelID,
4412
        channel *channeldb.OpenChannel) error {
26✔
4413

26✔
4414
        // Before we can add the channel to the peer, we'll need to ensure that
26✔
4415
        // we have an initial forwarding policy set. This should always be the
26✔
4416
        // case except for a channel that was created with lnd <= 0.15.5 and
26✔
4417
        // is still pending while updating to this version.
26✔
4418
        var needDBUpdate bool
26✔
4419
        forwardingPolicy, err := f.getInitialForwardingPolicy(chanID)
26✔
4420
        if err != nil {
26✔
4421
                log.Errorf("Unable to fetch initial forwarding policy, "+
×
4422
                        "falling back to default values: %v", err)
×
4423

×
4424
                forwardingPolicy = f.defaultForwardingPolicy(
×
4425
                        channel.LocalChanCfg.ChannelStateBounds,
×
4426
                )
×
4427
                needDBUpdate = true
×
4428
        }
×
4429

4430
        // We only started storing the actual values for MinHTLCOut and MaxHTLC
4431
        // after 0.16.x, so if a channel was opened with such a version and is
4432
        // still pending while updating to this version, we'll need to set the
4433
        // values to the default values.
4434
        if forwardingPolicy.MinHTLCOut == 0 {
39✔
4435
                forwardingPolicy.MinHTLCOut = channel.LocalChanCfg.MinHTLC
13✔
4436
                needDBUpdate = true
13✔
4437
        }
13✔
4438
        if forwardingPolicy.MaxHTLC == 0 {
39✔
4439
                forwardingPolicy.MaxHTLC = channel.LocalChanCfg.MaxPendingAmount
13✔
4440
                needDBUpdate = true
13✔
4441
        }
13✔
4442

4443
        // And finally, if we found that the values currently stored aren't
4444
        // sufficient for the link, we'll update the database.
4445
        if needDBUpdate {
39✔
4446
                err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
13✔
4447
                if err != nil {
13✔
4448
                        return fmt.Errorf("unable to update initial "+
×
4449
                                "forwarding policy: %v", err)
×
4450
                }
×
4451
        }
4452

4453
        return nil
26✔
4454
}
4455

4456
// chanAnnouncement encapsulates the two authenticated announcements that we
4457
// send out to the network after a new channel has been created locally.
4458
type chanAnnouncement struct {
4459
        chanAnn       *lnwire.ChannelAnnouncement1
4460
        chanUpdateAnn *lnwire.ChannelUpdate1
4461
        chanProof     *lnwire.AnnounceSignatures1
4462
}
4463

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

42✔
4479
        chainHash := *f.cfg.Wallet.Cfg.NetParams.GenesisHash
42✔
4480

42✔
4481
        // The unconditional section of the announcement is the ShortChannelID
42✔
4482
        // itself which compactly encodes the location of the funding output
42✔
4483
        // within the blockchain.
42✔
4484
        chanAnn := &lnwire.ChannelAnnouncement1{
42✔
4485
                ShortChannelID: shortChanID,
42✔
4486
                Features:       lnwire.NewRawFeatureVector(),
42✔
4487
                ChainHash:      chainHash,
42✔
4488
        }
42✔
4489

42✔
4490
        // If this is a taproot channel, then we'll set a special bit in the
42✔
4491
        // feature vector to indicate to the routing layer that this needs a
42✔
4492
        // slightly different type of validation.
42✔
4493
        //
42✔
4494
        // TODO(roasbeef): temp, remove after gossip 1.5
42✔
4495
        if chanType.IsTaproot() {
46✔
4496
                log.Debugf("Applying taproot feature bit to "+
4✔
4497
                        "ChannelAnnouncement for %v", chanID)
4✔
4498

4✔
4499
                chanAnn.Features.Set(
4✔
4500
                        lnwire.SimpleTaprootChannelsRequiredStaging,
4✔
4501
                )
4✔
4502
        }
4✔
4503

4504
        // The chanFlags field indicates which directed edge of the channel is
4505
        // being updated within the ChannelUpdateAnnouncement announcement
4506
        // below. A value of zero means it's the edge of the "first" node and 1
4507
        // being the other node.
4508
        var chanFlags lnwire.ChanUpdateChanFlags
42✔
4509

42✔
4510
        // The lexicographical ordering of the two identity public keys of the
42✔
4511
        // nodes indicates which of the nodes is "first". If our serialized
42✔
4512
        // identity key is lower than theirs then we're the "first" node and
42✔
4513
        // second otherwise.
42✔
4514
        selfBytes := localPubKey.SerializeCompressed()
42✔
4515
        remoteBytes := remotePubKey.SerializeCompressed()
42✔
4516
        if bytes.Compare(selfBytes, remoteBytes) == -1 {
63✔
4517
                copy(chanAnn.NodeID1[:], localPubKey.SerializeCompressed())
21✔
4518
                copy(chanAnn.NodeID2[:], remotePubKey.SerializeCompressed())
21✔
4519
                copy(
21✔
4520
                        chanAnn.BitcoinKey1[:],
21✔
4521
                        localFundingKey.PubKey.SerializeCompressed(),
21✔
4522
                )
21✔
4523
                copy(
21✔
4524
                        chanAnn.BitcoinKey2[:],
21✔
4525
                        remoteFundingKey.SerializeCompressed(),
21✔
4526
                )
21✔
4527

21✔
4528
                // If we're the first node then update the chanFlags to
21✔
4529
                // indicate the "direction" of the update.
21✔
4530
                chanFlags = 0
21✔
4531
        } else {
42✔
4532
                copy(chanAnn.NodeID1[:], remotePubKey.SerializeCompressed())
21✔
4533
                copy(chanAnn.NodeID2[:], localPubKey.SerializeCompressed())
21✔
4534
                copy(
21✔
4535
                        chanAnn.BitcoinKey1[:],
21✔
4536
                        remoteFundingKey.SerializeCompressed(),
21✔
4537
                )
21✔
4538
                copy(
21✔
4539
                        chanAnn.BitcoinKey2[:],
21✔
4540
                        localFundingKey.PubKey.SerializeCompressed(),
21✔
4541
                )
21✔
4542

21✔
4543
                // If we're the second node then update the chanFlags to
21✔
4544
                // indicate the "direction" of the update.
21✔
4545
                chanFlags = 1
21✔
4546
        }
21✔
4547

4548
        // Our channel update message flags will signal that we support the
4549
        // max_htlc field.
4550
        msgFlags := lnwire.ChanUpdateRequiredMaxHtlc
42✔
4551

42✔
4552
        // We announce the channel with the default values. Some of
42✔
4553
        // these values can later be changed by crafting a new ChannelUpdate.
42✔
4554
        chanUpdateAnn := &lnwire.ChannelUpdate1{
42✔
4555
                ShortChannelID: shortChanID,
42✔
4556
                ChainHash:      chainHash,
42✔
4557
                Timestamp:      uint32(time.Now().Unix()),
42✔
4558
                MessageFlags:   msgFlags,
42✔
4559
                ChannelFlags:   chanFlags,
42✔
4560
                TimeLockDelta: uint16(
42✔
4561
                        f.cfg.DefaultRoutingPolicy.TimeLockDelta,
42✔
4562
                ),
42✔
4563
                HtlcMinimumMsat: fwdMinHTLC,
42✔
4564
                HtlcMaximumMsat: fwdMaxHTLC,
42✔
4565
        }
42✔
4566

42✔
4567
        // The caller of newChanAnnouncement is expected to provide the initial
42✔
4568
        // forwarding policy to be announced. If no persisted initial policy
42✔
4569
        // values are found, then we will use the default policy values in the
42✔
4570
        // channel announcement.
42✔
4571
        storedFwdingPolicy, err := f.getInitialForwardingPolicy(chanID)
42✔
4572
        if err != nil && !errors.Is(err, channeldb.ErrChannelNotFound) {
42✔
4573
                return nil, fmt.Errorf("unable to generate channel "+
×
4574
                        "update announcement: %w", err)
×
4575
        }
×
4576

4577
        switch {
42✔
4578
        case ourPolicy != nil:
×
4579
                // If ourPolicy is non-nil, modify the default parameters of the
×
4580
                // ChannelUpdate.
×
4581
                chanUpdateAnn.MessageFlags = ourPolicy.MessageFlags
×
4582
                chanUpdateAnn.ChannelFlags = ourPolicy.ChannelFlags
×
4583
                chanUpdateAnn.TimeLockDelta = ourPolicy.TimeLockDelta
×
4584
                chanUpdateAnn.HtlcMinimumMsat = ourPolicy.MinHTLC
×
4585
                chanUpdateAnn.HtlcMaximumMsat = ourPolicy.MaxHTLC
×
4586
                chanUpdateAnn.BaseFee = uint32(ourPolicy.FeeBaseMSat)
×
4587
                chanUpdateAnn.FeeRate = uint32(
×
4588
                        ourPolicy.FeeProportionalMillionths,
×
4589
                )
×
4590

4591
        case storedFwdingPolicy != nil:
42✔
4592
                chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
42✔
4593
                chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
42✔
4594

4595
        default:
×
4596
                log.Infof("No channel forwarding policy specified for channel "+
×
4597
                        "announcement of ChannelID(%v). "+
×
4598
                        "Assuming default fee parameters.", chanID)
×
4599
                chanUpdateAnn.BaseFee = uint32(
×
4600
                        f.cfg.DefaultRoutingPolicy.BaseFee,
×
4601
                )
×
4602
                chanUpdateAnn.FeeRate = uint32(
×
4603
                        f.cfg.DefaultRoutingPolicy.FeeRate,
×
4604
                )
×
4605
        }
4606

4607
        // With the channel update announcement constructed, we'll generate a
4608
        // signature that signs a double-sha digest of the announcement.
4609
        // This'll serve to authenticate this announcement and any other future
4610
        // updates we may send.
4611
        chanUpdateMsg, err := chanUpdateAnn.DataToSign()
42✔
4612
        if err != nil {
42✔
4613
                return nil, err
×
4614
        }
×
4615
        sig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanUpdateMsg, true)
42✔
4616
        if err != nil {
42✔
4617
                return nil, fmt.Errorf("unable to generate channel "+
×
4618
                        "update announcement signature: %w", err)
×
4619
        }
×
4620
        chanUpdateAnn.Signature, err = lnwire.NewSigFromSignature(sig)
42✔
4621
        if err != nil {
42✔
4622
                return nil, fmt.Errorf("unable to generate channel "+
×
4623
                        "update announcement signature: %w", err)
×
4624
        }
×
4625

4626
        // The channel existence proofs itself is currently announced in
4627
        // distinct message. In order to properly authenticate this message, we
4628
        // need two signatures: one under the identity public key used which
4629
        // signs the message itself and another signature of the identity
4630
        // public key under the funding key itself.
4631
        //
4632
        // TODO(roasbeef): use SignAnnouncement here instead?
4633
        chanAnnMsg, err := chanAnn.DataToSign()
42✔
4634
        if err != nil {
42✔
4635
                return nil, err
×
4636
        }
×
4637
        nodeSig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanAnnMsg, true)
42✔
4638
        if err != nil {
42✔
4639
                return nil, fmt.Errorf("unable to generate node "+
×
4640
                        "signature for channel announcement: %w", err)
×
4641
        }
×
4642
        bitcoinSig, err := f.cfg.SignMessage(
42✔
4643
                localFundingKey.KeyLocator, chanAnnMsg, true,
42✔
4644
        )
42✔
4645
        if err != nil {
42✔
4646
                return nil, fmt.Errorf("unable to generate bitcoin "+
×
4647
                        "signature for node public key: %w", err)
×
4648
        }
×
4649

4650
        // Finally, we'll generate the announcement proof which we'll use to
4651
        // provide the other side with the necessary signatures required to
4652
        // allow them to reconstruct the full channel announcement.
4653
        proof := &lnwire.AnnounceSignatures1{
42✔
4654
                ChannelID:      chanID,
42✔
4655
                ShortChannelID: shortChanID,
42✔
4656
        }
42✔
4657
        proof.NodeSignature, err = lnwire.NewSigFromSignature(nodeSig)
42✔
4658
        if err != nil {
42✔
4659
                return nil, err
×
4660
        }
×
4661
        proof.BitcoinSignature, err = lnwire.NewSigFromSignature(bitcoinSig)
42✔
4662
        if err != nil {
42✔
4663
                return nil, err
×
4664
        }
×
4665

4666
        return &chanAnnouncement{
42✔
4667
                chanAnn:       chanAnn,
42✔
4668
                chanUpdateAnn: chanUpdateAnn,
42✔
4669
                chanProof:     proof,
42✔
4670
        }, nil
42✔
4671
}
4672

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

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

4701
        // We only send the channel proof announcement and the node announcement
4702
        // because addToGraph previously sent the ChannelAnnouncement and
4703
        // the ChannelUpdate announcement messages. The channel proof and node
4704
        // announcements are broadcast to the greater network.
4705
        errChan := f.cfg.SendAnnouncement(ann.chanProof)
16✔
4706
        select {
16✔
4707
        case err := <-errChan:
16✔
4708
                if err != nil {
16✔
4709
                        if graph.IsError(err, graph.ErrOutdated,
×
4710
                                graph.ErrIgnored) {
×
4711

×
4712
                                log.Debugf("Graph rejected "+
×
4713
                                        "AnnounceSignatures: %v", err)
×
4714
                        } else {
×
4715
                                log.Errorf("Unable to send channel "+
×
4716
                                        "proof: %v", err)
×
4717
                                return err
×
4718
                        }
×
4719
                }
4720

4721
        case <-f.quit:
×
4722
                return ErrFundingManagerShuttingDown
×
4723
        }
4724

4725
        // Now that the channel is announced to the network, we will also
4726
        // obtain and send a node announcement. This is done since a node
4727
        // announcement is only accepted after a channel is known for that
4728
        // particular node, and this might be our first channel.
4729
        nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
16✔
4730
        if err != nil {
16✔
4731
                log.Errorf("can't generate node announcement: %v", err)
×
4732
                return err
×
4733
        }
×
4734

4735
        errChan = f.cfg.SendAnnouncement(&nodeAnn)
16✔
4736
        select {
16✔
4737
        case err := <-errChan:
16✔
4738
                if err != nil {
16✔
4739
                        if graph.IsError(err, graph.ErrOutdated,
×
4740
                                graph.ErrIgnored) {
×
4741

×
4742
                                log.Debugf("Graph rejected "+
×
4743
                                        "NodeAnnouncement1: %v", err)
×
4744
                        } else {
×
4745
                                log.Errorf("Unable to send node "+
×
4746
                                        "announcement: %v", err)
×
4747
                                return err
×
4748
                        }
×
4749
                }
4750

4751
        case <-f.quit:
×
4752
                return ErrFundingManagerShuttingDown
×
4753
        }
4754

4755
        return nil
16✔
4756
}
4757

4758
// InitFundingWorkflow sends a message to the funding manager instructing it
4759
// to initiate a single funder workflow with the source peer.
4760
func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg) {
57✔
4761
        f.fundingRequests <- msg
57✔
4762
}
57✔
4763

4764
// getUpfrontShutdownScript takes a user provided script and a getScript
4765
// function which can be used to generate an upfront shutdown script. If our
4766
// peer does not support the feature, this function will error if a non-zero
4767
// script was provided by the user, and return an empty script otherwise. If
4768
// our peer does support the feature, we will return the user provided script
4769
// if non-zero, or a freshly generated script if our node is configured to set
4770
// upfront shutdown scripts automatically.
4771
func getUpfrontShutdownScript(enableUpfrontShutdown bool, peer lnpeer.Peer,
4772
        script lnwire.DeliveryAddress,
4773
        getScript func(bool) (lnwire.DeliveryAddress, error)) (lnwire.DeliveryAddress,
4774
        error) {
110✔
4775

110✔
4776
        // Check whether the remote peer supports upfront shutdown scripts.
110✔
4777
        remoteUpfrontShutdown := peer.RemoteFeatures().HasFeature(
110✔
4778
                lnwire.UpfrontShutdownScriptOptional,
110✔
4779
        )
110✔
4780

110✔
4781
        // If the peer does not support upfront shutdown scripts, and one has been
110✔
4782
        // provided, return an error because the feature is not supported.
110✔
4783
        if !remoteUpfrontShutdown && len(script) != 0 {
111✔
4784
                return nil, errUpfrontShutdownScriptNotSupported
1✔
4785
        }
1✔
4786

4787
        // If the peer does not support upfront shutdown, return an empty address.
4788
        if !remoteUpfrontShutdown {
214✔
4789
                return nil, nil
105✔
4790
        }
105✔
4791

4792
        // If the user has provided an script and the peer supports the feature,
4793
        // return it. Note that user set scripts override the enable upfront
4794
        // shutdown flag.
4795
        if len(script) > 0 {
6✔
4796
                return script, nil
2✔
4797
        }
2✔
4798

4799
        // If we do not have setting of upfront shutdown script enabled, return
4800
        // an empty script.
4801
        if !enableUpfrontShutdown {
3✔
4802
                return nil, nil
1✔
4803
        }
1✔
4804

4805
        // We can safely send a taproot address iff, both sides have negotiated
4806
        // the shutdown-any-segwit feature.
4807
        taprootOK := peer.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
1✔
4808
                peer.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
1✔
4809

1✔
4810
        return getScript(taprootOK)
1✔
4811
}
4812

4813
// handleInitFundingMsg creates a channel reservation within the daemon's
4814
// wallet, then sends a funding request to the remote peer kicking off the
4815
// funding workflow.
4816
func (f *Manager) handleInitFundingMsg(msg *InitFundingMsg) {
57✔
4817
        var (
57✔
4818
                peerKey        = msg.Peer.IdentityKey()
57✔
4819
                localAmt       = msg.LocalFundingAmt
57✔
4820
                baseFee        = msg.BaseFee
57✔
4821
                feeRate        = msg.FeeRate
57✔
4822
                minHtlcIn      = msg.MinHtlcIn
57✔
4823
                remoteCsvDelay = msg.RemoteCsvDelay
57✔
4824
                maxValue       = msg.MaxValueInFlight
57✔
4825
                maxHtlcs       = msg.MaxHtlcs
57✔
4826
                maxCSV         = msg.MaxLocalCsv
57✔
4827
                chanReserve    = msg.RemoteChanReserve
57✔
4828
                outpoints      = msg.Outpoints
57✔
4829
        )
57✔
4830

57✔
4831
        // If no maximum CSV delay was set for this channel, we use our default
57✔
4832
        // value.
57✔
4833
        if maxCSV == 0 {
114✔
4834
                maxCSV = f.cfg.MaxLocalCSVDelay
57✔
4835
        }
57✔
4836

4837
        log.Infof("Initiating fundingRequest(local_amt=%v "+
57✔
4838
                "(subtract_fees=%v), push_amt=%v, chain_hash=%v, peer=%x, "+
57✔
4839
                "min_confs=%v)", localAmt, msg.SubtractFees, msg.PushAmt,
57✔
4840
                msg.ChainHash, peerKey.SerializeCompressed(), msg.MinConfs)
57✔
4841

57✔
4842
        // We set the channel flags to indicate whether we want this channel to
57✔
4843
        // be announced to the network.
57✔
4844
        var channelFlags lnwire.FundingFlag
57✔
4845
        if !msg.Private {
109✔
4846
                // This channel will be announced.
52✔
4847
                channelFlags = lnwire.FFAnnounceChannel
52✔
4848
        }
52✔
4849

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

4868
        // If the funder did not provide an upfront-shutdown address, fall back
4869
        // to the configured shutdown script (if any).
4870
        shutdownScript := msg.ShutdownScript
57✔
4871
        if len(shutdownScript) == 0 {
114✔
4872
                f.cfg.ShutdownScript.WhenSome(
57✔
4873
                        func(script lnwire.DeliveryAddress) {
57✔
4874
                                shutdownScript = script
×
4875
                        },
×
4876
                )
4877
        }
4878

4879
        // Check whether the peer supports upfront shutdown, and get an address
4880
        // which should be used (either a user specified address or a new
4881
        // address from the wallet if our node is configured to set shutdown
4882
        // address by default).
4883
        shutdown, err := getUpfrontShutdownScript(
57✔
4884
                f.cfg.EnableUpfrontShutdown, msg.Peer, shutdownScript,
57✔
4885
                f.selectShutdownScript,
57✔
4886
        )
57✔
4887
        if err != nil {
57✔
4888
                msg.Err <- err
×
4889
                return
×
4890
        }
×
4891

4892
        // Initialize a funding reservation with the local wallet. If the
4893
        // wallet doesn't have enough funds to commit to this channel, then the
4894
        // request will fail, and be aborted.
4895
        //
4896
        // Before we init the channel, we'll also check to see what commitment
4897
        // format we can use with this peer. This is dependent on *both* us and
4898
        // the remote peer are signaling the proper feature bit.
4899
        chanType, commitType, err := negotiateCommitmentType(
57✔
4900
                msg.ChannelType, msg.Peer.LocalFeatures(),
57✔
4901
                msg.Peer.RemoteFeatures(),
57✔
4902
        )
57✔
4903
        if err != nil {
57✔
4904
                log.Errorf("channel type negotiation failed: %v", err)
×
4905
                msg.Err <- err
×
4906
                return
×
4907
        }
×
4908

4909
        var (
57✔
4910
                zeroConf bool
57✔
4911
                scid     bool
57✔
4912
        )
57✔
4913

57✔
4914
        if chanType != nil {
61✔
4915
                // Check if the returned chanType includes either the zero-conf
4✔
4916
                // or scid-alias bits.
4✔
4917
                featureVec := lnwire.RawFeatureVector(*chanType)
4✔
4918
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
4✔
4919
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
4✔
4920

4✔
4921
                // The option-scid-alias channel type for a public channel is
4✔
4922
                // disallowed.
4✔
4923
                if scid && !msg.Private {
4✔
4924
                        err = fmt.Errorf("option-scid-alias chantype for " +
×
4925
                                "public channel")
×
4926
                        log.Error(err)
×
4927
                        msg.Err <- err
×
4928

×
4929
                        return
×
4930
                }
×
4931
        }
4932

4933
        // First, we'll query the fee estimator for a fee that should get the
4934
        // commitment transaction confirmed by the next few blocks (conf target
4935
        // of 3). We target the near blocks here to ensure that we'll be able
4936
        // to execute a timely unilateral channel closure if needed.
4937
        commitFeePerKw, err := f.cfg.FeeEstimator.EstimateFeePerKW(3)
57✔
4938
        if err != nil {
57✔
4939
                msg.Err <- err
×
4940
                return
×
4941
        }
×
4942

4943
        // For anchor channels cap the initial commit fee rate at our defined
4944
        // maximum.
4945
        if commitType.HasAnchors() &&
57✔
4946
                commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
61✔
4947

4✔
4948
                commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate
4✔
4949
        }
4✔
4950

4951
        var scidFeatureVal bool
57✔
4952
        if hasFeatures(
57✔
4953
                msg.Peer.LocalFeatures(), msg.Peer.RemoteFeatures(),
57✔
4954
                lnwire.ScidAliasOptional,
57✔
4955
        ) {
60✔
4956

3✔
4957
                scidFeatureVal = true
3✔
4958
        }
3✔
4959

4960
        // At this point, if we have an AuxFundingController active, we'll check
4961
        // to see if we have a special tapscript root to use in our MuSig2
4962
        // funding output.
4963
        tapscriptRoot, err := fn.MapOptionZ(
57✔
4964
                f.cfg.AuxFundingController,
57✔
4965
                func(c AuxFundingController) AuxTapscriptResult {
57✔
4966
                        return c.DeriveTapscriptRoot(chanID)
×
4967
                },
×
4968
        ).Unpack()
4969
        if err != nil {
57✔
4970
                err = fmt.Errorf("error deriving tapscript root: %w", err)
×
4971
                log.Error(err)
×
4972
                msg.Err <- err
×
4973

×
4974
                return
×
4975
        }
×
4976

4977
        req := &lnwallet.InitFundingReserveMsg{
57✔
4978
                ChainHash:         &msg.ChainHash,
57✔
4979
                PendingChanID:     chanID,
57✔
4980
                NodeID:            peerKey,
57✔
4981
                NodeAddr:          msg.Peer.Address(),
57✔
4982
                SubtractFees:      msg.SubtractFees,
57✔
4983
                LocalFundingAmt:   localAmt,
57✔
4984
                RemoteFundingAmt:  0,
57✔
4985
                FundUpToMaxAmt:    msg.FundUpToMaxAmt,
57✔
4986
                MinFundAmt:        msg.MinFundAmt,
57✔
4987
                RemoteChanReserve: chanReserve,
57✔
4988
                Outpoints:         outpoints,
57✔
4989
                CommitFeePerKw:    commitFeePerKw,
57✔
4990
                FundingFeePerKw:   msg.FundingFeePerKw,
57✔
4991
                PushMSat:          msg.PushAmt,
57✔
4992
                Flags:             channelFlags,
57✔
4993
                MinConfs:          msg.MinConfs,
57✔
4994
                CommitType:        commitType,
57✔
4995
                ChanFunder:        msg.ChanFunder,
57✔
4996
                // Unconfirmed Utxos which are marked by the sweeper subsystem
57✔
4997
                // are excluded from the coin selection because they are not
57✔
4998
                // final and can be RBFed by the sweeper subsystem.
57✔
4999
                AllowUtxoForFunding: func(u lnwallet.Utxo) bool {
115✔
5000
                        // Utxos with at least 1 confirmation are safe to use
58✔
5001
                        // for channel openings because they don't bare the risk
58✔
5002
                        // of being replaced (BIP 125 RBF).
58✔
5003
                        if u.Confirmations > 0 {
58✔
5004
                                return true
×
5005
                        }
×
5006

5007
                        // Query the sweeper storage to make sure we don't use
5008
                        // an unconfirmed utxo still in use by the sweeper
5009
                        // subsystem.
5010
                        return !f.cfg.IsSweeperOutpoint(u.OutPoint)
58✔
5011
                },
5012
                ZeroConf:         zeroConf,
5013
                OptionScidAlias:  scid,
5014
                ScidAliasFeature: scidFeatureVal,
5015
                Memo:             msg.Memo,
5016
                TapscriptRoot:    tapscriptRoot,
5017
        }
5018

5019
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
57✔
5020
        if err != nil {
57✔
5021
                msg.Err <- err
×
5022
                return
×
5023
        }
×
5024

5025
        if zeroConf {
59✔
5026
                // Store the alias for zero-conf channels in the underlying
2✔
5027
                // partial channel state.
2✔
5028
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
2✔
5029
                if err != nil {
2✔
5030
                        msg.Err <- err
×
5031
                        return
×
5032
                }
×
5033

5034
                reservation.AddAlias(aliasScid)
2✔
5035
        }
5036

5037
        // Set our upfront shutdown address in the existing reservation.
5038
        reservation.SetOurUpfrontShutdown(shutdown)
57✔
5039

57✔
5040
        // Now that we have successfully reserved funds for this channel in the
57✔
5041
        // wallet, we can fetch the final channel capacity. This is done at
57✔
5042
        // this point since the final capacity might change in case of
57✔
5043
        // SubtractFees=true.
57✔
5044
        capacity := reservation.Capacity()
57✔
5045

57✔
5046
        log.Infof("Target commit tx sat/kw for pendingID(%x): %v", chanID,
57✔
5047
                int64(commitFeePerKw))
57✔
5048

57✔
5049
        // If the remote CSV delay was not set in the open channel request,
57✔
5050
        // we'll use the RequiredRemoteDelay closure to compute the delay we
57✔
5051
        // require given the total amount of funds within the channel.
57✔
5052
        if remoteCsvDelay == 0 {
113✔
5053
                remoteCsvDelay = f.cfg.RequiredRemoteDelay(capacity)
56✔
5054
        }
56✔
5055

5056
        // If no minimum HTLC value was specified, use the default one.
5057
        if minHtlcIn == 0 {
113✔
5058
                minHtlcIn = f.cfg.DefaultMinHtlcIn
56✔
5059
        }
56✔
5060

5061
        // If no max value was specified, use the default one.
5062
        if maxValue == 0 {
113✔
5063
                maxValue = f.cfg.RequiredRemoteMaxValue(capacity)
56✔
5064
        }
56✔
5065

5066
        if maxHtlcs == 0 {
114✔
5067
                maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
57✔
5068
        }
57✔
5069

5070
        // Once the reservation has been created, and indexed, queue a funding
5071
        // request to the remote peer, kicking off the funding workflow.
5072
        ourContribution := reservation.OurContribution()
57✔
5073

57✔
5074
        // Prepare the optional channel fee values from the initFundingMsg. If
57✔
5075
        // useBaseFee or useFeeRate are false the client did not provide fee
57✔
5076
        // values hence we assume default fee settings from the config.
57✔
5077
        forwardingPolicy := f.defaultForwardingPolicy(
57✔
5078
                ourContribution.ChannelStateBounds,
57✔
5079
        )
57✔
5080
        if baseFee != nil {
58✔
5081
                forwardingPolicy.BaseFee = lnwire.MilliSatoshi(*baseFee)
1✔
5082
        }
1✔
5083

5084
        if feeRate != nil {
58✔
5085
                forwardingPolicy.FeeRate = lnwire.MilliSatoshi(*feeRate)
1✔
5086
        }
1✔
5087

5088
        // Fetch our dust limit which is part of the default channel
5089
        // constraints, and log it.
5090
        ourDustLimit := ourContribution.DustLimit
57✔
5091

57✔
5092
        log.Infof("Dust limit for pendingID(%x): %v", chanID, ourDustLimit)
57✔
5093

57✔
5094
        // If the channel reserve is not specified, then we calculate an
57✔
5095
        // appropriate amount here.
57✔
5096
        if chanReserve == 0 {
110✔
5097
                chanReserve = f.cfg.RequiredRemoteChanReserve(
53✔
5098
                        capacity, ourDustLimit,
53✔
5099
                )
53✔
5100
        }
53✔
5101

5102
        // If a pending channel map for this peer isn't already created, then
5103
        // we create one, ultimately allowing us to track this pending
5104
        // reservation within the target peer.
5105
        peerIDKey := newSerializedKey(peerKey)
57✔
5106
        f.resMtx.Lock()
57✔
5107
        if _, ok := f.activeReservations[peerIDKey]; !ok {
107✔
5108
                f.activeReservations[peerIDKey] = make(pendingChannels)
50✔
5109
        }
50✔
5110

5111
        resCtx := &reservationWithCtx{
57✔
5112
                chanAmt:           capacity,
57✔
5113
                forwardingPolicy:  *forwardingPolicy,
57✔
5114
                remoteCsvDelay:    remoteCsvDelay,
57✔
5115
                remoteMinHtlc:     minHtlcIn,
57✔
5116
                remoteMaxValue:    maxValue,
57✔
5117
                remoteMaxHtlcs:    maxHtlcs,
57✔
5118
                remoteChanReserve: chanReserve,
57✔
5119
                maxLocalCsv:       maxCSV,
57✔
5120
                channelType:       chanType,
57✔
5121
                reservation:       reservation,
57✔
5122
                peer:              msg.Peer,
57✔
5123
                updates:           msg.Updates,
57✔
5124
                err:               msg.Err,
57✔
5125
        }
57✔
5126
        f.activeReservations[peerIDKey][chanID] = resCtx
57✔
5127
        f.resMtx.Unlock()
57✔
5128

57✔
5129
        // Update the timestamp once the InitFundingMsg has been handled.
57✔
5130
        defer resCtx.updateTimestamp()
57✔
5131

57✔
5132
        // Check the sanity of the selected channel constraints.
57✔
5133
        bounds := &channeldb.ChannelStateBounds{
57✔
5134
                ChanReserve:      chanReserve,
57✔
5135
                MaxPendingAmount: maxValue,
57✔
5136
                MinHTLC:          minHtlcIn,
57✔
5137
                MaxAcceptedHtlcs: maxHtlcs,
57✔
5138
        }
57✔
5139
        commitParams := &channeldb.CommitmentParams{
57✔
5140
                DustLimit: ourDustLimit,
57✔
5141
                CsvDelay:  remoteCsvDelay,
57✔
5142
        }
57✔
5143
        err = lnwallet.VerifyConstraints(
57✔
5144
                bounds, commitParams, resCtx.maxLocalCsv, capacity,
57✔
5145
        )
57✔
5146
        if err != nil {
59✔
5147
                _, reserveErr := f.cancelReservationCtx(peerKey, chanID, false)
2✔
5148
                if reserveErr != nil {
2✔
5149
                        log.Errorf("unable to cancel reservation: %v",
×
5150
                                reserveErr)
×
5151
                }
×
5152

5153
                msg.Err <- err
2✔
5154
                return
2✔
5155
        }
5156

5157
        // When opening a script enforced channel lease, include the required
5158
        // expiry TLV record in our proposal.
5159
        var leaseExpiry *lnwire.LeaseExpiry
55✔
5160
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
55✔
5161
                leaseExpiry = new(lnwire.LeaseExpiry)
×
5162
                *leaseExpiry = lnwire.LeaseExpiry(reservation.LeaseExpiry())
×
5163
        }
×
5164

5165
        log.Infof("Starting funding workflow with %v for pending_id(%x), "+
55✔
5166
                "committype=%v", msg.Peer.Address(), chanID, commitType)
55✔
5167

55✔
5168
        reservation.SetState(lnwallet.SentOpenChannel)
55✔
5169

55✔
5170
        fundingOpen := lnwire.OpenChannel{
55✔
5171
                ChainHash:             *f.cfg.Wallet.Cfg.NetParams.GenesisHash,
55✔
5172
                PendingChannelID:      chanID,
55✔
5173
                FundingAmount:         capacity,
55✔
5174
                PushAmount:            msg.PushAmt,
55✔
5175
                DustLimit:             ourDustLimit,
55✔
5176
                MaxValueInFlight:      maxValue,
55✔
5177
                ChannelReserve:        chanReserve,
55✔
5178
                HtlcMinimum:           minHtlcIn,
55✔
5179
                FeePerKiloWeight:      uint32(commitFeePerKw),
55✔
5180
                CsvDelay:              remoteCsvDelay,
55✔
5181
                MaxAcceptedHTLCs:      maxHtlcs,
55✔
5182
                FundingKey:            ourContribution.MultiSigKey.PubKey,
55✔
5183
                RevocationPoint:       ourContribution.RevocationBasePoint.PubKey,
55✔
5184
                PaymentPoint:          ourContribution.PaymentBasePoint.PubKey,
55✔
5185
                HtlcPoint:             ourContribution.HtlcBasePoint.PubKey,
55✔
5186
                DelayedPaymentPoint:   ourContribution.DelayBasePoint.PubKey,
55✔
5187
                FirstCommitmentPoint:  ourContribution.FirstCommitmentPoint,
55✔
5188
                ChannelFlags:          channelFlags,
55✔
5189
                UpfrontShutdownScript: shutdown,
55✔
5190
                ChannelType:           chanType,
55✔
5191
                LeaseExpiry:           leaseExpiry,
55✔
5192
        }
55✔
5193

55✔
5194
        if commitType.IsTaproot() {
57✔
5195
                fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
2✔
5196
                        ourContribution.LocalNonce.PubNonce,
2✔
5197
                )
2✔
5198
        }
2✔
5199

5200
        if err := msg.Peer.SendMessage(true, &fundingOpen); err != nil {
55✔
5201
                e := fmt.Errorf("unable to send funding request message: %w",
×
5202
                        err)
×
5203
                log.Errorf(e.Error())
×
5204

×
5205
                // Since we were unable to send the initial message to the peer
×
5206
                // and start the funding flow, we'll cancel this reservation.
×
5207
                _, err := f.cancelReservationCtx(peerKey, chanID, false)
×
5208
                if err != nil {
×
5209
                        log.Errorf("unable to cancel reservation: %v", err)
×
5210
                }
×
5211

5212
                msg.Err <- e
×
5213
                return
×
5214
        }
5215
}
5216

5217
// handleWarningMsg processes the warning which was received from remote peer.
5218
func (f *Manager) handleWarningMsg(peer lnpeer.Peer, msg *lnwire.Warning) {
44✔
5219
        log.Warnf("received warning message from peer %x: %v",
44✔
5220
                peer.IdentityKey().SerializeCompressed(), msg.Warning())
44✔
5221
}
44✔
5222

5223
// handleErrorMsg processes the error which was received from remote peer,
5224
// depending on the type of error we should do different clean up steps and
5225
// inform the user about it.
5226
func (f *Manager) handleErrorMsg(peer lnpeer.Peer, msg *lnwire.Error) {
×
5227
        chanID := msg.ChanID
×
5228
        peerKey := peer.IdentityKey()
×
5229

×
5230
        // First, we'll attempt to retrieve and cancel the funding workflow
×
5231
        // that this error was tied to. If we're unable to do so, then we'll
×
5232
        // exit early as this was an unwarranted error.
×
5233
        resCtx, err := f.cancelReservationCtx(peerKey, chanID, true)
×
5234
        if err != nil {
×
5235
                log.Warnf("Received error for non-existent funding "+
×
5236
                        "flow: %v (%v)", err, msg.Error())
×
5237
                return
×
5238
        }
×
5239

5240
        // If we did indeed find the funding workflow, then we'll return the
5241
        // error back to the caller (if any), and cancel the workflow itself.
5242
        fundingErr := fmt.Errorf("received funding error from %x: %v",
×
5243
                peerKey.SerializeCompressed(), msg.Error(),
×
5244
        )
×
5245
        log.Errorf(fundingErr.Error())
×
5246

×
5247
        // If this was a PSBT funding flow, the remote likely timed out because
×
5248
        // we waited too long. Return a nice error message to the user in that
×
5249
        // case so the user knows what's the problem.
×
5250
        if resCtx.reservation.IsPsbt() {
×
5251
                fundingErr = fmt.Errorf("%w: %v", chanfunding.ErrRemoteCanceled,
×
5252
                        fundingErr)
×
5253
        }
×
5254

5255
        resCtx.err <- fundingErr
×
5256
}
5257

5258
// pruneZombieReservations loops through all pending reservations and fails the
5259
// funding flow for any reservations that have not been updated since the
5260
// ReservationTimeout and are not locked waiting for the funding transaction.
5261
func (f *Manager) pruneZombieReservations() {
3✔
5262
        zombieReservations := make(pendingChannels)
3✔
5263

3✔
5264
        f.resMtx.RLock()
3✔
5265
        for _, pendingReservations := range f.activeReservations {
6✔
5266
                for pendingChanID, resCtx := range pendingReservations {
6✔
5267
                        if resCtx.isLocked() {
3✔
5268
                                continue
×
5269
                        }
5270

5271
                        // We don't want to expire PSBT funding reservations.
5272
                        // These reservations are always initiated by us and the
5273
                        // remote peer is likely going to cancel them after some
5274
                        // idle time anyway. So no need for us to also prune
5275
                        // them.
5276
                        sinceLastUpdate := time.Since(resCtx.lastUpdated)
3✔
5277
                        isExpired := sinceLastUpdate > f.cfg.ReservationTimeout
3✔
5278
                        if !resCtx.reservation.IsPsbt() && isExpired {
6✔
5279
                                zombieReservations[pendingChanID] = resCtx
3✔
5280
                        }
3✔
5281
                }
5282
        }
5283
        f.resMtx.RUnlock()
3✔
5284

3✔
5285
        for pendingChanID, resCtx := range zombieReservations {
6✔
5286
                err := fmt.Errorf("reservation timed out waiting for peer "+
3✔
5287
                        "(peer_id:%x, chan_id:%x)",
3✔
5288
                        resCtx.peer.IdentityKey().SerializeCompressed(),
3✔
5289
                        pendingChanID[:])
3✔
5290
                log.Warnf(err.Error())
3✔
5291

3✔
5292
                chanID := lnwire.NewChanIDFromOutPoint(
3✔
5293
                        *resCtx.reservation.FundingOutpoint(),
3✔
5294
                )
3✔
5295

3✔
5296
                // Create channel identifier and set the channel ID.
3✔
5297
                cid := newChanIdentifier(pendingChanID)
3✔
5298
                cid.setChanID(chanID)
3✔
5299

3✔
5300
                f.failFundingFlow(resCtx.peer, cid, err)
3✔
5301
        }
3✔
5302
}
5303

5304
// cancelReservationCtx does all needed work in order to securely cancel the
5305
// reservation.
5306
func (f *Manager) cancelReservationCtx(peerKey *btcec.PublicKey,
5307
        pendingChanID PendingChanID,
5308
        byRemote bool) (*reservationWithCtx, error) {
23✔
5309

23✔
5310
        log.Infof("Cancelling funding reservation for node_key=%x, "+
23✔
5311
                "chan_id=%x", peerKey.SerializeCompressed(), pendingChanID[:])
23✔
5312

23✔
5313
        peerIDKey := newSerializedKey(peerKey)
23✔
5314
        f.resMtx.Lock()
23✔
5315
        defer f.resMtx.Unlock()
23✔
5316

23✔
5317
        nodeReservations, ok := f.activeReservations[peerIDKey]
23✔
5318
        if !ok {
30✔
5319
                // No reservations for this node.
7✔
5320
                return nil, fmt.Errorf("no active reservations for peer(%x)",
7✔
5321
                        peerIDKey[:])
7✔
5322
        }
7✔
5323

5324
        ctx, ok := nodeReservations[pendingChanID]
16✔
5325
        if !ok {
18✔
5326
                return nil, fmt.Errorf("unknown channel (id: %x) for "+
2✔
5327
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
2✔
5328
        }
2✔
5329

5330
        // If the reservation was a PSBT funding flow and it was canceled by the
5331
        // remote peer, then we need to thread through a different error message
5332
        // to the subroutine that's waiting for the user input so it can return
5333
        // a nice error message to the user.
5334
        if ctx.reservation.IsPsbt() && byRemote {
14✔
5335
                ctx.reservation.RemoteCanceled()
×
5336
        }
×
5337

5338
        if err := ctx.reservation.Cancel(); err != nil {
14✔
5339
                return nil, fmt.Errorf("unable to cancel reservation: %w", err)
×
5340
        }
×
5341

5342
        delete(nodeReservations, pendingChanID)
14✔
5343

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

5352
// deleteReservationCtx deletes the reservation uniquely identified by the
5353
// target public key of the peer, and the specified pending channel ID.
5354
func (f *Manager) deleteReservationCtx(peerKey *btcec.PublicKey,
5355
        pendingChanID PendingChanID) {
56✔
5356

56✔
5357
        peerIDKey := newSerializedKey(peerKey)
56✔
5358
        f.resMtx.Lock()
56✔
5359
        defer f.resMtx.Unlock()
56✔
5360

56✔
5361
        nodeReservations, ok := f.activeReservations[peerIDKey]
56✔
5362
        if !ok {
56✔
5363
                // No reservations for this node.
×
5364
                return
×
5365
        }
×
5366
        delete(nodeReservations, pendingChanID)
56✔
5367

56✔
5368
        // If this was the last active reservation for this peer, delete the
56✔
5369
        // peer's entry altogether.
56✔
5370
        if len(nodeReservations) == 0 {
105✔
5371
                delete(f.activeReservations, peerIDKey)
49✔
5372
        }
49✔
5373
}
5374

5375
// getReservationCtx returns the reservation context for a particular pending
5376
// channel ID for a target peer.
5377
func (f *Manager) getReservationCtx(peerKey *btcec.PublicKey,
5378
        pendingChanID PendingChanID) (*reservationWithCtx, error) {
91✔
5379

91✔
5380
        peerIDKey := newSerializedKey(peerKey)
91✔
5381
        f.resMtx.RLock()
91✔
5382
        resCtx, ok := f.activeReservations[peerIDKey][pendingChanID]
91✔
5383
        f.resMtx.RUnlock()
91✔
5384

91✔
5385
        if !ok {
91✔
5386
                return nil, fmt.Errorf("unknown channel (id: %x) for "+
×
5387
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
×
5388
        }
×
5389

5390
        return resCtx, nil
91✔
5391
}
5392

5393
// IsPendingChannel returns a boolean indicating whether the channel identified
5394
// by the pendingChanID and given peer is pending, meaning it is in the process
5395
// of being funded. After the funding transaction has been confirmed, the
5396
// channel will receive a new, permanent channel ID, and will no longer be
5397
// considered pending.
5398
func (f *Manager) IsPendingChannel(pendingChanID PendingChanID,
5399
        peer lnpeer.Peer) bool {
×
5400

×
5401
        peerIDKey := newSerializedKey(peer.IdentityKey())
×
5402
        f.resMtx.RLock()
×
5403
        _, ok := f.activeReservations[peerIDKey][pendingChanID]
×
5404
        f.resMtx.RUnlock()
×
5405

×
5406
        return ok
×
5407
}
×
5408

5409
func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
385✔
5410
        var tmp btcec.JacobianPoint
385✔
5411
        pub.AsJacobian(&tmp)
385✔
5412
        tmp.ToAffine()
385✔
5413
        return btcec.NewPublicKey(&tmp.X, &tmp.Y)
385✔
5414
}
385✔
5415

5416
// defaultForwardingPolicy returns the default forwarding policy based on the
5417
// default routing policy and our local channel constraints.
5418
func (f *Manager) defaultForwardingPolicy(
5419
        bounds channeldb.ChannelStateBounds) *models.ForwardingPolicy {
104✔
5420

104✔
5421
        return &models.ForwardingPolicy{
104✔
5422
                MinHTLCOut:    bounds.MinHTLC,
104✔
5423
                MaxHTLC:       bounds.MaxPendingAmount,
104✔
5424
                BaseFee:       f.cfg.DefaultRoutingPolicy.BaseFee,
104✔
5425
                FeeRate:       f.cfg.DefaultRoutingPolicy.FeeRate,
104✔
5426
                TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
104✔
5427
        }
104✔
5428
}
104✔
5429

5430
// saveInitialForwardingPolicy saves the forwarding policy for the provided
5431
// chanPoint in the channelOpeningStateBucket.
5432
func (f *Manager) saveInitialForwardingPolicy(chanID lnwire.ChannelID,
5433
        forwardingPolicy *models.ForwardingPolicy) error {
69✔
5434

69✔
5435
        return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
69✔
5436
                chanID, forwardingPolicy,
69✔
5437
        )
69✔
5438
}
69✔
5439

5440
// getInitialForwardingPolicy fetches the initial forwarding policy for a given
5441
// channel id from the database which will be applied during the channel
5442
// announcement phase.
5443
func (f *Manager) getInitialForwardingPolicy(
5444
        chanID lnwire.ChannelID) (*models.ForwardingPolicy, error) {
94✔
5445

94✔
5446
        return f.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
94✔
5447
}
94✔
5448

5449
// deleteInitialForwardingPolicy removes channel fees for this chanID from
5450
// the database.
5451
func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
24✔
5452
        return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
24✔
5453
}
24✔
5454

5455
// saveChannelOpeningState saves the channelOpeningState for the provided
5456
// chanPoint to the channelOpeningStateBucket.
5457
func (f *Manager) saveChannelOpeningState(chanPoint *wire.OutPoint,
5458
        state channelOpeningState, shortChanID *lnwire.ShortChannelID) error {
92✔
5459

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

5465
        // Save state and the uint64 representation of the shortChanID
5466
        // for later use.
5467
        scratch := make([]byte, 10)
92✔
5468
        byteOrder.PutUint16(scratch[:2], uint16(state))
92✔
5469
        byteOrder.PutUint64(scratch[2:], shortChanID.ToUint64())
92✔
5470

92✔
5471
        return f.cfg.ChannelDB.SaveChannelOpeningState(
92✔
5472
                outpointBytes.Bytes(), scratch,
92✔
5473
        )
92✔
5474
}
5475

5476
// getChannelOpeningState fetches the channelOpeningState for the provided
5477
// chanPoint from the database, or returns ErrChannelNotFound if the channel
5478
// is not found.
5479
func (f *Manager) getChannelOpeningState(chanPoint *wire.OutPoint) (
5480
        channelOpeningState, *lnwire.ShortChannelID, error) {
253✔
5481

253✔
5482
        var outpointBytes bytes.Buffer
253✔
5483
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
253✔
5484
                return 0, nil, err
×
5485
        }
×
5486

5487
        value, err := f.cfg.ChannelDB.GetChannelOpeningState(
253✔
5488
                outpointBytes.Bytes(),
253✔
5489
        )
253✔
5490
        if err != nil {
302✔
5491
                return 0, nil, err
49✔
5492
        }
49✔
5493

5494
        state := channelOpeningState(byteOrder.Uint16(value[:2]))
204✔
5495
        shortChanID := lnwire.NewShortChanIDFromInt(byteOrder.Uint64(value[2:]))
204✔
5496
        return state, &shortChanID, nil
204✔
5497
}
5498

5499
// deleteChannelOpeningState removes any state for chanPoint from the database.
5500
func (f *Manager) deleteChannelOpeningState(chanPoint *wire.OutPoint) error {
24✔
5501
        var outpointBytes bytes.Buffer
24✔
5502
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
24✔
5503
                return err
×
5504
        }
×
5505

5506
        return f.cfg.ChannelDB.DeleteChannelOpeningState(
24✔
5507
                outpointBytes.Bytes(),
24✔
5508
        )
24✔
5509
}
5510

5511
// selectShutdownScript selects the shutdown script we should send to the peer.
5512
// If we can use taproot, then we prefer that, otherwise we'll use a p2wkh
5513
// script.
5514
func (f *Manager) selectShutdownScript(taprootOK bool,
5515
) (lnwire.DeliveryAddress, error) {
×
5516

×
5517
        addrType := lnwallet.WitnessPubKey
×
5518
        if taprootOK {
×
5519
                addrType = lnwallet.TaprootPubkey
×
5520
        }
×
5521

5522
        addr, err := f.cfg.Wallet.NewAddress(
×
5523
                addrType, false, lnwallet.DefaultAccountName,
×
5524
        )
×
5525
        if err != nil {
×
5526
                return nil, err
×
5527
        }
×
5528

5529
        return txscript.PayToAddrScript(addr)
×
5530
}
5531

5532
// waitForPeerOnline blocks until the peer specified by peerPubkey comes online
5533
// and then returns the online peer.
5534
func (f *Manager) waitForPeerOnline(peerPubkey *btcec.PublicKey) (lnpeer.Peer,
5535
        error) {
104✔
5536

104✔
5537
        peerChan := make(chan lnpeer.Peer, 1)
104✔
5538

104✔
5539
        var peerKey [33]byte
104✔
5540
        copy(peerKey[:], peerPubkey.SerializeCompressed())
104✔
5541

104✔
5542
        f.cfg.NotifyWhenOnline(peerKey, peerChan)
104✔
5543

104✔
5544
        var peer lnpeer.Peer
104✔
5545
        select {
104✔
5546
        case peer = <-peerChan:
103✔
5547
        case <-f.quit:
1✔
5548
                return peer, ErrFundingManagerShuttingDown
1✔
5549
        }
5550
        return peer, nil
103✔
5551
}
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