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

lightningnetwork / lnd / 11136034567

02 Oct 2024 01:06AM UTC coverage: 58.817% (+0.003%) from 58.814%
11136034567

push

github

web-flow
Merge pull request #8644 from Roasbeef/remove-sql-mutex-part-deux

kvdb/postgres: remove global application level lock

130416 of 221731 relevant lines covered (58.82%)

28306.61 hits per line

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

73.93
/funding/manager.go
1
package funding
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

102
        msgBufferSize = 50
103

104
        // MaxWaitNumBlocksFundingConf is the maximum number of blocks to wait
105
        // for the funding transaction to be confirmed before forgetting
106
        // channels that aren't initiated by us. 2016 blocks is ~2 weeks.
107
        MaxWaitNumBlocksFundingConf = 2016
108

109
        // pendingChansLimit is the maximum number of pending channels that we
110
        // can have. After this point, pending channel opens will start to be
111
        // rejected.
112
        pendingChansLimit = 1_000
113
)
114

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

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

128
        // errUpfrontShutdownScriptNotSupported is returned if an upfront
129
        // shutdown script is set for a peer that does not support the feature
130
        // bit.
131
        errUpfrontShutdownScriptNotSupported = errors.New("peer does not " +
132
                "support option upfront shutdown script")
133

134
        zeroID [32]byte
135
)
136

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

150
        chanAmt btcutil.Amount
151

152
        // forwardingPolicy is the policy provided by the initFundingMsg.
153
        forwardingPolicy models.ForwardingPolicy
154

155
        // Constraints we require for the remote.
156
        remoteCsvDelay    uint16
157
        remoteMinHtlc     lnwire.MilliSatoshi
158
        remoteMaxValue    lnwire.MilliSatoshi
159
        remoteMaxHtlcs    uint16
160
        remoteChanReserve btcutil.Amount
161

162
        // maxLocalCsv is the maximum csv we will accept from the remote.
163
        maxLocalCsv uint16
164

165
        // channelType is the explicit channel type proposed by the initiator of
166
        // the channel.
167
        channelType *lnwire.ChannelType
168

169
        updateMtx   sync.RWMutex
170
        lastUpdated time.Time
171

172
        updates chan *lnrpc.OpenStatusUpdate
173
        err     chan error
174
}
175

176
// isLocked checks the reservation's timestamp to determine whether it is
177
// locked.
178
func (r *reservationWithCtx) isLocked() bool {
7✔
179
        r.updateMtx.RLock()
7✔
180
        defer r.updateMtx.RUnlock()
7✔
181

7✔
182
        // The time zero value represents a locked reservation.
7✔
183
        return r.lastUpdated.IsZero()
7✔
184
}
7✔
185

186
// updateTimestamp updates the reservation's timestamp with the current time.
187
func (r *reservationWithCtx) updateTimestamp() {
138✔
188
        r.updateMtx.Lock()
138✔
189
        defer r.updateMtx.Unlock()
138✔
190

138✔
191
        r.lastUpdated = time.Now()
138✔
192
}
138✔
193

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

203
        // TargetPubkey is the public key of the peer.
204
        TargetPubkey *btcec.PublicKey
205

206
        // ChainHash is the target genesis hash for this channel.
207
        ChainHash chainhash.Hash
208

209
        // SubtractFees set to true means that fees will be subtracted
210
        // from the LocalFundingAmt.
211
        SubtractFees bool
212

213
        // LocalFundingAmt is the size of the channel.
214
        LocalFundingAmt btcutil.Amount
215

216
        // BaseFee is the base fee charged for routing payments regardless of
217
        // the number of milli-satoshis sent.
218
        BaseFee *uint64
219

220
        // FeeRate is the fee rate in ppm (parts per million) that will be
221
        // charged proportionally based on the value of each forwarded HTLC, the
222
        // lowest possible rate is 0 with a granularity of 0.000001
223
        // (millionths).
224
        FeeRate *uint64
225

226
        // PushAmt is the amount pushed to the counterparty.
227
        PushAmt lnwire.MilliSatoshi
228

229
        // FundingFeePerKw is the fee for the funding transaction.
230
        FundingFeePerKw chainfee.SatPerKWeight
231

232
        // Private determines whether or not this channel will be private.
233
        Private bool
234

235
        // MinHtlcIn is the minimum incoming HTLC that we accept.
236
        MinHtlcIn lnwire.MilliSatoshi
237

238
        // RemoteCsvDelay is the CSV delay we require for the remote peer.
239
        RemoteCsvDelay uint16
240

241
        // RemoteChanReserve is the channel reserve we required for the remote
242
        // peer.
243
        RemoteChanReserve btcutil.Amount
244

245
        // MinConfs indicates the minimum number of confirmations that each
246
        // output selected to fund the channel should satisfy.
247
        MinConfs int32
248

249
        // ShutdownScript is an optional upfront shutdown script for the
250
        // channel. This value is optional, so may be nil.
251
        ShutdownScript lnwire.DeliveryAddress
252

253
        // MaxValueInFlight is the maximum amount of coins in MilliSatoshi
254
        // that can be pending within the channel. It only applies to the
255
        // remote party.
256
        MaxValueInFlight lnwire.MilliSatoshi
257

258
        // MaxHtlcs is the maximum number of HTLCs that the remote peer
259
        // can offer us.
260
        MaxHtlcs uint16
261

262
        // MaxLocalCsv is the maximum local csv delay we will accept from our
263
        // peer.
264
        MaxLocalCsv uint16
265

266
        // FundUpToMaxAmt is the maximum amount to try to commit to. If set, the
267
        // MinFundAmt field denotes the acceptable minimum amount to commit to,
268
        // while trying to commit as many coins as possible up to this value.
269
        FundUpToMaxAmt btcutil.Amount
270

271
        // MinFundAmt must be set iff FundUpToMaxAmt is set. It denotes the
272
        // minimum amount to commit to.
273
        MinFundAmt btcutil.Amount
274

275
        // Outpoints is a list of client-selected outpoints that should be used
276
        // for funding a channel. If LocalFundingAmt is specified then this
277
        // amount is allocated from the sum of outpoints towards funding. If
278
        // the FundUpToMaxAmt is specified the entirety of selected funds is
279
        // allocated towards channel funding.
280
        Outpoints []wire.OutPoint
281

282
        // ChanFunder is an optional channel funder that allows the caller to
283
        // control exactly how the channel funding is carried out. If not
284
        // specified, then the default chanfunding.WalletAssembler will be
285
        // used.
286
        ChanFunder chanfunding.Assembler
287

288
        // PendingChanID is not all zeroes (the default value), then this will
289
        // be the pending channel ID used for the funding flow within the wire
290
        // protocol.
291
        PendingChanID PendingChanID
292

293
        // ChannelType allows the caller to use an explicit channel type for the
294
        // funding negotiation. This type will only be observed if BOTH sides
295
        // support explicit channel type negotiation.
296
        ChannelType *lnwire.ChannelType
297

298
        // Memo is any arbitrary information we wish to store locally about the
299
        // channel that will be useful to our future selves.
300
        Memo []byte
301

302
        // Updates is a channel which updates to the opening status of the
303
        // channel are sent on.
304
        Updates chan *lnrpc.OpenStatusUpdate
305

306
        // Err is a channel which errors encountered during the funding flow are
307
        // sent on.
308
        Err chan error
309
}
310

311
// fundingMsg is sent by the ProcessFundingMsg function and packages a
312
// funding-specific lnwire.Message along with the lnpeer.Peer that sent it.
313
type fundingMsg struct {
314
        msg  lnwire.Message
315
        peer lnpeer.Peer
316
}
317

318
// pendingChannels is a map instantiated per-peer which tracks all active
319
// pending single funded channels indexed by their pending channel identifier,
320
// which is a set of 32-bytes generated via a CSPRNG.
321
type pendingChannels map[PendingChanID]*reservationWithCtx
322

323
// serializedPubKey is used within the FundingManager's activeReservations list
324
// to identify the nodes with which the FundingManager is actively working to
325
// initiate new channels.
326
type serializedPubKey [33]byte
327

328
// newSerializedKey creates a new serialized public key from an instance of a
329
// live pubkey object.
330
func newSerializedKey(pubKey *btcec.PublicKey) serializedPubKey {
382✔
331
        var s serializedPubKey
382✔
332
        copy(s[:], pubKey.SerializeCompressed())
382✔
333
        return s
382✔
334
}
382✔
335

336
// DevConfig specifies configs used for integration test only.
337
type DevConfig struct {
338
        // ProcessChannelReadyWait is the duration to sleep before processing
339
        // remote node's channel ready message once the channel as been marked
340
        // as `channelReadySent`.
341
        ProcessChannelReadyWait time.Duration
342
}
343

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

511
        // NotifyOpenChannelEvent informs the ChannelNotifier when channels
512
        // transition from pending open to open.
513
        NotifyOpenChannelEvent func(wire.OutPoint)
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)
524

525
        // EnableUpfrontShutdown specifies whether the upfront shutdown script
526
        // is enabled.
527
        EnableUpfrontShutdown bool
528

529
        // MaxAnchorsCommitFeeRate is the max commitment fee rate we'll use as
530
        // the initiator for channels of the anchor type.
531
        MaxAnchorsCommitFeeRate chainfee.SatPerKWeight
532

533
        // DeleteAliasEdge allows the Manager to delete an alias channel edge
534
        // from the graph. It also returns our local to-be-deleted policy.
535
        DeleteAliasEdge func(scid lnwire.ShortChannelID) (
536
                *models.ChannelEdgePolicy, error)
537

538
        // AliasManager is an implementation of the aliasHandler interface that
539
        // abstracts away the handling of many alias functions.
540
        AliasManager aliasHandler
541

542
        // IsSweeperOutpoint queries the sweeper store for successfully
543
        // published sweeps. This is useful to decide for the internal wallet
544
        // backed funding flow to not use utxos still being swept by the sweeper
545
        // subsystem.
546
        IsSweeperOutpoint func(wire.OutPoint) bool
547

548
        // AuxLeafStore is an optional store that can be used to store auxiliary
549
        // leaves for certain custom channel types.
550
        AuxLeafStore fn.Option[lnwallet.AuxLeafStore]
551

552
        // AuxFundingController is an optional controller that can be used to
553
        // modify the way we handle certain custom channel types. It's also
554
        // able to automatically handle new custom protocol messages related to
555
        // the funding process.
556
        AuxFundingController fn.Option[AuxFundingController]
557

558
        // AuxSigner is an optional signer that can be used to sign auxiliary
559
        // leaves for certain custom channel types.
560
        AuxSigner fn.Option[lnwallet.AuxSigner]
561
}
562

563
// Manager acts as an orchestrator/bridge between the wallet's
564
// 'ChannelReservation' workflow, and the wire protocol's funding initiation
565
// messages. Any requests to initiate the funding workflow for a channel,
566
// either kicked-off locally or remotely are handled by the funding manager.
567
// Once a channel's funding workflow has been completed, any local callers, the
568
// local peer, and possibly the remote peer are notified of the completion of
569
// the channel workflow. Additionally, any temporary or permanent access
570
// controls between the wallet and remote peers are enforced via the funding
571
// manager.
572
type Manager struct {
573
        started sync.Once
574
        stopped sync.Once
575

576
        // cfg is a copy of the configuration struct that the FundingManager
577
        // was initialized with.
578
        cfg *Config
579

580
        // chanIDKey is a cryptographically random key that's used to generate
581
        // temporary channel ID's.
582
        chanIDKey [32]byte
583

584
        // chanIDNonce is a nonce that's incremented for each new funding
585
        // reservation created.
586
        chanIDNonce atomic.Uint64
587

588
        // nonceMtx is a mutex that guards the pendingMusigNonces.
589
        nonceMtx sync.RWMutex
590

591
        // pendingMusigNonces is used to store the musig2 nonce we generate to
592
        // send funding locked until we receive a funding locked message from
593
        // the remote party. We'll use this to keep track of the nonce we
594
        // generated, so we send the local+remote nonces to the peer state
595
        // machine.
596
        //
597
        // NOTE: This map is protected by the nonceMtx above.
598
        //
599
        // TODO(roasbeef): replace w/ generic concurrent map
600
        pendingMusigNonces map[lnwire.ChannelID]*musig2.Nonces
601

602
        // activeReservations is a map which houses the state of all pending
603
        // funding workflows.
604
        activeReservations map[serializedPubKey]pendingChannels
605

606
        // signedReservations is a utility map that maps the permanent channel
607
        // ID of a funding reservation to its temporary channel ID. This is
608
        // required as mid funding flow, we switch to referencing the channel
609
        // by its full channel ID once the commitment transactions have been
610
        // signed by both parties.
611
        signedReservations map[lnwire.ChannelID]PendingChanID
612

613
        // resMtx guards both of the maps above to ensure that all access is
614
        // goroutine safe.
615
        resMtx sync.RWMutex
616

617
        // fundingMsgs is a channel that relays fundingMsg structs from
618
        // external sub-systems using the ProcessFundingMsg call.
619
        fundingMsgs chan *fundingMsg
620

621
        // fundingRequests is a channel used to receive channel initiation
622
        // requests from a local subsystem within the daemon.
623
        fundingRequests chan *InitFundingMsg
624

625
        localDiscoverySignals *lnutils.SyncMap[lnwire.ChannelID, chan struct{}]
626

627
        handleChannelReadyBarriers *lnutils.SyncMap[lnwire.ChannelID, struct{}]
628

629
        quit chan struct{}
630
        wg   sync.WaitGroup
631
}
632

633
// channelOpeningState represents the different states a channel can be in
634
// between the funding transaction has been confirmed and the channel is
635
// announced to the network and ready to be used.
636
type channelOpeningState uint8
637

638
const (
639
        // markedOpen is the opening state of a channel if the funding
640
        // transaction is confirmed on-chain, but channelReady is not yet
641
        // successfully sent to the other peer.
642
        markedOpen channelOpeningState = iota
643

644
        // channelReadySent is the opening state of a channel if the
645
        // channelReady message has successfully been sent to the other peer,
646
        // but we still haven't announced the channel to the network.
647
        channelReadySent
648

649
        // addedToGraph is the opening state of a channel if the channel has
650
        // been successfully added to the graph immediately after the
651
        // channelReady message has been sent, but we still haven't announced
652
        // the channel to the network.
653
        addedToGraph
654
)
655

656
func (c channelOpeningState) String() string {
4✔
657
        switch c {
4✔
658
        case markedOpen:
4✔
659
                return "markedOpen"
4✔
660
        case channelReadySent:
4✔
661
                return "channelReadySent"
4✔
662
        case addedToGraph:
4✔
663
                return "addedToGraph"
4✔
664
        default:
×
665
                return "unknown"
×
666
        }
667
}
668

669
// NewFundingManager creates and initializes a new instance of the
670
// fundingManager.
671
func NewFundingManager(cfg Config) (*Manager, error) {
111✔
672
        return &Manager{
111✔
673
                cfg:       &cfg,
111✔
674
                chanIDKey: cfg.TempChanIDSeed,
111✔
675
                activeReservations: make(
111✔
676
                        map[serializedPubKey]pendingChannels,
111✔
677
                ),
111✔
678
                signedReservations: make(
111✔
679
                        map[lnwire.ChannelID][32]byte,
111✔
680
                ),
111✔
681
                fundingMsgs: make(
111✔
682
                        chan *fundingMsg, msgBufferSize,
111✔
683
                ),
111✔
684
                fundingRequests: make(
111✔
685
                        chan *InitFundingMsg, msgBufferSize,
111✔
686
                ),
111✔
687
                localDiscoverySignals: &lnutils.SyncMap[
111✔
688
                        lnwire.ChannelID, chan struct{},
111✔
689
                ]{},
111✔
690
                handleChannelReadyBarriers: &lnutils.SyncMap[
111✔
691
                        lnwire.ChannelID, struct{},
111✔
692
                ]{},
111✔
693
                pendingMusigNonces: make(
111✔
694
                        map[lnwire.ChannelID]*musig2.Nonces,
111✔
695
                ),
111✔
696
                quit: make(chan struct{}),
111✔
697
        }, nil
111✔
698
}
111✔
699

700
// Start launches all helper goroutines required for handling requests sent
701
// to the funding manager.
702
func (f *Manager) Start() error {
111✔
703
        var err error
111✔
704
        f.started.Do(func() {
222✔
705
                log.Info("Funding manager starting")
111✔
706
                err = f.start()
111✔
707
        })
111✔
708
        return err
111✔
709
}
710

711
func (f *Manager) start() error {
111✔
712
        // Upon restart, the Funding Manager will check the database to load any
111✔
713
        // channels that were  waiting for their funding transactions to be
111✔
714
        // confirmed on the blockchain at the time when the daemon last went
111✔
715
        // down.
111✔
716
        // TODO(roasbeef): store height that funding finished?
111✔
717
        //  * would then replace call below
111✔
718
        allChannels, err := f.cfg.ChannelDB.FetchAllChannels()
111✔
719
        if err != nil {
111✔
720
                return err
×
721
        }
×
722

723
        for _, channel := range allChannels {
124✔
724
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
13✔
725

13✔
726
                // For any channels that were in a pending state when the
13✔
727
                // daemon was last connected, the Funding Manager will
13✔
728
                // re-initialize the channel barriers, and republish the
13✔
729
                // funding transaction if we're the initiator.
13✔
730
                if channel.IsPending {
18✔
731
                        log.Tracef("Loading pending ChannelPoint(%v), "+
5✔
732
                                "creating chan barrier",
5✔
733
                                channel.FundingOutpoint)
5✔
734

5✔
735
                        f.localDiscoverySignals.Store(
5✔
736
                                chanID, make(chan struct{}),
5✔
737
                        )
5✔
738

5✔
739
                        // Rebroadcast the funding transaction for any pending
5✔
740
                        // channel that we initiated. No error will be returned
5✔
741
                        // if the transaction already has been broadcast.
5✔
742
                        chanType := channel.ChanType
5✔
743
                        if chanType.IsSingleFunder() &&
5✔
744
                                chanType.HasFundingTx() &&
5✔
745
                                channel.IsInitiator {
10✔
746

5✔
747
                                f.rebroadcastFundingTx(channel)
5✔
748
                        }
5✔
749
                } else if channel.ChanType.IsSingleFunder() &&
12✔
750
                        channel.ChanType.HasFundingTx() &&
12✔
751
                        channel.IsZeroConf() && channel.IsInitiator &&
12✔
752
                        !channel.ZeroConfConfirmed() {
14✔
753

2✔
754
                        // Rebroadcast the funding transaction for unconfirmed
2✔
755
                        // zero-conf channels if we have the funding tx and are
2✔
756
                        // also the initiator.
2✔
757
                        f.rebroadcastFundingTx(channel)
2✔
758
                }
2✔
759

760
                // We will restart the funding state machine for all channels,
761
                // which will wait for the channel's funding transaction to be
762
                // confirmed on the blockchain, and transmit the messages
763
                // necessary for the channel to be operational.
764
                f.wg.Add(1)
13✔
765
                go f.advanceFundingState(channel, chanID, nil)
13✔
766
        }
767

768
        f.wg.Add(1) // TODO(roasbeef): tune
111✔
769
        go f.reservationCoordinator()
111✔
770

111✔
771
        return nil
111✔
772
}
773

774
// Stop signals all helper goroutines to execute a graceful shutdown. This
775
// method will block until all goroutines have exited.
776
func (f *Manager) Stop() error {
108✔
777
        f.stopped.Do(func() {
215✔
778
                log.Info("Funding manager shutting down...")
107✔
779
                defer log.Debug("Funding manager shutdown complete")
107✔
780

107✔
781
                close(f.quit)
107✔
782
                f.wg.Wait()
107✔
783
        })
107✔
784

785
        return nil
108✔
786
}
787

788
// rebroadcastFundingTx publishes the funding tx on startup for each
789
// unconfirmed channel.
790
func (f *Manager) rebroadcastFundingTx(c *channeldb.OpenChannel) {
7✔
791
        var fundingTxBuf bytes.Buffer
7✔
792
        err := c.FundingTxn.Serialize(&fundingTxBuf)
7✔
793
        if err != nil {
7✔
794
                log.Errorf("Unable to serialize funding transaction %v: %v",
×
795
                        c.FundingTxn.TxHash(), err)
×
796

×
797
                // Clear the buffer of any bytes that were written before the
×
798
                // serialization error to prevent logging an incomplete
×
799
                // transaction.
×
800
                fundingTxBuf.Reset()
×
801
        } else {
7✔
802
                log.Debugf("Rebroadcasting funding tx for ChannelPoint(%v): "+
7✔
803
                        "%x", c.FundingOutpoint, fundingTxBuf.Bytes())
7✔
804
        }
7✔
805

806
        // Set a nil short channel ID at this stage because we do not know it
807
        // until our funding tx confirms.
808
        label := labels.MakeLabel(labels.LabelTypeChannelOpen, nil)
7✔
809

7✔
810
        err = f.cfg.PublishTransaction(c.FundingTxn, label)
7✔
811
        if err != nil {
7✔
812
                log.Errorf("Unable to rebroadcast funding tx %x for "+
×
813
                        "ChannelPoint(%v): %v", fundingTxBuf.Bytes(),
×
814
                        c.FundingOutpoint, err)
×
815
        }
×
816
}
817

818
// PendingChanID is a type that represents a pending channel ID. This might be
819
// selected by the caller, but if not, will be automatically selected.
820
type PendingChanID = [32]byte
821

822
// nextPendingChanID returns the next free pending channel ID to be used to
823
// identify a particular future channel funding workflow.
824
func (f *Manager) nextPendingChanID() PendingChanID {
60✔
825
        // Obtain a fresh nonce. We do this by encoding the incremented nonce.
60✔
826
        nextNonce := f.chanIDNonce.Add(1)
60✔
827

60✔
828
        var nonceBytes [8]byte
60✔
829
        binary.LittleEndian.PutUint64(nonceBytes[:], nextNonce)
60✔
830

60✔
831
        // We'll generate the next pending channelID by "encrypting" 32-bytes
60✔
832
        // of zeroes which'll extract 32 random bytes from our stream cipher.
60✔
833
        var (
60✔
834
                nextChanID PendingChanID
60✔
835
                zeroes     [32]byte
60✔
836
        )
60✔
837
        salsa20.XORKeyStream(
60✔
838
                nextChanID[:], zeroes[:], nonceBytes[:], &f.chanIDKey,
60✔
839
        )
60✔
840

60✔
841
        return nextChanID
60✔
842
}
60✔
843

844
// CancelPeerReservations cancels all active reservations associated with the
845
// passed node. This will ensure any outputs which have been pre committed,
846
// (and thus locked from coin selection), are properly freed.
847
func (f *Manager) CancelPeerReservations(nodePub [33]byte) {
4✔
848
        log.Debugf("Cancelling all reservations for peer %x", nodePub[:])
4✔
849

4✔
850
        f.resMtx.Lock()
4✔
851
        defer f.resMtx.Unlock()
4✔
852

4✔
853
        // We'll attempt to look up this node in the set of active
4✔
854
        // reservations.  If they don't have any, then there's no further work
4✔
855
        // to be done.
4✔
856
        nodeReservations, ok := f.activeReservations[nodePub]
4✔
857
        if !ok {
8✔
858
                log.Debugf("No active reservations for node: %x", nodePub[:])
4✔
859
                return
4✔
860
        }
4✔
861

862
        // If they do have any active reservations, then we'll cancel all of
863
        // them (which releases any locked UTXO's), and also delete it from the
864
        // reservation map.
865
        for pendingID, resCtx := range nodeReservations {
×
866
                if err := resCtx.reservation.Cancel(); err != nil {
×
867
                        log.Errorf("unable to cancel reservation for "+
×
868
                                "node=%x: %v", nodePub[:], err)
×
869
                }
×
870

871
                resCtx.err <- fmt.Errorf("peer disconnected")
×
872
                delete(nodeReservations, pendingID)
×
873
        }
874

875
        // Finally, we'll delete the node itself from the set of reservations.
876
        delete(f.activeReservations, nodePub)
×
877
}
878

879
// chanIdentifier wraps pending channel ID and channel ID into one struct so
880
// it's easier to identify a specific channel.
881
//
882
// TODO(yy): move to a different package to hide the private fields so direct
883
// access is disabled.
884
type chanIdentifier struct {
885
        // tempChanID is the pending channel ID created by the funder when
886
        // initializing the funding flow. For fundee, it's received from the
887
        // `open_channel` message.
888
        tempChanID lnwire.ChannelID
889

890
        // chanID is the channel ID created by the funder once the
891
        // `accept_channel` message is received. For fundee, it's received from
892
        // the `funding_created` message.
893
        chanID lnwire.ChannelID
894

895
        // chanIDSet is a boolean indicates whether the active channel ID is
896
        // set for this identifier. For zero conf channels, the `chanID` can be
897
        // all-zero, which is the same as the empty value of `ChannelID`. To
898
        // avoid the confusion, we use this boolean to explicitly signal
899
        // whether the `chanID` is set or not.
900
        chanIDSet bool
901
}
902

903
// newChanIdentifier creates a new chanIdentifier.
904
func newChanIdentifier(tempChanID lnwire.ChannelID) *chanIdentifier {
148✔
905
        return &chanIdentifier{
148✔
906
                tempChanID: tempChanID,
148✔
907
        }
148✔
908
}
148✔
909

910
// setChanID updates the `chanIdentifier` with the active channel ID.
911
func (c *chanIdentifier) setChanID(chanID lnwire.ChannelID) {
92✔
912
        c.chanID = chanID
92✔
913
        c.chanIDSet = true
92✔
914
}
92✔
915

916
// hasChanID returns true if the active channel ID has been set.
917
func (c *chanIdentifier) hasChanID() bool {
25✔
918
        return c.chanIDSet
25✔
919
}
25✔
920

921
// failFundingFlow will fail the active funding flow with the target peer,
922
// identified by its unique temporary channel ID. This method will send an
923
// error to the remote peer, and also remove the reservation from our set of
924
// pending reservations.
925
//
926
// TODO(roasbeef): if peer disconnects, and haven't yet broadcast funding
927
// transaction, then all reservations should be cleared.
928
func (f *Manager) failFundingFlow(peer lnpeer.Peer, cid *chanIdentifier,
929
        fundingErr error) {
25✔
930

25✔
931
        log.Debugf("Failing funding flow for pending_id=%v: %v",
25✔
932
                cid.tempChanID, fundingErr)
25✔
933

25✔
934
        // First, notify Brontide to remove the pending channel.
25✔
935
        //
25✔
936
        // NOTE: depending on where we fail the flow, we may not have the
25✔
937
        // active channel ID yet.
25✔
938
        if cid.hasChanID() {
34✔
939
                err := peer.RemovePendingChannel(cid.chanID)
9✔
940
                if err != nil {
9✔
941
                        log.Errorf("Unable to remove channel %v with peer %x: "+
×
942
                                "%v", cid,
×
943
                                peer.IdentityKey().SerializeCompressed(), err)
×
944
                }
×
945
        }
946

947
        ctx, err := f.cancelReservationCtx(
25✔
948
                peer.IdentityKey(), cid.tempChanID, false,
25✔
949
        )
25✔
950
        if err != nil {
38✔
951
                log.Errorf("unable to cancel reservation: %v", err)
13✔
952
        }
13✔
953

954
        // In case the case where the reservation existed, send the funding
955
        // error on the error channel.
956
        if ctx != nil {
41✔
957
                ctx.err <- fundingErr
16✔
958
        }
16✔
959

960
        // We only send the exact error if it is part of out whitelisted set of
961
        // errors (lnwire.FundingError or lnwallet.ReservationError).
962
        var msg lnwire.ErrorData
25✔
963
        switch e := fundingErr.(type) {
25✔
964
        // Let the actual error message be sent to the remote for the
965
        // whitelisted types.
966
        case lnwallet.ReservationError:
9✔
967
                msg = lnwire.ErrorData(e.Error())
9✔
968
        case lnwire.FundingError:
8✔
969
                msg = lnwire.ErrorData(e.Error())
8✔
970
        case chanacceptor.ChanAcceptError:
4✔
971
                msg = lnwire.ErrorData(e.Error())
4✔
972

973
        // For all other error types we just send a generic error.
974
        default:
16✔
975
                msg = lnwire.ErrorData("funding failed due to internal error")
16✔
976
        }
977

978
        errMsg := &lnwire.Error{
25✔
979
                ChanID: cid.tempChanID,
25✔
980
                Data:   msg,
25✔
981
        }
25✔
982

25✔
983
        log.Debugf("Sending funding error to peer (%x): %v",
25✔
984
                peer.IdentityKey().SerializeCompressed(), spew.Sdump(errMsg))
25✔
985
        if err := peer.SendMessage(false, errMsg); err != nil {
25✔
986
                log.Errorf("unable to send error message to peer %v", err)
×
987
        }
×
988
}
989

990
// sendWarning sends a new warning message to the target peer, targeting the
991
// specified cid with the passed funding error.
992
func (f *Manager) sendWarning(peer lnpeer.Peer, cid *chanIdentifier,
993
        fundingErr error) {
×
994

×
995
        msg := fundingErr.Error()
×
996

×
997
        errMsg := &lnwire.Warning{
×
998
                ChanID: cid.tempChanID,
×
999
                Data:   lnwire.WarningData(msg),
×
1000
        }
×
1001

×
1002
        log.Debugf("Sending funding warning to peer (%x): %v",
×
1003
                peer.IdentityKey().SerializeCompressed(),
×
1004
                spew.Sdump(errMsg),
×
1005
        )
×
1006

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

1012
// reservationCoordinator is the primary goroutine tasked with progressing the
1013
// funding workflow between the wallet, and any outside peers or local callers.
1014
//
1015
// NOTE: This MUST be run as a goroutine.
1016
func (f *Manager) reservationCoordinator() {
111✔
1017
        defer f.wg.Done()
111✔
1018

111✔
1019
        zombieSweepTicker := time.NewTicker(f.cfg.ZombieSweeperInterval)
111✔
1020
        defer zombieSweepTicker.Stop()
111✔
1021

111✔
1022
        for {
487✔
1023
                select {
376✔
1024
                case fmsg := <-f.fundingMsgs:
213✔
1025
                        switch msg := fmsg.msg.(type) {
213✔
1026
                        case *lnwire.OpenChannel:
57✔
1027
                                f.fundeeProcessOpenChannel(fmsg.peer, msg)
57✔
1028

1029
                        case *lnwire.AcceptChannel:
36✔
1030
                                f.funderProcessAcceptChannel(fmsg.peer, msg)
36✔
1031

1032
                        case *lnwire.FundingCreated:
31✔
1033
                                f.fundeeProcessFundingCreated(fmsg.peer, msg)
31✔
1034

1035
                        case *lnwire.FundingSigned:
31✔
1036
                                f.funderProcessFundingSigned(fmsg.peer, msg)
31✔
1037

1038
                        case *lnwire.ChannelReady:
32✔
1039
                                f.wg.Add(1)
32✔
1040
                                go f.handleChannelReady(fmsg.peer, msg)
32✔
1041

1042
                        case *lnwire.Warning:
42✔
1043
                                f.handleWarningMsg(fmsg.peer, msg)
42✔
1044

1045
                        case *lnwire.Error:
4✔
1046
                                f.handleErrorMsg(fmsg.peer, msg)
4✔
1047
                        }
1048
                case req := <-f.fundingRequests:
60✔
1049
                        f.handleInitFundingMsg(req)
60✔
1050

1051
                case <-zombieSweepTicker.C:
4✔
1052
                        f.pruneZombieReservations()
4✔
1053

1054
                case <-f.quit:
107✔
1055
                        return
107✔
1056
                }
1057
        }
1058
}
1059

1060
// advanceFundingState will advance the channel through the steps after the
1061
// funding transaction is broadcasted, up until the point where the channel is
1062
// ready for operation. This includes waiting for the funding transaction to
1063
// confirm, sending channel_ready to the peer, adding the channel to the graph,
1064
// and announcing the channel. The updateChan can be set non-nil to get
1065
// OpenStatusUpdates.
1066
//
1067
// NOTE: This MUST be run as a goroutine.
1068
func (f *Manager) advanceFundingState(channel *channeldb.OpenChannel,
1069
        pendingChanID PendingChanID,
1070
        updateChan chan<- *lnrpc.OpenStatusUpdate) {
67✔
1071

67✔
1072
        defer f.wg.Done()
67✔
1073

67✔
1074
        // If the channel is still pending we must wait for the funding
67✔
1075
        // transaction to confirm.
67✔
1076
        if channel.IsPending {
126✔
1077
                err := f.advancePendingChannelState(channel, pendingChanID)
59✔
1078
                if err != nil {
84✔
1079
                        log.Errorf("Unable to advance pending state of "+
25✔
1080
                                "ChannelPoint(%v): %v",
25✔
1081
                                channel.FundingOutpoint, err)
25✔
1082
                        return
25✔
1083
                }
25✔
1084
        }
1085

1086
        var chanOpts []lnwallet.ChannelOpt
46✔
1087
        f.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
88✔
1088
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
42✔
1089
        })
42✔
1090
        f.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
88✔
1091
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
42✔
1092
        })
42✔
1093

1094
        // We create the state-machine object which wraps the database state.
1095
        lnChannel, err := lnwallet.NewLightningChannel(
46✔
1096
                nil, channel, nil, chanOpts...,
46✔
1097
        )
46✔
1098
        if err != nil {
46✔
1099
                log.Errorf("Unable to create LightningChannel(%v): %v",
×
1100
                        channel.FundingOutpoint, err)
×
1101
                return
×
1102
        }
×
1103

1104
        for {
198✔
1105
                channelState, shortChanID, err := f.getChannelOpeningState(
152✔
1106
                        &channel.FundingOutpoint,
152✔
1107
                )
152✔
1108
                if err == channeldb.ErrChannelNotFound {
181✔
1109
                        // Channel not in fundingManager's opening database,
29✔
1110
                        // meaning it was successfully announced to the
29✔
1111
                        // network.
29✔
1112
                        // TODO(halseth): could do graph consistency check
29✔
1113
                        // here, and re-add the edge if missing.
29✔
1114
                        log.Debugf("ChannelPoint(%v) with chan_id=%x not "+
29✔
1115
                                "found in opening database, assuming already "+
29✔
1116
                                "announced to the network",
29✔
1117
                                channel.FundingOutpoint, pendingChanID)
29✔
1118
                        return
29✔
1119
                } else if err != nil {
156✔
1120
                        log.Errorf("Unable to query database for "+
×
1121
                                "channel opening state(%v): %v",
×
1122
                                channel.FundingOutpoint, err)
×
1123
                        return
×
1124
                }
×
1125

1126
                // If we did find the channel in the opening state database, we
1127
                // have seen the funding transaction being confirmed, but there
1128
                // are still steps left of the setup procedure. We continue the
1129
                // procedure where we left off.
1130
                err = f.stateStep(
127✔
1131
                        channel, lnChannel, shortChanID, pendingChanID,
127✔
1132
                        channelState, updateChan,
127✔
1133
                )
127✔
1134
                if err != nil {
148✔
1135
                        log.Errorf("Unable to advance state(%v): %v",
21✔
1136
                                channel.FundingOutpoint, err)
21✔
1137
                        return
21✔
1138
                }
21✔
1139
        }
1140
}
1141

1142
// stateStep advances the confirmed channel one step in the funding state
1143
// machine. This method is synchronous and the new channel opening state will
1144
// have been written to the database when it successfully returns. The
1145
// updateChan can be set non-nil to get OpenStatusUpdates.
1146
func (f *Manager) stateStep(channel *channeldb.OpenChannel,
1147
        lnChannel *lnwallet.LightningChannel,
1148
        shortChanID *lnwire.ShortChannelID, pendingChanID PendingChanID,
1149
        channelState channelOpeningState,
1150
        updateChan chan<- *lnrpc.OpenStatusUpdate) error {
127✔
1151

127✔
1152
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
127✔
1153
        log.Debugf("Channel(%v) with ShortChanID %v has opening state %v",
127✔
1154
                chanID, shortChanID, channelState)
127✔
1155

127✔
1156
        switch channelState {
127✔
1157
        // The funding transaction was confirmed, but we did not successfully
1158
        // send the channelReady message to the peer, so let's do that now.
1159
        case markedOpen:
39✔
1160
                err := f.sendChannelReady(channel, lnChannel)
39✔
1161
                if err != nil {
40✔
1162
                        return fmt.Errorf("failed sending channelReady: %w",
1✔
1163
                                err)
1✔
1164
                }
1✔
1165

1166
                // As the channelReady message is now sent to the peer, the
1167
                // channel is moved to the next state of the state machine. It
1168
                // will be moved to the last state (actually deleted from the
1169
                // database) after the channel is finally announced.
1170
                err = f.saveChannelOpeningState(
38✔
1171
                        &channel.FundingOutpoint, channelReadySent,
38✔
1172
                        shortChanID,
38✔
1173
                )
38✔
1174
                if err != nil {
38✔
1175
                        return fmt.Errorf("error setting channel state to"+
×
1176
                                " channelReadySent: %w", err)
×
1177
                }
×
1178

1179
                log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
38✔
1180
                        "sent ChannelReady", chanID, shortChanID)
38✔
1181

38✔
1182
                return nil
38✔
1183

1184
        // channelReady was sent to peer, but the channel was not added to the
1185
        // graph and the channel announcement was not sent.
1186
        case channelReadySent:
64✔
1187
                // We must wait until we've received the peer's channel_ready
64✔
1188
                // before sending a channel_update according to BOLT#07.
64✔
1189
                received, err := f.receivedChannelReady(
64✔
1190
                        channel.IdentityPub, chanID,
64✔
1191
                )
64✔
1192
                if err != nil {
64✔
1193
                        return fmt.Errorf("failed to check if channel_ready "+
×
1194
                                "was received: %v", err)
×
1195
                }
×
1196

1197
                if !received {
104✔
1198
                        // We haven't received ChannelReady, so we'll continue
40✔
1199
                        // to the next iteration of the loop after sleeping for
40✔
1200
                        // checkPeerChannelReadyInterval.
40✔
1201
                        select {
40✔
1202
                        case <-time.After(checkPeerChannelReadyInterval):
28✔
1203
                        case <-f.quit:
12✔
1204
                                return ErrFundingManagerShuttingDown
12✔
1205
                        }
1206

1207
                        return nil
28✔
1208
                }
1209

1210
                return f.handleChannelReadyReceived(
28✔
1211
                        channel, shortChanID, pendingChanID, updateChan,
28✔
1212
                )
28✔
1213

1214
        // The channel was added to the Router's topology, but the channel
1215
        // announcement was not sent.
1216
        case addedToGraph:
32✔
1217
                if channel.IsZeroConf() {
42✔
1218
                        // If this is a zero-conf channel, then we will wait
10✔
1219
                        // for it to be confirmed before announcing it to the
10✔
1220
                        // greater network.
10✔
1221
                        err := f.waitForZeroConfChannel(channel)
10✔
1222
                        if err != nil {
16✔
1223
                                return fmt.Errorf("failed waiting for zero "+
6✔
1224
                                        "channel: %v", err)
6✔
1225
                        }
6✔
1226

1227
                        // Update the local shortChanID variable such that
1228
                        // annAfterSixConfs uses the confirmed SCID.
1229
                        confirmedScid := channel.ZeroConfRealScid()
8✔
1230
                        shortChanID = &confirmedScid
8✔
1231
                }
1232

1233
                err := f.annAfterSixConfs(channel, shortChanID)
30✔
1234
                if err != nil {
36✔
1235
                        return fmt.Errorf("error sending channel "+
6✔
1236
                                "announcement: %v", err)
6✔
1237
                }
6✔
1238

1239
                // We delete the channel opening state from our internal
1240
                // database as the opening process has succeeded. We can do
1241
                // this because we assume the AuthenticatedGossiper queues the
1242
                // announcement messages, and persists them in case of a daemon
1243
                // shutdown.
1244
                err = f.deleteChannelOpeningState(&channel.FundingOutpoint)
28✔
1245
                if err != nil {
28✔
1246
                        return fmt.Errorf("error deleting channel state: %w",
×
1247
                                err)
×
1248
                }
×
1249

1250
                // After the fee parameters have been stored in the
1251
                // announcement we can delete them from the database. For
1252
                // private channels we do not announce the channel policy to
1253
                // the network but still need to delete them from the database.
1254
                err = f.deleteInitialForwardingPolicy(chanID)
28✔
1255
                if err != nil {
28✔
1256
                        log.Infof("Could not delete initial policy for chanId "+
×
1257
                                "%x", chanID)
×
1258
                }
×
1259

1260
                log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
28✔
1261
                        "announced", chanID, shortChanID)
28✔
1262

28✔
1263
                return nil
28✔
1264
        }
1265

1266
        return fmt.Errorf("undefined channelState: %v", channelState)
×
1267
}
1268

1269
// advancePendingChannelState waits for a pending channel's funding tx to
1270
// confirm, and marks it open in the database when that happens.
1271
func (f *Manager) advancePendingChannelState(channel *channeldb.OpenChannel,
1272
        pendingChanID PendingChanID) error {
59✔
1273

59✔
1274
        if channel.IsZeroConf() {
67✔
1275
                // Persist the alias to the alias database.
8✔
1276
                baseScid := channel.ShortChannelID
8✔
1277
                err := f.cfg.AliasManager.AddLocalAlias(
8✔
1278
                        baseScid, baseScid, true, false,
8✔
1279
                )
8✔
1280
                if err != nil {
8✔
1281
                        return fmt.Errorf("error adding local alias to "+
×
1282
                                "store: %v", err)
×
1283
                }
×
1284

1285
                // We don't wait for zero-conf channels to be confirmed and
1286
                // instead immediately proceed with the rest of the funding
1287
                // flow. The channel opening state is stored under the alias
1288
                // SCID.
1289
                err = f.saveChannelOpeningState(
8✔
1290
                        &channel.FundingOutpoint, markedOpen,
8✔
1291
                        &channel.ShortChannelID,
8✔
1292
                )
8✔
1293
                if err != nil {
8✔
1294
                        return fmt.Errorf("error setting zero-conf channel "+
×
1295
                                "state to markedOpen: %v", err)
×
1296
                }
×
1297

1298
                // The ShortChannelID is already set since it's an alias, but
1299
                // we still need to mark the channel as no longer pending.
1300
                err = channel.MarkAsOpen(channel.ShortChannelID)
8✔
1301
                if err != nil {
8✔
1302
                        return fmt.Errorf("error setting zero-conf channel's "+
×
1303
                                "pending flag to false: %v", err)
×
1304
                }
×
1305

1306
                // Inform the ChannelNotifier that the channel has transitioned
1307
                // from pending open to open.
1308
                f.cfg.NotifyOpenChannelEvent(channel.FundingOutpoint)
8✔
1309

8✔
1310
                // Find and close the discoverySignal for this channel such
8✔
1311
                // that ChannelReady messages will be processed.
8✔
1312
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
8✔
1313
                discoverySignal, ok := f.localDiscoverySignals.Load(chanID)
8✔
1314
                if ok {
16✔
1315
                        close(discoverySignal)
8✔
1316
                }
8✔
1317

1318
                return nil
8✔
1319
        }
1320

1321
        confChannel, err := f.waitForFundingWithTimeout(channel)
55✔
1322
        if err == ErrConfirmationTimeout {
57✔
1323
                return f.fundingTimeout(channel, pendingChanID)
2✔
1324
        } else if err != nil {
78✔
1325
                return fmt.Errorf("error waiting for funding "+
23✔
1326
                        "confirmation for ChannelPoint(%v): %v",
23✔
1327
                        channel.FundingOutpoint, err)
23✔
1328
        }
23✔
1329

1330
        if blockchain.IsCoinBaseTx(confChannel.fundingTx) {
36✔
1331
                // If it's a coinbase transaction, we need to wait for it to
2✔
1332
                // mature. We wait out an additional MinAcceptDepth on top of
2✔
1333
                // the coinbase maturity as an extra margin of safety.
2✔
1334
                maturity := f.cfg.Wallet.Cfg.NetParams.CoinbaseMaturity
2✔
1335
                numCoinbaseConfs := uint32(maturity)
2✔
1336

2✔
1337
                if channel.NumConfsRequired > maturity {
2✔
1338
                        numCoinbaseConfs = uint32(channel.NumConfsRequired)
×
1339
                }
×
1340

1341
                txid := &channel.FundingOutpoint.Hash
2✔
1342
                fundingScript, err := makeFundingScript(channel)
2✔
1343
                if err != nil {
2✔
1344
                        log.Errorf("unable to create funding script for "+
×
1345
                                "ChannelPoint(%v): %v",
×
1346
                                channel.FundingOutpoint, err)
×
1347

×
1348
                        return err
×
1349
                }
×
1350

1351
                confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
2✔
1352
                        txid, fundingScript, numCoinbaseConfs,
2✔
1353
                        channel.BroadcastHeight(),
2✔
1354
                )
2✔
1355
                if err != nil {
2✔
1356
                        log.Errorf("Unable to register for confirmation of "+
×
1357
                                "ChannelPoint(%v): %v",
×
1358
                                channel.FundingOutpoint, err)
×
1359

×
1360
                        return err
×
1361
                }
×
1362

1363
                select {
2✔
1364
                case _, ok := <-confNtfn.Confirmed:
2✔
1365
                        if !ok {
2✔
1366
                                return fmt.Errorf("ChainNotifier shutting "+
×
1367
                                        "down, can't complete funding flow "+
×
1368
                                        "for ChannelPoint(%v)",
×
1369
                                        channel.FundingOutpoint)
×
1370
                        }
×
1371

1372
                case <-f.quit:
×
1373
                        return ErrFundingManagerShuttingDown
×
1374
                }
1375
        }
1376

1377
        // Success, funding transaction was confirmed.
1378
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
34✔
1379
        log.Debugf("ChannelID(%v) is now fully confirmed! "+
34✔
1380
                "(shortChanID=%v)", chanID, confChannel.shortChanID)
34✔
1381

34✔
1382
        err = f.handleFundingConfirmation(channel, confChannel)
34✔
1383
        if err != nil {
34✔
1384
                return fmt.Errorf("unable to handle funding "+
×
1385
                        "confirmation for ChannelPoint(%v): %v",
×
1386
                        channel.FundingOutpoint, err)
×
1387
        }
×
1388

1389
        return nil
34✔
1390
}
1391

1392
// ProcessFundingMsg sends a message to the internal fundingManager goroutine,
1393
// allowing it to handle the lnwire.Message.
1394
func (f *Manager) ProcessFundingMsg(msg lnwire.Message, peer lnpeer.Peer) {
214✔
1395
        select {
214✔
1396
        case f.fundingMsgs <- &fundingMsg{msg, peer}:
214✔
1397
        case <-f.quit:
×
1398
                return
×
1399
        }
1400
}
1401

1402
// fundeeProcessOpenChannel creates an initial 'ChannelReservation' within the
1403
// wallet, then responds to the source peer with an accept channel message
1404
// progressing the funding workflow.
1405
//
1406
// TODO(roasbeef): add error chan to all, let channelManager handle
1407
// error+propagate.
1408
//
1409
//nolint:funlen
1410
func (f *Manager) fundeeProcessOpenChannel(peer lnpeer.Peer,
1411
        msg *lnwire.OpenChannel) {
57✔
1412

57✔
1413
        // Check number of pending channels to be smaller than maximum allowed
57✔
1414
        // number and send ErrorGeneric to remote peer if condition is
57✔
1415
        // violated.
57✔
1416
        peerPubKey := peer.IdentityKey()
57✔
1417
        peerIDKey := newSerializedKey(peerPubKey)
57✔
1418

57✔
1419
        amt := msg.FundingAmount
57✔
1420

57✔
1421
        // We get all pending channels for this peer. This is the list of the
57✔
1422
        // active reservations and the channels pending open in the database.
57✔
1423
        f.resMtx.RLock()
57✔
1424
        reservations := f.activeReservations[peerIDKey]
57✔
1425

57✔
1426
        // We don't count reservations that were created from a canned funding
57✔
1427
        // shim. The user has registered the shim and therefore expects this
57✔
1428
        // channel to arrive.
57✔
1429
        numPending := 0
57✔
1430
        for _, res := range reservations {
69✔
1431
                if !res.reservation.IsCannedShim() {
24✔
1432
                        numPending++
12✔
1433
                }
12✔
1434
        }
1435
        f.resMtx.RUnlock()
57✔
1436

57✔
1437
        // Create the channel identifier.
57✔
1438
        cid := newChanIdentifier(msg.PendingChannelID)
57✔
1439

57✔
1440
        // Also count the channels that are already pending. There we don't know
57✔
1441
        // the underlying intent anymore, unfortunately.
57✔
1442
        channels, err := f.cfg.ChannelDB.FetchOpenChannels(peerPubKey)
57✔
1443
        if err != nil {
57✔
1444
                f.failFundingFlow(peer, cid, err)
×
1445
                return
×
1446
        }
×
1447

1448
        for _, c := range channels {
73✔
1449
                // Pending channels that have a non-zero thaw height were also
16✔
1450
                // created through a canned funding shim. Those also don't
16✔
1451
                // count towards the DoS protection limit.
16✔
1452
                //
16✔
1453
                // TODO(guggero): Properly store the funding type (wallet, shim,
16✔
1454
                // PSBT) on the channel so we don't need to use the thaw height.
16✔
1455
                if c.IsPending && c.ThawHeight == 0 {
28✔
1456
                        numPending++
12✔
1457
                }
12✔
1458
        }
1459

1460
        // TODO(roasbeef): modify to only accept a _single_ pending channel per
1461
        // block unless white listed
1462
        if numPending >= f.cfg.MaxPendingChannels {
65✔
1463
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
8✔
1464

8✔
1465
                return
8✔
1466
        }
8✔
1467

1468
        // Ensure that the pendingChansLimit is respected.
1469
        pendingChans, err := f.cfg.ChannelDB.FetchPendingChannels()
53✔
1470
        if err != nil {
53✔
1471
                f.failFundingFlow(peer, cid, err)
×
1472
                return
×
1473
        }
×
1474

1475
        if len(pendingChans) > pendingChansLimit {
53✔
1476
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
×
1477
                return
×
1478
        }
×
1479

1480
        // We'll also reject any requests to create channels until we're fully
1481
        // synced to the network as we won't be able to properly validate the
1482
        // confirmation of the funding transaction.
1483
        isSynced, _, err := f.cfg.Wallet.IsSynced()
53✔
1484
        if err != nil || !isSynced {
53✔
1485
                if err != nil {
×
1486
                        log.Errorf("unable to query wallet: %v", err)
×
1487
                }
×
1488
                err := errors.New("Synchronizing blockchain")
×
1489
                f.failFundingFlow(peer, cid, err)
×
1490
                return
×
1491
        }
1492

1493
        // Ensure that the remote party respects our maximum channel size.
1494
        if amt > f.cfg.MaxChanSize {
59✔
1495
                f.failFundingFlow(
6✔
1496
                        peer, cid,
6✔
1497
                        lnwallet.ErrChanTooLarge(amt, f.cfg.MaxChanSize),
6✔
1498
                )
6✔
1499
                return
6✔
1500
        }
6✔
1501

1502
        // We'll, also ensure that the remote party isn't attempting to propose
1503
        // a channel that's below our current min channel size.
1504
        if amt < f.cfg.MinChanSize {
55✔
1505
                f.failFundingFlow(
4✔
1506
                        peer, cid,
4✔
1507
                        lnwallet.ErrChanTooSmall(amt, f.cfg.MinChanSize),
4✔
1508
                )
4✔
1509
                return
4✔
1510
        }
4✔
1511

1512
        // If request specifies non-zero push amount and 'rejectpush' is set,
1513
        // signal an error.
1514
        if f.cfg.RejectPush && msg.PushAmount > 0 {
52✔
1515
                f.failFundingFlow(peer, cid, lnwallet.ErrNonZeroPushAmount())
1✔
1516
                return
1✔
1517
        }
1✔
1518

1519
        // Send the OpenChannel request to the ChannelAcceptor to determine
1520
        // whether this node will accept the channel.
1521
        chanReq := &chanacceptor.ChannelAcceptRequest{
50✔
1522
                Node:        peer.IdentityKey(),
50✔
1523
                OpenChanMsg: msg,
50✔
1524
        }
50✔
1525

50✔
1526
        // Query our channel acceptor to determine whether we should reject
50✔
1527
        // the channel.
50✔
1528
        acceptorResp := f.cfg.OpenChannelPredicate.Accept(chanReq)
50✔
1529
        if acceptorResp.RejectChannel() {
54✔
1530
                f.failFundingFlow(peer, cid, acceptorResp.ChanAcceptError)
4✔
1531
                return
4✔
1532
        }
4✔
1533

1534
        log.Infof("Recv'd fundingRequest(amt=%v, push=%v, delay=%v, "+
50✔
1535
                "pendingId=%x) from peer(%x)", amt, msg.PushAmount,
50✔
1536
                msg.CsvDelay, msg.PendingChannelID,
50✔
1537
                peer.IdentityKey().SerializeCompressed())
50✔
1538

50✔
1539
        // Attempt to initialize a reservation within the wallet. If the wallet
50✔
1540
        // has insufficient resources to create the channel, then the
50✔
1541
        // reservation attempt may be rejected. Note that since we're on the
50✔
1542
        // responding side of a single funder workflow, we don't commit any
50✔
1543
        // funds to the channel ourselves.
50✔
1544
        //
50✔
1545
        // Before we init the channel, we'll also check to see what commitment
50✔
1546
        // format we can use with this peer. This is dependent on *both* us and
50✔
1547
        // the remote peer are signaling the proper feature bit if we're using
50✔
1548
        // implicit negotiation, and simply the channel type sent over if we're
50✔
1549
        // using explicit negotiation.
50✔
1550
        chanType, commitType, err := negotiateCommitmentType(
50✔
1551
                msg.ChannelType, peer.LocalFeatures(), peer.RemoteFeatures(),
50✔
1552
        )
50✔
1553
        if err != nil {
50✔
1554
                // TODO(roasbeef): should be using soft errors
×
1555
                log.Errorf("channel type negotiation failed: %v", err)
×
1556
                f.failFundingFlow(peer, cid, err)
×
1557
                return
×
1558
        }
×
1559

1560
        var scidFeatureVal bool
50✔
1561
        if hasFeatures(
50✔
1562
                peer.LocalFeatures(), peer.RemoteFeatures(),
50✔
1563
                lnwire.ScidAliasOptional,
50✔
1564
        ) {
57✔
1565

7✔
1566
                scidFeatureVal = true
7✔
1567
        }
7✔
1568

1569
        var (
50✔
1570
                zeroConf bool
50✔
1571
                scid     bool
50✔
1572
        )
50✔
1573

50✔
1574
        // Only echo back a channel type in AcceptChannel if we actually used
50✔
1575
        // explicit negotiation above.
50✔
1576
        if chanType != nil {
58✔
1577
                // Check if the channel type includes the zero-conf or
8✔
1578
                // scid-alias bits.
8✔
1579
                featureVec := lnwire.RawFeatureVector(*chanType)
8✔
1580
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
8✔
1581
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
8✔
1582

8✔
1583
                // If the zero-conf channel type was negotiated, ensure that
8✔
1584
                // the acceptor allows it.
8✔
1585
                if zeroConf && !acceptorResp.ZeroConf {
8✔
1586
                        // Fail the funding flow.
×
1587
                        flowErr := fmt.Errorf("channel acceptor blocked " +
×
1588
                                "zero-conf channel negotiation")
×
1589
                        log.Errorf("Cancelling funding flow for %v based on "+
×
1590
                                "channel acceptor response: %v", cid, flowErr)
×
1591
                        f.failFundingFlow(peer, cid, flowErr)
×
1592
                        return
×
1593
                }
×
1594

1595
                // If the zero-conf channel type wasn't negotiated and the
1596
                // fundee still wants a zero-conf channel, perform more checks.
1597
                // Require that both sides have the scid-alias feature bit set.
1598
                // We don't require anchors here - this is for compatibility
1599
                // with LDK.
1600
                if !zeroConf && acceptorResp.ZeroConf {
8✔
1601
                        if !scidFeatureVal {
×
1602
                                // Fail the funding flow.
×
1603
                                flowErr := fmt.Errorf("scid-alias feature " +
×
1604
                                        "must be negotiated for zero-conf")
×
1605
                                log.Errorf("Cancelling funding flow for "+
×
1606
                                        "zero-conf channel %v: %v", cid,
×
1607
                                        flowErr)
×
1608
                                f.failFundingFlow(peer, cid, flowErr)
×
1609
                                return
×
1610
                        }
×
1611

1612
                        // Set zeroConf to true to enable the zero-conf flow.
1613
                        zeroConf = true
×
1614
                }
1615
        }
1616

1617
        public := msg.ChannelFlags&lnwire.FFAnnounceChannel != 0
50✔
1618
        switch {
50✔
1619
        // Sending the option-scid-alias channel type for a public channel is
1620
        // disallowed.
1621
        case public && scid:
×
1622
                err = fmt.Errorf("option-scid-alias chantype for public " +
×
1623
                        "channel")
×
1624
                log.Errorf("Cancelling funding flow for public channel %v "+
×
1625
                        "with scid-alias: %v", cid, err)
×
1626
                f.failFundingFlow(peer, cid, err)
×
1627

×
1628
                return
×
1629

1630
        // The current variant of taproot channels can only be used with
1631
        // unadvertised channels for now.
1632
        case commitType.IsTaproot() && public:
×
1633
                err = fmt.Errorf("taproot channel type for public channel")
×
1634
                log.Errorf("Cancelling funding flow for public taproot "+
×
1635
                        "channel %v: %v", cid, err)
×
1636
                f.failFundingFlow(peer, cid, err)
×
1637

×
1638
                return
×
1639
        }
1640

1641
        // At this point, if we have an AuxFundingController active, we'll
1642
        // check to see if we have a special tapscript root to use in our
1643
        // MuSig funding output.
1644
        tapscriptRoot, err := fn.MapOptionZ(
50✔
1645
                f.cfg.AuxFundingController,
50✔
1646
                func(c AuxFundingController) AuxTapscriptResult {
50✔
1647
                        return c.DeriveTapscriptRoot(msg.PendingChannelID)
×
1648
                },
×
1649
        ).Unpack()
1650
        if err != nil {
50✔
1651
                err = fmt.Errorf("error deriving tapscript root: %w", err)
×
1652
                log.Error(err)
×
1653
                f.failFundingFlow(peer, cid, err)
×
1654

×
1655
                return
×
1656
        }
×
1657

1658
        req := &lnwallet.InitFundingReserveMsg{
50✔
1659
                ChainHash:        &msg.ChainHash,
50✔
1660
                PendingChanID:    msg.PendingChannelID,
50✔
1661
                NodeID:           peer.IdentityKey(),
50✔
1662
                NodeAddr:         peer.Address(),
50✔
1663
                LocalFundingAmt:  0,
50✔
1664
                RemoteFundingAmt: amt,
50✔
1665
                CommitFeePerKw:   chainfee.SatPerKWeight(msg.FeePerKiloWeight),
50✔
1666
                FundingFeePerKw:  0,
50✔
1667
                PushMSat:         msg.PushAmount,
50✔
1668
                Flags:            msg.ChannelFlags,
50✔
1669
                MinConfs:         1,
50✔
1670
                CommitType:       commitType,
50✔
1671
                ZeroConf:         zeroConf,
50✔
1672
                OptionScidAlias:  scid,
50✔
1673
                ScidAliasFeature: scidFeatureVal,
50✔
1674
                TapscriptRoot:    tapscriptRoot,
50✔
1675
        }
50✔
1676

50✔
1677
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
50✔
1678
        if err != nil {
50✔
1679
                log.Errorf("Unable to initialize reservation: %v", err)
×
1680
                f.failFundingFlow(peer, cid, err)
×
1681
                return
×
1682
        }
×
1683

1684
        log.Debugf("Initialized channel reservation: zeroConf=%v, psbt=%v, "+
50✔
1685
                "cannedShim=%v", reservation.IsZeroConf(),
50✔
1686
                reservation.IsPsbt(), reservation.IsCannedShim())
50✔
1687

50✔
1688
        if zeroConf {
56✔
1689
                // Store an alias for zero-conf channels. Other option-scid
6✔
1690
                // channels will do this at a later point.
6✔
1691
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
6✔
1692
                if err != nil {
6✔
1693
                        log.Errorf("Unable to request alias: %v", err)
×
1694
                        f.failFundingFlow(peer, cid, err)
×
1695
                        return
×
1696
                }
×
1697

1698
                reservation.AddAlias(aliasScid)
6✔
1699
        }
1700

1701
        // As we're the responder, we get to specify the number of confirmations
1702
        // that we require before both of us consider the channel open. We'll
1703
        // use our mapping to derive the proper number of confirmations based on
1704
        // the amount of the channel, and also if any funds are being pushed to
1705
        // us. If a depth value was set by our channel acceptor, we will use
1706
        // that value instead.
1707
        numConfsReq := f.cfg.NumRequiredConfs(msg.FundingAmount, msg.PushAmount)
50✔
1708
        if acceptorResp.MinAcceptDepth != 0 {
50✔
1709
                numConfsReq = acceptorResp.MinAcceptDepth
×
1710
        }
×
1711

1712
        // We'll ignore the min_depth calculated above if this is a zero-conf
1713
        // channel.
1714
        if zeroConf {
56✔
1715
                numConfsReq = 0
6✔
1716
        }
6✔
1717

1718
        reservation.SetNumConfsRequired(numConfsReq)
50✔
1719

50✔
1720
        // We'll also validate and apply all the constraints the initiating
50✔
1721
        // party is attempting to dictate for our commitment transaction.
50✔
1722
        stateBounds := &channeldb.ChannelStateBounds{
50✔
1723
                ChanReserve:      msg.ChannelReserve,
50✔
1724
                MaxPendingAmount: msg.MaxValueInFlight,
50✔
1725
                MinHTLC:          msg.HtlcMinimum,
50✔
1726
                MaxAcceptedHtlcs: msg.MaxAcceptedHTLCs,
50✔
1727
        }
50✔
1728
        commitParams := &channeldb.CommitmentParams{
50✔
1729
                DustLimit: msg.DustLimit,
50✔
1730
                CsvDelay:  msg.CsvDelay,
50✔
1731
        }
50✔
1732
        err = reservation.CommitConstraints(
50✔
1733
                stateBounds, commitParams, f.cfg.MaxLocalCSVDelay, true,
50✔
1734
        )
50✔
1735
        if err != nil {
50✔
1736
                log.Errorf("Unacceptable channel constraints: %v", err)
×
1737
                f.failFundingFlow(peer, cid, err)
×
1738
                return
×
1739
        }
×
1740

1741
        // Check whether the peer supports upfront shutdown, and get a new
1742
        // wallet address if our node is configured to set shutdown addresses by
1743
        // default. We use the upfront shutdown script provided by our channel
1744
        // acceptor (if any) in lieu of user input.
1745
        shutdown, err := getUpfrontShutdownScript(
50✔
1746
                f.cfg.EnableUpfrontShutdown, peer, acceptorResp.UpfrontShutdown,
50✔
1747
                f.selectShutdownScript,
50✔
1748
        )
50✔
1749
        if err != nil {
50✔
1750
                f.failFundingFlow(
×
1751
                        peer, cid,
×
1752
                        fmt.Errorf("getUpfrontShutdownScript error: %w", err),
×
1753
                )
×
1754
                return
×
1755
        }
×
1756
        reservation.SetOurUpfrontShutdown(shutdown)
50✔
1757

50✔
1758
        // If a script enforced channel lease is being proposed, we'll need to
50✔
1759
        // validate its custom TLV records.
50✔
1760
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
54✔
1761
                if msg.LeaseExpiry == nil {
4✔
1762
                        err := errors.New("missing lease expiry")
×
1763
                        f.failFundingFlow(peer, cid, err)
×
1764
                        return
×
1765
                }
×
1766

1767
                // If we had a shim registered for this channel prior to
1768
                // receiving its corresponding OpenChannel message, then we'll
1769
                // validate the proposed LeaseExpiry against what was registered
1770
                // in our shim.
1771
                if reservation.LeaseExpiry() != 0 {
8✔
1772
                        if uint32(*msg.LeaseExpiry) !=
4✔
1773
                                reservation.LeaseExpiry() {
4✔
1774

×
1775
                                err := errors.New("lease expiry mismatch")
×
1776
                                f.failFundingFlow(peer, cid, err)
×
1777
                                return
×
1778
                        }
×
1779
                }
1780
        }
1781

1782
        log.Infof("Requiring %v confirmations for pendingChan(%x): "+
50✔
1783
                "amt=%v, push_amt=%v, committype=%v, upfrontShutdown=%x",
50✔
1784
                numConfsReq, msg.PendingChannelID, amt, msg.PushAmount,
50✔
1785
                commitType, msg.UpfrontShutdownScript)
50✔
1786

50✔
1787
        // Generate our required constraints for the remote party, using the
50✔
1788
        // values provided by the channel acceptor if they are non-zero.
50✔
1789
        remoteCsvDelay := f.cfg.RequiredRemoteDelay(amt)
50✔
1790
        if acceptorResp.CSVDelay != 0 {
50✔
1791
                remoteCsvDelay = acceptorResp.CSVDelay
×
1792
        }
×
1793

1794
        // If our default dust limit was above their ChannelReserve, we change
1795
        // it to the ChannelReserve. We must make sure the ChannelReserve we
1796
        // send in the AcceptChannel message is above both dust limits.
1797
        // Therefore, take the maximum of msg.DustLimit and our dust limit.
1798
        //
1799
        // NOTE: Even with this bounding, the ChannelAcceptor may return an
1800
        // BOLT#02-invalid ChannelReserve.
1801
        maxDustLimit := reservation.OurContribution().DustLimit
50✔
1802
        if msg.DustLimit > maxDustLimit {
50✔
1803
                maxDustLimit = msg.DustLimit
×
1804
        }
×
1805

1806
        chanReserve := f.cfg.RequiredRemoteChanReserve(amt, maxDustLimit)
50✔
1807
        if acceptorResp.Reserve != 0 {
50✔
1808
                chanReserve = acceptorResp.Reserve
×
1809
        }
×
1810

1811
        remoteMaxValue := f.cfg.RequiredRemoteMaxValue(amt)
50✔
1812
        if acceptorResp.InFlightTotal != 0 {
50✔
1813
                remoteMaxValue = acceptorResp.InFlightTotal
×
1814
        }
×
1815

1816
        maxHtlcs := f.cfg.RequiredRemoteMaxHTLCs(amt)
50✔
1817
        if acceptorResp.HtlcLimit != 0 {
50✔
1818
                maxHtlcs = acceptorResp.HtlcLimit
×
1819
        }
×
1820

1821
        // Default to our default minimum hltc value, replacing it with the
1822
        // channel acceptor's value if it is set.
1823
        minHtlc := f.cfg.DefaultMinHtlcIn
50✔
1824
        if acceptorResp.MinHtlcIn != 0 {
50✔
1825
                minHtlc = acceptorResp.MinHtlcIn
×
1826
        }
×
1827

1828
        // If we are handling a FundingOpen request then we need to specify the
1829
        // default channel fees since they are not provided by the responder
1830
        // interactively.
1831
        ourContribution := reservation.OurContribution()
50✔
1832
        forwardingPolicy := f.defaultForwardingPolicy(
50✔
1833
                ourContribution.ChannelStateBounds,
50✔
1834
        )
50✔
1835

50✔
1836
        // Once the reservation has been created successfully, we add it to
50✔
1837
        // this peer's map of pending reservations to track this particular
50✔
1838
        // reservation until either abort or completion.
50✔
1839
        f.resMtx.Lock()
50✔
1840
        if _, ok := f.activeReservations[peerIDKey]; !ok {
96✔
1841
                f.activeReservations[peerIDKey] = make(pendingChannels)
46✔
1842
        }
46✔
1843
        resCtx := &reservationWithCtx{
50✔
1844
                reservation:       reservation,
50✔
1845
                chanAmt:           amt,
50✔
1846
                forwardingPolicy:  *forwardingPolicy,
50✔
1847
                remoteCsvDelay:    remoteCsvDelay,
50✔
1848
                remoteMinHtlc:     minHtlc,
50✔
1849
                remoteMaxValue:    remoteMaxValue,
50✔
1850
                remoteMaxHtlcs:    maxHtlcs,
50✔
1851
                remoteChanReserve: chanReserve,
50✔
1852
                maxLocalCsv:       f.cfg.MaxLocalCSVDelay,
50✔
1853
                channelType:       chanType,
50✔
1854
                err:               make(chan error, 1),
50✔
1855
                peer:              peer,
50✔
1856
        }
50✔
1857
        f.activeReservations[peerIDKey][msg.PendingChannelID] = resCtx
50✔
1858
        f.resMtx.Unlock()
50✔
1859

50✔
1860
        // Update the timestamp once the fundingOpenMsg has been handled.
50✔
1861
        defer resCtx.updateTimestamp()
50✔
1862

50✔
1863
        cfg := channeldb.ChannelConfig{
50✔
1864
                ChannelStateBounds: channeldb.ChannelStateBounds{
50✔
1865
                        MaxPendingAmount: remoteMaxValue,
50✔
1866
                        ChanReserve:      chanReserve,
50✔
1867
                        MinHTLC:          minHtlc,
50✔
1868
                        MaxAcceptedHtlcs: maxHtlcs,
50✔
1869
                },
50✔
1870
                CommitmentParams: channeldb.CommitmentParams{
50✔
1871
                        DustLimit: msg.DustLimit,
50✔
1872
                        CsvDelay:  remoteCsvDelay,
50✔
1873
                },
50✔
1874
                MultiSigKey: keychain.KeyDescriptor{
50✔
1875
                        PubKey: copyPubKey(msg.FundingKey),
50✔
1876
                },
50✔
1877
                RevocationBasePoint: keychain.KeyDescriptor{
50✔
1878
                        PubKey: copyPubKey(msg.RevocationPoint),
50✔
1879
                },
50✔
1880
                PaymentBasePoint: keychain.KeyDescriptor{
50✔
1881
                        PubKey: copyPubKey(msg.PaymentPoint),
50✔
1882
                },
50✔
1883
                DelayBasePoint: keychain.KeyDescriptor{
50✔
1884
                        PubKey: copyPubKey(msg.DelayedPaymentPoint),
50✔
1885
                },
50✔
1886
                HtlcBasePoint: keychain.KeyDescriptor{
50✔
1887
                        PubKey: copyPubKey(msg.HtlcPoint),
50✔
1888
                },
50✔
1889
        }
50✔
1890

50✔
1891
        // With our parameters set, we'll now process their contribution so we
50✔
1892
        // can move the funding workflow ahead.
50✔
1893
        remoteContribution := &lnwallet.ChannelContribution{
50✔
1894
                FundingAmount:        amt,
50✔
1895
                FirstCommitmentPoint: msg.FirstCommitmentPoint,
50✔
1896
                ChannelConfig:        &cfg,
50✔
1897
                UpfrontShutdown:      msg.UpfrontShutdownScript,
50✔
1898
        }
50✔
1899

50✔
1900
        if resCtx.reservation.IsTaproot() {
56✔
1901
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
6✔
1902
                if err != nil {
6✔
1903
                        log.Error(errNoLocalNonce)
×
1904

×
1905
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
1906

×
1907
                        return
×
1908
                }
×
1909

1910
                remoteContribution.LocalNonce = &musig2.Nonces{
6✔
1911
                        PubNonce: localNonce,
6✔
1912
                }
6✔
1913
        }
1914

1915
        err = reservation.ProcessSingleContribution(remoteContribution)
50✔
1916
        if err != nil {
56✔
1917
                log.Errorf("unable to add contribution reservation: %v", err)
6✔
1918
                f.failFundingFlow(peer, cid, err)
6✔
1919
                return
6✔
1920
        }
6✔
1921

1922
        log.Infof("Sending fundingResp for pending_id(%x)",
44✔
1923
                msg.PendingChannelID)
44✔
1924
        bounds := remoteContribution.ChannelConfig.ChannelStateBounds
44✔
1925
        log.Debugf("Remote party accepted channel state space bounds: %v",
44✔
1926
                lnutils.SpewLogClosure(bounds))
44✔
1927
        params := remoteContribution.ChannelConfig.CommitmentParams
44✔
1928
        log.Debugf("Remote party accepted commitment rendering params: %v",
44✔
1929
                lnutils.SpewLogClosure(params))
44✔
1930

44✔
1931
        reservation.SetState(lnwallet.SentAcceptChannel)
44✔
1932

44✔
1933
        // With the initiator's contribution recorded, respond with our
44✔
1934
        // contribution in the next message of the workflow.
44✔
1935
        fundingAccept := lnwire.AcceptChannel{
44✔
1936
                PendingChannelID:      msg.PendingChannelID,
44✔
1937
                DustLimit:             ourContribution.DustLimit,
44✔
1938
                MaxValueInFlight:      remoteMaxValue,
44✔
1939
                ChannelReserve:        chanReserve,
44✔
1940
                MinAcceptDepth:        uint32(numConfsReq),
44✔
1941
                HtlcMinimum:           minHtlc,
44✔
1942
                CsvDelay:              remoteCsvDelay,
44✔
1943
                MaxAcceptedHTLCs:      maxHtlcs,
44✔
1944
                FundingKey:            ourContribution.MultiSigKey.PubKey,
44✔
1945
                RevocationPoint:       ourContribution.RevocationBasePoint.PubKey,
44✔
1946
                PaymentPoint:          ourContribution.PaymentBasePoint.PubKey,
44✔
1947
                DelayedPaymentPoint:   ourContribution.DelayBasePoint.PubKey,
44✔
1948
                HtlcPoint:             ourContribution.HtlcBasePoint.PubKey,
44✔
1949
                FirstCommitmentPoint:  ourContribution.FirstCommitmentPoint,
44✔
1950
                UpfrontShutdownScript: ourContribution.UpfrontShutdown,
44✔
1951
                ChannelType:           chanType,
44✔
1952
                LeaseExpiry:           msg.LeaseExpiry,
44✔
1953
        }
44✔
1954

44✔
1955
        if commitType.IsTaproot() {
50✔
1956
                fundingAccept.LocalNonce = lnwire.SomeMusig2Nonce(
6✔
1957
                        ourContribution.LocalNonce.PubNonce,
6✔
1958
                )
6✔
1959
        }
6✔
1960

1961
        if err := peer.SendMessage(true, &fundingAccept); err != nil {
44✔
1962
                log.Errorf("unable to send funding response to peer: %v", err)
×
1963
                f.failFundingFlow(peer, cid, err)
×
1964
                return
×
1965
        }
×
1966
}
1967

1968
// funderProcessAcceptChannel processes a response to the workflow initiation
1969
// sent by the remote peer. This message then queues a message with the funding
1970
// outpoint, and a commitment signature to the remote peer.
1971
//
1972
//nolint:funlen
1973
func (f *Manager) funderProcessAcceptChannel(peer lnpeer.Peer,
1974
        msg *lnwire.AcceptChannel) {
36✔
1975

36✔
1976
        pendingChanID := msg.PendingChannelID
36✔
1977
        peerKey := peer.IdentityKey()
36✔
1978
        var peerKeyBytes []byte
36✔
1979
        if peerKey != nil {
72✔
1980
                peerKeyBytes = peerKey.SerializeCompressed()
36✔
1981
        }
36✔
1982

1983
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
36✔
1984
        if err != nil {
36✔
1985
                log.Warnf("Can't find reservation (peerKey:%x, chan_id:%v)",
×
1986
                        peerKeyBytes, pendingChanID)
×
1987
                return
×
1988
        }
×
1989

1990
        // Update the timestamp once the fundingAcceptMsg has been handled.
1991
        defer resCtx.updateTimestamp()
36✔
1992

36✔
1993
        if resCtx.reservation.State() != lnwallet.SentOpenChannel {
36✔
1994
                return
×
1995
        }
×
1996

1997
        log.Infof("Recv'd fundingResponse for pending_id(%x)",
36✔
1998
                pendingChanID[:])
36✔
1999

36✔
2000
        // Create the channel identifier.
36✔
2001
        cid := newChanIdentifier(msg.PendingChannelID)
36✔
2002

36✔
2003
        // Perform some basic validation of any custom TLV records included.
36✔
2004
        //
36✔
2005
        // TODO: Return errors as funding.Error to give context to remote peer?
36✔
2006
        if resCtx.channelType != nil {
44✔
2007
                // We'll want to quickly check that the ChannelType echoed by
8✔
2008
                // the channel request recipient matches what we proposed.
8✔
2009
                if msg.ChannelType == nil {
9✔
2010
                        err := errors.New("explicit channel type not echoed " +
1✔
2011
                                "back")
1✔
2012
                        f.failFundingFlow(peer, cid, err)
1✔
2013
                        return
1✔
2014
                }
1✔
2015
                proposedFeatures := lnwire.RawFeatureVector(*resCtx.channelType)
7✔
2016
                ackedFeatures := lnwire.RawFeatureVector(*msg.ChannelType)
7✔
2017
                if !proposedFeatures.Equals(&ackedFeatures) {
7✔
2018
                        err := errors.New("channel type mismatch")
×
2019
                        f.failFundingFlow(peer, cid, err)
×
2020
                        return
×
2021
                }
×
2022

2023
                // We'll want to do the same with the LeaseExpiry if one should
2024
                // be set.
2025
                if resCtx.reservation.LeaseExpiry() != 0 {
11✔
2026
                        if msg.LeaseExpiry == nil {
4✔
2027
                                err := errors.New("lease expiry not echoed " +
×
2028
                                        "back")
×
2029
                                f.failFundingFlow(peer, cid, err)
×
2030
                                return
×
2031
                        }
×
2032
                        if uint32(*msg.LeaseExpiry) !=
4✔
2033
                                resCtx.reservation.LeaseExpiry() {
4✔
2034

×
2035
                                err := errors.New("lease expiry mismatch")
×
2036
                                f.failFundingFlow(peer, cid, err)
×
2037
                                return
×
2038
                        }
×
2039
                }
2040
        } else if msg.ChannelType != nil {
28✔
2041
                // The spec isn't too clear about whether it's okay to set the
×
2042
                // channel type in the accept_channel response if we didn't
×
2043
                // explicitly set it in the open_channel message. For now, we
×
2044
                // check that it's the same type we'd have arrived through
×
2045
                // implicit negotiation. If it's another type, we fail the flow.
×
2046
                _, implicitCommitType := implicitNegotiateCommitmentType(
×
2047
                        peer.LocalFeatures(), peer.RemoteFeatures(),
×
2048
                )
×
2049

×
2050
                _, negotiatedCommitType, err := negotiateCommitmentType(
×
2051
                        msg.ChannelType, peer.LocalFeatures(),
×
2052
                        peer.RemoteFeatures(),
×
2053
                )
×
2054
                if err != nil {
×
2055
                        err := errors.New("received unexpected channel type")
×
2056
                        f.failFundingFlow(peer, cid, err)
×
2057
                        return
×
2058
                }
×
2059

2060
                if implicitCommitType != negotiatedCommitType {
×
2061
                        err := errors.New("negotiated unexpected channel type")
×
2062
                        f.failFundingFlow(peer, cid, err)
×
2063
                        return
×
2064
                }
×
2065
        }
2066

2067
        // The required number of confirmations should not be greater than the
2068
        // maximum number of confirmations required by the ChainNotifier to
2069
        // properly dispatch confirmations.
2070
        if msg.MinAcceptDepth > chainntnfs.MaxNumConfs {
36✔
2071
                err := lnwallet.ErrNumConfsTooLarge(
1✔
2072
                        msg.MinAcceptDepth, chainntnfs.MaxNumConfs,
1✔
2073
                )
1✔
2074
                log.Warnf("Unacceptable channel constraints: %v", err)
1✔
2075
                f.failFundingFlow(peer, cid, err)
1✔
2076
                return
1✔
2077
        }
1✔
2078

2079
        // Check that zero-conf channels have minimum depth set to 0.
2080
        if resCtx.reservation.IsZeroConf() && msg.MinAcceptDepth != 0 {
34✔
2081
                err = fmt.Errorf("zero-conf channel has min_depth non-zero")
×
2082
                log.Warn(err)
×
2083
                f.failFundingFlow(peer, cid, err)
×
2084
                return
×
2085
        }
×
2086

2087
        // If this is not a zero-conf channel but the peer responded with a
2088
        // min-depth of zero, we will use our minimum of 1 instead.
2089
        minDepth := msg.MinAcceptDepth
34✔
2090
        if !resCtx.reservation.IsZeroConf() && minDepth == 0 {
34✔
2091
                log.Infof("Responder to pending_id=%v sent a minimum "+
×
2092
                        "confirmation depth of 0 for non-zero-conf channel. "+
×
2093
                        "We will use a minimum depth of 1 instead.",
×
2094
                        cid.tempChanID)
×
2095

×
2096
                minDepth = 1
×
2097
        }
×
2098

2099
        // We'll also specify the responder's preference for the number of
2100
        // required confirmations, and also the set of channel constraints
2101
        // they've specified for commitment states we can create.
2102
        resCtx.reservation.SetNumConfsRequired(uint16(minDepth))
34✔
2103
        bounds := channeldb.ChannelStateBounds{
34✔
2104
                ChanReserve:      msg.ChannelReserve,
34✔
2105
                MaxPendingAmount: msg.MaxValueInFlight,
34✔
2106
                MinHTLC:          msg.HtlcMinimum,
34✔
2107
                MaxAcceptedHtlcs: msg.MaxAcceptedHTLCs,
34✔
2108
        }
34✔
2109
        commitParams := channeldb.CommitmentParams{
34✔
2110
                DustLimit: msg.DustLimit,
34✔
2111
                CsvDelay:  msg.CsvDelay,
34✔
2112
        }
34✔
2113
        err = resCtx.reservation.CommitConstraints(
34✔
2114
                &bounds, &commitParams, resCtx.maxLocalCsv, false,
34✔
2115
        )
34✔
2116
        if err != nil {
35✔
2117
                log.Warnf("Unacceptable channel constraints: %v", err)
1✔
2118
                f.failFundingFlow(peer, cid, err)
1✔
2119
                return
1✔
2120
        }
1✔
2121

2122
        cfg := channeldb.ChannelConfig{
33✔
2123
                ChannelStateBounds: channeldb.ChannelStateBounds{
33✔
2124
                        MaxPendingAmount: resCtx.remoteMaxValue,
33✔
2125
                        ChanReserve:      resCtx.remoteChanReserve,
33✔
2126
                        MinHTLC:          resCtx.remoteMinHtlc,
33✔
2127
                        MaxAcceptedHtlcs: resCtx.remoteMaxHtlcs,
33✔
2128
                },
33✔
2129
                CommitmentParams: channeldb.CommitmentParams{
33✔
2130
                        DustLimit: msg.DustLimit,
33✔
2131
                        CsvDelay:  resCtx.remoteCsvDelay,
33✔
2132
                },
33✔
2133
                MultiSigKey: keychain.KeyDescriptor{
33✔
2134
                        PubKey: copyPubKey(msg.FundingKey),
33✔
2135
                },
33✔
2136
                RevocationBasePoint: keychain.KeyDescriptor{
33✔
2137
                        PubKey: copyPubKey(msg.RevocationPoint),
33✔
2138
                },
33✔
2139
                PaymentBasePoint: keychain.KeyDescriptor{
33✔
2140
                        PubKey: copyPubKey(msg.PaymentPoint),
33✔
2141
                },
33✔
2142
                DelayBasePoint: keychain.KeyDescriptor{
33✔
2143
                        PubKey: copyPubKey(msg.DelayedPaymentPoint),
33✔
2144
                },
33✔
2145
                HtlcBasePoint: keychain.KeyDescriptor{
33✔
2146
                        PubKey: copyPubKey(msg.HtlcPoint),
33✔
2147
                },
33✔
2148
        }
33✔
2149

33✔
2150
        // The remote node has responded with their portion of the channel
33✔
2151
        // contribution. At this point, we can process their contribution which
33✔
2152
        // allows us to construct and sign both the commitment transaction, and
33✔
2153
        // the funding transaction.
33✔
2154
        remoteContribution := &lnwallet.ChannelContribution{
33✔
2155
                FirstCommitmentPoint: msg.FirstCommitmentPoint,
33✔
2156
                ChannelConfig:        &cfg,
33✔
2157
                UpfrontShutdown:      msg.UpfrontShutdownScript,
33✔
2158
        }
33✔
2159

33✔
2160
        if resCtx.reservation.IsTaproot() {
39✔
2161
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
6✔
2162
                if err != nil {
6✔
2163
                        log.Error(errNoLocalNonce)
×
2164

×
2165
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
2166

×
2167
                        return
×
2168
                }
×
2169

2170
                remoteContribution.LocalNonce = &musig2.Nonces{
6✔
2171
                        PubNonce: localNonce,
6✔
2172
                }
6✔
2173
        }
2174

2175
        err = resCtx.reservation.ProcessContribution(remoteContribution)
33✔
2176

33✔
2177
        // The wallet has detected that a PSBT funding process was requested by
33✔
2178
        // the user and has halted the funding process after negotiating the
33✔
2179
        // multisig keys. We now have everything that is needed for the user to
33✔
2180
        // start constructing a PSBT that sends to the multisig funding address.
33✔
2181
        var psbtIntent *chanfunding.PsbtIntent
33✔
2182
        if psbtErr, ok := err.(*lnwallet.PsbtFundingRequired); ok {
37✔
2183
                // Return the information that is needed by the user to
4✔
2184
                // construct the PSBT back to the caller.
4✔
2185
                addr, amt, packet, err := psbtErr.Intent.FundingParams()
4✔
2186
                if err != nil {
4✔
2187
                        log.Errorf("Unable to process PSBT funding params "+
×
2188
                                "for contribution from %x: %v", peerKeyBytes,
×
2189
                                err)
×
2190
                        f.failFundingFlow(peer, cid, err)
×
2191
                        return
×
2192
                }
×
2193
                var buf bytes.Buffer
4✔
2194
                err = packet.Serialize(&buf)
4✔
2195
                if err != nil {
4✔
2196
                        log.Errorf("Unable to serialize PSBT for "+
×
2197
                                "contribution from %x: %v", peerKeyBytes, err)
×
2198
                        f.failFundingFlow(peer, cid, err)
×
2199
                        return
×
2200
                }
×
2201
                resCtx.updates <- &lnrpc.OpenStatusUpdate{
4✔
2202
                        PendingChanId: pendingChanID[:],
4✔
2203
                        Update: &lnrpc.OpenStatusUpdate_PsbtFund{
4✔
2204
                                PsbtFund: &lnrpc.ReadyForPsbtFunding{
4✔
2205
                                        FundingAddress: addr.EncodeAddress(),
4✔
2206
                                        FundingAmount:  amt,
4✔
2207
                                        Psbt:           buf.Bytes(),
4✔
2208
                                },
4✔
2209
                        },
4✔
2210
                }
4✔
2211
                psbtIntent = psbtErr.Intent
4✔
2212
        } else if err != nil {
33✔
2213
                log.Errorf("Unable to process contribution from %x: %v",
×
2214
                        peerKeyBytes, err)
×
2215
                f.failFundingFlow(peer, cid, err)
×
2216
                return
×
2217
        }
×
2218

2219
        log.Infof("pendingChan(%x): remote party proposes num_confs=%v, "+
33✔
2220
                "csv_delay=%v", pendingChanID[:], msg.MinAcceptDepth,
33✔
2221
                msg.CsvDelay)
33✔
2222
        bounds = remoteContribution.ChannelConfig.ChannelStateBounds
33✔
2223
        log.Debugf("Remote party accepted channel state space bounds: %v",
33✔
2224
                lnutils.SpewLogClosure(bounds))
33✔
2225
        commitParams = remoteContribution.ChannelConfig.CommitmentParams
33✔
2226
        log.Debugf("Remote party accepted commitment rendering params: %v",
33✔
2227
                lnutils.SpewLogClosure(commitParams))
33✔
2228

33✔
2229
        // If the user requested funding through a PSBT, we cannot directly
33✔
2230
        // continue now and need to wait for the fully funded and signed PSBT
33✔
2231
        // to arrive. To not block any other channels from opening, we wait in
33✔
2232
        // a separate goroutine.
33✔
2233
        if psbtIntent != nil {
37✔
2234
                f.wg.Add(1)
4✔
2235
                go func() {
8✔
2236
                        defer f.wg.Done()
4✔
2237

4✔
2238
                        f.waitForPsbt(psbtIntent, resCtx, cid)
4✔
2239
                }()
4✔
2240

2241
                // With the new goroutine spawned, we can now exit to unblock
2242
                // the main event loop.
2243
                return
4✔
2244
        }
2245

2246
        // In a normal, non-PSBT funding flow, we can jump directly to the next
2247
        // step where we expect our contribution to be finalized.
2248
        f.continueFundingAccept(resCtx, cid)
33✔
2249
}
2250

2251
// waitForPsbt blocks until either a signed PSBT arrives, an error occurs or
2252
// the funding manager shuts down. In the case of a valid PSBT, the funding flow
2253
// is continued.
2254
//
2255
// NOTE: This method must be called as a goroutine.
2256
func (f *Manager) waitForPsbt(intent *chanfunding.PsbtIntent,
2257
        resCtx *reservationWithCtx, cid *chanIdentifier) {
4✔
2258

4✔
2259
        // failFlow is a helper that logs an error message with the current
4✔
2260
        // context and then fails the funding flow.
4✔
2261
        peerKey := resCtx.peer.IdentityKey()
4✔
2262
        failFlow := func(errMsg string, cause error) {
8✔
2263
                log.Errorf("Unable to handle funding accept message "+
4✔
2264
                        "for peer_key=%x, pending_chan_id=%x: %s: %v",
4✔
2265
                        peerKey.SerializeCompressed(), cid.tempChanID, errMsg,
4✔
2266
                        cause)
4✔
2267
                f.failFundingFlow(resCtx.peer, cid, cause)
4✔
2268
        }
4✔
2269

2270
        // We'll now wait until the intent has received the final and complete
2271
        // funding transaction. If the channel is closed without any error being
2272
        // sent, we know everything's going as expected.
2273
        select {
4✔
2274
        case err := <-intent.PsbtReady:
4✔
2275
                switch err {
4✔
2276
                // If the user canceled the funding reservation, we need to
2277
                // inform the other peer about us canceling the reservation.
2278
                case chanfunding.ErrUserCanceled:
4✔
2279
                        failFlow("aborting PSBT flow", err)
4✔
2280
                        return
4✔
2281

2282
                // If the remote canceled the funding reservation, we don't need
2283
                // to send another fail message. But we want to inform the user
2284
                // about what happened.
2285
                case chanfunding.ErrRemoteCanceled:
4✔
2286
                        log.Infof("Remote canceled, aborting PSBT flow "+
4✔
2287
                                "for peer_key=%x, pending_chan_id=%x",
4✔
2288
                                peerKey.SerializeCompressed(), cid.tempChanID)
4✔
2289
                        return
4✔
2290

2291
                // Nil error means the flow continues normally now.
2292
                case nil:
4✔
2293

2294
                // For any other error, we'll fail the funding flow.
2295
                default:
×
2296
                        failFlow("error waiting for PSBT flow", err)
×
2297
                        return
×
2298
                }
2299

2300
                // At this point, we'll see if there's an AuxFundingDesc we
2301
                // need to deliver so the funding process can continue
2302
                // properly.
2303
                auxFundingDesc, err := fn.MapOptionZ(
4✔
2304
                        f.cfg.AuxFundingController,
4✔
2305
                        func(c AuxFundingController) AuxFundingDescResult {
4✔
2306
                                return c.DescFromPendingChanID(
×
2307
                                        cid.tempChanID,
×
2308
                                        lnwallet.NewAuxChanState(
×
2309
                                                resCtx.reservation.ChanState(),
×
2310
                                        ),
×
2311
                                        resCtx.reservation.CommitmentKeyRings(),
×
2312
                                        true,
×
2313
                                )
×
2314
                        },
×
2315
                ).Unpack()
2316
                if err != nil {
4✔
2317
                        failFlow("error continuing PSBT flow", err)
×
2318
                        return
×
2319
                }
×
2320

2321
                // A non-nil error means we can continue the funding flow.
2322
                // Notify the wallet so it can prepare everything we need to
2323
                // continue.
2324
                //
2325
                // We'll also pass along the aux funding controller as well,
2326
                // which may be used to help process the finalized PSBT.
2327
                err = resCtx.reservation.ProcessPsbt(auxFundingDesc)
4✔
2328
                if err != nil {
4✔
2329
                        failFlow("error continuing PSBT flow", err)
×
2330
                        return
×
2331
                }
×
2332

2333
                // We are now ready to continue the funding flow.
2334
                f.continueFundingAccept(resCtx, cid)
4✔
2335

2336
        // Handle a server shutdown as well because the reservation won't
2337
        // survive a restart as it's in memory only.
2338
        case <-f.quit:
×
2339
                log.Errorf("Unable to handle funding accept message "+
×
2340
                        "for peer_key=%x, pending_chan_id=%x: funding manager "+
×
2341
                        "shutting down", peerKey.SerializeCompressed(),
×
2342
                        cid.tempChanID)
×
2343
                return
×
2344
        }
2345
}
2346

2347
// continueFundingAccept continues the channel funding flow once our
2348
// contribution is finalized, the channel output is known and the funding
2349
// transaction is signed.
2350
func (f *Manager) continueFundingAccept(resCtx *reservationWithCtx,
2351
        cid *chanIdentifier) {
33✔
2352

33✔
2353
        // Now that we have their contribution, we can extract, then send over
33✔
2354
        // both the funding out point and our signature for their version of
33✔
2355
        // the commitment transaction to the remote peer.
33✔
2356
        outPoint := resCtx.reservation.FundingOutpoint()
33✔
2357
        _, sig := resCtx.reservation.OurSignatures()
33✔
2358

33✔
2359
        // A new channel has almost finished the funding process. In order to
33✔
2360
        // properly synchronize with the writeHandler goroutine, we add a new
33✔
2361
        // channel to the barriers map which will be closed once the channel is
33✔
2362
        // fully open.
33✔
2363
        channelID := lnwire.NewChanIDFromOutPoint(*outPoint)
33✔
2364
        log.Debugf("Creating chan barrier for ChanID(%v)", channelID)
33✔
2365

33✔
2366
        // The next message that advances the funding flow will reference the
33✔
2367
        // channel via its permanent channel ID, so we'll set up this mapping
33✔
2368
        // so we can retrieve the reservation context once we get the
33✔
2369
        // FundingSigned message.
33✔
2370
        f.resMtx.Lock()
33✔
2371
        f.signedReservations[channelID] = cid.tempChanID
33✔
2372
        f.resMtx.Unlock()
33✔
2373

33✔
2374
        log.Infof("Generated ChannelPoint(%v) for pending_id(%x)", outPoint,
33✔
2375
                cid.tempChanID[:])
33✔
2376

33✔
2377
        // Before sending FundingCreated sent, we notify Brontide to keep track
33✔
2378
        // of this pending open channel.
33✔
2379
        err := resCtx.peer.AddPendingChannel(channelID, f.quit)
33✔
2380
        if err != nil {
33✔
2381
                pubKey := resCtx.peer.IdentityKey().SerializeCompressed()
×
2382
                log.Errorf("Unable to add pending channel %v with peer %x: %v",
×
2383
                        channelID, pubKey, err)
×
2384
        }
×
2385

2386
        // Once Brontide is aware of this channel, we need to set it in
2387
        // chanIdentifier so this channel will be removed from Brontide if the
2388
        // funding flow fails.
2389
        cid.setChanID(channelID)
33✔
2390

33✔
2391
        // Send the FundingCreated msg.
33✔
2392
        fundingCreated := &lnwire.FundingCreated{
33✔
2393
                PendingChannelID: cid.tempChanID,
33✔
2394
                FundingPoint:     *outPoint,
33✔
2395
        }
33✔
2396

33✔
2397
        // If this is a taproot channel, then we'll need to populate the musig2
33✔
2398
        // partial sig field instead of the regular commit sig field.
33✔
2399
        if resCtx.reservation.IsTaproot() {
39✔
2400
                partialSig, ok := sig.(*lnwallet.MusigPartialSig)
6✔
2401
                if !ok {
6✔
2402
                        err := fmt.Errorf("expected musig partial sig, got %T",
×
2403
                                sig)
×
2404
                        log.Error(err)
×
2405
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2406

×
2407
                        return
×
2408
                }
×
2409

2410
                fundingCreated.PartialSig = lnwire.MaybePartialSigWithNonce(
6✔
2411
                        partialSig.ToWireSig(),
6✔
2412
                )
6✔
2413
        } else {
31✔
2414
                fundingCreated.CommitSig, err = lnwire.NewSigFromSignature(sig)
31✔
2415
                if err != nil {
31✔
2416
                        log.Errorf("Unable to parse signature: %v", err)
×
2417
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2418
                        return
×
2419
                }
×
2420
        }
2421

2422
        resCtx.reservation.SetState(lnwallet.SentFundingCreated)
33✔
2423

33✔
2424
        if err := resCtx.peer.SendMessage(true, fundingCreated); err != nil {
33✔
2425
                log.Errorf("Unable to send funding complete message: %v", err)
×
2426
                f.failFundingFlow(resCtx.peer, cid, err)
×
2427
                return
×
2428
        }
×
2429
}
2430

2431
// fundeeProcessFundingCreated progresses the funding workflow when the daemon
2432
// is on the responding side of a single funder workflow. Once this message has
2433
// been processed, a signature is sent to the remote peer allowing it to
2434
// broadcast the funding transaction, progressing the workflow into the final
2435
// stage.
2436
//
2437
//nolint:funlen
2438
func (f *Manager) fundeeProcessFundingCreated(peer lnpeer.Peer,
2439
        msg *lnwire.FundingCreated) {
31✔
2440

31✔
2441
        peerKey := peer.IdentityKey()
31✔
2442
        pendingChanID := msg.PendingChannelID
31✔
2443

31✔
2444
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
31✔
2445
        if err != nil {
31✔
2446
                log.Warnf("can't find reservation (peer_id:%v, chan_id:%x)",
×
2447
                        peerKey, pendingChanID[:])
×
2448
                return
×
2449
        }
×
2450

2451
        // The channel initiator has responded with the funding outpoint of the
2452
        // final funding transaction, as well as a signature for our version of
2453
        // the commitment transaction. So at this point, we can validate the
2454
        // initiator's commitment transaction, then send our own if it's valid.
2455
        fundingOut := msg.FundingPoint
31✔
2456
        log.Infof("completing pending_id(%x) with ChannelPoint(%v)",
31✔
2457
                pendingChanID[:], fundingOut)
31✔
2458

31✔
2459
        if resCtx.reservation.State() != lnwallet.SentAcceptChannel {
31✔
2460
                return
×
2461
        }
×
2462

2463
        // Create the channel identifier without setting the active channel ID.
2464
        cid := newChanIdentifier(pendingChanID)
31✔
2465

31✔
2466
        // For taproot channels, the commit signature is actually the partial
31✔
2467
        // signature. Otherwise, we can convert the ECDSA commit signature into
31✔
2468
        // our internal input.Signature type.
31✔
2469
        var commitSig input.Signature
31✔
2470
        if resCtx.reservation.IsTaproot() {
37✔
2471
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
6✔
2472
                if err != nil {
6✔
2473
                        f.failFundingFlow(peer, cid, err)
×
2474

×
2475
                        return
×
2476
                }
×
2477

2478
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
6✔
2479
                        &partialSig,
6✔
2480
                )
6✔
2481
        } else {
29✔
2482
                commitSig, err = msg.CommitSig.ToSignature()
29✔
2483
                if err != nil {
29✔
2484
                        log.Errorf("unable to parse signature: %v", err)
×
2485
                        f.failFundingFlow(peer, cid, err)
×
2486
                        return
×
2487
                }
×
2488
        }
2489

2490
        // At this point, we'll see if there's an AuxFundingDesc we need to
2491
        // deliver so the funding process can continue properly.
2492
        auxFundingDesc, err := fn.MapOptionZ(
31✔
2493
                f.cfg.AuxFundingController,
31✔
2494
                func(c AuxFundingController) AuxFundingDescResult {
31✔
2495
                        return c.DescFromPendingChanID(
×
2496
                                cid.tempChanID, lnwallet.NewAuxChanState(
×
2497
                                        resCtx.reservation.ChanState(),
×
2498
                                ), resCtx.reservation.CommitmentKeyRings(),
×
2499
                                true,
×
2500
                        )
×
2501
                },
×
2502
        ).Unpack()
2503
        if err != nil {
31✔
2504
                log.Errorf("error continuing PSBT flow: %v", err)
×
2505
                f.failFundingFlow(peer, cid, err)
×
2506
                return
×
2507
        }
×
2508

2509
        // With all the necessary data available, attempt to advance the
2510
        // funding workflow to the next stage. If this succeeds then the
2511
        // funding transaction will broadcast after our next message.
2512
        // CompleteReservationSingle will also mark the channel as 'IsPending'
2513
        // in the database.
2514
        //
2515
        // We'll also directly pass in the AuxFunding controller as well,
2516
        // which may be used by the reservation system to finalize funding our
2517
        // side.
2518
        completeChan, err := resCtx.reservation.CompleteReservationSingle(
31✔
2519
                &fundingOut, commitSig, auxFundingDesc,
31✔
2520
        )
31✔
2521
        if err != nil {
31✔
2522
                log.Errorf("unable to complete single reservation: %v", err)
×
2523
                f.failFundingFlow(peer, cid, err)
×
2524
                return
×
2525
        }
×
2526

2527
        // Get forwarding policy before deleting the reservation context.
2528
        forwardingPolicy := resCtx.forwardingPolicy
31✔
2529

31✔
2530
        // The channel is marked IsPending in the database, and can be removed
31✔
2531
        // from the set of active reservations.
31✔
2532
        f.deleteReservationCtx(peerKey, cid.tempChanID)
31✔
2533

31✔
2534
        // If something goes wrong before the funding transaction is confirmed,
31✔
2535
        // we use this convenience method to delete the pending OpenChannel
31✔
2536
        // from the database.
31✔
2537
        deleteFromDatabase := func() {
31✔
2538
                localBalance := completeChan.LocalCommitment.LocalBalance.ToSatoshis()
×
2539
                closeInfo := &channeldb.ChannelCloseSummary{
×
2540
                        ChanPoint:               completeChan.FundingOutpoint,
×
2541
                        ChainHash:               completeChan.ChainHash,
×
2542
                        RemotePub:               completeChan.IdentityPub,
×
2543
                        CloseType:               channeldb.FundingCanceled,
×
2544
                        Capacity:                completeChan.Capacity,
×
2545
                        SettledBalance:          localBalance,
×
2546
                        RemoteCurrentRevocation: completeChan.RemoteCurrentRevocation,
×
2547
                        RemoteNextRevocation:    completeChan.RemoteNextRevocation,
×
2548
                        LocalChanConfig:         completeChan.LocalChanCfg,
×
2549
                }
×
2550

×
2551
                // Close the channel with us as the initiator because we are
×
2552
                // deciding to exit the funding flow due to an internal error.
×
2553
                if err := completeChan.CloseChannel(
×
2554
                        closeInfo, channeldb.ChanStatusLocalCloseInitiator,
×
2555
                ); err != nil {
×
2556
                        log.Errorf("Failed closing channel %v: %v",
×
2557
                                completeChan.FundingOutpoint, err)
×
2558
                }
×
2559
        }
2560

2561
        // A new channel has almost finished the funding process. In order to
2562
        // properly synchronize with the writeHandler goroutine, we add a new
2563
        // channel to the barriers map which will be closed once the channel is
2564
        // fully open.
2565
        channelID := lnwire.NewChanIDFromOutPoint(fundingOut)
31✔
2566
        log.Debugf("Creating chan barrier for ChanID(%v)", channelID)
31✔
2567

31✔
2568
        fundingSigned := &lnwire.FundingSigned{}
31✔
2569

31✔
2570
        // For taproot channels, we'll need to send over a partial signature
31✔
2571
        // that includes the nonce along side the signature.
31✔
2572
        _, sig := resCtx.reservation.OurSignatures()
31✔
2573
        if resCtx.reservation.IsTaproot() {
37✔
2574
                partialSig, ok := sig.(*lnwallet.MusigPartialSig)
6✔
2575
                if !ok {
6✔
2576
                        err := fmt.Errorf("expected musig partial sig, got %T",
×
2577
                                sig)
×
2578
                        log.Error(err)
×
2579
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2580
                        deleteFromDatabase()
×
2581

×
2582
                        return
×
2583
                }
×
2584

2585
                fundingSigned.PartialSig = lnwire.MaybePartialSigWithNonce(
6✔
2586
                        partialSig.ToWireSig(),
6✔
2587
                )
6✔
2588
        } else {
29✔
2589
                fundingSigned.CommitSig, err = lnwire.NewSigFromSignature(sig)
29✔
2590
                if err != nil {
29✔
2591
                        log.Errorf("unable to parse signature: %v", err)
×
2592
                        f.failFundingFlow(peer, cid, err)
×
2593
                        deleteFromDatabase()
×
2594

×
2595
                        return
×
2596
                }
×
2597
        }
2598

2599
        // Before sending FundingSigned, we notify Brontide first to keep track
2600
        // of this pending open channel.
2601
        if err := peer.AddPendingChannel(channelID, f.quit); err != nil {
31✔
2602
                pubKey := peer.IdentityKey().SerializeCompressed()
×
2603
                log.Errorf("Unable to add pending channel %v with peer %x: %v",
×
2604
                        cid.chanID, pubKey, err)
×
2605
        }
×
2606

2607
        // Once Brontide is aware of this channel, we need to set it in
2608
        // chanIdentifier so this channel will be removed from Brontide if the
2609
        // funding flow fails.
2610
        cid.setChanID(channelID)
31✔
2611

31✔
2612
        fundingSigned.ChanID = cid.chanID
31✔
2613

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

31✔
2617
        // With their signature for our version of the commitment transaction
31✔
2618
        // verified, we can now send over our signature to the remote peer.
31✔
2619
        if err := peer.SendMessage(true, fundingSigned); err != nil {
31✔
2620
                log.Errorf("unable to send FundingSigned message: %v", err)
×
2621
                f.failFundingFlow(peer, cid, err)
×
2622
                deleteFromDatabase()
×
2623
                return
×
2624
        }
×
2625

2626
        // With a permanent channel id established we can save the respective
2627
        // forwarding policy in the database. In the channel announcement phase
2628
        // this forwarding policy is retrieved and applied.
2629
        err = f.saveInitialForwardingPolicy(cid.chanID, &forwardingPolicy)
31✔
2630
        if err != nil {
31✔
2631
                log.Errorf("Unable to store the forwarding policy: %v", err)
×
2632
        }
×
2633

2634
        // Now that we've sent over our final signature for this channel, we'll
2635
        // send it to the ChainArbitrator so it can watch for any on-chain
2636
        // actions during this final confirmation stage.
2637
        if err := f.cfg.WatchNewChannel(completeChan, peerKey); err != nil {
31✔
2638
                log.Errorf("Unable to send new ChannelPoint(%v) for "+
×
2639
                        "arbitration: %v", fundingOut, err)
×
2640
        }
×
2641

2642
        // Create an entry in the local discovery map so we can ensure that we
2643
        // process the channel confirmation fully before we receive a
2644
        // channel_ready message.
2645
        f.localDiscoverySignals.Store(cid.chanID, make(chan struct{}))
31✔
2646

31✔
2647
        // Inform the ChannelNotifier that the channel has entered
31✔
2648
        // pending open state.
31✔
2649
        f.cfg.NotifyPendingOpenChannelEvent(fundingOut, completeChan)
31✔
2650

31✔
2651
        // At this point we have sent our last funding message to the
31✔
2652
        // initiating peer before the funding transaction will be broadcast.
31✔
2653
        // With this last message, our job as the responder is now complete.
31✔
2654
        // We'll wait for the funding transaction to reach the specified number
31✔
2655
        // of confirmations, then start normal operations.
31✔
2656
        //
31✔
2657
        // When we get to this point we have sent the signComplete message to
31✔
2658
        // the channel funder, and BOLT#2 specifies that we MUST remember the
31✔
2659
        // channel for reconnection. The channel is already marked
31✔
2660
        // as pending in the database, so in case of a disconnect or restart,
31✔
2661
        // we will continue waiting for the confirmation the next time we start
31✔
2662
        // the funding manager. In case the funding transaction never appears
31✔
2663
        // on the blockchain, we must forget this channel. We therefore
31✔
2664
        // completely forget about this channel if we haven't seen the funding
31✔
2665
        // transaction in 288 blocks (~ 48 hrs), by canceling the reservation
31✔
2666
        // and canceling the wait for the funding confirmation.
31✔
2667
        f.wg.Add(1)
31✔
2668
        go f.advanceFundingState(completeChan, pendingChanID, nil)
31✔
2669
}
2670

2671
// funderProcessFundingSigned processes the final message received in a single
2672
// funder workflow. Once this message is processed, the funding transaction is
2673
// broadcast. Once the funding transaction reaches a sufficient number of
2674
// confirmations, a message is sent to the responding peer along with a compact
2675
// encoding of the location of the channel within the blockchain.
2676
func (f *Manager) funderProcessFundingSigned(peer lnpeer.Peer,
2677
        msg *lnwire.FundingSigned) {
31✔
2678

31✔
2679
        // As the funding signed message will reference the reservation by its
31✔
2680
        // permanent channel ID, we'll need to perform an intermediate look up
31✔
2681
        // before we can obtain the reservation.
31✔
2682
        f.resMtx.Lock()
31✔
2683
        pendingChanID, ok := f.signedReservations[msg.ChanID]
31✔
2684
        delete(f.signedReservations, msg.ChanID)
31✔
2685
        f.resMtx.Unlock()
31✔
2686

31✔
2687
        // Create the channel identifier and set the channel ID.
31✔
2688
        //
31✔
2689
        // NOTE: we may get an empty pending channel ID here if the key cannot
31✔
2690
        // be found, which means when we cancel the reservation context in
31✔
2691
        // `failFundingFlow`, we will get an error. In this case, we will send
31✔
2692
        // an error msg to our peer using the active channel ID.
31✔
2693
        //
31✔
2694
        // TODO(yy): refactor the funding flow to fix this case.
31✔
2695
        cid := newChanIdentifier(pendingChanID)
31✔
2696
        cid.setChanID(msg.ChanID)
31✔
2697

31✔
2698
        // If the pending channel ID is not found, fail the funding flow.
31✔
2699
        if !ok {
31✔
2700
                // NOTE: we directly overwrite the pending channel ID here for
×
2701
                // this rare case since we don't have a valid pending channel
×
2702
                // ID.
×
2703
                cid.tempChanID = msg.ChanID
×
2704

×
2705
                err := fmt.Errorf("unable to find signed reservation for "+
×
2706
                        "chan_id=%x", msg.ChanID)
×
2707
                log.Warnf(err.Error())
×
2708
                f.failFundingFlow(peer, cid, err)
×
2709
                return
×
2710
        }
×
2711

2712
        peerKey := peer.IdentityKey()
31✔
2713
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
31✔
2714
        if err != nil {
31✔
2715
                log.Warnf("Unable to find reservation (peer_id:%v, "+
×
2716
                        "chan_id:%x)", peerKey, pendingChanID[:])
×
2717
                // TODO: add ErrChanNotFound?
×
2718
                f.failFundingFlow(peer, cid, err)
×
2719
                return
×
2720
        }
×
2721

2722
        if resCtx.reservation.State() != lnwallet.SentFundingCreated {
31✔
2723
                err := fmt.Errorf("unable to find reservation for chan_id=%x",
×
2724
                        msg.ChanID)
×
2725
                f.failFundingFlow(peer, cid, err)
×
2726

×
2727
                return
×
2728
        }
×
2729

2730
        // Create an entry in the local discovery map so we can ensure that we
2731
        // process the channel confirmation fully before we receive a
2732
        // channel_ready message.
2733
        fundingPoint := resCtx.reservation.FundingOutpoint()
31✔
2734
        permChanID := lnwire.NewChanIDFromOutPoint(*fundingPoint)
31✔
2735
        f.localDiscoverySignals.Store(permChanID, make(chan struct{}))
31✔
2736

31✔
2737
        // We have to store the forwardingPolicy before the reservation context
31✔
2738
        // is deleted. The policy will then be read and applied in
31✔
2739
        // newChanAnnouncement.
31✔
2740
        err = f.saveInitialForwardingPolicy(
31✔
2741
                permChanID, &resCtx.forwardingPolicy,
31✔
2742
        )
31✔
2743
        if err != nil {
31✔
2744
                log.Errorf("Unable to store the forwarding policy: %v", err)
×
2745
        }
×
2746

2747
        // For taproot channels, the commit signature is actually the partial
2748
        // signature. Otherwise, we can convert the ECDSA commit signature into
2749
        // our internal input.Signature type.
2750
        var commitSig input.Signature
31✔
2751
        if resCtx.reservation.IsTaproot() {
37✔
2752
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
6✔
2753
                if err != nil {
6✔
2754
                        f.failFundingFlow(peer, cid, err)
×
2755

×
2756
                        return
×
2757
                }
×
2758

2759
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
6✔
2760
                        &partialSig,
6✔
2761
                )
6✔
2762
        } else {
29✔
2763
                commitSig, err = msg.CommitSig.ToSignature()
29✔
2764
                if err != nil {
29✔
2765
                        log.Errorf("unable to parse signature: %v", err)
×
2766
                        f.failFundingFlow(peer, cid, err)
×
2767
                        return
×
2768
                }
×
2769
        }
2770

2771
        completeChan, err := resCtx.reservation.CompleteReservation(
31✔
2772
                nil, commitSig,
31✔
2773
        )
31✔
2774
        if err != nil {
31✔
2775
                log.Errorf("Unable to complete reservation sign "+
×
2776
                        "complete: %v", err)
×
2777
                f.failFundingFlow(peer, cid, err)
×
2778
                return
×
2779
        }
×
2780

2781
        // The channel is now marked IsPending in the database, and we can
2782
        // delete it from our set of active reservations.
2783
        f.deleteReservationCtx(peerKey, pendingChanID)
31✔
2784

31✔
2785
        // Broadcast the finalized funding transaction to the network, but only
31✔
2786
        // if we actually have the funding transaction.
31✔
2787
        if completeChan.ChanType.HasFundingTx() {
61✔
2788
                fundingTx := completeChan.FundingTxn
30✔
2789
                var fundingTxBuf bytes.Buffer
30✔
2790
                if err := fundingTx.Serialize(&fundingTxBuf); err != nil {
30✔
2791
                        log.Errorf("Unable to serialize funding "+
×
2792
                                "transaction %v: %v", fundingTx.TxHash(), err)
×
2793

×
2794
                        // Clear the buffer of any bytes that were written
×
2795
                        // before the serialization error to prevent logging an
×
2796
                        // incomplete transaction.
×
2797
                        fundingTxBuf.Reset()
×
2798
                }
×
2799

2800
                log.Infof("Broadcasting funding tx for ChannelPoint(%v): %x",
30✔
2801
                        completeChan.FundingOutpoint, fundingTxBuf.Bytes())
30✔
2802

30✔
2803
                // Set a nil short channel ID at this stage because we do not
30✔
2804
                // know it until our funding tx confirms.
30✔
2805
                label := labels.MakeLabel(
30✔
2806
                        labels.LabelTypeChannelOpen, nil,
30✔
2807
                )
30✔
2808

30✔
2809
                err = f.cfg.PublishTransaction(fundingTx, label)
30✔
2810
                if err != nil {
30✔
2811
                        log.Errorf("Unable to broadcast funding tx %x for "+
×
2812
                                "ChannelPoint(%v): %v", fundingTxBuf.Bytes(),
×
2813
                                completeChan.FundingOutpoint, err)
×
2814

×
2815
                        // We failed to broadcast the funding transaction, but
×
2816
                        // watch the channel regardless, in case the
×
2817
                        // transaction made it to the network. We will retry
×
2818
                        // broadcast at startup.
×
2819
                        //
×
2820
                        // TODO(halseth): retry more often? Handle with CPFP?
×
2821
                        // Just delete from the DB?
×
2822
                }
×
2823
        }
2824

2825
        // Before we proceed, if we have a funding hook that wants a
2826
        // notification that it's safe to broadcast the funding transaction,
2827
        // then we'll send that now.
2828
        err = fn.MapOptionZ(
31✔
2829
                f.cfg.AuxFundingController,
31✔
2830
                func(controller AuxFundingController) error {
31✔
2831
                        return controller.ChannelFinalized(cid.tempChanID)
×
2832
                },
×
2833
        )
2834
        if err != nil {
31✔
2835
                log.Errorf("Failed to inform aux funding controller about "+
×
2836
                        "ChannelPoint(%v) being finalized: %v", fundingPoint,
×
2837
                        err)
×
2838
        }
×
2839

2840
        // Now that we have a finalized reservation for this funding flow,
2841
        // we'll send the to be active channel to the ChainArbitrator so it can
2842
        // watch for any on-chain actions before the channel has fully
2843
        // confirmed.
2844
        if err := f.cfg.WatchNewChannel(completeChan, peerKey); err != nil {
31✔
2845
                log.Errorf("Unable to send new ChannelPoint(%v) for "+
×
2846
                        "arbitration: %v", fundingPoint, err)
×
2847
        }
×
2848

2849
        log.Infof("Finalizing pending_id(%x) over ChannelPoint(%v), "+
31✔
2850
                "waiting for channel open on-chain", pendingChanID[:],
31✔
2851
                fundingPoint)
31✔
2852

31✔
2853
        // Send an update to the upstream client that the negotiation process
31✔
2854
        // is over.
31✔
2855
        upd := &lnrpc.OpenStatusUpdate{
31✔
2856
                Update: &lnrpc.OpenStatusUpdate_ChanPending{
31✔
2857
                        ChanPending: &lnrpc.PendingUpdate{
31✔
2858
                                Txid:        fundingPoint.Hash[:],
31✔
2859
                                OutputIndex: fundingPoint.Index,
31✔
2860
                        },
31✔
2861
                },
31✔
2862
                PendingChanId: pendingChanID[:],
31✔
2863
        }
31✔
2864

31✔
2865
        select {
31✔
2866
        case resCtx.updates <- upd:
31✔
2867
                // Inform the ChannelNotifier that the channel has entered
31✔
2868
                // pending open state.
31✔
2869
                f.cfg.NotifyPendingOpenChannelEvent(*fundingPoint, completeChan)
31✔
2870
        case <-f.quit:
×
2871
                return
×
2872
        }
2873

2874
        // At this point we have broadcast the funding transaction and done all
2875
        // necessary processing.
2876
        f.wg.Add(1)
31✔
2877
        go f.advanceFundingState(completeChan, pendingChanID, resCtx.updates)
31✔
2878
}
2879

2880
// confirmedChannel wraps a confirmed funding transaction, as well as the short
2881
// channel ID which identifies that channel into a single struct. We'll use
2882
// this to pass around the final state of a channel after it has been
2883
// confirmed.
2884
type confirmedChannel struct {
2885
        // shortChanID expresses where in the block the funding transaction was
2886
        // located.
2887
        shortChanID lnwire.ShortChannelID
2888

2889
        // fundingTx is the funding transaction that created the channel.
2890
        fundingTx *wire.MsgTx
2891
}
2892

2893
// fundingTimeout is called when callers of waitForFundingWithTimeout receive
2894
// an ErrConfirmationTimeout. It is used to clean-up channel state and mark the
2895
// channel as closed. The error is only returned for the responder of the
2896
// channel flow.
2897
func (f *Manager) fundingTimeout(c *channeldb.OpenChannel,
2898
        pendingID PendingChanID) error {
2✔
2899

2✔
2900
        // We'll get a timeout if the number of blocks mined since the channel
2✔
2901
        // was initiated reaches MaxWaitNumBlocksFundingConf and we are not the
2✔
2902
        // channel initiator.
2✔
2903
        localBalance := c.LocalCommitment.LocalBalance.ToSatoshis()
2✔
2904
        closeInfo := &channeldb.ChannelCloseSummary{
2✔
2905
                ChainHash:               c.ChainHash,
2✔
2906
                ChanPoint:               c.FundingOutpoint,
2✔
2907
                RemotePub:               c.IdentityPub,
2✔
2908
                Capacity:                c.Capacity,
2✔
2909
                SettledBalance:          localBalance,
2✔
2910
                CloseType:               channeldb.FundingCanceled,
2✔
2911
                RemoteCurrentRevocation: c.RemoteCurrentRevocation,
2✔
2912
                RemoteNextRevocation:    c.RemoteNextRevocation,
2✔
2913
                LocalChanConfig:         c.LocalChanCfg,
2✔
2914
        }
2✔
2915

2✔
2916
        // Close the channel with us as the initiator because we are timing the
2✔
2917
        // channel out.
2✔
2918
        if err := c.CloseChannel(
2✔
2919
                closeInfo, channeldb.ChanStatusLocalCloseInitiator,
2✔
2920
        ); err != nil {
2✔
2921
                return fmt.Errorf("failed closing channel %v: %w",
×
2922
                        c.FundingOutpoint, err)
×
2923
        }
×
2924

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

2✔
2928
        // When the peer comes online, we'll notify it that we are now
2✔
2929
        // considering the channel flow canceled.
2✔
2930
        f.wg.Add(1)
2✔
2931
        go func() {
4✔
2932
                defer f.wg.Done()
2✔
2933

2✔
2934
                peer, err := f.waitForPeerOnline(c.IdentityPub)
2✔
2935
                switch err {
2✔
2936
                // We're already shutting down, so we can just return.
2937
                case ErrFundingManagerShuttingDown:
×
2938
                        return
×
2939

2940
                // nil error means we continue on.
2941
                case nil:
2✔
2942

2943
                // For unexpected errors, we print the error and still try to
2944
                // fail the funding flow.
2945
                default:
×
2946
                        log.Errorf("Unexpected error while waiting for peer "+
×
2947
                                "to come online: %v", err)
×
2948
                }
2949

2950
                // Create channel identifier and set the channel ID.
2951
                cid := newChanIdentifier(pendingID)
2✔
2952
                cid.setChanID(lnwire.NewChanIDFromOutPoint(c.FundingOutpoint))
2✔
2953

2✔
2954
                // TODO(halseth): should this send be made
2✔
2955
                // reliable?
2✔
2956

2✔
2957
                // The reservation won't exist at this point, but we'll send an
2✔
2958
                // Error message over anyways with ChanID set to pendingID.
2✔
2959
                f.failFundingFlow(peer, cid, timeoutErr)
2✔
2960
        }()
2961

2962
        return timeoutErr
2✔
2963
}
2964

2965
// waitForFundingWithTimeout is a wrapper around waitForFundingConfirmation and
2966
// waitForTimeout that will return ErrConfirmationTimeout if we are not the
2967
// channel initiator and the MaxWaitNumBlocksFundingConf has passed from the
2968
// funding broadcast height. In case of confirmation, the short channel ID of
2969
// the channel and the funding transaction will be returned.
2970
func (f *Manager) waitForFundingWithTimeout(
2971
        ch *channeldb.OpenChannel) (*confirmedChannel, error) {
61✔
2972

61✔
2973
        confChan := make(chan *confirmedChannel)
61✔
2974
        timeoutChan := make(chan error, 1)
61✔
2975
        cancelChan := make(chan struct{})
61✔
2976

61✔
2977
        f.wg.Add(1)
61✔
2978
        go f.waitForFundingConfirmation(ch, cancelChan, confChan)
61✔
2979

61✔
2980
        // If we are not the initiator, we have no money at stake and will
61✔
2981
        // timeout waiting for the funding transaction to confirm after a
61✔
2982
        // while.
61✔
2983
        if !ch.IsInitiator && !ch.IsZeroConf() {
90✔
2984
                f.wg.Add(1)
29✔
2985
                go f.waitForTimeout(ch, cancelChan, timeoutChan)
29✔
2986
        }
29✔
2987
        defer close(cancelChan)
61✔
2988

61✔
2989
        select {
61✔
2990
        case err := <-timeoutChan:
2✔
2991
                if err != nil {
2✔
2992
                        return nil, err
×
2993
                }
×
2994
                return nil, ErrConfirmationTimeout
2✔
2995

2996
        case <-f.quit:
25✔
2997
                // The fundingManager is shutting down, and will resume wait on
25✔
2998
                // startup.
25✔
2999
                return nil, ErrFundingManagerShuttingDown
25✔
3000

3001
        case confirmedChannel, ok := <-confChan:
38✔
3002
                if !ok {
38✔
3003
                        return nil, fmt.Errorf("waiting for funding" +
×
3004
                                "confirmation failed")
×
3005
                }
×
3006
                return confirmedChannel, nil
38✔
3007
        }
3008
}
3009

3010
// makeFundingScript re-creates the funding script for the funding transaction
3011
// of the target channel.
3012
func makeFundingScript(channel *channeldb.OpenChannel) ([]byte, error) {
81✔
3013
        localKey := channel.LocalChanCfg.MultiSigKey.PubKey
81✔
3014
        remoteKey := channel.RemoteChanCfg.MultiSigKey.PubKey
81✔
3015

81✔
3016
        if channel.ChanType.IsTaproot() {
90✔
3017
                pkScript, _, err := input.GenTaprootFundingScript(
9✔
3018
                        localKey, remoteKey, int64(channel.Capacity),
9✔
3019
                        channel.TapscriptRoot,
9✔
3020
                )
9✔
3021
                if err != nil {
9✔
3022
                        return nil, err
×
3023
                }
×
3024

3025
                return pkScript, nil
9✔
3026
        }
3027

3028
        multiSigScript, err := input.GenMultiSigScript(
76✔
3029
                localKey.SerializeCompressed(),
76✔
3030
                remoteKey.SerializeCompressed(),
76✔
3031
        )
76✔
3032
        if err != nil {
76✔
3033
                return nil, err
×
3034
        }
×
3035

3036
        return input.WitnessScriptHash(multiSigScript)
76✔
3037
}
3038

3039
// waitForFundingConfirmation handles the final stages of the channel funding
3040
// process once the funding transaction has been broadcast. The primary
3041
// function of waitForFundingConfirmation is to wait for blockchain
3042
// confirmation, and then to notify the other systems that must be notified
3043
// when a channel has become active for lightning transactions.
3044
// The wait can be canceled by closing the cancelChan. In case of success,
3045
// a *lnwire.ShortChannelID will be passed to confChan.
3046
//
3047
// NOTE: This MUST be run as a goroutine.
3048
func (f *Manager) waitForFundingConfirmation(
3049
        completeChan *channeldb.OpenChannel, cancelChan <-chan struct{},
3050
        confChan chan<- *confirmedChannel) {
61✔
3051

61✔
3052
        defer f.wg.Done()
61✔
3053
        defer close(confChan)
61✔
3054

61✔
3055
        // Register with the ChainNotifier for a notification once the funding
61✔
3056
        // transaction reaches `numConfs` confirmations.
61✔
3057
        txid := completeChan.FundingOutpoint.Hash
61✔
3058
        fundingScript, err := makeFundingScript(completeChan)
61✔
3059
        if err != nil {
61✔
3060
                log.Errorf("unable to create funding script for "+
×
3061
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3062
                        err)
×
3063
                return
×
3064
        }
×
3065
        numConfs := uint32(completeChan.NumConfsRequired)
61✔
3066

61✔
3067
        // If the underlying channel is a zero-conf channel, we'll set numConfs
61✔
3068
        // to 6, since it will be zero here.
61✔
3069
        if completeChan.IsZeroConf() {
71✔
3070
                numConfs = 6
10✔
3071
        }
10✔
3072

3073
        confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
61✔
3074
                &txid, fundingScript, numConfs,
61✔
3075
                completeChan.BroadcastHeight(),
61✔
3076
        )
61✔
3077
        if err != nil {
61✔
3078
                log.Errorf("Unable to register for confirmation of "+
×
3079
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3080
                        err)
×
3081
                return
×
3082
        }
×
3083

3084
        log.Infof("Waiting for funding tx (%v) to reach %v confirmations",
61✔
3085
                txid, numConfs)
61✔
3086

61✔
3087
        var confDetails *chainntnfs.TxConfirmation
61✔
3088
        var ok bool
61✔
3089

61✔
3090
        // Wait until the specified number of confirmations has been reached,
61✔
3091
        // we get a cancel signal, or the wallet signals a shutdown.
61✔
3092
        select {
61✔
3093
        case confDetails, ok = <-confNtfn.Confirmed:
38✔
3094
                // fallthrough
3095

3096
        case <-cancelChan:
2✔
3097
                log.Warnf("canceled waiting for funding confirmation, "+
2✔
3098
                        "stopping funding flow for ChannelPoint(%v)",
2✔
3099
                        completeChan.FundingOutpoint)
2✔
3100
                return
2✔
3101

3102
        case <-f.quit:
25✔
3103
                log.Warnf("fundingManager shutting down, stopping funding "+
25✔
3104
                        "flow for ChannelPoint(%v)",
25✔
3105
                        completeChan.FundingOutpoint)
25✔
3106
                return
25✔
3107
        }
3108

3109
        if !ok {
38✔
3110
                log.Warnf("ChainNotifier shutting down, cannot complete "+
×
3111
                        "funding flow for ChannelPoint(%v)",
×
3112
                        completeChan.FundingOutpoint)
×
3113
                return
×
3114
        }
×
3115

3116
        fundingPoint := completeChan.FundingOutpoint
38✔
3117
        log.Infof("ChannelPoint(%v) is now active: ChannelID(%v)",
38✔
3118
                fundingPoint, lnwire.NewChanIDFromOutPoint(fundingPoint))
38✔
3119

38✔
3120
        // With the block height and the transaction index known, we can
38✔
3121
        // construct the compact chanID which is used on the network to unique
38✔
3122
        // identify channels.
38✔
3123
        shortChanID := lnwire.ShortChannelID{
38✔
3124
                BlockHeight: confDetails.BlockHeight,
38✔
3125
                TxIndex:     confDetails.TxIndex,
38✔
3126
                TxPosition:  uint16(fundingPoint.Index),
38✔
3127
        }
38✔
3128

38✔
3129
        select {
38✔
3130
        case confChan <- &confirmedChannel{
3131
                shortChanID: shortChanID,
3132
                fundingTx:   confDetails.Tx,
3133
        }:
38✔
3134
        case <-f.quit:
×
3135
                return
×
3136
        }
3137
}
3138

3139
// waitForTimeout will close the timeout channel if MaxWaitNumBlocksFundingConf
3140
// has passed from the broadcast height of the given channel. In case of error,
3141
// the error is sent on timeoutChan. The wait can be canceled by closing the
3142
// cancelChan.
3143
//
3144
// NOTE: timeoutChan MUST be buffered.
3145
// NOTE: This MUST be run as a goroutine.
3146
func (f *Manager) waitForTimeout(completeChan *channeldb.OpenChannel,
3147
        cancelChan <-chan struct{}, timeoutChan chan<- error) {
29✔
3148

29✔
3149
        defer f.wg.Done()
29✔
3150

29✔
3151
        epochClient, err := f.cfg.Notifier.RegisterBlockEpochNtfn(nil)
29✔
3152
        if err != nil {
29✔
3153
                timeoutChan <- fmt.Errorf("unable to register for epoch "+
×
3154
                        "notification: %v", err)
×
3155
                return
×
3156
        }
×
3157

3158
        defer epochClient.Cancel()
29✔
3159

29✔
3160
        // On block maxHeight we will cancel the funding confirmation wait.
29✔
3161
        broadcastHeight := completeChan.BroadcastHeight()
29✔
3162
        maxHeight := broadcastHeight + MaxWaitNumBlocksFundingConf
29✔
3163
        for {
60✔
3164
                select {
31✔
3165
                case epoch, ok := <-epochClient.Epochs:
8✔
3166
                        if !ok {
8✔
3167
                                timeoutChan <- fmt.Errorf("epoch client " +
×
3168
                                        "shutting down")
×
3169
                                return
×
3170
                        }
×
3171

3172
                        // Close the timeout channel and exit if the block is
3173
                        // above the max height.
3174
                        if uint32(epoch.Height) >= maxHeight {
10✔
3175
                                log.Warnf("Waited for %v blocks without "+
2✔
3176
                                        "seeing funding transaction confirmed,"+
2✔
3177
                                        " cancelling.",
2✔
3178
                                        MaxWaitNumBlocksFundingConf)
2✔
3179

2✔
3180
                                // Notify the caller of the timeout.
2✔
3181
                                close(timeoutChan)
2✔
3182
                                return
2✔
3183
                        }
2✔
3184

3185
                        // TODO: If we are the channel initiator implement
3186
                        // a method for recovering the funds from the funding
3187
                        // transaction
3188

3189
                case <-cancelChan:
19✔
3190
                        return
19✔
3191

3192
                case <-f.quit:
12✔
3193
                        // The fundingManager is shutting down, will resume
12✔
3194
                        // waiting for the funding transaction on startup.
12✔
3195
                        return
12✔
3196
                }
3197
        }
3198
}
3199

3200
// makeLabelForTx updates the label for the confirmed funding transaction. If
3201
// we opened the channel, and lnd's wallet published our funding tx (which is
3202
// not the case for some channels) then we update our transaction label with
3203
// our short channel ID, which is known now that our funding transaction has
3204
// confirmed. We do not label transactions we did not publish, because our
3205
// wallet has no knowledge of them.
3206
func (f *Manager) makeLabelForTx(c *channeldb.OpenChannel) {
38✔
3207
        if c.IsInitiator && c.ChanType.HasFundingTx() {
58✔
3208
                shortChanID := c.ShortChanID()
20✔
3209

20✔
3210
                // For zero-conf channels, we'll use the actually-confirmed
20✔
3211
                // short channel id.
20✔
3212
                if c.IsZeroConf() {
26✔
3213
                        shortChanID = c.ZeroConfRealScid()
6✔
3214
                }
6✔
3215

3216
                label := labels.MakeLabel(
20✔
3217
                        labels.LabelTypeChannelOpen, &shortChanID,
20✔
3218
                )
20✔
3219

20✔
3220
                err := f.cfg.UpdateLabel(c.FundingOutpoint.Hash, label)
20✔
3221
                if err != nil {
20✔
3222
                        log.Errorf("unable to update label: %v", err)
×
3223
                }
×
3224
        }
3225
}
3226

3227
// handleFundingConfirmation marks a channel as open in the database, and set
3228
// the channelOpeningState markedOpen. In addition it will report the now
3229
// decided short channel ID to the switch, and close the local discovery signal
3230
// for this channel.
3231
func (f *Manager) handleFundingConfirmation(
3232
        completeChan *channeldb.OpenChannel,
3233
        confChannel *confirmedChannel) error {
34✔
3234

34✔
3235
        fundingPoint := completeChan.FundingOutpoint
34✔
3236
        chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
34✔
3237

34✔
3238
        // TODO(roasbeef): ideally persistent state update for chan above
34✔
3239
        // should be abstracted
34✔
3240

34✔
3241
        // Now that that the channel has been fully confirmed, we'll request
34✔
3242
        // that the wallet fully verify this channel to ensure that it can be
34✔
3243
        // used.
34✔
3244
        err := f.cfg.Wallet.ValidateChannel(completeChan, confChannel.fundingTx)
34✔
3245
        if err != nil {
34✔
3246
                // TODO(roasbeef): delete chan state?
×
3247
                return fmt.Errorf("unable to validate channel: %w", err)
×
3248
        }
×
3249

3250
        // Now that the channel has been validated, we'll persist an alias for
3251
        // this channel if the option-scid-alias feature-bit was negotiated.
3252
        if completeChan.NegotiatedAliasFeature() {
40✔
3253
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
6✔
3254
                if err != nil {
6✔
3255
                        return fmt.Errorf("unable to request alias: %w", err)
×
3256
                }
×
3257

3258
                err = f.cfg.AliasManager.AddLocalAlias(
6✔
3259
                        aliasScid, confChannel.shortChanID, true, false,
6✔
3260
                )
6✔
3261
                if err != nil {
6✔
3262
                        return fmt.Errorf("unable to request alias: %w", err)
×
3263
                }
×
3264
        }
3265

3266
        // The funding transaction now being confirmed, we add this channel to
3267
        // the fundingManager's internal persistent state machine that we use
3268
        // to track the remaining process of the channel opening. This is
3269
        // useful to resume the opening process in case of restarts. We set the
3270
        // opening state before we mark the channel opened in the database,
3271
        // such that we can receover from one of the db writes failing.
3272
        err = f.saveChannelOpeningState(
34✔
3273
                &fundingPoint, markedOpen, &confChannel.shortChanID,
34✔
3274
        )
34✔
3275
        if err != nil {
34✔
3276
                return fmt.Errorf("error setting channel state to "+
×
3277
                        "markedOpen: %v", err)
×
3278
        }
×
3279

3280
        // Now that the channel has been fully confirmed and we successfully
3281
        // saved the opening state, we'll mark it as open within the database.
3282
        err = completeChan.MarkAsOpen(confChannel.shortChanID)
34✔
3283
        if err != nil {
34✔
3284
                return fmt.Errorf("error setting channel pending flag to "+
×
3285
                        "false:        %v", err)
×
3286
        }
×
3287

3288
        // Update the confirmed funding transaction label.
3289
        f.makeLabelForTx(completeChan)
34✔
3290

34✔
3291
        // Inform the ChannelNotifier that the channel has transitioned from
34✔
3292
        // pending open to open.
34✔
3293
        f.cfg.NotifyOpenChannelEvent(completeChan.FundingOutpoint)
34✔
3294

34✔
3295
        // Close the discoverySignal channel, indicating to a separate
34✔
3296
        // goroutine that the channel now is marked as open in the database
34✔
3297
        // and that it is acceptable to process channel_ready messages
34✔
3298
        // from the peer.
34✔
3299
        if discoverySignal, ok := f.localDiscoverySignals.Load(chanID); ok {
68✔
3300
                close(discoverySignal)
34✔
3301
        }
34✔
3302

3303
        return nil
34✔
3304
}
3305

3306
// sendChannelReady creates and sends the channelReady message.
3307
// This should be called after the funding transaction has been confirmed,
3308
// and the channelState is 'markedOpen'.
3309
func (f *Manager) sendChannelReady(completeChan *channeldb.OpenChannel,
3310
        channel *lnwallet.LightningChannel) error {
39✔
3311

39✔
3312
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
39✔
3313

39✔
3314
        var peerKey [33]byte
39✔
3315
        copy(peerKey[:], completeChan.IdentityPub.SerializeCompressed())
39✔
3316

39✔
3317
        // Next, we'll send over the channel_ready message which marks that we
39✔
3318
        // consider the channel open by presenting the remote party with our
39✔
3319
        // next revocation key. Without the revocation key, the remote party
39✔
3320
        // will be unable to propose state transitions.
39✔
3321
        nextRevocation, err := channel.NextRevocationKey()
39✔
3322
        if err != nil {
39✔
3323
                return fmt.Errorf("unable to create next revocation: %w", err)
×
3324
        }
×
3325
        channelReadyMsg := lnwire.NewChannelReady(chanID, nextRevocation)
39✔
3326

39✔
3327
        // If this is a taproot channel, then we also need to send along our
39✔
3328
        // set of musig2 nonces as well.
39✔
3329
        if completeChan.ChanType.IsTaproot() {
47✔
3330
                log.Infof("ChanID(%v): generating musig2 nonces...",
8✔
3331
                        chanID)
8✔
3332

8✔
3333
                f.nonceMtx.Lock()
8✔
3334
                localNonce, ok := f.pendingMusigNonces[chanID]
8✔
3335
                if !ok {
16✔
3336
                        // If we don't have any nonces generated yet for this
8✔
3337
                        // first state, then we'll generate them now and stow
8✔
3338
                        // them away.  When we receive the funding locked
8✔
3339
                        // message, we'll then pass along this same set of
8✔
3340
                        // nonces.
8✔
3341
                        newNonce, err := channel.GenMusigNonces()
8✔
3342
                        if err != nil {
8✔
3343
                                f.nonceMtx.Unlock()
×
3344
                                return err
×
3345
                        }
×
3346

3347
                        // Now that we've generated the nonce for this channel,
3348
                        // we'll store it in the set of pending nonces.
3349
                        localNonce = newNonce
8✔
3350
                        f.pendingMusigNonces[chanID] = localNonce
8✔
3351
                }
3352
                f.nonceMtx.Unlock()
8✔
3353

8✔
3354
                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
8✔
3355
                        localNonce.PubNonce,
8✔
3356
                )
8✔
3357
        }
3358

3359
        // If the channel negotiated the option-scid-alias feature bit, we'll
3360
        // send a TLV segment that includes an alias the peer can use in their
3361
        // invoice hop hints. We'll send the first alias we find for the
3362
        // channel since it does not matter which alias we send. We'll error
3363
        // out in the odd case that no aliases are found.
3364
        if completeChan.NegotiatedAliasFeature() {
49✔
3365
                aliases := f.cfg.AliasManager.GetAliases(
10✔
3366
                        completeChan.ShortChanID(),
10✔
3367
                )
10✔
3368
                if len(aliases) == 0 {
10✔
3369
                        return fmt.Errorf("no aliases found")
×
3370
                }
×
3371

3372
                // We can use a pointer to aliases since GetAliases returns a
3373
                // copy of the alias slice.
3374
                channelReadyMsg.AliasScid = &aliases[0]
10✔
3375
        }
3376

3377
        // If the peer has disconnected before we reach this point, we will need
3378
        // to wait for him to come back online before sending the channelReady
3379
        // message. This is special for channelReady, since failing to send any
3380
        // of the previous messages in the funding flow just cancels the flow.
3381
        // But now the funding transaction is confirmed, the channel is open
3382
        // and we have to make sure the peer gets the channelReady message when
3383
        // it comes back online. This is also crucial during restart of lnd,
3384
        // where we might try to resend the channelReady message before the
3385
        // server has had the time to connect to the peer. We keep trying to
3386
        // send channelReady until we succeed, or the fundingManager is shut
3387
        // down.
3388
        for {
78✔
3389
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
39✔
3390
                if err != nil {
40✔
3391
                        return err
1✔
3392
                }
1✔
3393

3394
                localAlias := peer.LocalFeatures().HasFeature(
38✔
3395
                        lnwire.ScidAliasOptional,
38✔
3396
                )
38✔
3397
                remoteAlias := peer.RemoteFeatures().HasFeature(
38✔
3398
                        lnwire.ScidAliasOptional,
38✔
3399
                )
38✔
3400

38✔
3401
                // We could also refresh the channel state instead of checking
38✔
3402
                // whether the feature was negotiated, but this saves us a
38✔
3403
                // database read.
38✔
3404
                if channelReadyMsg.AliasScid == nil && localAlias &&
38✔
3405
                        remoteAlias {
38✔
3406

×
3407
                        // If an alias was not assigned above and the scid
×
3408
                        // alias feature was negotiated, check if we already
×
3409
                        // have an alias stored in case handleChannelReady was
×
3410
                        // called before this. If an alias exists, use that in
×
3411
                        // channel_ready. Otherwise, request and store an
×
3412
                        // alias and use that.
×
3413
                        aliases := f.cfg.AliasManager.GetAliases(
×
3414
                                completeChan.ShortChannelID,
×
3415
                        )
×
3416
                        if len(aliases) == 0 {
×
3417
                                // No aliases were found.
×
3418
                                alias, err := f.cfg.AliasManager.RequestAlias()
×
3419
                                if err != nil {
×
3420
                                        return err
×
3421
                                }
×
3422

3423
                                err = f.cfg.AliasManager.AddLocalAlias(
×
3424
                                        alias, completeChan.ShortChannelID,
×
3425
                                        false, false,
×
3426
                                )
×
3427
                                if err != nil {
×
3428
                                        return err
×
3429
                                }
×
3430

3431
                                channelReadyMsg.AliasScid = &alias
×
3432
                        } else {
×
3433
                                channelReadyMsg.AliasScid = &aliases[0]
×
3434
                        }
×
3435
                }
3436

3437
                log.Infof("Peer(%x) is online, sending ChannelReady "+
38✔
3438
                        "for ChannelID(%v)", peerKey, chanID)
38✔
3439

38✔
3440
                if err := peer.SendMessage(true, channelReadyMsg); err == nil {
76✔
3441
                        // Sending succeeded, we can break out and continue the
38✔
3442
                        // funding flow.
38✔
3443
                        break
38✔
3444
                }
3445

3446
                log.Warnf("Unable to send channelReady to peer %x: %v. "+
×
3447
                        "Will retry when online", peerKey, err)
×
3448
        }
3449

3450
        return nil
38✔
3451
}
3452

3453
// receivedChannelReady checks whether or not we've received a ChannelReady
3454
// from the remote peer. If we have, RemoteNextRevocation will be set.
3455
func (f *Manager) receivedChannelReady(node *btcec.PublicKey,
3456
        chanID lnwire.ChannelID) (bool, error) {
64✔
3457

64✔
3458
        // If the funding manager has exited, return an error to stop looping.
64✔
3459
        // Note that the peer may appear as online while the funding manager
64✔
3460
        // has stopped due to the shutdown order in the server.
64✔
3461
        select {
64✔
3462
        case <-f.quit:
×
3463
                return false, ErrFundingManagerShuttingDown
×
3464
        default:
64✔
3465
        }
3466

3467
        // Avoid a tight loop if peer is offline.
3468
        if _, err := f.waitForPeerOnline(node); err != nil {
64✔
3469
                log.Errorf("Wait for peer online failed: %v", err)
×
3470
                return false, err
×
3471
        }
×
3472

3473
        // If we cannot find the channel, then we haven't processed the
3474
        // remote's channelReady message.
3475
        channel, err := f.cfg.FindChannel(node, chanID)
64✔
3476
        if err != nil {
64✔
3477
                log.Errorf("Unable to locate ChannelID(%v) to determine if "+
×
3478
                        "ChannelReady was received", chanID)
×
3479
                return false, err
×
3480
        }
×
3481

3482
        // If we haven't insert the next revocation point, we haven't finished
3483
        // processing the channel ready message.
3484
        if channel.RemoteNextRevocation == nil {
103✔
3485
                return false, nil
39✔
3486
        }
39✔
3487

3488
        // Finally, the barrier signal is removed once we finish
3489
        // `handleChannelReady`. If we can still find the signal, we haven't
3490
        // finished processing it yet.
3491
        _, loaded := f.handleChannelReadyBarriers.Load(chanID)
29✔
3492

29✔
3493
        return !loaded, nil
29✔
3494
}
3495

3496
// extractAnnounceParams extracts the various channel announcement and update
3497
// parameters that will be needed to construct a ChannelAnnouncement and a
3498
// ChannelUpdate.
3499
func (f *Manager) extractAnnounceParams(c *channeldb.OpenChannel) (
3500
        lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
30✔
3501

30✔
3502
        // We'll obtain the min HTLC value we can forward in our direction, as
30✔
3503
        // we'll use this value within our ChannelUpdate. This constraint is
30✔
3504
        // originally set by the remote node, as it will be the one that will
30✔
3505
        // need to determine the smallest HTLC it deems economically relevant.
30✔
3506
        fwdMinHTLC := c.LocalChanCfg.MinHTLC
30✔
3507

30✔
3508
        // We don't necessarily want to go as low as the remote party allows.
30✔
3509
        // Check it against our default forwarding policy.
30✔
3510
        if fwdMinHTLC < f.cfg.DefaultRoutingPolicy.MinHTLCOut {
34✔
3511
                fwdMinHTLC = f.cfg.DefaultRoutingPolicy.MinHTLCOut
4✔
3512
        }
4✔
3513

3514
        // We'll obtain the max HTLC value we can forward in our direction, as
3515
        // we'll use this value within our ChannelUpdate. This value must be <=
3516
        // channel capacity and <= the maximum in-flight msats set by the peer.
3517
        fwdMaxHTLC := c.LocalChanCfg.MaxPendingAmount
30✔
3518
        capacityMSat := lnwire.NewMSatFromSatoshis(c.Capacity)
30✔
3519
        if fwdMaxHTLC > capacityMSat {
30✔
3520
                fwdMaxHTLC = capacityMSat
×
3521
        }
×
3522

3523
        return fwdMinHTLC, fwdMaxHTLC
30✔
3524
}
3525

3526
// addToGraph sends a ChannelAnnouncement and a ChannelUpdate to the
3527
// gossiper so that the channel is added to the graph builder's internal graph.
3528
// These announcement messages are NOT broadcasted to the greater network,
3529
// only to the channel counter party. The proofs required to announce the
3530
// channel to the greater network will be created and sent in annAfterSixConfs.
3531
// The peerAlias is used for zero-conf channels to give the counter-party a
3532
// ChannelUpdate they understand. ourPolicy may be set for various
3533
// option-scid-alias channels to re-use the same policy.
3534
func (f *Manager) addToGraph(completeChan *channeldb.OpenChannel,
3535
        shortChanID *lnwire.ShortChannelID,
3536
        peerAlias *lnwire.ShortChannelID,
3537
        ourPolicy *models.ChannelEdgePolicy) error {
30✔
3538

30✔
3539
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
30✔
3540

30✔
3541
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
30✔
3542

30✔
3543
        ann, err := f.newChanAnnouncement(
30✔
3544
                f.cfg.IDKey, completeChan.IdentityPub,
30✔
3545
                &completeChan.LocalChanCfg.MultiSigKey,
30✔
3546
                completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
30✔
3547
                chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
30✔
3548
                completeChan.ChanType,
30✔
3549
        )
30✔
3550
        if err != nil {
30✔
3551
                return fmt.Errorf("error generating channel "+
×
3552
                        "announcement: %v", err)
×
3553
        }
×
3554

3555
        // Send ChannelAnnouncement and ChannelUpdate to the gossiper to add
3556
        // to the Router's topology.
3557
        errChan := f.cfg.SendAnnouncement(
30✔
3558
                ann.chanAnn, discovery.ChannelCapacity(completeChan.Capacity),
30✔
3559
                discovery.ChannelPoint(completeChan.FundingOutpoint),
30✔
3560
                discovery.TapscriptRoot(completeChan.TapscriptRoot),
30✔
3561
        )
30✔
3562
        select {
30✔
3563
        case err := <-errChan:
30✔
3564
                if err != nil {
30✔
3565
                        if graph.IsError(err, graph.ErrOutdated,
×
3566
                                graph.ErrIgnored) {
×
3567

×
3568
                                log.Debugf("Graph rejected "+
×
3569
                                        "ChannelAnnouncement: %v", err)
×
3570
                        } else {
×
3571
                                return fmt.Errorf("error sending channel "+
×
3572
                                        "announcement: %v", err)
×
3573
                        }
×
3574
                }
3575
        case <-f.quit:
×
3576
                return ErrFundingManagerShuttingDown
×
3577
        }
3578

3579
        errChan = f.cfg.SendAnnouncement(
30✔
3580
                ann.chanUpdateAnn, discovery.RemoteAlias(peerAlias),
30✔
3581
        )
30✔
3582
        select {
30✔
3583
        case err := <-errChan:
30✔
3584
                if err != nil {
30✔
3585
                        if graph.IsError(err, graph.ErrOutdated,
×
3586
                                graph.ErrIgnored) {
×
3587

×
3588
                                log.Debugf("Graph rejected "+
×
3589
                                        "ChannelUpdate: %v", err)
×
3590
                        } else {
×
3591
                                return fmt.Errorf("error sending channel "+
×
3592
                                        "update: %v", err)
×
3593
                        }
×
3594
                }
3595
        case <-f.quit:
×
3596
                return ErrFundingManagerShuttingDown
×
3597
        }
3598

3599
        return nil
30✔
3600
}
3601

3602
// annAfterSixConfs broadcasts the necessary channel announcement messages to
3603
// the network after 6 confs. Should be called after the channelReady message
3604
// is sent and the channel is added to the graph (channelState is
3605
// 'addedToGraph') and the channel is ready to be used. This is the last
3606
// step in the channel opening process, and the opening state will be deleted
3607
// from the database if successful.
3608
func (f *Manager) annAfterSixConfs(completeChan *channeldb.OpenChannel,
3609
        shortChanID *lnwire.ShortChannelID) error {
30✔
3610

30✔
3611
        // If this channel is not meant to be announced to the greater network,
30✔
3612
        // we'll only send our NodeAnnouncement to our counterparty to ensure we
30✔
3613
        // don't leak any of our information.
30✔
3614
        announceChan := completeChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
30✔
3615
        if !announceChan {
42✔
3616
                log.Debugf("Will not announce private channel %v.",
12✔
3617
                        shortChanID.ToUint64())
12✔
3618

12✔
3619
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
12✔
3620
                if err != nil {
12✔
3621
                        return err
×
3622
                }
×
3623

3624
                nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
12✔
3625
                if err != nil {
12✔
3626
                        return fmt.Errorf("unable to retrieve current node "+
×
3627
                                "announcement: %v", err)
×
3628
                }
×
3629

3630
                chanID := lnwire.NewChanIDFromOutPoint(
12✔
3631
                        completeChan.FundingOutpoint,
12✔
3632
                )
12✔
3633
                pubKey := peer.PubKey()
12✔
3634
                log.Debugf("Sending our NodeAnnouncement for "+
12✔
3635
                        "ChannelID(%v) to %x", chanID, pubKey)
12✔
3636

12✔
3637
                // TODO(halseth): make reliable. If the peer is not online this
12✔
3638
                // will fail, and the opening process will stop. Should instead
12✔
3639
                // block here, waiting for the peer to come online.
12✔
3640
                if err := peer.SendMessage(true, &nodeAnn); err != nil {
12✔
3641
                        return fmt.Errorf("unable to send node announcement "+
×
3642
                                "to peer %x: %v", pubKey, err)
×
3643
                }
×
3644
        } else {
22✔
3645
                // Otherwise, we'll wait until the funding transaction has
22✔
3646
                // reached 6 confirmations before announcing it.
22✔
3647
                numConfs := uint32(completeChan.NumConfsRequired)
22✔
3648
                if numConfs < 6 {
44✔
3649
                        numConfs = 6
22✔
3650
                }
22✔
3651
                txid := completeChan.FundingOutpoint.Hash
22✔
3652
                log.Debugf("Will announce channel %v after ChannelPoint"+
22✔
3653
                        "(%v) has gotten %d confirmations",
22✔
3654
                        shortChanID.ToUint64(), completeChan.FundingOutpoint,
22✔
3655
                        numConfs)
22✔
3656

22✔
3657
                fundingScript, err := makeFundingScript(completeChan)
22✔
3658
                if err != nil {
22✔
3659
                        return fmt.Errorf("unable to create funding script "+
×
3660
                                "for ChannelPoint(%v): %v",
×
3661
                                completeChan.FundingOutpoint, err)
×
3662
                }
×
3663

3664
                // Register with the ChainNotifier for a notification once the
3665
                // funding transaction reaches at least 6 confirmations.
3666
                confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
22✔
3667
                        &txid, fundingScript, numConfs,
22✔
3668
                        completeChan.BroadcastHeight(),
22✔
3669
                )
22✔
3670
                if err != nil {
22✔
3671
                        return fmt.Errorf("unable to register for "+
×
3672
                                "confirmation of ChannelPoint(%v): %v",
×
3673
                                completeChan.FundingOutpoint, err)
×
3674
                }
×
3675

3676
                // Wait until 6 confirmations has been reached or the wallet
3677
                // signals a shutdown.
3678
                select {
22✔
3679
                case _, ok := <-confNtfn.Confirmed:
20✔
3680
                        if !ok {
20✔
3681
                                return fmt.Errorf("ChainNotifier shutting "+
×
3682
                                        "down, cannot complete funding flow "+
×
3683
                                        "for ChannelPoint(%v)",
×
3684
                                        completeChan.FundingOutpoint)
×
3685
                        }
×
3686
                        // Fallthrough.
3687

3688
                case <-f.quit:
6✔
3689
                        return fmt.Errorf("%v, stopping funding flow for "+
6✔
3690
                                "ChannelPoint(%v)",
6✔
3691
                                ErrFundingManagerShuttingDown,
6✔
3692
                                completeChan.FundingOutpoint)
6✔
3693
                }
3694

3695
                fundingPoint := completeChan.FundingOutpoint
20✔
3696
                chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
20✔
3697

20✔
3698
                log.Infof("Announcing ChannelPoint(%v), short_chan_id=%v",
20✔
3699
                        &fundingPoint, shortChanID)
20✔
3700

20✔
3701
                // If this is a non-zero-conf option-scid-alias channel, we'll
20✔
3702
                // delete the mappings the gossiper uses so that ChannelUpdates
20✔
3703
                // with aliases won't be accepted. This is done elsewhere for
20✔
3704
                // zero-conf channels.
20✔
3705
                isScidFeature := completeChan.NegotiatedAliasFeature()
20✔
3706
                isZeroConf := completeChan.IsZeroConf()
20✔
3707
                if isScidFeature && !isZeroConf {
24✔
3708
                        baseScid := completeChan.ShortChanID()
4✔
3709
                        err := f.cfg.AliasManager.DeleteSixConfs(baseScid)
4✔
3710
                        if err != nil {
4✔
3711
                                return fmt.Errorf("failed deleting six confs "+
×
3712
                                        "maps: %v", err)
×
3713
                        }
×
3714

3715
                        // We'll delete the edge and add it again via
3716
                        // addToGraph. This is because the peer may have
3717
                        // sent us a ChannelUpdate with an alias and we don't
3718
                        // want to relay this.
3719
                        ourPolicy, err := f.cfg.DeleteAliasEdge(baseScid)
4✔
3720
                        if err != nil {
4✔
3721
                                return fmt.Errorf("failed deleting real edge "+
×
3722
                                        "for alias channel from graph: %v",
×
3723
                                        err)
×
3724
                        }
×
3725

3726
                        err = f.addToGraph(
4✔
3727
                                completeChan, &baseScid, nil, ourPolicy,
4✔
3728
                        )
4✔
3729
                        if err != nil {
4✔
3730
                                return fmt.Errorf("failed to re-add to "+
×
3731
                                        "graph: %v", err)
×
3732
                        }
×
3733
                }
3734

3735
                // Create and broadcast the proofs required to make this channel
3736
                // public and usable for other nodes for routing.
3737
                err = f.announceChannel(
20✔
3738
                        f.cfg.IDKey, completeChan.IdentityPub,
20✔
3739
                        &completeChan.LocalChanCfg.MultiSigKey,
20✔
3740
                        completeChan.RemoteChanCfg.MultiSigKey.PubKey,
20✔
3741
                        *shortChanID, chanID, completeChan.ChanType,
20✔
3742
                )
20✔
3743
                if err != nil {
24✔
3744
                        return fmt.Errorf("channel announcement failed: %w",
4✔
3745
                                err)
4✔
3746
                }
4✔
3747

3748
                log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+
20✔
3749
                        "sent to gossiper", &fundingPoint, shortChanID)
20✔
3750
        }
3751

3752
        return nil
28✔
3753
}
3754

3755
// waitForZeroConfChannel is called when the state is addedToGraph with
3756
// a zero-conf channel. This will wait for the real confirmation, add the
3757
// confirmed SCID to the router graph, and then announce after six confs.
3758
func (f *Manager) waitForZeroConfChannel(c *channeldb.OpenChannel) error {
10✔
3759
        // First we'll check whether the channel is confirmed on-chain. If it
10✔
3760
        // is already confirmed, the chainntnfs subsystem will return with the
10✔
3761
        // confirmed tx. Otherwise, we'll wait here until confirmation occurs.
10✔
3762
        confChan, err := f.waitForFundingWithTimeout(c)
10✔
3763
        if err != nil {
16✔
3764
                return fmt.Errorf("error waiting for zero-conf funding "+
6✔
3765
                        "confirmation for ChannelPoint(%v): %v",
6✔
3766
                        c.FundingOutpoint, err)
6✔
3767
        }
6✔
3768

3769
        // We'll need to refresh the channel state so that things are properly
3770
        // populated when validating the channel state. Otherwise, a panic may
3771
        // occur due to inconsistency in the OpenChannel struct.
3772
        err = c.Refresh()
8✔
3773
        if err != nil {
12✔
3774
                return fmt.Errorf("unable to refresh channel state: %w", err)
4✔
3775
        }
4✔
3776

3777
        // Now that we have the confirmed transaction and the proper SCID,
3778
        // we'll call ValidateChannel to ensure the confirmed tx is properly
3779
        // formatted.
3780
        err = f.cfg.Wallet.ValidateChannel(c, confChan.fundingTx)
8✔
3781
        if err != nil {
8✔
3782
                return fmt.Errorf("unable to validate zero-conf channel: "+
×
3783
                        "%v", err)
×
3784
        }
×
3785

3786
        // Once we know the confirmed ShortChannelID, we'll need to save it to
3787
        // the database and refresh the OpenChannel struct with it.
3788
        err = c.MarkRealScid(confChan.shortChanID)
8✔
3789
        if err != nil {
8✔
3790
                return fmt.Errorf("unable to set confirmed SCID for zero "+
×
3791
                        "channel: %v", err)
×
3792
        }
×
3793

3794
        // Six confirmations have been reached. If this channel is public,
3795
        // we'll delete some of the alias mappings the gossiper uses.
3796
        isPublic := c.ChannelFlags&lnwire.FFAnnounceChannel != 0
8✔
3797
        if isPublic {
14✔
3798
                err = f.cfg.AliasManager.DeleteSixConfs(c.ShortChannelID)
6✔
3799
                if err != nil {
6✔
3800
                        return fmt.Errorf("unable to delete base alias after "+
×
3801
                                "six confirmations: %v", err)
×
3802
                }
×
3803

3804
                // TODO: Make this atomic!
3805
                ourPolicy, err := f.cfg.DeleteAliasEdge(c.ShortChanID())
6✔
3806
                if err != nil {
6✔
3807
                        return fmt.Errorf("unable to delete alias edge from "+
×
3808
                                "graph: %v", err)
×
3809
                }
×
3810

3811
                // We'll need to update the graph with the new ShortChannelID
3812
                // via an addToGraph call. We don't pass in the peer's
3813
                // alias since we'll be using the confirmed SCID from now on
3814
                // regardless if it's public or not.
3815
                err = f.addToGraph(
6✔
3816
                        c, &confChan.shortChanID, nil, ourPolicy,
6✔
3817
                )
6✔
3818
                if err != nil {
6✔
3819
                        return fmt.Errorf("failed adding confirmed zero-conf "+
×
3820
                                "SCID to graph: %v", err)
×
3821
                }
×
3822
        }
3823

3824
        // Since we have now marked down the confirmed SCID, we'll also need to
3825
        // tell the Switch to refresh the relevant ChannelLink so that forwards
3826
        // under the confirmed SCID are possible if this is a public channel.
3827
        err = f.cfg.ReportShortChanID(c.FundingOutpoint)
8✔
3828
        if err != nil {
8✔
3829
                // This should only fail if the link is not found in the
×
3830
                // Switch's linkIndex map. If this is the case, then the peer
×
3831
                // has gone offline and the next time the link is loaded, it
×
3832
                // will have a refreshed state. Just log an error here.
×
3833
                log.Errorf("unable to report scid for zero-conf channel "+
×
3834
                        "channel: %v", err)
×
3835
        }
×
3836

3837
        // Update the confirmed transaction's label.
3838
        f.makeLabelForTx(c)
8✔
3839

8✔
3840
        return nil
8✔
3841
}
3842

3843
// genFirstStateMusigNonce generates a nonces for the "first" local state. This
3844
// is the verification nonce for the state created for us after the initial
3845
// commitment transaction signed as part of the funding flow.
3846
func genFirstStateMusigNonce(channel *channeldb.OpenChannel,
3847
) (*musig2.Nonces, error) {
8✔
3848

8✔
3849
        musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
8✔
3850
                channel.RevocationProducer,
8✔
3851
        )
8✔
3852
        if err != nil {
8✔
3853
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3854
                        "nonces: %v", err)
×
3855
        }
×
3856

3857
        // We use the _next_ commitment height here as we need to generate the
3858
        // nonce for the next state the remote party will sign for us.
3859
        verNonce, err := channeldb.NewMusigVerificationNonce(
8✔
3860
                channel.LocalChanCfg.MultiSigKey.PubKey,
8✔
3861
                channel.LocalCommitment.CommitHeight+1,
8✔
3862
                musig2ShaChain,
8✔
3863
        )
8✔
3864
        if err != nil {
8✔
3865
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3866
                        "nonces: %v", err)
×
3867
        }
×
3868

3869
        return verNonce, nil
8✔
3870
}
3871

3872
// handleChannelReady finalizes the channel funding process and enables the
3873
// channel to enter normal operating mode.
3874
func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen
3875
        msg *lnwire.ChannelReady) {
32✔
3876

32✔
3877
        defer f.wg.Done()
32✔
3878

32✔
3879
        // If we are in development mode, we'll wait for specified duration
32✔
3880
        // before processing the channel ready message.
32✔
3881
        if f.cfg.Dev != nil {
36✔
3882
                duration := f.cfg.Dev.ProcessChannelReadyWait
4✔
3883
                log.Warnf("Channel(%v): sleeping %v before processing "+
4✔
3884
                        "channel_ready", msg.ChanID, duration)
4✔
3885

4✔
3886
                select {
4✔
3887
                case <-time.After(duration):
4✔
3888
                        log.Warnf("Channel(%v): slept %v before processing "+
4✔
3889
                                "channel_ready", msg.ChanID, duration)
4✔
3890
                case <-f.quit:
×
3891
                        log.Warnf("Channel(%v): quit sleeping", msg.ChanID)
×
3892
                        return
×
3893
                }
3894
        }
3895

3896
        log.Debugf("Received ChannelReady for ChannelID(%v) from "+
32✔
3897
                "peer %x", msg.ChanID,
32✔
3898
                peer.IdentityKey().SerializeCompressed())
32✔
3899

32✔
3900
        // We now load or create a new channel barrier for this channel.
32✔
3901
        _, loaded := f.handleChannelReadyBarriers.LoadOrStore(
32✔
3902
                msg.ChanID, struct{}{},
32✔
3903
        )
32✔
3904

32✔
3905
        // If we are currently in the process of handling a channel_ready
32✔
3906
        // message for this channel, ignore.
32✔
3907
        if loaded {
37✔
3908
                log.Infof("Already handling channelReady for "+
5✔
3909
                        "ChannelID(%v), ignoring.", msg.ChanID)
5✔
3910
                return
5✔
3911
        }
5✔
3912

3913
        // If not already handling channelReady for this channel, then the
3914
        // `LoadOrStore` has set up a barrier, and it will be removed once this
3915
        // function exits.
3916
        defer f.handleChannelReadyBarriers.Delete(msg.ChanID)
31✔
3917

31✔
3918
        localDiscoverySignal, ok := f.localDiscoverySignals.Load(msg.ChanID)
31✔
3919
        if ok {
60✔
3920
                // Before we proceed with processing the channel_ready
29✔
3921
                // message, we'll wait for the local waitForFundingConfirmation
29✔
3922
                // goroutine to signal that it has the necessary state in
29✔
3923
                // place. Otherwise, we may be missing critical information
29✔
3924
                // required to handle forwarded HTLC's.
29✔
3925
                select {
29✔
3926
                case <-localDiscoverySignal:
29✔
3927
                        // Fallthrough
3928
                case <-f.quit:
×
3929
                        return
×
3930
                }
3931

3932
                // With the signal received, we can now safely delete the entry
3933
                // from the map.
3934
                f.localDiscoverySignals.Delete(msg.ChanID)
29✔
3935
        }
3936

3937
        // First, we'll attempt to locate the channel whose funding workflow is
3938
        // being finalized by this message. We go to the database rather than
3939
        // our reservation map as we may have restarted, mid funding flow. Also
3940
        // provide the node's public key to make the search faster.
3941
        chanID := msg.ChanID
31✔
3942
        channel, err := f.cfg.FindChannel(peer.IdentityKey(), chanID)
31✔
3943
        if err != nil {
31✔
3944
                log.Errorf("Unable to locate ChannelID(%v), cannot complete "+
×
3945
                        "funding", chanID)
×
3946
                return
×
3947
        }
×
3948

3949
        // If this is a taproot channel, then we can generate the set of nonces
3950
        // the remote party needs to send the next remote commitment here.
3951
        var firstVerNonce *musig2.Nonces
31✔
3952
        if channel.ChanType.IsTaproot() {
39✔
3953
                firstVerNonce, err = genFirstStateMusigNonce(channel)
8✔
3954
                if err != nil {
8✔
3955
                        log.Error(err)
×
3956
                        return
×
3957
                }
×
3958
        }
3959

3960
        // We'll need to store the received TLV alias if the option_scid_alias
3961
        // feature was negotiated. This will be used to provide route hints
3962
        // during invoice creation. In the zero-conf case, it is also used to
3963
        // provide a ChannelUpdate to the remote peer. This is done before the
3964
        // call to InsertNextRevocation in case the call to PutPeerAlias fails.
3965
        // If it were to fail on the first call to handleChannelReady, we
3966
        // wouldn't want the channel to be usable yet.
3967
        if channel.NegotiatedAliasFeature() {
41✔
3968
                // If the AliasScid field is nil, we must fail out. We will
10✔
3969
                // most likely not be able to route through the peer.
10✔
3970
                if msg.AliasScid == nil {
10✔
3971
                        log.Debugf("Consider closing ChannelID(%v), peer "+
×
3972
                                "does not implement the option-scid-alias "+
×
3973
                                "feature properly", chanID)
×
3974
                        return
×
3975
                }
×
3976

3977
                // We'll store the AliasScid so that invoice creation can use
3978
                // it.
3979
                err = f.cfg.AliasManager.PutPeerAlias(chanID, *msg.AliasScid)
10✔
3980
                if err != nil {
10✔
3981
                        log.Errorf("unable to store peer's alias: %v", err)
×
3982
                        return
×
3983
                }
×
3984

3985
                // If we do not have an alias stored, we'll create one now.
3986
                // This is only used in the upgrade case where a user toggles
3987
                // the option-scid-alias feature-bit to on. We'll also send the
3988
                // channel_ready message here in case the link is created
3989
                // before sendChannelReady is called.
3990
                aliases := f.cfg.AliasManager.GetAliases(
10✔
3991
                        channel.ShortChannelID,
10✔
3992
                )
10✔
3993
                if len(aliases) == 0 {
10✔
3994
                        // No aliases were found so we'll request and store an
×
3995
                        // alias and use it in the channel_ready message.
×
3996
                        alias, err := f.cfg.AliasManager.RequestAlias()
×
3997
                        if err != nil {
×
3998
                                log.Errorf("unable to request alias: %v", err)
×
3999
                                return
×
4000
                        }
×
4001

4002
                        err = f.cfg.AliasManager.AddLocalAlias(
×
4003
                                alias, channel.ShortChannelID, false, false,
×
4004
                        )
×
4005
                        if err != nil {
×
4006
                                log.Errorf("unable to add local alias: %v",
×
4007
                                        err)
×
4008
                                return
×
4009
                        }
×
4010

4011
                        secondPoint, err := channel.SecondCommitmentPoint()
×
4012
                        if err != nil {
×
4013
                                log.Errorf("unable to fetch second "+
×
4014
                                        "commitment point: %v", err)
×
4015
                                return
×
4016
                        }
×
4017

4018
                        channelReadyMsg := lnwire.NewChannelReady(
×
4019
                                chanID, secondPoint,
×
4020
                        )
×
4021
                        channelReadyMsg.AliasScid = &alias
×
4022

×
4023
                        if firstVerNonce != nil {
×
4024
                                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:lll
×
4025
                                        firstVerNonce.PubNonce,
×
4026
                                )
×
4027
                        }
×
4028

4029
                        err = peer.SendMessage(true, channelReadyMsg)
×
4030
                        if err != nil {
×
4031
                                log.Errorf("unable to send channel_ready: %v",
×
4032
                                        err)
×
4033
                                return
×
4034
                        }
×
4035
                }
4036
        }
4037

4038
        // If the RemoteNextRevocation is non-nil, it means that we have
4039
        // already processed channelReady for this channel, so ignore. This
4040
        // check is after the alias logic so we store the peer's most recent
4041
        // alias. The spec requires us to validate that subsequent
4042
        // channel_ready messages use the same per commitment point (the
4043
        // second), but it is not actually necessary since we'll just end up
4044
        // ignoring it. We are, however, required to *send* the same per
4045
        // commitment point, since another pedantic implementation might
4046
        // verify it.
4047
        if channel.RemoteNextRevocation != nil {
36✔
4048
                log.Infof("Received duplicate channelReady for "+
5✔
4049
                        "ChannelID(%v), ignoring.", chanID)
5✔
4050
                return
5✔
4051
        }
5✔
4052

4053
        // If this is a taproot channel, then we'll need to map the received
4054
        // nonces to a nonce pair, and also fetch our pending nonces, which are
4055
        // required in order to make the channel whole.
4056
        var chanOpts []lnwallet.ChannelOpt
30✔
4057
        if channel.ChanType.IsTaproot() {
38✔
4058
                f.nonceMtx.Lock()
8✔
4059
                localNonce, ok := f.pendingMusigNonces[chanID]
8✔
4060
                if !ok {
12✔
4061
                        // If there's no pending nonce for this channel ID,
4✔
4062
                        // we'll use the one generated above.
4✔
4063
                        localNonce = firstVerNonce
4✔
4064
                        f.pendingMusigNonces[chanID] = firstVerNonce
4✔
4065
                }
4✔
4066
                f.nonceMtx.Unlock()
8✔
4067

8✔
4068
                log.Infof("ChanID(%v): applying local+remote musig2 nonces",
8✔
4069
                        chanID)
8✔
4070

8✔
4071
                remoteNonce, err := msg.NextLocalNonce.UnwrapOrErrV(
8✔
4072
                        errNoLocalNonce,
8✔
4073
                )
8✔
4074
                if err != nil {
8✔
4075
                        cid := newChanIdentifier(msg.ChanID)
×
4076
                        f.sendWarning(peer, cid, err)
×
4077

×
4078
                        return
×
4079
                }
×
4080

4081
                chanOpts = append(
8✔
4082
                        chanOpts,
8✔
4083
                        lnwallet.WithLocalMusigNonces(localNonce),
8✔
4084
                        lnwallet.WithRemoteMusigNonces(&musig2.Nonces{
8✔
4085
                                PubNonce: remoteNonce,
8✔
4086
                        }),
8✔
4087
                )
8✔
4088

8✔
4089
                // Inform the aux funding controller that the liquidity in the
8✔
4090
                // custom channel is now ready to be advertised. We potentially
8✔
4091
                // haven't sent our own channel ready message yet, but other
8✔
4092
                // than that the channel is ready to count toward available
8✔
4093
                // liquidity.
8✔
4094
                err = fn.MapOptionZ(
8✔
4095
                        f.cfg.AuxFundingController,
8✔
4096
                        func(controller AuxFundingController) error {
8✔
4097
                                return controller.ChannelReady(
×
4098
                                        lnwallet.NewAuxChanState(channel),
×
4099
                                )
×
4100
                        },
×
4101
                )
4102
                if err != nil {
8✔
4103
                        cid := newChanIdentifier(msg.ChanID)
×
4104
                        f.sendWarning(peer, cid, err)
×
4105

×
4106
                        return
×
4107
                }
×
4108
        }
4109

4110
        // The channel_ready message contains the next commitment point we'll
4111
        // need to create the next commitment state for the remote party. So
4112
        // we'll insert that into the channel now before passing it along to
4113
        // other sub-systems.
4114
        err = channel.InsertNextRevocation(msg.NextPerCommitmentPoint)
30✔
4115
        if err != nil {
30✔
4116
                log.Errorf("unable to insert next commitment point: %v", err)
×
4117
                return
×
4118
        }
×
4119

4120
        // Before we can add the channel to the peer, we'll need to ensure that
4121
        // we have an initial forwarding policy set.
4122
        if err := f.ensureInitialForwardingPolicy(chanID, channel); err != nil {
30✔
4123
                log.Errorf("Unable to ensure initial forwarding policy: %v",
×
4124
                        err)
×
4125
        }
×
4126

4127
        err = peer.AddNewChannel(&lnpeer.NewChannel{
30✔
4128
                OpenChannel: channel,
30✔
4129
                ChanOpts:    chanOpts,
30✔
4130
        }, f.quit)
30✔
4131
        if err != nil {
30✔
4132
                log.Errorf("Unable to add new channel %v with peer %x: %v",
×
4133
                        channel.FundingOutpoint,
×
4134
                        peer.IdentityKey().SerializeCompressed(), err,
×
4135
                )
×
4136
        }
×
4137
}
4138

4139
// handleChannelReadyReceived is called once the remote's channelReady message
4140
// is received and processed. At this stage, we must have sent out our
4141
// channelReady message, once the remote's channelReady is processed, the
4142
// channel is now active, thus we change its state to `addedToGraph` to
4143
// let the channel start handling routing.
4144
func (f *Manager) handleChannelReadyReceived(channel *channeldb.OpenChannel,
4145
        scid *lnwire.ShortChannelID, pendingChanID PendingChanID,
4146
        updateChan chan<- *lnrpc.OpenStatusUpdate) error {
28✔
4147

28✔
4148
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
28✔
4149

28✔
4150
        // Since we've sent+received funding locked at this point, we
28✔
4151
        // can clean up the pending musig2 nonce state.
28✔
4152
        f.nonceMtx.Lock()
28✔
4153
        delete(f.pendingMusigNonces, chanID)
28✔
4154
        f.nonceMtx.Unlock()
28✔
4155

28✔
4156
        var peerAlias *lnwire.ShortChannelID
28✔
4157
        if channel.IsZeroConf() {
36✔
4158
                // We'll need to wait until channel_ready has been received and
8✔
4159
                // the peer lets us know the alias they want to use for the
8✔
4160
                // channel. With this information, we can then construct a
8✔
4161
                // ChannelUpdate for them.  If an alias does not yet exist,
8✔
4162
                // we'll just return, letting the next iteration of the loop
8✔
4163
                // check again.
8✔
4164
                var defaultAlias lnwire.ShortChannelID
8✔
4165
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
8✔
4166
                foundAlias, _ := f.cfg.AliasManager.GetPeerAlias(chanID)
8✔
4167
                if foundAlias == defaultAlias {
8✔
4168
                        return nil
×
4169
                }
×
4170

4171
                peerAlias = &foundAlias
8✔
4172
        }
4173

4174
        err := f.addToGraph(channel, scid, peerAlias, nil)
28✔
4175
        if err != nil {
28✔
4176
                return fmt.Errorf("failed adding to graph: %w", err)
×
4177
        }
×
4178

4179
        // As the channel is now added to the ChannelRouter's topology, the
4180
        // channel is moved to the next state of the state machine. It will be
4181
        // moved to the last state (actually deleted from the database) after
4182
        // the channel is finally announced.
4183
        err = f.saveChannelOpeningState(
28✔
4184
                &channel.FundingOutpoint, addedToGraph, scid,
28✔
4185
        )
28✔
4186
        if err != nil {
28✔
4187
                return fmt.Errorf("error setting channel state to"+
×
4188
                        " addedToGraph: %w", err)
×
4189
        }
×
4190

4191
        log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
28✔
4192
                "added to graph", chanID, scid)
28✔
4193

28✔
4194
        err = fn.MapOptionZ(
28✔
4195
                f.cfg.AuxFundingController,
28✔
4196
                func(controller AuxFundingController) error {
28✔
4197
                        return controller.ChannelReady(
×
4198
                                lnwallet.NewAuxChanState(channel),
×
4199
                        )
×
4200
                },
×
4201
        )
4202
        if err != nil {
28✔
4203
                return fmt.Errorf("failed notifying aux funding controller "+
×
4204
                        "about channel ready: %w", err)
×
4205
        }
×
4206

4207
        // Give the caller a final update notifying them that the channel is
4208
        fundingPoint := channel.FundingOutpoint
28✔
4209
        cp := &lnrpc.ChannelPoint{
28✔
4210
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
28✔
4211
                        FundingTxidBytes: fundingPoint.Hash[:],
28✔
4212
                },
28✔
4213
                OutputIndex: fundingPoint.Index,
28✔
4214
        }
28✔
4215

28✔
4216
        if updateChan != nil {
42✔
4217
                upd := &lnrpc.OpenStatusUpdate{
14✔
4218
                        Update: &lnrpc.OpenStatusUpdate_ChanOpen{
14✔
4219
                                ChanOpen: &lnrpc.ChannelOpenUpdate{
14✔
4220
                                        ChannelPoint: cp,
14✔
4221
                                },
14✔
4222
                        },
14✔
4223
                        PendingChanId: pendingChanID[:],
14✔
4224
                }
14✔
4225

14✔
4226
                select {
14✔
4227
                case updateChan <- upd:
14✔
4228
                case <-f.quit:
×
4229
                        return ErrFundingManagerShuttingDown
×
4230
                }
4231
        }
4232

4233
        return nil
28✔
4234
}
4235

4236
// ensureInitialForwardingPolicy ensures that we have an initial forwarding
4237
// policy set for the given channel. If we don't, we'll fall back to the default
4238
// values.
4239
func (f *Manager) ensureInitialForwardingPolicy(chanID lnwire.ChannelID,
4240
        channel *channeldb.OpenChannel) error {
30✔
4241

30✔
4242
        // Before we can add the channel to the peer, we'll need to ensure that
30✔
4243
        // we have an initial forwarding policy set. This should always be the
30✔
4244
        // case except for a channel that was created with lnd <= 0.15.5 and
30✔
4245
        // is still pending while updating to this version.
30✔
4246
        var needDBUpdate bool
30✔
4247
        forwardingPolicy, err := f.getInitialForwardingPolicy(chanID)
30✔
4248
        if err != nil {
30✔
4249
                log.Errorf("Unable to fetch initial forwarding policy, "+
×
4250
                        "falling back to default values: %v", err)
×
4251

×
4252
                forwardingPolicy = f.defaultForwardingPolicy(
×
4253
                        channel.LocalChanCfg.ChannelStateBounds,
×
4254
                )
×
4255
                needDBUpdate = true
×
4256
        }
×
4257

4258
        // We only started storing the actual values for MinHTLCOut and MaxHTLC
4259
        // after 0.16.x, so if a channel was opened with such a version and is
4260
        // still pending while updating to this version, we'll need to set the
4261
        // values to the default values.
4262
        if forwardingPolicy.MinHTLCOut == 0 {
47✔
4263
                forwardingPolicy.MinHTLCOut = channel.LocalChanCfg.MinHTLC
17✔
4264
                needDBUpdate = true
17✔
4265
        }
17✔
4266
        if forwardingPolicy.MaxHTLC == 0 {
47✔
4267
                forwardingPolicy.MaxHTLC = channel.LocalChanCfg.MaxPendingAmount
17✔
4268
                needDBUpdate = true
17✔
4269
        }
17✔
4270

4271
        // And finally, if we found that the values currently stored aren't
4272
        // sufficient for the link, we'll update the database.
4273
        if needDBUpdate {
47✔
4274
                err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
17✔
4275
                if err != nil {
17✔
4276
                        return fmt.Errorf("unable to update initial "+
×
4277
                                "forwarding policy: %v", err)
×
4278
                }
×
4279
        }
4280

4281
        return nil
30✔
4282
}
4283

4284
// chanAnnouncement encapsulates the two authenticated announcements that we
4285
// send out to the network after a new channel has been created locally.
4286
type chanAnnouncement struct {
4287
        chanAnn       *lnwire.ChannelAnnouncement1
4288
        chanUpdateAnn *lnwire.ChannelUpdate1
4289
        chanProof     *lnwire.AnnounceSignatures1
4290
}
4291

4292
// newChanAnnouncement creates the authenticated channel announcement messages
4293
// required to broadcast a newly created channel to the network. The
4294
// announcement is two part: the first part authenticates the existence of the
4295
// channel and contains four signatures binding the funding pub keys and
4296
// identity pub keys of both parties to the channel, and the second segment is
4297
// authenticated only by us and contains our directional routing policy for the
4298
// channel. ourPolicy may be set in order to re-use an existing, non-default
4299
// policy.
4300
func (f *Manager) newChanAnnouncement(localPubKey,
4301
        remotePubKey *btcec.PublicKey, localFundingKey *keychain.KeyDescriptor,
4302
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4303
        chanID lnwire.ChannelID, fwdMinHTLC, fwdMaxHTLC lnwire.MilliSatoshi,
4304
        ourPolicy *models.ChannelEdgePolicy,
4305
        chanType channeldb.ChannelType) (*chanAnnouncement, error) {
46✔
4306

46✔
4307
        chainHash := *f.cfg.Wallet.Cfg.NetParams.GenesisHash
46✔
4308

46✔
4309
        // The unconditional section of the announcement is the ShortChannelID
46✔
4310
        // itself which compactly encodes the location of the funding output
46✔
4311
        // within the blockchain.
46✔
4312
        chanAnn := &lnwire.ChannelAnnouncement1{
46✔
4313
                ShortChannelID: shortChanID,
46✔
4314
                Features:       lnwire.NewRawFeatureVector(),
46✔
4315
                ChainHash:      chainHash,
46✔
4316
        }
46✔
4317

46✔
4318
        // If this is a taproot channel, then we'll set a special bit in the
46✔
4319
        // feature vector to indicate to the routing layer that this needs a
46✔
4320
        // slightly different type of validation.
46✔
4321
        //
46✔
4322
        // TODO(roasbeef): temp, remove after gossip 1.5
46✔
4323
        if chanType.IsTaproot() {
54✔
4324
                log.Debugf("Applying taproot feature bit to "+
8✔
4325
                        "ChannelAnnouncement for %v", chanID)
8✔
4326

8✔
4327
                chanAnn.Features.Set(
8✔
4328
                        lnwire.SimpleTaprootChannelsRequiredStaging,
8✔
4329
                )
8✔
4330
        }
8✔
4331

4332
        // The chanFlags field indicates which directed edge of the channel is
4333
        // being updated within the ChannelUpdateAnnouncement announcement
4334
        // below. A value of zero means it's the edge of the "first" node and 1
4335
        // being the other node.
4336
        var chanFlags lnwire.ChanUpdateChanFlags
46✔
4337

46✔
4338
        // The lexicographical ordering of the two identity public keys of the
46✔
4339
        // nodes indicates which of the nodes is "first". If our serialized
46✔
4340
        // identity key is lower than theirs then we're the "first" node and
46✔
4341
        // second otherwise.
46✔
4342
        selfBytes := localPubKey.SerializeCompressed()
46✔
4343
        remoteBytes := remotePubKey.SerializeCompressed()
46✔
4344
        if bytes.Compare(selfBytes, remoteBytes) == -1 {
71✔
4345
                copy(chanAnn.NodeID1[:], localPubKey.SerializeCompressed())
25✔
4346
                copy(chanAnn.NodeID2[:], remotePubKey.SerializeCompressed())
25✔
4347
                copy(
25✔
4348
                        chanAnn.BitcoinKey1[:],
25✔
4349
                        localFundingKey.PubKey.SerializeCompressed(),
25✔
4350
                )
25✔
4351
                copy(
25✔
4352
                        chanAnn.BitcoinKey2[:],
25✔
4353
                        remoteFundingKey.SerializeCompressed(),
25✔
4354
                )
25✔
4355

25✔
4356
                // If we're the first node then update the chanFlags to
25✔
4357
                // indicate the "direction" of the update.
25✔
4358
                chanFlags = 0
25✔
4359
        } else {
50✔
4360
                copy(chanAnn.NodeID1[:], remotePubKey.SerializeCompressed())
25✔
4361
                copy(chanAnn.NodeID2[:], localPubKey.SerializeCompressed())
25✔
4362
                copy(
25✔
4363
                        chanAnn.BitcoinKey1[:],
25✔
4364
                        remoteFundingKey.SerializeCompressed(),
25✔
4365
                )
25✔
4366
                copy(
25✔
4367
                        chanAnn.BitcoinKey2[:],
25✔
4368
                        localFundingKey.PubKey.SerializeCompressed(),
25✔
4369
                )
25✔
4370

25✔
4371
                // If we're the second node then update the chanFlags to
25✔
4372
                // indicate the "direction" of the update.
25✔
4373
                chanFlags = 1
25✔
4374
        }
25✔
4375

4376
        // Our channel update message flags will signal that we support the
4377
        // max_htlc field.
4378
        msgFlags := lnwire.ChanUpdateRequiredMaxHtlc
46✔
4379

46✔
4380
        // We announce the channel with the default values. Some of
46✔
4381
        // these values can later be changed by crafting a new ChannelUpdate.
46✔
4382
        chanUpdateAnn := &lnwire.ChannelUpdate1{
46✔
4383
                ShortChannelID: shortChanID,
46✔
4384
                ChainHash:      chainHash,
46✔
4385
                Timestamp:      uint32(time.Now().Unix()),
46✔
4386
                MessageFlags:   msgFlags,
46✔
4387
                ChannelFlags:   chanFlags,
46✔
4388
                TimeLockDelta: uint16(
46✔
4389
                        f.cfg.DefaultRoutingPolicy.TimeLockDelta,
46✔
4390
                ),
46✔
4391
                HtlcMinimumMsat: fwdMinHTLC,
46✔
4392
                HtlcMaximumMsat: fwdMaxHTLC,
46✔
4393
        }
46✔
4394

46✔
4395
        // The caller of newChanAnnouncement is expected to provide the initial
46✔
4396
        // forwarding policy to be announced. If no persisted initial policy
46✔
4397
        // values are found, then we will use the default policy values in the
46✔
4398
        // channel announcement.
46✔
4399
        storedFwdingPolicy, err := f.getInitialForwardingPolicy(chanID)
46✔
4400
        if err != nil && !errors.Is(err, channeldb.ErrChannelNotFound) {
46✔
4401
                return nil, errors.Errorf("unable to generate channel "+
×
4402
                        "update announcement: %v", err)
×
4403
        }
×
4404

4405
        switch {
46✔
4406
        case ourPolicy != nil:
4✔
4407
                // If ourPolicy is non-nil, modify the default parameters of the
4✔
4408
                // ChannelUpdate.
4✔
4409
                chanUpdateAnn.MessageFlags = ourPolicy.MessageFlags
4✔
4410
                chanUpdateAnn.ChannelFlags = ourPolicy.ChannelFlags
4✔
4411
                chanUpdateAnn.TimeLockDelta = ourPolicy.TimeLockDelta
4✔
4412
                chanUpdateAnn.HtlcMinimumMsat = ourPolicy.MinHTLC
4✔
4413
                chanUpdateAnn.HtlcMaximumMsat = ourPolicy.MaxHTLC
4✔
4414
                chanUpdateAnn.BaseFee = uint32(ourPolicy.FeeBaseMSat)
4✔
4415
                chanUpdateAnn.FeeRate = uint32(
4✔
4416
                        ourPolicy.FeeProportionalMillionths,
4✔
4417
                )
4✔
4418

4419
        case storedFwdingPolicy != nil:
46✔
4420
                chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
46✔
4421
                chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
46✔
4422

4423
        default:
×
4424
                log.Infof("No channel forwarding policy specified for channel "+
×
4425
                        "announcement of ChannelID(%v). "+
×
4426
                        "Assuming default fee parameters.", chanID)
×
4427
                chanUpdateAnn.BaseFee = uint32(
×
4428
                        f.cfg.DefaultRoutingPolicy.BaseFee,
×
4429
                )
×
4430
                chanUpdateAnn.FeeRate = uint32(
×
4431
                        f.cfg.DefaultRoutingPolicy.FeeRate,
×
4432
                )
×
4433
        }
4434

4435
        // With the channel update announcement constructed, we'll generate a
4436
        // signature that signs a double-sha digest of the announcement.
4437
        // This'll serve to authenticate this announcement and any other future
4438
        // updates we may send.
4439
        chanUpdateMsg, err := chanUpdateAnn.DataToSign()
46✔
4440
        if err != nil {
46✔
4441
                return nil, err
×
4442
        }
×
4443
        sig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanUpdateMsg, true)
46✔
4444
        if err != nil {
46✔
4445
                return nil, errors.Errorf("unable to generate channel "+
×
4446
                        "update announcement signature: %v", err)
×
4447
        }
×
4448
        chanUpdateAnn.Signature, err = lnwire.NewSigFromSignature(sig)
46✔
4449
        if err != nil {
46✔
4450
                return nil, errors.Errorf("unable to generate channel "+
×
4451
                        "update announcement signature: %v", err)
×
4452
        }
×
4453

4454
        // The channel existence proofs itself is currently announced in
4455
        // distinct message. In order to properly authenticate this message, we
4456
        // need two signatures: one under the identity public key used which
4457
        // signs the message itself and another signature of the identity
4458
        // public key under the funding key itself.
4459
        //
4460
        // TODO(roasbeef): use SignAnnouncement here instead?
4461
        chanAnnMsg, err := chanAnn.DataToSign()
46✔
4462
        if err != nil {
46✔
4463
                return nil, err
×
4464
        }
×
4465
        nodeSig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanAnnMsg, true)
46✔
4466
        if err != nil {
46✔
4467
                return nil, errors.Errorf("unable to generate node "+
×
4468
                        "signature for channel announcement: %v", err)
×
4469
        }
×
4470
        bitcoinSig, err := f.cfg.SignMessage(
46✔
4471
                localFundingKey.KeyLocator, chanAnnMsg, true,
46✔
4472
        )
46✔
4473
        if err != nil {
46✔
4474
                return nil, errors.Errorf("unable to generate bitcoin "+
×
4475
                        "signature for node public key: %v", err)
×
4476
        }
×
4477

4478
        // Finally, we'll generate the announcement proof which we'll use to
4479
        // provide the other side with the necessary signatures required to
4480
        // allow them to reconstruct the full channel announcement.
4481
        proof := &lnwire.AnnounceSignatures1{
46✔
4482
                ChannelID:      chanID,
46✔
4483
                ShortChannelID: shortChanID,
46✔
4484
        }
46✔
4485
        proof.NodeSignature, err = lnwire.NewSigFromSignature(nodeSig)
46✔
4486
        if err != nil {
46✔
4487
                return nil, err
×
4488
        }
×
4489
        proof.BitcoinSignature, err = lnwire.NewSigFromSignature(bitcoinSig)
46✔
4490
        if err != nil {
46✔
4491
                return nil, err
×
4492
        }
×
4493

4494
        return &chanAnnouncement{
46✔
4495
                chanAnn:       chanAnn,
46✔
4496
                chanUpdateAnn: chanUpdateAnn,
46✔
4497
                chanProof:     proof,
46✔
4498
        }, nil
46✔
4499
}
4500

4501
// announceChannel announces a newly created channel to the rest of the network
4502
// by crafting the two authenticated announcements required for the peers on
4503
// the network to recognize the legitimacy of the channel. The crafted
4504
// announcements are then sent to the channel router to handle broadcasting to
4505
// the network during its next trickle.
4506
// This method is synchronous and will return when all the network requests
4507
// finish, either successfully or with an error.
4508
func (f *Manager) announceChannel(localIDKey, remoteIDKey *btcec.PublicKey,
4509
        localFundingKey *keychain.KeyDescriptor,
4510
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4511
        chanID lnwire.ChannelID, chanType channeldb.ChannelType) error {
20✔
4512

20✔
4513
        // First, we'll create the batch of announcements to be sent upon
20✔
4514
        // initial channel creation. This includes the channel announcement
20✔
4515
        // itself, the channel update announcement, and our half of the channel
20✔
4516
        // proof needed to fully authenticate the channel.
20✔
4517
        //
20✔
4518
        // We can pass in zeroes for the min and max htlc policy, because we
20✔
4519
        // only use the channel announcement message from the returned struct.
20✔
4520
        ann, err := f.newChanAnnouncement(
20✔
4521
                localIDKey, remoteIDKey, localFundingKey, remoteFundingKey,
20✔
4522
                shortChanID, chanID, 0, 0, nil, chanType,
20✔
4523
        )
20✔
4524
        if err != nil {
20✔
4525
                log.Errorf("can't generate channel announcement: %v", err)
×
4526
                return err
×
4527
        }
×
4528

4529
        // We only send the channel proof announcement and the node announcement
4530
        // because addToGraph previously sent the ChannelAnnouncement and
4531
        // the ChannelUpdate announcement messages. The channel proof and node
4532
        // announcements are broadcast to the greater network.
4533
        errChan := f.cfg.SendAnnouncement(ann.chanProof)
20✔
4534
        select {
20✔
4535
        case err := <-errChan:
20✔
4536
                if err != nil {
24✔
4537
                        if graph.IsError(err, graph.ErrOutdated,
4✔
4538
                                graph.ErrIgnored) {
4✔
4539

×
4540
                                log.Debugf("Graph rejected "+
×
4541
                                        "AnnounceSignatures: %v", err)
×
4542
                        } else {
4✔
4543
                                log.Errorf("Unable to send channel "+
4✔
4544
                                        "proof: %v", err)
4✔
4545
                                return err
4✔
4546
                        }
4✔
4547
                }
4548

4549
        case <-f.quit:
×
4550
                return ErrFundingManagerShuttingDown
×
4551
        }
4552

4553
        // Now that the channel is announced to the network, we will also
4554
        // obtain and send a node announcement. This is done since a node
4555
        // announcement is only accepted after a channel is known for that
4556
        // particular node, and this might be our first channel.
4557
        nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
20✔
4558
        if err != nil {
20✔
4559
                log.Errorf("can't generate node announcement: %v", err)
×
4560
                return err
×
4561
        }
×
4562

4563
        errChan = f.cfg.SendAnnouncement(&nodeAnn)
20✔
4564
        select {
20✔
4565
        case err := <-errChan:
20✔
4566
                if err != nil {
23✔
4567
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4568
                                graph.ErrIgnored) {
6✔
4569

3✔
4570
                                log.Debugf("Graph rejected "+
3✔
4571
                                        "NodeAnnouncement: %v", err)
3✔
4572
                        } else {
3✔
4573
                                log.Errorf("Unable to send node "+
×
4574
                                        "announcement: %v", err)
×
4575
                                return err
×
4576
                        }
×
4577
                }
4578

4579
        case <-f.quit:
×
4580
                return ErrFundingManagerShuttingDown
×
4581
        }
4582

4583
        return nil
20✔
4584
}
4585

4586
// InitFundingWorkflow sends a message to the funding manager instructing it
4587
// to initiate a single funder workflow with the source peer.
4588
func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg) {
60✔
4589
        f.fundingRequests <- msg
60✔
4590
}
60✔
4591

4592
// getUpfrontShutdownScript takes a user provided script and a getScript
4593
// function which can be used to generate an upfront shutdown script. If our
4594
// peer does not support the feature, this function will error if a non-zero
4595
// script was provided by the user, and return an empty script otherwise. If
4596
// our peer does support the feature, we will return the user provided script
4597
// if non-zero, or a freshly generated script if our node is configured to set
4598
// upfront shutdown scripts automatically.
4599
func getUpfrontShutdownScript(enableUpfrontShutdown bool, peer lnpeer.Peer,
4600
        script lnwire.DeliveryAddress,
4601
        getScript func(bool) (lnwire.DeliveryAddress, error)) (lnwire.DeliveryAddress,
4602
        error) {
112✔
4603

112✔
4604
        // Check whether the remote peer supports upfront shutdown scripts.
112✔
4605
        remoteUpfrontShutdown := peer.RemoteFeatures().HasFeature(
112✔
4606
                lnwire.UpfrontShutdownScriptOptional,
112✔
4607
        )
112✔
4608

112✔
4609
        // If the peer does not support upfront shutdown scripts, and one has been
112✔
4610
        // provided, return an error because the feature is not supported.
112✔
4611
        if !remoteUpfrontShutdown && len(script) != 0 {
113✔
4612
                return nil, errUpfrontShutdownScriptNotSupported
1✔
4613
        }
1✔
4614

4615
        // If the peer does not support upfront shutdown, return an empty address.
4616
        if !remoteUpfrontShutdown {
214✔
4617
                return nil, nil
103✔
4618
        }
103✔
4619

4620
        // If the user has provided an script and the peer supports the feature,
4621
        // return it. Note that user set scripts override the enable upfront
4622
        // shutdown flag.
4623
        if len(script) > 0 {
14✔
4624
                return script, nil
6✔
4625
        }
6✔
4626

4627
        // If we do not have setting of upfront shutdown script enabled, return
4628
        // an empty script.
4629
        if !enableUpfrontShutdown {
11✔
4630
                return nil, nil
5✔
4631
        }
5✔
4632

4633
        // We can safely send a taproot address iff, both sides have negotiated
4634
        // the shutdown-any-segwit feature.
4635
        taprootOK := peer.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
1✔
4636
                peer.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
1✔
4637

1✔
4638
        return getScript(taprootOK)
1✔
4639
}
4640

4641
// handleInitFundingMsg creates a channel reservation within the daemon's
4642
// wallet, then sends a funding request to the remote peer kicking off the
4643
// funding workflow.
4644
func (f *Manager) handleInitFundingMsg(msg *InitFundingMsg) {
60✔
4645
        var (
60✔
4646
                peerKey        = msg.Peer.IdentityKey()
60✔
4647
                localAmt       = msg.LocalFundingAmt
60✔
4648
                baseFee        = msg.BaseFee
60✔
4649
                feeRate        = msg.FeeRate
60✔
4650
                minHtlcIn      = msg.MinHtlcIn
60✔
4651
                remoteCsvDelay = msg.RemoteCsvDelay
60✔
4652
                maxValue       = msg.MaxValueInFlight
60✔
4653
                maxHtlcs       = msg.MaxHtlcs
60✔
4654
                maxCSV         = msg.MaxLocalCsv
60✔
4655
                chanReserve    = msg.RemoteChanReserve
60✔
4656
                outpoints      = msg.Outpoints
60✔
4657
        )
60✔
4658

60✔
4659
        // If no maximum CSV delay was set for this channel, we use our default
60✔
4660
        // value.
60✔
4661
        if maxCSV == 0 {
120✔
4662
                maxCSV = f.cfg.MaxLocalCSVDelay
60✔
4663
        }
60✔
4664

4665
        log.Infof("Initiating fundingRequest(local_amt=%v "+
60✔
4666
                "(subtract_fees=%v), push_amt=%v, chain_hash=%v, peer=%x, "+
60✔
4667
                "min_confs=%v)", localAmt, msg.SubtractFees, msg.PushAmt,
60✔
4668
                msg.ChainHash, peerKey.SerializeCompressed(), msg.MinConfs)
60✔
4669

60✔
4670
        // We set the channel flags to indicate whether we want this channel to
60✔
4671
        // be announced to the network.
60✔
4672
        var channelFlags lnwire.FundingFlag
60✔
4673
        if !msg.Private {
115✔
4674
                // This channel will be announced.
55✔
4675
                channelFlags = lnwire.FFAnnounceChannel
55✔
4676
        }
55✔
4677

4678
        // If the caller specified their own channel ID, then we'll use that.
4679
        // Otherwise we'll generate a fresh one as normal.  This will be used
4680
        // to track this reservation throughout its lifetime.
4681
        var chanID PendingChanID
60✔
4682
        if msg.PendingChanID == zeroID {
120✔
4683
                chanID = f.nextPendingChanID()
60✔
4684
        } else {
64✔
4685
                // If the user specified their own pending channel ID, then
4✔
4686
                // we'll ensure it doesn't collide with any existing pending
4✔
4687
                // channel ID.
4✔
4688
                chanID = msg.PendingChanID
4✔
4689
                if _, err := f.getReservationCtx(peerKey, chanID); err == nil {
4✔
4690
                        msg.Err <- fmt.Errorf("pendingChannelID(%x) "+
×
4691
                                "already present", chanID[:])
×
4692
                        return
×
4693
                }
×
4694
        }
4695

4696
        // Check whether the peer supports upfront shutdown, and get an address
4697
        // which should be used (either a user specified address or a new
4698
        // address from the wallet if our node is configured to set shutdown
4699
        // address by default).
4700
        shutdown, err := getUpfrontShutdownScript(
60✔
4701
                f.cfg.EnableUpfrontShutdown, msg.Peer, msg.ShutdownScript,
60✔
4702
                f.selectShutdownScript,
60✔
4703
        )
60✔
4704
        if err != nil {
60✔
4705
                msg.Err <- err
×
4706
                return
×
4707
        }
×
4708

4709
        // Initialize a funding reservation with the local wallet. If the
4710
        // wallet doesn't have enough funds to commit to this channel, then the
4711
        // request will fail, and be aborted.
4712
        //
4713
        // Before we init the channel, we'll also check to see what commitment
4714
        // format we can use with this peer. This is dependent on *both* us and
4715
        // the remote peer are signaling the proper feature bit.
4716
        chanType, commitType, err := negotiateCommitmentType(
60✔
4717
                msg.ChannelType, msg.Peer.LocalFeatures(),
60✔
4718
                msg.Peer.RemoteFeatures(),
60✔
4719
        )
60✔
4720
        if err != nil {
64✔
4721
                log.Errorf("channel type negotiation failed: %v", err)
4✔
4722
                msg.Err <- err
4✔
4723
                return
4✔
4724
        }
4✔
4725

4726
        var (
60✔
4727
                zeroConf bool
60✔
4728
                scid     bool
60✔
4729
        )
60✔
4730

60✔
4731
        if chanType != nil {
68✔
4732
                // Check if the returned chanType includes either the zero-conf
8✔
4733
                // or scid-alias bits.
8✔
4734
                featureVec := lnwire.RawFeatureVector(*chanType)
8✔
4735
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
8✔
4736
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
8✔
4737

8✔
4738
                // The option-scid-alias channel type for a public channel is
8✔
4739
                // disallowed.
8✔
4740
                if scid && !msg.Private {
8✔
4741
                        err = fmt.Errorf("option-scid-alias chantype for " +
×
4742
                                "public channel")
×
4743
                        log.Error(err)
×
4744
                        msg.Err <- err
×
4745

×
4746
                        return
×
4747
                }
×
4748
        }
4749

4750
        // First, we'll query the fee estimator for a fee that should get the
4751
        // commitment transaction confirmed by the next few blocks (conf target
4752
        // of 3). We target the near blocks here to ensure that we'll be able
4753
        // to execute a timely unilateral channel closure if needed.
4754
        commitFeePerKw, err := f.cfg.FeeEstimator.EstimateFeePerKW(3)
60✔
4755
        if err != nil {
60✔
4756
                msg.Err <- err
×
4757
                return
×
4758
        }
×
4759

4760
        // For anchor channels cap the initial commit fee rate at our defined
4761
        // maximum.
4762
        if commitType.HasAnchors() &&
60✔
4763
                commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
68✔
4764

8✔
4765
                commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate
8✔
4766
        }
8✔
4767

4768
        var scidFeatureVal bool
60✔
4769
        if hasFeatures(
60✔
4770
                msg.Peer.LocalFeatures(), msg.Peer.RemoteFeatures(),
60✔
4771
                lnwire.ScidAliasOptional,
60✔
4772
        ) {
67✔
4773

7✔
4774
                scidFeatureVal = true
7✔
4775
        }
7✔
4776

4777
        // At this point, if we have an AuxFundingController active, we'll check
4778
        // to see if we have a special tapscript root to use in our MuSig2
4779
        // funding output.
4780
        tapscriptRoot, err := fn.MapOptionZ(
60✔
4781
                f.cfg.AuxFundingController,
60✔
4782
                func(c AuxFundingController) AuxTapscriptResult {
60✔
4783
                        return c.DeriveTapscriptRoot(chanID)
×
4784
                },
×
4785
        ).Unpack()
4786
        if err != nil {
60✔
4787
                err = fmt.Errorf("error deriving tapscript root: %w", err)
×
4788
                log.Error(err)
×
4789
                msg.Err <- err
×
4790

×
4791
                return
×
4792
        }
×
4793

4794
        req := &lnwallet.InitFundingReserveMsg{
60✔
4795
                ChainHash:         &msg.ChainHash,
60✔
4796
                PendingChanID:     chanID,
60✔
4797
                NodeID:            peerKey,
60✔
4798
                NodeAddr:          msg.Peer.Address(),
60✔
4799
                SubtractFees:      msg.SubtractFees,
60✔
4800
                LocalFundingAmt:   localAmt,
60✔
4801
                RemoteFundingAmt:  0,
60✔
4802
                FundUpToMaxAmt:    msg.FundUpToMaxAmt,
60✔
4803
                MinFundAmt:        msg.MinFundAmt,
60✔
4804
                RemoteChanReserve: chanReserve,
60✔
4805
                Outpoints:         outpoints,
60✔
4806
                CommitFeePerKw:    commitFeePerKw,
60✔
4807
                FundingFeePerKw:   msg.FundingFeePerKw,
60✔
4808
                PushMSat:          msg.PushAmt,
60✔
4809
                Flags:             channelFlags,
60✔
4810
                MinConfs:          msg.MinConfs,
60✔
4811
                CommitType:        commitType,
60✔
4812
                ChanFunder:        msg.ChanFunder,
60✔
4813
                // Unconfirmed Utxos which are marked by the sweeper subsystem
60✔
4814
                // are excluded from the coin selection because they are not
60✔
4815
                // final and can be RBFed by the sweeper subsystem.
60✔
4816
                AllowUtxoForFunding: func(u lnwallet.Utxo) bool {
121✔
4817
                        // Utxos with at least 1 confirmation are safe to use
61✔
4818
                        // for channel openings because they don't bare the risk
61✔
4819
                        // of being replaced (BIP 125 RBF).
61✔
4820
                        if u.Confirmations > 0 {
65✔
4821
                                return true
4✔
4822
                        }
4✔
4823

4824
                        // Query the sweeper storage to make sure we don't use
4825
                        // an unconfirmed utxo still in use by the sweeper
4826
                        // subsystem.
4827
                        return !f.cfg.IsSweeperOutpoint(u.OutPoint)
61✔
4828
                },
4829
                ZeroConf:         zeroConf,
4830
                OptionScidAlias:  scid,
4831
                ScidAliasFeature: scidFeatureVal,
4832
                Memo:             msg.Memo,
4833
                TapscriptRoot:    tapscriptRoot,
4834
        }
4835

4836
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
60✔
4837
        if err != nil {
64✔
4838
                msg.Err <- err
4✔
4839
                return
4✔
4840
        }
4✔
4841

4842
        if zeroConf {
66✔
4843
                // Store the alias for zero-conf channels in the underlying
6✔
4844
                // partial channel state.
6✔
4845
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
6✔
4846
                if err != nil {
6✔
4847
                        msg.Err <- err
×
4848
                        return
×
4849
                }
×
4850

4851
                reservation.AddAlias(aliasScid)
6✔
4852
        }
4853

4854
        // Set our upfront shutdown address in the existing reservation.
4855
        reservation.SetOurUpfrontShutdown(shutdown)
60✔
4856

60✔
4857
        // Now that we have successfully reserved funds for this channel in the
60✔
4858
        // wallet, we can fetch the final channel capacity. This is done at
60✔
4859
        // this point since the final capacity might change in case of
60✔
4860
        // SubtractFees=true.
60✔
4861
        capacity := reservation.Capacity()
60✔
4862

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

60✔
4866
        // If the remote CSV delay was not set in the open channel request,
60✔
4867
        // we'll use the RequiredRemoteDelay closure to compute the delay we
60✔
4868
        // require given the total amount of funds within the channel.
60✔
4869
        if remoteCsvDelay == 0 {
119✔
4870
                remoteCsvDelay = f.cfg.RequiredRemoteDelay(capacity)
59✔
4871
        }
59✔
4872

4873
        // If no minimum HTLC value was specified, use the default one.
4874
        if minHtlcIn == 0 {
119✔
4875
                minHtlcIn = f.cfg.DefaultMinHtlcIn
59✔
4876
        }
59✔
4877

4878
        // If no max value was specified, use the default one.
4879
        if maxValue == 0 {
119✔
4880
                maxValue = f.cfg.RequiredRemoteMaxValue(capacity)
59✔
4881
        }
59✔
4882

4883
        if maxHtlcs == 0 {
120✔
4884
                maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
60✔
4885
        }
60✔
4886

4887
        // Once the reservation has been created, and indexed, queue a funding
4888
        // request to the remote peer, kicking off the funding workflow.
4889
        ourContribution := reservation.OurContribution()
60✔
4890

60✔
4891
        // Prepare the optional channel fee values from the initFundingMsg. If
60✔
4892
        // useBaseFee or useFeeRate are false the client did not provide fee
60✔
4893
        // values hence we assume default fee settings from the config.
60✔
4894
        forwardingPolicy := f.defaultForwardingPolicy(
60✔
4895
                ourContribution.ChannelStateBounds,
60✔
4896
        )
60✔
4897
        if baseFee != nil {
65✔
4898
                forwardingPolicy.BaseFee = lnwire.MilliSatoshi(*baseFee)
5✔
4899
        }
5✔
4900

4901
        if feeRate != nil {
65✔
4902
                forwardingPolicy.FeeRate = lnwire.MilliSatoshi(*feeRate)
5✔
4903
        }
5✔
4904

4905
        // Fetch our dust limit which is part of the default channel
4906
        // constraints, and log it.
4907
        ourDustLimit := ourContribution.DustLimit
60✔
4908

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

60✔
4911
        // If the channel reserve is not specified, then we calculate an
60✔
4912
        // appropriate amount here.
60✔
4913
        if chanReserve == 0 {
116✔
4914
                chanReserve = f.cfg.RequiredRemoteChanReserve(
56✔
4915
                        capacity, ourDustLimit,
56✔
4916
                )
56✔
4917
        }
56✔
4918

4919
        // If a pending channel map for this peer isn't already created, then
4920
        // we create one, ultimately allowing us to track this pending
4921
        // reservation within the target peer.
4922
        peerIDKey := newSerializedKey(peerKey)
60✔
4923
        f.resMtx.Lock()
60✔
4924
        if _, ok := f.activeReservations[peerIDKey]; !ok {
113✔
4925
                f.activeReservations[peerIDKey] = make(pendingChannels)
53✔
4926
        }
53✔
4927

4928
        resCtx := &reservationWithCtx{
60✔
4929
                chanAmt:           capacity,
60✔
4930
                forwardingPolicy:  *forwardingPolicy,
60✔
4931
                remoteCsvDelay:    remoteCsvDelay,
60✔
4932
                remoteMinHtlc:     minHtlcIn,
60✔
4933
                remoteMaxValue:    maxValue,
60✔
4934
                remoteMaxHtlcs:    maxHtlcs,
60✔
4935
                remoteChanReserve: chanReserve,
60✔
4936
                maxLocalCsv:       maxCSV,
60✔
4937
                channelType:       chanType,
60✔
4938
                reservation:       reservation,
60✔
4939
                peer:              msg.Peer,
60✔
4940
                updates:           msg.Updates,
60✔
4941
                err:               msg.Err,
60✔
4942
        }
60✔
4943
        f.activeReservations[peerIDKey][chanID] = resCtx
60✔
4944
        f.resMtx.Unlock()
60✔
4945

60✔
4946
        // Update the timestamp once the InitFundingMsg has been handled.
60✔
4947
        defer resCtx.updateTimestamp()
60✔
4948

60✔
4949
        // Check the sanity of the selected channel constraints.
60✔
4950
        bounds := &channeldb.ChannelStateBounds{
60✔
4951
                ChanReserve:      chanReserve,
60✔
4952
                MaxPendingAmount: maxValue,
60✔
4953
                MinHTLC:          minHtlcIn,
60✔
4954
                MaxAcceptedHtlcs: maxHtlcs,
60✔
4955
        }
60✔
4956
        commitParams := &channeldb.CommitmentParams{
60✔
4957
                DustLimit: ourDustLimit,
60✔
4958
                CsvDelay:  remoteCsvDelay,
60✔
4959
        }
60✔
4960
        err = lnwallet.VerifyConstraints(
60✔
4961
                bounds, commitParams, resCtx.maxLocalCsv, capacity,
60✔
4962
        )
60✔
4963
        if err != nil {
62✔
4964
                _, reserveErr := f.cancelReservationCtx(peerKey, chanID, false)
2✔
4965
                if reserveErr != nil {
2✔
4966
                        log.Errorf("unable to cancel reservation: %v",
×
4967
                                reserveErr)
×
4968
                }
×
4969

4970
                msg.Err <- err
2✔
4971
                return
2✔
4972
        }
4973

4974
        // When opening a script enforced channel lease, include the required
4975
        // expiry TLV record in our proposal.
4976
        var leaseExpiry *lnwire.LeaseExpiry
58✔
4977
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
62✔
4978
                leaseExpiry = new(lnwire.LeaseExpiry)
4✔
4979
                *leaseExpiry = lnwire.LeaseExpiry(reservation.LeaseExpiry())
4✔
4980
        }
4✔
4981

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

58✔
4985
        reservation.SetState(lnwallet.SentOpenChannel)
58✔
4986

58✔
4987
        fundingOpen := lnwire.OpenChannel{
58✔
4988
                ChainHash:             *f.cfg.Wallet.Cfg.NetParams.GenesisHash,
58✔
4989
                PendingChannelID:      chanID,
58✔
4990
                FundingAmount:         capacity,
58✔
4991
                PushAmount:            msg.PushAmt,
58✔
4992
                DustLimit:             ourDustLimit,
58✔
4993
                MaxValueInFlight:      maxValue,
58✔
4994
                ChannelReserve:        chanReserve,
58✔
4995
                HtlcMinimum:           minHtlcIn,
58✔
4996
                FeePerKiloWeight:      uint32(commitFeePerKw),
58✔
4997
                CsvDelay:              remoteCsvDelay,
58✔
4998
                MaxAcceptedHTLCs:      maxHtlcs,
58✔
4999
                FundingKey:            ourContribution.MultiSigKey.PubKey,
58✔
5000
                RevocationPoint:       ourContribution.RevocationBasePoint.PubKey,
58✔
5001
                PaymentPoint:          ourContribution.PaymentBasePoint.PubKey,
58✔
5002
                HtlcPoint:             ourContribution.HtlcBasePoint.PubKey,
58✔
5003
                DelayedPaymentPoint:   ourContribution.DelayBasePoint.PubKey,
58✔
5004
                FirstCommitmentPoint:  ourContribution.FirstCommitmentPoint,
58✔
5005
                ChannelFlags:          channelFlags,
58✔
5006
                UpfrontShutdownScript: shutdown,
58✔
5007
                ChannelType:           chanType,
58✔
5008
                LeaseExpiry:           leaseExpiry,
58✔
5009
        }
58✔
5010

58✔
5011
        if commitType.IsTaproot() {
64✔
5012
                fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
6✔
5013
                        ourContribution.LocalNonce.PubNonce,
6✔
5014
                )
6✔
5015
        }
6✔
5016

5017
        if err := msg.Peer.SendMessage(true, &fundingOpen); err != nil {
58✔
5018
                e := fmt.Errorf("unable to send funding request message: %w",
×
5019
                        err)
×
5020
                log.Errorf(e.Error())
×
5021

×
5022
                // Since we were unable to send the initial message to the peer
×
5023
                // and start the funding flow, we'll cancel this reservation.
×
5024
                _, err := f.cancelReservationCtx(peerKey, chanID, false)
×
5025
                if err != nil {
×
5026
                        log.Errorf("unable to cancel reservation: %v", err)
×
5027
                }
×
5028

5029
                msg.Err <- e
×
5030
                return
×
5031
        }
5032
}
5033

5034
// handleWarningMsg processes the warning which was received from remote peer.
5035
func (f *Manager) handleWarningMsg(peer lnpeer.Peer, msg *lnwire.Warning) {
42✔
5036
        log.Warnf("received warning message from peer %x: %v",
42✔
5037
                peer.IdentityKey().SerializeCompressed(), msg.Warning())
42✔
5038
}
42✔
5039

5040
// handleErrorMsg processes the error which was received from remote peer,
5041
// depending on the type of error we should do different clean up steps and
5042
// inform the user about it.
5043
func (f *Manager) handleErrorMsg(peer lnpeer.Peer, msg *lnwire.Error) {
4✔
5044
        chanID := msg.ChanID
4✔
5045
        peerKey := peer.IdentityKey()
4✔
5046

4✔
5047
        // First, we'll attempt to retrieve and cancel the funding workflow
4✔
5048
        // that this error was tied to. If we're unable to do so, then we'll
4✔
5049
        // exit early as this was an unwarranted error.
4✔
5050
        resCtx, err := f.cancelReservationCtx(peerKey, chanID, true)
4✔
5051
        if err != nil {
4✔
5052
                log.Warnf("Received error for non-existent funding "+
×
5053
                        "flow: %v (%v)", err, msg.Error())
×
5054
                return
×
5055
        }
×
5056

5057
        // If we did indeed find the funding workflow, then we'll return the
5058
        // error back to the caller (if any), and cancel the workflow itself.
5059
        fundingErr := fmt.Errorf("received funding error from %x: %v",
4✔
5060
                peerKey.SerializeCompressed(), msg.Error(),
4✔
5061
        )
4✔
5062
        log.Errorf(fundingErr.Error())
4✔
5063

4✔
5064
        // If this was a PSBT funding flow, the remote likely timed out because
4✔
5065
        // we waited too long. Return a nice error message to the user in that
4✔
5066
        // case so the user knows what's the problem.
4✔
5067
        if resCtx.reservation.IsPsbt() {
8✔
5068
                fundingErr = fmt.Errorf("%w: %v", chanfunding.ErrRemoteCanceled,
4✔
5069
                        fundingErr)
4✔
5070
        }
4✔
5071

5072
        resCtx.err <- fundingErr
4✔
5073
}
5074

5075
// pruneZombieReservations loops through all pending reservations and fails the
5076
// funding flow for any reservations that have not been updated since the
5077
// ReservationTimeout and are not locked waiting for the funding transaction.
5078
func (f *Manager) pruneZombieReservations() {
7✔
5079
        zombieReservations := make(pendingChannels)
7✔
5080

7✔
5081
        f.resMtx.RLock()
7✔
5082
        for _, pendingReservations := range f.activeReservations {
14✔
5083
                for pendingChanID, resCtx := range pendingReservations {
14✔
5084
                        if resCtx.isLocked() {
7✔
5085
                                continue
×
5086
                        }
5087

5088
                        // We don't want to expire PSBT funding reservations.
5089
                        // These reservations are always initiated by us and the
5090
                        // remote peer is likely going to cancel them after some
5091
                        // idle time anyway. So no need for us to also prune
5092
                        // them.
5093
                        sinceLastUpdate := time.Since(resCtx.lastUpdated)
7✔
5094
                        isExpired := sinceLastUpdate > f.cfg.ReservationTimeout
7✔
5095
                        if !resCtx.reservation.IsPsbt() && isExpired {
14✔
5096
                                zombieReservations[pendingChanID] = resCtx
7✔
5097
                        }
7✔
5098
                }
5099
        }
5100
        f.resMtx.RUnlock()
7✔
5101

7✔
5102
        for pendingChanID, resCtx := range zombieReservations {
14✔
5103
                err := fmt.Errorf("reservation timed out waiting for peer "+
7✔
5104
                        "(peer_id:%x, chan_id:%x)",
7✔
5105
                        resCtx.peer.IdentityKey().SerializeCompressed(),
7✔
5106
                        pendingChanID[:])
7✔
5107
                log.Warnf(err.Error())
7✔
5108

7✔
5109
                chanID := lnwire.NewChanIDFromOutPoint(
7✔
5110
                        *resCtx.reservation.FundingOutpoint(),
7✔
5111
                )
7✔
5112

7✔
5113
                // Create channel identifier and set the channel ID.
7✔
5114
                cid := newChanIdentifier(pendingChanID)
7✔
5115
                cid.setChanID(chanID)
7✔
5116

7✔
5117
                f.failFundingFlow(resCtx.peer, cid, err)
7✔
5118
        }
7✔
5119
}
5120

5121
// cancelReservationCtx does all needed work in order to securely cancel the
5122
// reservation.
5123
func (f *Manager) cancelReservationCtx(peerKey *btcec.PublicKey,
5124
        pendingChanID PendingChanID,
5125
        byRemote bool) (*reservationWithCtx, error) {
27✔
5126

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

27✔
5130
        peerIDKey := newSerializedKey(peerKey)
27✔
5131
        f.resMtx.Lock()
27✔
5132
        defer f.resMtx.Unlock()
27✔
5133

27✔
5134
        nodeReservations, ok := f.activeReservations[peerIDKey]
27✔
5135
        if !ok {
38✔
5136
                // No reservations for this node.
11✔
5137
                return nil, errors.Errorf("no active reservations for peer(%x)",
11✔
5138
                        peerIDKey[:])
11✔
5139
        }
11✔
5140

5141
        ctx, ok := nodeReservations[pendingChanID]
20✔
5142
        if !ok {
22✔
5143
                return nil, errors.Errorf("unknown channel (id: %x) for "+
2✔
5144
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
2✔
5145
        }
2✔
5146

5147
        // If the reservation was a PSBT funding flow and it was canceled by the
5148
        // remote peer, then we need to thread through a different error message
5149
        // to the subroutine that's waiting for the user input so it can return
5150
        // a nice error message to the user.
5151
        if ctx.reservation.IsPsbt() && byRemote {
22✔
5152
                ctx.reservation.RemoteCanceled()
4✔
5153
        }
4✔
5154

5155
        if err := ctx.reservation.Cancel(); err != nil {
18✔
5156
                return nil, errors.Errorf("unable to cancel reservation: %v",
×
5157
                        err)
×
5158
        }
×
5159

5160
        delete(nodeReservations, pendingChanID)
18✔
5161

18✔
5162
        // If this was the last active reservation for this peer, delete the
18✔
5163
        // peer's entry altogether.
18✔
5164
        if len(nodeReservations) == 0 {
36✔
5165
                delete(f.activeReservations, peerIDKey)
18✔
5166
        }
18✔
5167
        return ctx, nil
18✔
5168
}
5169

5170
// deleteReservationCtx deletes the reservation uniquely identified by the
5171
// target public key of the peer, and the specified pending channel ID.
5172
func (f *Manager) deleteReservationCtx(peerKey *btcec.PublicKey,
5173
        pendingChanID PendingChanID) {
58✔
5174

58✔
5175
        peerIDKey := newSerializedKey(peerKey)
58✔
5176
        f.resMtx.Lock()
58✔
5177
        defer f.resMtx.Unlock()
58✔
5178

58✔
5179
        nodeReservations, ok := f.activeReservations[peerIDKey]
58✔
5180
        if !ok {
58✔
5181
                // No reservations for this node.
×
5182
                return
×
5183
        }
×
5184
        delete(nodeReservations, pendingChanID)
58✔
5185

58✔
5186
        // If this was the last active reservation for this peer, delete the
58✔
5187
        // peer's entry altogether.
58✔
5188
        if len(nodeReservations) == 0 {
109✔
5189
                delete(f.activeReservations, peerIDKey)
51✔
5190
        }
51✔
5191
}
5192

5193
// getReservationCtx returns the reservation context for a particular pending
5194
// channel ID for a target peer.
5195
func (f *Manager) getReservationCtx(peerKey *btcec.PublicKey,
5196
        pendingChanID PendingChanID) (*reservationWithCtx, error) {
92✔
5197

92✔
5198
        peerIDKey := newSerializedKey(peerKey)
92✔
5199
        f.resMtx.RLock()
92✔
5200
        resCtx, ok := f.activeReservations[peerIDKey][pendingChanID]
92✔
5201
        f.resMtx.RUnlock()
92✔
5202

92✔
5203
        if !ok {
96✔
5204
                return nil, errors.Errorf("unknown channel (id: %x) for "+
4✔
5205
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
4✔
5206
        }
4✔
5207

5208
        return resCtx, nil
92✔
5209
}
5210

5211
// IsPendingChannel returns a boolean indicating whether the channel identified
5212
// by the pendingChanID and given peer is pending, meaning it is in the process
5213
// of being funded. After the funding transaction has been confirmed, the
5214
// channel will receive a new, permanent channel ID, and will no longer be
5215
// considered pending.
5216
func (f *Manager) IsPendingChannel(pendingChanID PendingChanID,
5217
        peer lnpeer.Peer) bool {
4✔
5218

4✔
5219
        peerIDKey := newSerializedKey(peer.IdentityKey())
4✔
5220
        f.resMtx.RLock()
4✔
5221
        _, ok := f.activeReservations[peerIDKey][pendingChanID]
4✔
5222
        f.resMtx.RUnlock()
4✔
5223

4✔
5224
        return ok
4✔
5225
}
4✔
5226

5227
func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
379✔
5228
        var tmp btcec.JacobianPoint
379✔
5229
        pub.AsJacobian(&tmp)
379✔
5230
        tmp.ToAffine()
379✔
5231
        return btcec.NewPublicKey(&tmp.X, &tmp.Y)
379✔
5232
}
379✔
5233

5234
// defaultForwardingPolicy returns the default forwarding policy based on the
5235
// default routing policy and our local channel constraints.
5236
func (f *Manager) defaultForwardingPolicy(
5237
        bounds channeldb.ChannelStateBounds) *models.ForwardingPolicy {
106✔
5238

106✔
5239
        return &models.ForwardingPolicy{
106✔
5240
                MinHTLCOut:    bounds.MinHTLC,
106✔
5241
                MaxHTLC:       bounds.MaxPendingAmount,
106✔
5242
                BaseFee:       f.cfg.DefaultRoutingPolicy.BaseFee,
106✔
5243
                FeeRate:       f.cfg.DefaultRoutingPolicy.FeeRate,
106✔
5244
                TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
106✔
5245
        }
106✔
5246
}
106✔
5247

5248
// saveInitialForwardingPolicy saves the forwarding policy for the provided
5249
// chanPoint in the channelOpeningStateBucket.
5250
func (f *Manager) saveInitialForwardingPolicy(chanID lnwire.ChannelID,
5251
        forwardingPolicy *models.ForwardingPolicy) error {
71✔
5252

71✔
5253
        return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
71✔
5254
                chanID, forwardingPolicy,
71✔
5255
        )
71✔
5256
}
71✔
5257

5258
// getInitialForwardingPolicy fetches the initial forwarding policy for a given
5259
// channel id from the database which will be applied during the channel
5260
// announcement phase.
5261
func (f *Manager) getInitialForwardingPolicy(
5262
        chanID lnwire.ChannelID) (*models.ForwardingPolicy, error) {
98✔
5263

98✔
5264
        return f.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
98✔
5265
}
98✔
5266

5267
// deleteInitialForwardingPolicy removes channel fees for this chanID from
5268
// the database.
5269
func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
28✔
5270
        return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
28✔
5271
}
28✔
5272

5273
// saveChannelOpeningState saves the channelOpeningState for the provided
5274
// chanPoint to the channelOpeningStateBucket.
5275
func (f *Manager) saveChannelOpeningState(chanPoint *wire.OutPoint,
5276
        state channelOpeningState, shortChanID *lnwire.ShortChannelID) error {
96✔
5277

96✔
5278
        var outpointBytes bytes.Buffer
96✔
5279
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
96✔
5280
                return err
×
5281
        }
×
5282

5283
        // Save state and the uint64 representation of the shortChanID
5284
        // for later use.
5285
        scratch := make([]byte, 10)
96✔
5286
        byteOrder.PutUint16(scratch[:2], uint16(state))
96✔
5287
        byteOrder.PutUint64(scratch[2:], shortChanID.ToUint64())
96✔
5288

96✔
5289
        return f.cfg.ChannelDB.SaveChannelOpeningState(
96✔
5290
                outpointBytes.Bytes(), scratch,
96✔
5291
        )
96✔
5292
}
5293

5294
// getChannelOpeningState fetches the channelOpeningState for the provided
5295
// chanPoint from the database, or returns ErrChannelNotFound if the channel
5296
// is not found.
5297
func (f *Manager) getChannelOpeningState(chanPoint *wire.OutPoint) (
5298
        channelOpeningState, *lnwire.ShortChannelID, error) {
256✔
5299

256✔
5300
        var outpointBytes bytes.Buffer
256✔
5301
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
256✔
5302
                return 0, nil, err
×
5303
        }
×
5304

5305
        value, err := f.cfg.ChannelDB.GetChannelOpeningState(
256✔
5306
                outpointBytes.Bytes(),
256✔
5307
        )
256✔
5308
        if err != nil {
307✔
5309
                return 0, nil, err
51✔
5310
        }
51✔
5311

5312
        state := channelOpeningState(byteOrder.Uint16(value[:2]))
209✔
5313
        shortChanID := lnwire.NewShortChanIDFromInt(byteOrder.Uint64(value[2:]))
209✔
5314
        return state, &shortChanID, nil
209✔
5315
}
5316

5317
// deleteChannelOpeningState removes any state for chanPoint from the database.
5318
func (f *Manager) deleteChannelOpeningState(chanPoint *wire.OutPoint) error {
28✔
5319
        var outpointBytes bytes.Buffer
28✔
5320
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
28✔
5321
                return err
×
5322
        }
×
5323

5324
        return f.cfg.ChannelDB.DeleteChannelOpeningState(
28✔
5325
                outpointBytes.Bytes(),
28✔
5326
        )
28✔
5327
}
5328

5329
// selectShutdownScript selects the shutdown script we should send to the peer.
5330
// If we can use taproot, then we prefer that, otherwise we'll use a p2wkh
5331
// script.
5332
func (f *Manager) selectShutdownScript(taprootOK bool,
5333
) (lnwire.DeliveryAddress, error) {
×
5334

×
5335
        addrType := lnwallet.WitnessPubKey
×
5336
        if taprootOK {
×
5337
                addrType = lnwallet.TaprootPubkey
×
5338
        }
×
5339

5340
        addr, err := f.cfg.Wallet.NewAddress(
×
5341
                addrType, false, lnwallet.DefaultAccountName,
×
5342
        )
×
5343
        if err != nil {
×
5344
                return nil, err
×
5345
        }
×
5346

5347
        return txscript.PayToAddrScript(addr)
×
5348
}
5349

5350
// waitForPeerOnline blocks until the peer specified by peerPubkey comes online
5351
// and then returns the online peer.
5352
func (f *Manager) waitForPeerOnline(peerPubkey *btcec.PublicKey) (lnpeer.Peer,
5353
        error) {
109✔
5354

109✔
5355
        peerChan := make(chan lnpeer.Peer, 1)
109✔
5356

109✔
5357
        var peerKey [33]byte
109✔
5358
        copy(peerKey[:], peerPubkey.SerializeCompressed())
109✔
5359

109✔
5360
        f.cfg.NotifyWhenOnline(peerKey, peerChan)
109✔
5361

109✔
5362
        var peer lnpeer.Peer
109✔
5363
        select {
109✔
5364
        case peer = <-peerChan:
108✔
5365
        case <-f.quit:
1✔
5366
                return peer, ErrFundingManagerShuttingDown
1✔
5367
        }
5368
        return peer, nil
108✔
5369
}
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