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

lightningnetwork / lnd / 12231552240

09 Dec 2024 08:17AM UTC coverage: 58.955% (+0.02%) from 58.933%
12231552240

Pull #9242

github

aakselrod
go.mod: update btcwallet to latest to eliminate waddrmgr deadlock
Pull Request #9242: Reapply #8644

24 of 40 new or added lines in 3 files covered. (60.0%)

89 existing lines in 18 files now uncovered.

133525 of 226485 relevant lines covered (58.96%)

19398.62 hits per line

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

73.89
/funding/manager.go
1
package funding
2

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

12
        "github.com/btcsuite/btcd/blockchain"
13
        "github.com/btcsuite/btcd/btcec/v2"
14
        "github.com/btcsuite/btcd/btcec/v2/ecdsa"
15
        "github.com/btcsuite/btcd/btcec/v2/schnorr/musig2"
16
        "github.com/btcsuite/btcd/btcutil"
17
        "github.com/btcsuite/btcd/chaincfg/chainhash"
18
        "github.com/btcsuite/btcd/txscript"
19
        "github.com/btcsuite/btcd/wire"
20
        "github.com/davecgh/go-spew/spew"
21
        "github.com/go-errors/errors"
22
        "github.com/lightningnetwork/lnd/chainntnfs"
23
        "github.com/lightningnetwork/lnd/chanacceptor"
24
        "github.com/lightningnetwork/lnd/channeldb"
25
        "github.com/lightningnetwork/lnd/discovery"
26
        "github.com/lightningnetwork/lnd/fn"
27
        "github.com/lightningnetwork/lnd/graph"
28
        "github.com/lightningnetwork/lnd/graph/db/models"
29
        "github.com/lightningnetwork/lnd/input"
30
        "github.com/lightningnetwork/lnd/keychain"
31
        "github.com/lightningnetwork/lnd/labels"
32
        "github.com/lightningnetwork/lnd/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
        // AuxResolver is an optional interface that can be used to modify the
563
        // way contracts are resolved.
564
        AuxResolver fn.Option[lnwallet.AuxContractResolver]
565
}
566

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

580
        // cfg is a copy of the configuration struct that the FundingManager
581
        // was initialized with.
582
        cfg *Config
583

584
        // chanIDKey is a cryptographically random key that's used to generate
585
        // temporary channel ID's.
586
        chanIDKey [32]byte
587

588
        // chanIDNonce is a nonce that's incremented for each new funding
589
        // reservation created.
590
        chanIDNonce atomic.Uint64
591

592
        // nonceMtx is a mutex that guards the pendingMusigNonces.
593
        nonceMtx sync.RWMutex
594

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

606
        // activeReservations is a map which houses the state of all pending
607
        // funding workflows.
608
        activeReservations map[serializedPubKey]pendingChannels
609

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

617
        // resMtx guards both of the maps above to ensure that all access is
618
        // goroutine safe.
619
        resMtx sync.RWMutex
620

621
        // fundingMsgs is a channel that relays fundingMsg structs from
622
        // external sub-systems using the ProcessFundingMsg call.
623
        fundingMsgs chan *fundingMsg
624

625
        // fundingRequests is a channel used to receive channel initiation
626
        // requests from a local subsystem within the daemon.
627
        fundingRequests chan *InitFundingMsg
628

629
        localDiscoverySignals *lnutils.SyncMap[lnwire.ChannelID, chan struct{}]
630

631
        handleChannelReadyBarriers *lnutils.SyncMap[lnwire.ChannelID, struct{}]
632

633
        quit chan struct{}
634
        wg   sync.WaitGroup
635
}
636

637
// channelOpeningState represents the different states a channel can be in
638
// between the funding transaction has been confirmed and the channel is
639
// announced to the network and ready to be used.
640
type channelOpeningState uint8
641

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

648
        // channelReadySent is the opening state of a channel if the
649
        // channelReady message has successfully been sent to the other peer,
650
        // but we still haven't announced the channel to the network.
651
        channelReadySent
652

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

660
func (c channelOpeningState) String() string {
4✔
661
        switch c {
4✔
662
        case markedOpen:
4✔
663
                return "markedOpen"
4✔
664
        case channelReadySent:
4✔
665
                return "channelReadySent"
4✔
666
        case addedToGraph:
4✔
667
                return "addedToGraph"
4✔
668
        default:
×
669
                return "unknown"
×
670
        }
671
}
672

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

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

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

727
        for _, channel := range allChannels {
124✔
728
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
13✔
729

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

5✔
739
                        f.localDiscoverySignals.Store(
5✔
740
                                chanID, make(chan struct{}),
5✔
741
                        )
5✔
742

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

5✔
751
                                f.rebroadcastFundingTx(channel)
5✔
752
                        }
5✔
753
                } else if channel.ChanType.IsSingleFunder() &&
12✔
754
                        channel.ChanType.HasFundingTx() &&
12✔
755
                        channel.IsZeroConf() && channel.IsInitiator &&
12✔
756
                        !channel.ZeroConfConfirmed() {
14✔
757

2✔
758
                        // Rebroadcast the funding transaction for unconfirmed
2✔
759
                        // zero-conf channels if we have the funding tx and are
2✔
760
                        // also the initiator.
2✔
761
                        f.rebroadcastFundingTx(channel)
2✔
762
                }
2✔
763

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

772
        f.wg.Add(1) // TODO(roasbeef): tune
111✔
773
        go f.reservationCoordinator()
111✔
774

111✔
775
        return nil
111✔
776
}
777

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

107✔
785
                close(f.quit)
107✔
786
                f.wg.Wait()
107✔
787
        })
107✔
788

789
        return nil
108✔
790
}
791

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

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

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

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

822
// PendingChanID is a type that represents a pending channel ID. This might be
823
// selected by the caller, but if not, will be automatically selected.
824
type PendingChanID = [32]byte
825

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

60✔
832
        var nonceBytes [8]byte
60✔
833
        binary.LittleEndian.PutUint64(nonceBytes[:], nextNonce)
60✔
834

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

60✔
845
        return nextChanID
60✔
846
}
60✔
847

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

4✔
854
        f.resMtx.Lock()
4✔
855
        defer f.resMtx.Unlock()
4✔
856

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

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

875
                resCtx.err <- fmt.Errorf("peer disconnected")
×
876
                delete(nodeReservations, pendingID)
×
877
        }
878

879
        // Finally, we'll delete the node itself from the set of reservations.
880
        delete(f.activeReservations, nodePub)
×
881
}
882

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

894
        // chanID is the channel ID created by the funder once the
895
        // `accept_channel` message is received. For fundee, it's received from
896
        // the `funding_created` message.
897
        chanID lnwire.ChannelID
898

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

907
// newChanIdentifier creates a new chanIdentifier.
908
func newChanIdentifier(tempChanID lnwire.ChannelID) *chanIdentifier {
148✔
909
        return &chanIdentifier{
148✔
910
                tempChanID: tempChanID,
148✔
911
        }
148✔
912
}
148✔
913

914
// setChanID updates the `chanIdentifier` with the active channel ID.
915
func (c *chanIdentifier) setChanID(chanID lnwire.ChannelID) {
92✔
916
        c.chanID = chanID
92✔
917
        c.chanIDSet = true
92✔
918
}
92✔
919

920
// hasChanID returns true if the active channel ID has been set.
921
func (c *chanIdentifier) hasChanID() bool {
25✔
922
        return c.chanIDSet
25✔
923
}
25✔
924

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

25✔
935
        log.Debugf("Failing funding flow for pending_id=%v: %v",
25✔
936
                cid.tempChanID, fundingErr)
25✔
937

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

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

958
        // In case the case where the reservation existed, send the funding
959
        // error on the error channel.
960
        if ctx != nil {
41✔
961
                ctx.err <- fundingErr
16✔
962
        }
16✔
963

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

977
        // For all other error types we just send a generic error.
978
        default:
16✔
979
                msg = lnwire.ErrorData("funding failed due to internal error")
16✔
980
        }
981

982
        errMsg := &lnwire.Error{
25✔
983
                ChanID: cid.tempChanID,
25✔
984
                Data:   msg,
25✔
985
        }
25✔
986

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

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

×
999
        msg := fundingErr.Error()
×
1000

×
1001
        errMsg := &lnwire.Warning{
×
1002
                ChanID: cid.tempChanID,
×
1003
                Data:   lnwire.WarningData(msg),
×
1004
        }
×
1005

×
1006
        log.Debugf("Sending funding warning to peer (%x): %v",
×
1007
                peer.IdentityKey().SerializeCompressed(),
×
1008
                spew.Sdump(errMsg),
×
1009
        )
×
1010

×
1011
        if err := peer.SendMessage(false, errMsg); err != nil {
×
1012
                log.Errorf("unable to send error message to peer %v", err)
×
1013
        }
×
1014
}
1015

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

111✔
1023
        zombieSweepTicker := time.NewTicker(f.cfg.ZombieSweeperInterval)
111✔
1024
        defer zombieSweepTicker.Stop()
111✔
1025

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

1033
                        case *lnwire.AcceptChannel:
36✔
1034
                                f.funderProcessAcceptChannel(fmsg.peer, msg)
36✔
1035

1036
                        case *lnwire.FundingCreated:
31✔
1037
                                f.fundeeProcessFundingCreated(fmsg.peer, msg)
31✔
1038

1039
                        case *lnwire.FundingSigned:
31✔
1040
                                f.funderProcessFundingSigned(fmsg.peer, msg)
31✔
1041

1042
                        case *lnwire.ChannelReady:
32✔
1043
                                f.wg.Add(1)
32✔
1044
                                go f.handleChannelReady(fmsg.peer, msg)
32✔
1045

1046
                        case *lnwire.Warning:
42✔
1047
                                f.handleWarningMsg(fmsg.peer, msg)
42✔
1048

1049
                        case *lnwire.Error:
4✔
1050
                                f.handleErrorMsg(fmsg.peer, msg)
4✔
1051
                        }
1052
                case req := <-f.fundingRequests:
60✔
1053
                        f.handleInitFundingMsg(req)
60✔
1054

1055
                case <-zombieSweepTicker.C:
4✔
1056
                        f.pruneZombieReservations()
4✔
1057

1058
                case <-f.quit:
107✔
1059
                        return
107✔
1060
                }
1061
        }
1062
}
1063

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

67✔
1076
        defer f.wg.Done()
67✔
1077

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

1090
        var chanOpts []lnwallet.ChannelOpt
46✔
1091
        f.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
88✔
1092
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
42✔
1093
        })
42✔
1094
        f.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
88✔
1095
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
42✔
1096
        })
42✔
1097
        f.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
46✔
1098
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
1099
        })
×
1100

1101
        // We create the state-machine object which wraps the database state.
1102
        lnChannel, err := lnwallet.NewLightningChannel(
46✔
1103
                nil, channel, nil, chanOpts...,
46✔
1104
        )
46✔
1105
        if err != nil {
46✔
1106
                log.Errorf("Unable to create LightningChannel(%v): %v",
×
1107
                        channel.FundingOutpoint, err)
×
1108
                return
×
1109
        }
×
1110

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

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

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

127✔
1159
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
127✔
1160
        log.Debugf("Channel(%v) with ShortChanID %v has opening state %v",
127✔
1161
                chanID, shortChanID, channelState)
127✔
1162

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

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

1186
                log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
38✔
1187
                        "sent ChannelReady", chanID, shortChanID)
38✔
1188

38✔
1189
                return nil
38✔
1190

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

1204
                if !received {
104✔
1205
                        // We haven't received ChannelReady, so we'll continue
40✔
1206
                        // to the next iteration of the loop after sleeping for
40✔
1207
                        // checkPeerChannelReadyInterval.
40✔
1208
                        select {
40✔
1209
                        case <-time.After(checkPeerChannelReadyInterval):
28✔
1210
                        case <-f.quit:
12✔
1211
                                return ErrFundingManagerShuttingDown
12✔
1212
                        }
1213

1214
                        return nil
28✔
1215
                }
1216

1217
                return f.handleChannelReadyReceived(
28✔
1218
                        channel, shortChanID, pendingChanID, updateChan,
28✔
1219
                )
28✔
1220

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

1234
                        // Update the local shortChanID variable such that
1235
                        // annAfterSixConfs uses the confirmed SCID.
1236
                        confirmedScid := channel.ZeroConfRealScid()
8✔
1237
                        shortChanID = &confirmedScid
8✔
1238
                }
1239

1240
                err := f.annAfterSixConfs(channel, shortChanID)
30✔
1241
                if err != nil {
36✔
1242
                        return fmt.Errorf("error sending channel "+
6✔
1243
                                "announcement: %v", err)
6✔
1244
                }
6✔
1245

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

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

1267
                log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
28✔
1268
                        "announced", chanID, shortChanID)
28✔
1269

28✔
1270
                return nil
28✔
1271
        }
1272

1273
        return fmt.Errorf("undefined channelState: %v", channelState)
×
1274
}
1275

1276
// advancePendingChannelState waits for a pending channel's funding tx to
1277
// confirm, and marks it open in the database when that happens.
1278
func (f *Manager) advancePendingChannelState(channel *channeldb.OpenChannel,
1279
        pendingChanID PendingChanID) error {
59✔
1280

59✔
1281
        if channel.IsZeroConf() {
67✔
1282
                // Persist the alias to the alias database.
8✔
1283
                baseScid := channel.ShortChannelID
8✔
1284
                err := f.cfg.AliasManager.AddLocalAlias(
8✔
1285
                        baseScid, baseScid, true, false,
8✔
1286
                )
8✔
1287
                if err != nil {
8✔
1288
                        return fmt.Errorf("error adding local alias to "+
×
1289
                                "store: %v", err)
×
1290
                }
×
1291

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

1305
                // The ShortChannelID is already set since it's an alias, but
1306
                // we still need to mark the channel as no longer pending.
1307
                err = channel.MarkAsOpen(channel.ShortChannelID)
8✔
1308
                if err != nil {
8✔
1309
                        return fmt.Errorf("error setting zero-conf channel's "+
×
1310
                                "pending flag to false: %v", err)
×
1311
                }
×
1312

1313
                // Inform the ChannelNotifier that the channel has transitioned
1314
                // from pending open to open.
1315
                f.cfg.NotifyOpenChannelEvent(channel.FundingOutpoint)
8✔
1316

8✔
1317
                // Find and close the discoverySignal for this channel such
8✔
1318
                // that ChannelReady messages will be processed.
8✔
1319
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
8✔
1320
                discoverySignal, ok := f.localDiscoverySignals.Load(chanID)
8✔
1321
                if ok {
16✔
1322
                        close(discoverySignal)
8✔
1323
                }
8✔
1324

1325
                return nil
8✔
1326
        }
1327

1328
        confChannel, err := f.waitForFundingWithTimeout(channel)
55✔
1329
        if err == ErrConfirmationTimeout {
57✔
1330
                return f.fundingTimeout(channel, pendingChanID)
2✔
1331
        } else if err != nil {
78✔
1332
                return fmt.Errorf("error waiting for funding "+
23✔
1333
                        "confirmation for ChannelPoint(%v): %v",
23✔
1334
                        channel.FundingOutpoint, err)
23✔
1335
        }
23✔
1336

1337
        if blockchain.IsCoinBaseTx(confChannel.fundingTx) {
36✔
1338
                // If it's a coinbase transaction, we need to wait for it to
2✔
1339
                // mature. We wait out an additional MinAcceptDepth on top of
2✔
1340
                // the coinbase maturity as an extra margin of safety.
2✔
1341
                maturity := f.cfg.Wallet.Cfg.NetParams.CoinbaseMaturity
2✔
1342
                numCoinbaseConfs := uint32(maturity)
2✔
1343

2✔
1344
                if channel.NumConfsRequired > maturity {
2✔
1345
                        numCoinbaseConfs = uint32(channel.NumConfsRequired)
×
1346
                }
×
1347

1348
                txid := &channel.FundingOutpoint.Hash
2✔
1349
                fundingScript, err := makeFundingScript(channel)
2✔
1350
                if err != nil {
2✔
1351
                        log.Errorf("unable to create funding script for "+
×
1352
                                "ChannelPoint(%v): %v",
×
1353
                                channel.FundingOutpoint, err)
×
1354

×
1355
                        return err
×
1356
                }
×
1357

1358
                confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
2✔
1359
                        txid, fundingScript, numCoinbaseConfs,
2✔
1360
                        channel.BroadcastHeight(),
2✔
1361
                )
2✔
1362
                if err != nil {
2✔
1363
                        log.Errorf("Unable to register for confirmation of "+
×
1364
                                "ChannelPoint(%v): %v",
×
1365
                                channel.FundingOutpoint, err)
×
1366

×
1367
                        return err
×
1368
                }
×
1369

1370
                select {
2✔
1371
                case _, ok := <-confNtfn.Confirmed:
2✔
1372
                        if !ok {
2✔
1373
                                return fmt.Errorf("ChainNotifier shutting "+
×
1374
                                        "down, can't complete funding flow "+
×
1375
                                        "for ChannelPoint(%v)",
×
1376
                                        channel.FundingOutpoint)
×
1377
                        }
×
1378

1379
                case <-f.quit:
×
1380
                        return ErrFundingManagerShuttingDown
×
1381
                }
1382
        }
1383

1384
        // Success, funding transaction was confirmed.
1385
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
34✔
1386
        log.Debugf("ChannelID(%v) is now fully confirmed! "+
34✔
1387
                "(shortChanID=%v)", chanID, confChannel.shortChanID)
34✔
1388

34✔
1389
        err = f.handleFundingConfirmation(channel, confChannel)
34✔
1390
        if err != nil {
34✔
1391
                return fmt.Errorf("unable to handle funding "+
×
1392
                        "confirmation for ChannelPoint(%v): %v",
×
1393
                        channel.FundingOutpoint, err)
×
1394
        }
×
1395

1396
        return nil
34✔
1397
}
1398

1399
// ProcessFundingMsg sends a message to the internal fundingManager goroutine,
1400
// allowing it to handle the lnwire.Message.
1401
func (f *Manager) ProcessFundingMsg(msg lnwire.Message, peer lnpeer.Peer) {
214✔
1402
        select {
214✔
1403
        case f.fundingMsgs <- &fundingMsg{msg, peer}:
214✔
1404
        case <-f.quit:
×
1405
                return
×
1406
        }
1407
}
1408

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

57✔
1420
        // Check number of pending channels to be smaller than maximum allowed
57✔
1421
        // number and send ErrorGeneric to remote peer if condition is
57✔
1422
        // violated.
57✔
1423
        peerPubKey := peer.IdentityKey()
57✔
1424
        peerIDKey := newSerializedKey(peerPubKey)
57✔
1425

57✔
1426
        amt := msg.FundingAmount
57✔
1427

57✔
1428
        // We get all pending channels for this peer. This is the list of the
57✔
1429
        // active reservations and the channels pending open in the database.
57✔
1430
        f.resMtx.RLock()
57✔
1431
        reservations := f.activeReservations[peerIDKey]
57✔
1432

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

57✔
1444
        // Create the channel identifier.
57✔
1445
        cid := newChanIdentifier(msg.PendingChannelID)
57✔
1446

57✔
1447
        // Also count the channels that are already pending. There we don't know
57✔
1448
        // the underlying intent anymore, unfortunately.
57✔
1449
        channels, err := f.cfg.ChannelDB.FetchOpenChannels(peerPubKey)
57✔
1450
        if err != nil {
57✔
1451
                f.failFundingFlow(peer, cid, err)
×
1452
                return
×
1453
        }
×
1454

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

1467
        // TODO(roasbeef): modify to only accept a _single_ pending channel per
1468
        // block unless white listed
1469
        if numPending >= f.cfg.MaxPendingChannels {
65✔
1470
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
8✔
1471

8✔
1472
                return
8✔
1473
        }
8✔
1474

1475
        // Ensure that the pendingChansLimit is respected.
1476
        pendingChans, err := f.cfg.ChannelDB.FetchPendingChannels()
53✔
1477
        if err != nil {
53✔
1478
                f.failFundingFlow(peer, cid, err)
×
1479
                return
×
1480
        }
×
1481

1482
        if len(pendingChans) > pendingChansLimit {
53✔
1483
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
×
1484
                return
×
1485
        }
×
1486

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

1500
        // Ensure that the remote party respects our maximum channel size.
1501
        if amt > f.cfg.MaxChanSize {
59✔
1502
                f.failFundingFlow(
6✔
1503
                        peer, cid,
6✔
1504
                        lnwallet.ErrChanTooLarge(amt, f.cfg.MaxChanSize),
6✔
1505
                )
6✔
1506
                return
6✔
1507
        }
6✔
1508

1509
        // We'll, also ensure that the remote party isn't attempting to propose
1510
        // a channel that's below our current min channel size.
1511
        if amt < f.cfg.MinChanSize {
55✔
1512
                f.failFundingFlow(
4✔
1513
                        peer, cid,
4✔
1514
                        lnwallet.ErrChanTooSmall(amt, f.cfg.MinChanSize),
4✔
1515
                )
4✔
1516
                return
4✔
1517
        }
4✔
1518

1519
        // If request specifies non-zero push amount and 'rejectpush' is set,
1520
        // signal an error.
1521
        if f.cfg.RejectPush && msg.PushAmount > 0 {
52✔
1522
                f.failFundingFlow(peer, cid, lnwallet.ErrNonZeroPushAmount())
1✔
1523
                return
1✔
1524
        }
1✔
1525

1526
        // Send the OpenChannel request to the ChannelAcceptor to determine
1527
        // whether this node will accept the channel.
1528
        chanReq := &chanacceptor.ChannelAcceptRequest{
50✔
1529
                Node:        peer.IdentityKey(),
50✔
1530
                OpenChanMsg: msg,
50✔
1531
        }
50✔
1532

50✔
1533
        // Query our channel acceptor to determine whether we should reject
50✔
1534
        // the channel.
50✔
1535
        acceptorResp := f.cfg.OpenChannelPredicate.Accept(chanReq)
50✔
1536
        if acceptorResp.RejectChannel() {
54✔
1537
                f.failFundingFlow(peer, cid, acceptorResp.ChanAcceptError)
4✔
1538
                return
4✔
1539
        }
4✔
1540

1541
        log.Infof("Recv'd fundingRequest(amt=%v, push=%v, delay=%v, "+
50✔
1542
                "pendingId=%x) from peer(%x)", amt, msg.PushAmount,
50✔
1543
                msg.CsvDelay, msg.PendingChannelID,
50✔
1544
                peer.IdentityKey().SerializeCompressed())
50✔
1545

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

1567
        var scidFeatureVal bool
50✔
1568
        if hasFeatures(
50✔
1569
                peer.LocalFeatures(), peer.RemoteFeatures(),
50✔
1570
                lnwire.ScidAliasOptional,
50✔
1571
        ) {
57✔
1572

7✔
1573
                scidFeatureVal = true
7✔
1574
        }
7✔
1575

1576
        var (
50✔
1577
                zeroConf bool
50✔
1578
                scid     bool
50✔
1579
        )
50✔
1580

50✔
1581
        // Only echo back a channel type in AcceptChannel if we actually used
50✔
1582
        // explicit negotiation above.
50✔
1583
        if chanType != nil {
58✔
1584
                // Check if the channel type includes the zero-conf or
8✔
1585
                // scid-alias bits.
8✔
1586
                featureVec := lnwire.RawFeatureVector(*chanType)
8✔
1587
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
8✔
1588
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
8✔
1589

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

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

1619
                        // Set zeroConf to true to enable the zero-conf flow.
1620
                        zeroConf = true
×
1621
                }
1622
        }
1623

1624
        public := msg.ChannelFlags&lnwire.FFAnnounceChannel != 0
50✔
1625
        switch {
50✔
1626
        // Sending the option-scid-alias channel type for a public channel is
1627
        // disallowed.
1628
        case public && scid:
×
1629
                err = fmt.Errorf("option-scid-alias chantype for public " +
×
1630
                        "channel")
×
1631
                log.Errorf("Cancelling funding flow for public channel %v "+
×
1632
                        "with scid-alias: %v", cid, err)
×
1633
                f.failFundingFlow(peer, cid, err)
×
1634

×
1635
                return
×
1636

1637
        // The current variant of taproot channels can only be used with
1638
        // unadvertised channels for now.
1639
        case commitType.IsTaproot() && public:
×
1640
                err = fmt.Errorf("taproot channel type for public channel")
×
1641
                log.Errorf("Cancelling funding flow for public taproot "+
×
1642
                        "channel %v: %v", cid, err)
×
1643
                f.failFundingFlow(peer, cid, err)
×
1644

×
1645
                return
×
1646
        }
1647

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

×
1662
                return
×
1663
        }
×
1664

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

50✔
1684
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
50✔
1685
        if err != nil {
50✔
1686
                log.Errorf("Unable to initialize reservation: %v", err)
×
1687
                f.failFundingFlow(peer, cid, err)
×
1688
                return
×
1689
        }
×
1690

1691
        log.Debugf("Initialized channel reservation: zeroConf=%v, psbt=%v, "+
50✔
1692
                "cannedShim=%v", reservation.IsZeroConf(),
50✔
1693
                reservation.IsPsbt(), reservation.IsCannedShim())
50✔
1694

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

1705
                reservation.AddAlias(aliasScid)
6✔
1706
        }
1707

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

1719
        // We'll ignore the min_depth calculated above if this is a zero-conf
1720
        // channel.
1721
        if zeroConf {
56✔
1722
                numConfsReq = 0
6✔
1723
        }
6✔
1724

1725
        reservation.SetNumConfsRequired(numConfsReq)
50✔
1726

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

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

50✔
1765
        // If a script enforced channel lease is being proposed, we'll need to
50✔
1766
        // validate its custom TLV records.
50✔
1767
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
54✔
1768
                if msg.LeaseExpiry == nil {
4✔
1769
                        err := errors.New("missing lease expiry")
×
1770
                        f.failFundingFlow(peer, cid, err)
×
1771
                        return
×
1772
                }
×
1773

1774
                // If we had a shim registered for this channel prior to
1775
                // receiving its corresponding OpenChannel message, then we'll
1776
                // validate the proposed LeaseExpiry against what was registered
1777
                // in our shim.
1778
                if reservation.LeaseExpiry() != 0 {
8✔
1779
                        if uint32(*msg.LeaseExpiry) !=
4✔
1780
                                reservation.LeaseExpiry() {
4✔
1781

×
1782
                                err := errors.New("lease expiry mismatch")
×
1783
                                f.failFundingFlow(peer, cid, err)
×
1784
                                return
×
1785
                        }
×
1786
                }
1787
        }
1788

1789
        log.Infof("Requiring %v confirmations for pendingChan(%x): "+
50✔
1790
                "amt=%v, push_amt=%v, committype=%v, upfrontShutdown=%x",
50✔
1791
                numConfsReq, msg.PendingChannelID, amt, msg.PushAmount,
50✔
1792
                commitType, msg.UpfrontShutdownScript)
50✔
1793

50✔
1794
        // Generate our required constraints for the remote party, using the
50✔
1795
        // values provided by the channel acceptor if they are non-zero.
50✔
1796
        remoteCsvDelay := f.cfg.RequiredRemoteDelay(amt)
50✔
1797
        if acceptorResp.CSVDelay != 0 {
50✔
1798
                remoteCsvDelay = acceptorResp.CSVDelay
×
1799
        }
×
1800

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

1813
        chanReserve := f.cfg.RequiredRemoteChanReserve(amt, maxDustLimit)
50✔
1814
        if acceptorResp.Reserve != 0 {
50✔
1815
                chanReserve = acceptorResp.Reserve
×
1816
        }
×
1817

1818
        remoteMaxValue := f.cfg.RequiredRemoteMaxValue(amt)
50✔
1819
        if acceptorResp.InFlightTotal != 0 {
50✔
1820
                remoteMaxValue = acceptorResp.InFlightTotal
×
1821
        }
×
1822

1823
        maxHtlcs := f.cfg.RequiredRemoteMaxHTLCs(amt)
50✔
1824
        if acceptorResp.HtlcLimit != 0 {
50✔
1825
                maxHtlcs = acceptorResp.HtlcLimit
×
1826
        }
×
1827

1828
        // Default to our default minimum hltc value, replacing it with the
1829
        // channel acceptor's value if it is set.
1830
        minHtlc := f.cfg.DefaultMinHtlcIn
50✔
1831
        if acceptorResp.MinHtlcIn != 0 {
50✔
1832
                minHtlc = acceptorResp.MinHtlcIn
×
1833
        }
×
1834

1835
        // If we are handling a FundingOpen request then we need to specify the
1836
        // default channel fees since they are not provided by the responder
1837
        // interactively.
1838
        ourContribution := reservation.OurContribution()
50✔
1839
        forwardingPolicy := f.defaultForwardingPolicy(
50✔
1840
                ourContribution.ChannelStateBounds,
50✔
1841
        )
50✔
1842

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

50✔
1867
        // Update the timestamp once the fundingOpenMsg has been handled.
50✔
1868
        defer resCtx.updateTimestamp()
50✔
1869

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

50✔
1898
        // With our parameters set, we'll now process their contribution so we
50✔
1899
        // can move the funding workflow ahead.
50✔
1900
        remoteContribution := &lnwallet.ChannelContribution{
50✔
1901
                FundingAmount:        amt,
50✔
1902
                FirstCommitmentPoint: msg.FirstCommitmentPoint,
50✔
1903
                ChannelConfig:        &cfg,
50✔
1904
                UpfrontShutdown:      msg.UpfrontShutdownScript,
50✔
1905
        }
50✔
1906

50✔
1907
        if resCtx.reservation.IsTaproot() {
56✔
1908
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
6✔
1909
                if err != nil {
6✔
1910
                        log.Error(errNoLocalNonce)
×
1911

×
1912
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
1913

×
1914
                        return
×
1915
                }
×
1916

1917
                remoteContribution.LocalNonce = &musig2.Nonces{
6✔
1918
                        PubNonce: localNonce,
6✔
1919
                }
6✔
1920
        }
1921

1922
        err = reservation.ProcessSingleContribution(remoteContribution)
50✔
1923
        if err != nil {
56✔
1924
                log.Errorf("unable to add contribution reservation: %v", err)
6✔
1925
                f.failFundingFlow(peer, cid, err)
6✔
1926
                return
6✔
1927
        }
6✔
1928

1929
        log.Infof("Sending fundingResp for pending_id(%x)",
44✔
1930
                msg.PendingChannelID)
44✔
1931
        bounds := remoteContribution.ChannelConfig.ChannelStateBounds
44✔
1932
        log.Debugf("Remote party accepted channel state space bounds: %v",
44✔
1933
                lnutils.SpewLogClosure(bounds))
44✔
1934
        params := remoteContribution.ChannelConfig.CommitmentParams
44✔
1935
        log.Debugf("Remote party accepted commitment rendering params: %v",
44✔
1936
                lnutils.SpewLogClosure(params))
44✔
1937

44✔
1938
        reservation.SetState(lnwallet.SentAcceptChannel)
44✔
1939

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

44✔
1962
        if commitType.IsTaproot() {
50✔
1963
                fundingAccept.LocalNonce = lnwire.SomeMusig2Nonce(
6✔
1964
                        ourContribution.LocalNonce.PubNonce,
6✔
1965
                )
6✔
1966
        }
6✔
1967

1968
        if err := peer.SendMessage(true, &fundingAccept); err != nil {
44✔
1969
                log.Errorf("unable to send funding response to peer: %v", err)
×
1970
                f.failFundingFlow(peer, cid, err)
×
1971
                return
×
1972
        }
×
1973
}
1974

1975
// funderProcessAcceptChannel processes a response to the workflow initiation
1976
// sent by the remote peer. This message then queues a message with the funding
1977
// outpoint, and a commitment signature to the remote peer.
1978
//
1979
//nolint:funlen
1980
func (f *Manager) funderProcessAcceptChannel(peer lnpeer.Peer,
1981
        msg *lnwire.AcceptChannel) {
36✔
1982

36✔
1983
        pendingChanID := msg.PendingChannelID
36✔
1984
        peerKey := peer.IdentityKey()
36✔
1985
        var peerKeyBytes []byte
36✔
1986
        if peerKey != nil {
72✔
1987
                peerKeyBytes = peerKey.SerializeCompressed()
36✔
1988
        }
36✔
1989

1990
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
36✔
1991
        if err != nil {
36✔
1992
                log.Warnf("Can't find reservation (peerKey:%x, chan_id:%v)",
×
1993
                        peerKeyBytes, pendingChanID)
×
1994
                return
×
1995
        }
×
1996

1997
        // Update the timestamp once the fundingAcceptMsg has been handled.
1998
        defer resCtx.updateTimestamp()
36✔
1999

36✔
2000
        if resCtx.reservation.State() != lnwallet.SentOpenChannel {
36✔
2001
                return
×
2002
        }
×
2003

2004
        log.Infof("Recv'd fundingResponse for pending_id(%x)",
36✔
2005
                pendingChanID[:])
36✔
2006

36✔
2007
        // Create the channel identifier.
36✔
2008
        cid := newChanIdentifier(msg.PendingChannelID)
36✔
2009

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

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

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

×
2057
                _, negotiatedCommitType, err := negotiateCommitmentType(
×
2058
                        msg.ChannelType, peer.LocalFeatures(),
×
2059
                        peer.RemoteFeatures(),
×
2060
                )
×
2061
                if err != nil {
×
2062
                        err := errors.New("received unexpected channel type")
×
2063
                        f.failFundingFlow(peer, cid, err)
×
2064
                        return
×
2065
                }
×
2066

2067
                if implicitCommitType != negotiatedCommitType {
×
2068
                        err := errors.New("negotiated unexpected channel type")
×
2069
                        f.failFundingFlow(peer, cid, err)
×
2070
                        return
×
2071
                }
×
2072
        }
2073

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

2086
        // Check that zero-conf channels have minimum depth set to 0.
2087
        if resCtx.reservation.IsZeroConf() && msg.MinAcceptDepth != 0 {
34✔
2088
                err = fmt.Errorf("zero-conf channel has min_depth non-zero")
×
2089
                log.Warn(err)
×
2090
                f.failFundingFlow(peer, cid, err)
×
2091
                return
×
2092
        }
×
2093

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

×
2103
                minDepth = 1
×
2104
        }
×
2105

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

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

33✔
2157
        // The remote node has responded with their portion of the channel
33✔
2158
        // contribution. At this point, we can process their contribution which
33✔
2159
        // allows us to construct and sign both the commitment transaction, and
33✔
2160
        // the funding transaction.
33✔
2161
        remoteContribution := &lnwallet.ChannelContribution{
33✔
2162
                FirstCommitmentPoint: msg.FirstCommitmentPoint,
33✔
2163
                ChannelConfig:        &cfg,
33✔
2164
                UpfrontShutdown:      msg.UpfrontShutdownScript,
33✔
2165
        }
33✔
2166

33✔
2167
        if resCtx.reservation.IsTaproot() {
39✔
2168
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
6✔
2169
                if err != nil {
6✔
2170
                        log.Error(errNoLocalNonce)
×
2171

×
2172
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
2173

×
2174
                        return
×
2175
                }
×
2176

2177
                remoteContribution.LocalNonce = &musig2.Nonces{
6✔
2178
                        PubNonce: localNonce,
6✔
2179
                }
6✔
2180
        }
2181

2182
        err = resCtx.reservation.ProcessContribution(remoteContribution)
33✔
2183

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

2226
        log.Infof("pendingChan(%x): remote party proposes num_confs=%v, "+
33✔
2227
                "csv_delay=%v", pendingChanID[:], msg.MinAcceptDepth,
33✔
2228
                msg.CsvDelay)
33✔
2229
        bounds = remoteContribution.ChannelConfig.ChannelStateBounds
33✔
2230
        log.Debugf("Remote party accepted channel state space bounds: %v",
33✔
2231
                lnutils.SpewLogClosure(bounds))
33✔
2232
        commitParams = remoteContribution.ChannelConfig.CommitmentParams
33✔
2233
        log.Debugf("Remote party accepted commitment rendering params: %v",
33✔
2234
                lnutils.SpewLogClosure(commitParams))
33✔
2235

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

4✔
2245
                        f.waitForPsbt(psbtIntent, resCtx, cid)
4✔
2246
                }()
4✔
2247

2248
                // With the new goroutine spawned, we can now exit to unblock
2249
                // the main event loop.
2250
                return
4✔
2251
        }
2252

2253
        // In a normal, non-PSBT funding flow, we can jump directly to the next
2254
        // step where we expect our contribution to be finalized.
2255
        f.continueFundingAccept(resCtx, cid)
33✔
2256
}
2257

2258
// waitForPsbt blocks until either a signed PSBT arrives, an error occurs or
2259
// the funding manager shuts down. In the case of a valid PSBT, the funding flow
2260
// is continued.
2261
//
2262
// NOTE: This method must be called as a goroutine.
2263
func (f *Manager) waitForPsbt(intent *chanfunding.PsbtIntent,
2264
        resCtx *reservationWithCtx, cid *chanIdentifier) {
4✔
2265

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

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

2289
                // If the remote canceled the funding reservation, we don't need
2290
                // to send another fail message. But we want to inform the user
2291
                // about what happened.
2292
                case chanfunding.ErrRemoteCanceled:
4✔
2293
                        log.Infof("Remote canceled, aborting PSBT flow "+
4✔
2294
                                "for peer_key=%x, pending_chan_id=%x",
4✔
2295
                                peerKey.SerializeCompressed(), cid.tempChanID)
4✔
2296
                        return
4✔
2297

2298
                // Nil error means the flow continues normally now.
2299
                case nil:
4✔
2300

2301
                // For any other error, we'll fail the funding flow.
2302
                default:
×
2303
                        failFlow("error waiting for PSBT flow", err)
×
2304
                        return
×
2305
                }
2306

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

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

2340
                // We are now ready to continue the funding flow.
2341
                f.continueFundingAccept(resCtx, cid)
4✔
2342

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

2354
// continueFundingAccept continues the channel funding flow once our
2355
// contribution is finalized, the channel output is known and the funding
2356
// transaction is signed.
2357
func (f *Manager) continueFundingAccept(resCtx *reservationWithCtx,
2358
        cid *chanIdentifier) {
33✔
2359

33✔
2360
        // Now that we have their contribution, we can extract, then send over
33✔
2361
        // both the funding out point and our signature for their version of
33✔
2362
        // the commitment transaction to the remote peer.
33✔
2363
        outPoint := resCtx.reservation.FundingOutpoint()
33✔
2364
        _, sig := resCtx.reservation.OurSignatures()
33✔
2365

33✔
2366
        // A new channel has almost finished the funding process. In order to
33✔
2367
        // properly synchronize with the writeHandler goroutine, we add a new
33✔
2368
        // channel to the barriers map which will be closed once the channel is
33✔
2369
        // fully open.
33✔
2370
        channelID := lnwire.NewChanIDFromOutPoint(*outPoint)
33✔
2371
        log.Debugf("Creating chan barrier for ChanID(%v)", channelID)
33✔
2372

33✔
2373
        // The next message that advances the funding flow will reference the
33✔
2374
        // channel via its permanent channel ID, so we'll set up this mapping
33✔
2375
        // so we can retrieve the reservation context once we get the
33✔
2376
        // FundingSigned message.
33✔
2377
        f.resMtx.Lock()
33✔
2378
        f.signedReservations[channelID] = cid.tempChanID
33✔
2379
        f.resMtx.Unlock()
33✔
2380

33✔
2381
        log.Infof("Generated ChannelPoint(%v) for pending_id(%x)", outPoint,
33✔
2382
                cid.tempChanID[:])
33✔
2383

33✔
2384
        // Before sending FundingCreated sent, we notify Brontide to keep track
33✔
2385
        // of this pending open channel.
33✔
2386
        err := resCtx.peer.AddPendingChannel(channelID, f.quit)
33✔
2387
        if err != nil {
33✔
2388
                pubKey := resCtx.peer.IdentityKey().SerializeCompressed()
×
2389
                log.Errorf("Unable to add pending channel %v with peer %x: %v",
×
2390
                        channelID, pubKey, err)
×
2391
        }
×
2392

2393
        // Once Brontide is aware of this channel, we need to set it in
2394
        // chanIdentifier so this channel will be removed from Brontide if the
2395
        // funding flow fails.
2396
        cid.setChanID(channelID)
33✔
2397

33✔
2398
        // Send the FundingCreated msg.
33✔
2399
        fundingCreated := &lnwire.FundingCreated{
33✔
2400
                PendingChannelID: cid.tempChanID,
33✔
2401
                FundingPoint:     *outPoint,
33✔
2402
        }
33✔
2403

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

×
2414
                        return
×
2415
                }
×
2416

2417
                fundingCreated.PartialSig = lnwire.MaybePartialSigWithNonce(
6✔
2418
                        partialSig.ToWireSig(),
6✔
2419
                )
6✔
2420
        } else {
31✔
2421
                fundingCreated.CommitSig, err = lnwire.NewSigFromSignature(sig)
31✔
2422
                if err != nil {
31✔
2423
                        log.Errorf("Unable to parse signature: %v", err)
×
2424
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2425
                        return
×
2426
                }
×
2427
        }
2428

2429
        resCtx.reservation.SetState(lnwallet.SentFundingCreated)
33✔
2430

33✔
2431
        if err := resCtx.peer.SendMessage(true, fundingCreated); err != nil {
33✔
2432
                log.Errorf("Unable to send funding complete message: %v", err)
×
2433
                f.failFundingFlow(resCtx.peer, cid, err)
×
2434
                return
×
2435
        }
×
2436
}
2437

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

31✔
2448
        peerKey := peer.IdentityKey()
31✔
2449
        pendingChanID := msg.PendingChannelID
31✔
2450

31✔
2451
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
31✔
2452
        if err != nil {
31✔
2453
                log.Warnf("can't find reservation (peer_id:%v, chan_id:%x)",
×
2454
                        peerKey, pendingChanID[:])
×
2455
                return
×
2456
        }
×
2457

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

31✔
2466
        if resCtx.reservation.State() != lnwallet.SentAcceptChannel {
31✔
2467
                return
×
2468
        }
×
2469

2470
        // Create the channel identifier without setting the active channel ID.
2471
        cid := newChanIdentifier(pendingChanID)
31✔
2472

31✔
2473
        // For taproot channels, the commit signature is actually the partial
31✔
2474
        // signature. Otherwise, we can convert the ECDSA commit signature into
31✔
2475
        // our internal input.Signature type.
31✔
2476
        var commitSig input.Signature
31✔
2477
        if resCtx.reservation.IsTaproot() {
37✔
2478
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
6✔
2479
                if err != nil {
6✔
2480
                        f.failFundingFlow(peer, cid, err)
×
2481

×
2482
                        return
×
2483
                }
×
2484

2485
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
6✔
2486
                        &partialSig,
6✔
2487
                )
6✔
2488
        } else {
29✔
2489
                commitSig, err = msg.CommitSig.ToSignature()
29✔
2490
                if err != nil {
29✔
2491
                        log.Errorf("unable to parse signature: %v", err)
×
2492
                        f.failFundingFlow(peer, cid, err)
×
2493
                        return
×
2494
                }
×
2495
        }
2496

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

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

2534
        // Get forwarding policy before deleting the reservation context.
2535
        forwardingPolicy := resCtx.forwardingPolicy
31✔
2536

31✔
2537
        // The channel is marked IsPending in the database, and can be removed
31✔
2538
        // from the set of active reservations.
31✔
2539
        f.deleteReservationCtx(peerKey, cid.tempChanID)
31✔
2540

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

×
2558
                // Close the channel with us as the initiator because we are
×
2559
                // deciding to exit the funding flow due to an internal error.
×
2560
                if err := completeChan.CloseChannel(
×
2561
                        closeInfo, channeldb.ChanStatusLocalCloseInitiator,
×
2562
                ); err != nil {
×
2563
                        log.Errorf("Failed closing channel %v: %v",
×
2564
                                completeChan.FundingOutpoint, err)
×
2565
                }
×
2566
        }
2567

2568
        // A new channel has almost finished the funding process. In order to
2569
        // properly synchronize with the writeHandler goroutine, we add a new
2570
        // channel to the barriers map which will be closed once the channel is
2571
        // fully open.
2572
        channelID := lnwire.NewChanIDFromOutPoint(fundingOut)
31✔
2573
        log.Debugf("Creating chan barrier for ChanID(%v)", channelID)
31✔
2574

31✔
2575
        fundingSigned := &lnwire.FundingSigned{}
31✔
2576

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

×
2589
                        return
×
2590
                }
×
2591

2592
                fundingSigned.PartialSig = lnwire.MaybePartialSigWithNonce(
6✔
2593
                        partialSig.ToWireSig(),
6✔
2594
                )
6✔
2595
        } else {
29✔
2596
                fundingSigned.CommitSig, err = lnwire.NewSigFromSignature(sig)
29✔
2597
                if err != nil {
29✔
2598
                        log.Errorf("unable to parse signature: %v", err)
×
2599
                        f.failFundingFlow(peer, cid, err)
×
2600
                        deleteFromDatabase()
×
2601

×
2602
                        return
×
2603
                }
×
2604
        }
2605

2606
        // Before sending FundingSigned, we notify Brontide first to keep track
2607
        // of this pending open channel.
2608
        if err := peer.AddPendingChannel(channelID, f.quit); err != nil {
31✔
2609
                pubKey := peer.IdentityKey().SerializeCompressed()
×
2610
                log.Errorf("Unable to add pending channel %v with peer %x: %v",
×
2611
                        cid.chanID, pubKey, err)
×
2612
        }
×
2613

2614
        // Once Brontide is aware of this channel, we need to set it in
2615
        // chanIdentifier so this channel will be removed from Brontide if the
2616
        // funding flow fails.
2617
        cid.setChanID(channelID)
31✔
2618

31✔
2619
        fundingSigned.ChanID = cid.chanID
31✔
2620

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

31✔
2624
        // With their signature for our version of the commitment transaction
31✔
2625
        // verified, we can now send over our signature to the remote peer.
31✔
2626
        if err := peer.SendMessage(true, fundingSigned); err != nil {
31✔
2627
                log.Errorf("unable to send FundingSigned message: %v", err)
×
2628
                f.failFundingFlow(peer, cid, err)
×
2629
                deleteFromDatabase()
×
2630
                return
×
2631
        }
×
2632

2633
        // With a permanent channel id established we can save the respective
2634
        // forwarding policy in the database. In the channel announcement phase
2635
        // this forwarding policy is retrieved and applied.
2636
        err = f.saveInitialForwardingPolicy(cid.chanID, &forwardingPolicy)
31✔
2637
        if err != nil {
31✔
2638
                log.Errorf("Unable to store the forwarding policy: %v", err)
×
2639
        }
×
2640

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

2649
        // Create an entry in the local discovery map so we can ensure that we
2650
        // process the channel confirmation fully before we receive a
2651
        // channel_ready message.
2652
        f.localDiscoverySignals.Store(cid.chanID, make(chan struct{}))
31✔
2653

31✔
2654
        // Inform the ChannelNotifier that the channel has entered
31✔
2655
        // pending open state.
31✔
2656
        f.cfg.NotifyPendingOpenChannelEvent(fundingOut, completeChan)
31✔
2657

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

2678
// funderProcessFundingSigned processes the final message received in a single
2679
// funder workflow. Once this message is processed, the funding transaction is
2680
// broadcast. Once the funding transaction reaches a sufficient number of
2681
// confirmations, a message is sent to the responding peer along with a compact
2682
// encoding of the location of the channel within the blockchain.
2683
func (f *Manager) funderProcessFundingSigned(peer lnpeer.Peer,
2684
        msg *lnwire.FundingSigned) {
31✔
2685

31✔
2686
        // As the funding signed message will reference the reservation by its
31✔
2687
        // permanent channel ID, we'll need to perform an intermediate look up
31✔
2688
        // before we can obtain the reservation.
31✔
2689
        f.resMtx.Lock()
31✔
2690
        pendingChanID, ok := f.signedReservations[msg.ChanID]
31✔
2691
        delete(f.signedReservations, msg.ChanID)
31✔
2692
        f.resMtx.Unlock()
31✔
2693

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

31✔
2705
        // If the pending channel ID is not found, fail the funding flow.
31✔
2706
        if !ok {
31✔
2707
                // NOTE: we directly overwrite the pending channel ID here for
×
2708
                // this rare case since we don't have a valid pending channel
×
2709
                // ID.
×
2710
                cid.tempChanID = msg.ChanID
×
2711

×
2712
                err := fmt.Errorf("unable to find signed reservation for "+
×
2713
                        "chan_id=%x", msg.ChanID)
×
2714
                log.Warnf(err.Error())
×
2715
                f.failFundingFlow(peer, cid, err)
×
2716
                return
×
2717
        }
×
2718

2719
        peerKey := peer.IdentityKey()
31✔
2720
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
31✔
2721
        if err != nil {
31✔
2722
                log.Warnf("Unable to find reservation (peer_id:%v, "+
×
2723
                        "chan_id:%x)", peerKey, pendingChanID[:])
×
2724
                // TODO: add ErrChanNotFound?
×
2725
                f.failFundingFlow(peer, cid, err)
×
2726
                return
×
2727
        }
×
2728

2729
        if resCtx.reservation.State() != lnwallet.SentFundingCreated {
31✔
2730
                err := fmt.Errorf("unable to find reservation for chan_id=%x",
×
2731
                        msg.ChanID)
×
2732
                f.failFundingFlow(peer, cid, err)
×
2733

×
2734
                return
×
2735
        }
×
2736

2737
        // Create an entry in the local discovery map so we can ensure that we
2738
        // process the channel confirmation fully before we receive a
2739
        // channel_ready message.
2740
        fundingPoint := resCtx.reservation.FundingOutpoint()
31✔
2741
        permChanID := lnwire.NewChanIDFromOutPoint(*fundingPoint)
31✔
2742
        f.localDiscoverySignals.Store(permChanID, make(chan struct{}))
31✔
2743

31✔
2744
        // We have to store the forwardingPolicy before the reservation context
31✔
2745
        // is deleted. The policy will then be read and applied in
31✔
2746
        // newChanAnnouncement.
31✔
2747
        err = f.saveInitialForwardingPolicy(
31✔
2748
                permChanID, &resCtx.forwardingPolicy,
31✔
2749
        )
31✔
2750
        if err != nil {
31✔
2751
                log.Errorf("Unable to store the forwarding policy: %v", err)
×
2752
        }
×
2753

2754
        // For taproot channels, the commit signature is actually the partial
2755
        // signature. Otherwise, we can convert the ECDSA commit signature into
2756
        // our internal input.Signature type.
2757
        var commitSig input.Signature
31✔
2758
        if resCtx.reservation.IsTaproot() {
37✔
2759
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
6✔
2760
                if err != nil {
6✔
2761
                        f.failFundingFlow(peer, cid, err)
×
2762

×
2763
                        return
×
2764
                }
×
2765

2766
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
6✔
2767
                        &partialSig,
6✔
2768
                )
6✔
2769
        } else {
29✔
2770
                commitSig, err = msg.CommitSig.ToSignature()
29✔
2771
                if err != nil {
29✔
2772
                        log.Errorf("unable to parse signature: %v", err)
×
2773
                        f.failFundingFlow(peer, cid, err)
×
2774
                        return
×
2775
                }
×
2776
        }
2777

2778
        completeChan, err := resCtx.reservation.CompleteReservation(
31✔
2779
                nil, commitSig,
31✔
2780
        )
31✔
2781
        if err != nil {
31✔
2782
                log.Errorf("Unable to complete reservation sign "+
×
2783
                        "complete: %v", err)
×
2784
                f.failFundingFlow(peer, cid, err)
×
2785
                return
×
2786
        }
×
2787

2788
        // The channel is now marked IsPending in the database, and we can
2789
        // delete it from our set of active reservations.
2790
        f.deleteReservationCtx(peerKey, pendingChanID)
31✔
2791

31✔
2792
        // Broadcast the finalized funding transaction to the network, but only
31✔
2793
        // if we actually have the funding transaction.
31✔
2794
        if completeChan.ChanType.HasFundingTx() {
61✔
2795
                fundingTx := completeChan.FundingTxn
30✔
2796
                var fundingTxBuf bytes.Buffer
30✔
2797
                if err := fundingTx.Serialize(&fundingTxBuf); err != nil {
30✔
2798
                        log.Errorf("Unable to serialize funding "+
×
2799
                                "transaction %v: %v", fundingTx.TxHash(), err)
×
2800

×
2801
                        // Clear the buffer of any bytes that were written
×
2802
                        // before the serialization error to prevent logging an
×
2803
                        // incomplete transaction.
×
2804
                        fundingTxBuf.Reset()
×
2805
                }
×
2806

2807
                log.Infof("Broadcasting funding tx for ChannelPoint(%v): %x",
30✔
2808
                        completeChan.FundingOutpoint, fundingTxBuf.Bytes())
30✔
2809

30✔
2810
                // Set a nil short channel ID at this stage because we do not
30✔
2811
                // know it until our funding tx confirms.
30✔
2812
                label := labels.MakeLabel(
30✔
2813
                        labels.LabelTypeChannelOpen, nil,
30✔
2814
                )
30✔
2815

30✔
2816
                err = f.cfg.PublishTransaction(fundingTx, label)
30✔
2817
                if err != nil {
30✔
2818
                        log.Errorf("Unable to broadcast funding tx %x for "+
×
2819
                                "ChannelPoint(%v): %v", fundingTxBuf.Bytes(),
×
2820
                                completeChan.FundingOutpoint, err)
×
2821

×
2822
                        // We failed to broadcast the funding transaction, but
×
2823
                        // watch the channel regardless, in case the
×
2824
                        // transaction made it to the network. We will retry
×
2825
                        // broadcast at startup.
×
2826
                        //
×
2827
                        // TODO(halseth): retry more often? Handle with CPFP?
×
2828
                        // Just delete from the DB?
×
2829
                }
×
2830
        }
2831

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

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

2856
        log.Infof("Finalizing pending_id(%x) over ChannelPoint(%v), "+
31✔
2857
                "waiting for channel open on-chain", pendingChanID[:],
31✔
2858
                fundingPoint)
31✔
2859

31✔
2860
        // Send an update to the upstream client that the negotiation process
31✔
2861
        // is over.
31✔
2862
        upd := &lnrpc.OpenStatusUpdate{
31✔
2863
                Update: &lnrpc.OpenStatusUpdate_ChanPending{
31✔
2864
                        ChanPending: &lnrpc.PendingUpdate{
31✔
2865
                                Txid:        fundingPoint.Hash[:],
31✔
2866
                                OutputIndex: fundingPoint.Index,
31✔
2867
                        },
31✔
2868
                },
31✔
2869
                PendingChanId: pendingChanID[:],
31✔
2870
        }
31✔
2871

31✔
2872
        select {
31✔
2873
        case resCtx.updates <- upd:
31✔
2874
                // Inform the ChannelNotifier that the channel has entered
31✔
2875
                // pending open state.
31✔
2876
                f.cfg.NotifyPendingOpenChannelEvent(*fundingPoint, completeChan)
31✔
2877
        case <-f.quit:
×
2878
                return
×
2879
        }
2880

2881
        // At this point we have broadcast the funding transaction and done all
2882
        // necessary processing.
2883
        f.wg.Add(1)
31✔
2884
        go f.advanceFundingState(completeChan, pendingChanID, resCtx.updates)
31✔
2885
}
2886

2887
// confirmedChannel wraps a confirmed funding transaction, as well as the short
2888
// channel ID which identifies that channel into a single struct. We'll use
2889
// this to pass around the final state of a channel after it has been
2890
// confirmed.
2891
type confirmedChannel struct {
2892
        // shortChanID expresses where in the block the funding transaction was
2893
        // located.
2894
        shortChanID lnwire.ShortChannelID
2895

2896
        // fundingTx is the funding transaction that created the channel.
2897
        fundingTx *wire.MsgTx
2898
}
2899

2900
// fundingTimeout is called when callers of waitForFundingWithTimeout receive
2901
// an ErrConfirmationTimeout. It is used to clean-up channel state and mark the
2902
// channel as closed. The error is only returned for the responder of the
2903
// channel flow.
2904
func (f *Manager) fundingTimeout(c *channeldb.OpenChannel,
2905
        pendingID PendingChanID) error {
2✔
2906

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

2✔
2923
        // Close the channel with us as the initiator because we are timing the
2✔
2924
        // channel out.
2✔
2925
        if err := c.CloseChannel(
2✔
2926
                closeInfo, channeldb.ChanStatusLocalCloseInitiator,
2✔
2927
        ); err != nil {
2✔
2928
                return fmt.Errorf("failed closing channel %v: %w",
×
2929
                        c.FundingOutpoint, err)
×
2930
        }
×
2931

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

2✔
2935
        // When the peer comes online, we'll notify it that we are now
2✔
2936
        // considering the channel flow canceled.
2✔
2937
        f.wg.Add(1)
2✔
2938
        go func() {
4✔
2939
                defer f.wg.Done()
2✔
2940

2✔
2941
                peer, err := f.waitForPeerOnline(c.IdentityPub)
2✔
2942
                switch err {
2✔
2943
                // We're already shutting down, so we can just return.
2944
                case ErrFundingManagerShuttingDown:
×
2945
                        return
×
2946

2947
                // nil error means we continue on.
2948
                case nil:
2✔
2949

2950
                // For unexpected errors, we print the error and still try to
2951
                // fail the funding flow.
2952
                default:
×
2953
                        log.Errorf("Unexpected error while waiting for peer "+
×
2954
                                "to come online: %v", err)
×
2955
                }
2956

2957
                // Create channel identifier and set the channel ID.
2958
                cid := newChanIdentifier(pendingID)
2✔
2959
                cid.setChanID(lnwire.NewChanIDFromOutPoint(c.FundingOutpoint))
2✔
2960

2✔
2961
                // TODO(halseth): should this send be made
2✔
2962
                // reliable?
2✔
2963

2✔
2964
                // The reservation won't exist at this point, but we'll send an
2✔
2965
                // Error message over anyways with ChanID set to pendingID.
2✔
2966
                f.failFundingFlow(peer, cid, timeoutErr)
2✔
2967
        }()
2968

2969
        return timeoutErr
2✔
2970
}
2971

2972
// waitForFundingWithTimeout is a wrapper around waitForFundingConfirmation and
2973
// waitForTimeout that will return ErrConfirmationTimeout if we are not the
2974
// channel initiator and the MaxWaitNumBlocksFundingConf has passed from the
2975
// funding broadcast height. In case of confirmation, the short channel ID of
2976
// the channel and the funding transaction will be returned.
2977
func (f *Manager) waitForFundingWithTimeout(
2978
        ch *channeldb.OpenChannel) (*confirmedChannel, error) {
61✔
2979

61✔
2980
        confChan := make(chan *confirmedChannel)
61✔
2981
        timeoutChan := make(chan error, 1)
61✔
2982
        cancelChan := make(chan struct{})
61✔
2983

61✔
2984
        f.wg.Add(1)
61✔
2985
        go f.waitForFundingConfirmation(ch, cancelChan, confChan)
61✔
2986

61✔
2987
        // If we are not the initiator, we have no money at stake and will
61✔
2988
        // timeout waiting for the funding transaction to confirm after a
61✔
2989
        // while.
61✔
2990
        if !ch.IsInitiator && !ch.IsZeroConf() {
90✔
2991
                f.wg.Add(1)
29✔
2992
                go f.waitForTimeout(ch, cancelChan, timeoutChan)
29✔
2993
        }
29✔
2994
        defer close(cancelChan)
61✔
2995

61✔
2996
        select {
61✔
2997
        case err := <-timeoutChan:
2✔
2998
                if err != nil {
2✔
2999
                        return nil, err
×
3000
                }
×
3001
                return nil, ErrConfirmationTimeout
2✔
3002

3003
        case <-f.quit:
25✔
3004
                // The fundingManager is shutting down, and will resume wait on
25✔
3005
                // startup.
25✔
3006
                return nil, ErrFundingManagerShuttingDown
25✔
3007

3008
        case confirmedChannel, ok := <-confChan:
38✔
3009
                if !ok {
38✔
3010
                        return nil, fmt.Errorf("waiting for funding" +
×
3011
                                "confirmation failed")
×
3012
                }
×
3013
                return confirmedChannel, nil
38✔
3014
        }
3015
}
3016

3017
// makeFundingScript re-creates the funding script for the funding transaction
3018
// of the target channel.
3019
func makeFundingScript(channel *channeldb.OpenChannel) ([]byte, error) {
81✔
3020
        localKey := channel.LocalChanCfg.MultiSigKey.PubKey
81✔
3021
        remoteKey := channel.RemoteChanCfg.MultiSigKey.PubKey
81✔
3022

81✔
3023
        if channel.ChanType.IsTaproot() {
90✔
3024
                pkScript, _, err := input.GenTaprootFundingScript(
9✔
3025
                        localKey, remoteKey, int64(channel.Capacity),
9✔
3026
                        channel.TapscriptRoot,
9✔
3027
                )
9✔
3028
                if err != nil {
9✔
3029
                        return nil, err
×
3030
                }
×
3031

3032
                return pkScript, nil
9✔
3033
        }
3034

3035
        multiSigScript, err := input.GenMultiSigScript(
76✔
3036
                localKey.SerializeCompressed(),
76✔
3037
                remoteKey.SerializeCompressed(),
76✔
3038
        )
76✔
3039
        if err != nil {
76✔
3040
                return nil, err
×
3041
        }
×
3042

3043
        return input.WitnessScriptHash(multiSigScript)
76✔
3044
}
3045

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

61✔
3059
        defer f.wg.Done()
61✔
3060
        defer close(confChan)
61✔
3061

61✔
3062
        // Register with the ChainNotifier for a notification once the funding
61✔
3063
        // transaction reaches `numConfs` confirmations.
61✔
3064
        txid := completeChan.FundingOutpoint.Hash
61✔
3065
        fundingScript, err := makeFundingScript(completeChan)
61✔
3066
        if err != nil {
61✔
3067
                log.Errorf("unable to create funding script for "+
×
3068
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3069
                        err)
×
3070
                return
×
3071
        }
×
3072
        numConfs := uint32(completeChan.NumConfsRequired)
61✔
3073

61✔
3074
        // If the underlying channel is a zero-conf channel, we'll set numConfs
61✔
3075
        // to 6, since it will be zero here.
61✔
3076
        if completeChan.IsZeroConf() {
71✔
3077
                numConfs = 6
10✔
3078
        }
10✔
3079

3080
        confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
61✔
3081
                &txid, fundingScript, numConfs,
61✔
3082
                completeChan.BroadcastHeight(),
61✔
3083
        )
61✔
3084
        if err != nil {
61✔
3085
                log.Errorf("Unable to register for confirmation of "+
×
3086
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3087
                        err)
×
3088
                return
×
3089
        }
×
3090

3091
        log.Infof("Waiting for funding tx (%v) to reach %v confirmations",
61✔
3092
                txid, numConfs)
61✔
3093

61✔
3094
        var confDetails *chainntnfs.TxConfirmation
61✔
3095
        var ok bool
61✔
3096

61✔
3097
        // Wait until the specified number of confirmations has been reached,
61✔
3098
        // we get a cancel signal, or the wallet signals a shutdown.
61✔
3099
        select {
61✔
3100
        case confDetails, ok = <-confNtfn.Confirmed:
38✔
3101
                // fallthrough
3102

3103
        case <-cancelChan:
4✔
3104
                log.Warnf("canceled waiting for funding confirmation, "+
4✔
3105
                        "stopping funding flow for ChannelPoint(%v)",
4✔
3106
                        completeChan.FundingOutpoint)
4✔
3107
                return
4✔
3108

3109
        case <-f.quit:
23✔
3110
                log.Warnf("fundingManager shutting down, stopping funding "+
23✔
3111
                        "flow for ChannelPoint(%v)",
23✔
3112
                        completeChan.FundingOutpoint)
23✔
3113
                return
23✔
3114
        }
3115

3116
        if !ok {
38✔
3117
                log.Warnf("ChainNotifier shutting down, cannot complete "+
×
3118
                        "funding flow for ChannelPoint(%v)",
×
3119
                        completeChan.FundingOutpoint)
×
3120
                return
×
3121
        }
×
3122

3123
        fundingPoint := completeChan.FundingOutpoint
38✔
3124
        log.Infof("ChannelPoint(%v) is now active: ChannelID(%v)",
38✔
3125
                fundingPoint, lnwire.NewChanIDFromOutPoint(fundingPoint))
38✔
3126

38✔
3127
        // With the block height and the transaction index known, we can
38✔
3128
        // construct the compact chanID which is used on the network to unique
38✔
3129
        // identify channels.
38✔
3130
        shortChanID := lnwire.ShortChannelID{
38✔
3131
                BlockHeight: confDetails.BlockHeight,
38✔
3132
                TxIndex:     confDetails.TxIndex,
38✔
3133
                TxPosition:  uint16(fundingPoint.Index),
38✔
3134
        }
38✔
3135

38✔
3136
        select {
38✔
3137
        case confChan <- &confirmedChannel{
3138
                shortChanID: shortChanID,
3139
                fundingTx:   confDetails.Tx,
3140
        }:
38✔
3141
        case <-f.quit:
×
3142
                return
×
3143
        }
3144
}
3145

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

29✔
3156
        defer f.wg.Done()
29✔
3157

29✔
3158
        epochClient, err := f.cfg.Notifier.RegisterBlockEpochNtfn(nil)
29✔
3159
        if err != nil {
29✔
3160
                timeoutChan <- fmt.Errorf("unable to register for epoch "+
×
3161
                        "notification: %v", err)
×
3162
                return
×
3163
        }
×
3164

3165
        defer epochClient.Cancel()
29✔
3166

29✔
3167
        // On block maxHeight we will cancel the funding confirmation wait.
29✔
3168
        broadcastHeight := completeChan.BroadcastHeight()
29✔
3169
        maxHeight := broadcastHeight + MaxWaitNumBlocksFundingConf
29✔
3170
        for {
60✔
3171
                select {
31✔
3172
                case epoch, ok := <-epochClient.Epochs:
8✔
3173
                        if !ok {
8✔
3174
                                timeoutChan <- fmt.Errorf("epoch client " +
×
3175
                                        "shutting down")
×
3176
                                return
×
3177
                        }
×
3178

3179
                        // Close the timeout channel and exit if the block is
3180
                        // above the max height.
3181
                        if uint32(epoch.Height) >= maxHeight {
10✔
3182
                                log.Warnf("Waited for %v blocks without "+
2✔
3183
                                        "seeing funding transaction confirmed,"+
2✔
3184
                                        " cancelling.",
2✔
3185
                                        MaxWaitNumBlocksFundingConf)
2✔
3186

2✔
3187
                                // Notify the caller of the timeout.
2✔
3188
                                close(timeoutChan)
2✔
3189
                                return
2✔
3190
                        }
2✔
3191

3192
                        // TODO: If we are the channel initiator implement
3193
                        // a method for recovering the funds from the funding
3194
                        // transaction
3195

3196
                case <-cancelChan:
19✔
3197
                        return
19✔
3198

3199
                case <-f.quit:
12✔
3200
                        // The fundingManager is shutting down, will resume
12✔
3201
                        // waiting for the funding transaction on startup.
12✔
3202
                        return
12✔
3203
                }
3204
        }
3205
}
3206

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

20✔
3217
                // For zero-conf channels, we'll use the actually-confirmed
20✔
3218
                // short channel id.
20✔
3219
                if c.IsZeroConf() {
26✔
3220
                        shortChanID = c.ZeroConfRealScid()
6✔
3221
                }
6✔
3222

3223
                label := labels.MakeLabel(
20✔
3224
                        labels.LabelTypeChannelOpen, &shortChanID,
20✔
3225
                )
20✔
3226

20✔
3227
                err := f.cfg.UpdateLabel(c.FundingOutpoint.Hash, label)
20✔
3228
                if err != nil {
20✔
3229
                        log.Errorf("unable to update label: %v", err)
×
3230
                }
×
3231
        }
3232
}
3233

3234
// handleFundingConfirmation marks a channel as open in the database, and set
3235
// the channelOpeningState markedOpen. In addition it will report the now
3236
// decided short channel ID to the switch, and close the local discovery signal
3237
// for this channel.
3238
func (f *Manager) handleFundingConfirmation(
3239
        completeChan *channeldb.OpenChannel,
3240
        confChannel *confirmedChannel) error {
34✔
3241

34✔
3242
        fundingPoint := completeChan.FundingOutpoint
34✔
3243
        chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
34✔
3244

34✔
3245
        // TODO(roasbeef): ideally persistent state update for chan above
34✔
3246
        // should be abstracted
34✔
3247

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

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

3265
                err = f.cfg.AliasManager.AddLocalAlias(
6✔
3266
                        aliasScid, confChannel.shortChanID, true, false,
6✔
3267
                )
6✔
3268
                if err != nil {
6✔
3269
                        return fmt.Errorf("unable to request alias: %w", err)
×
3270
                }
×
3271
        }
3272

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

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

3295
        // Update the confirmed funding transaction label.
3296
        f.makeLabelForTx(completeChan)
34✔
3297

34✔
3298
        // Inform the ChannelNotifier that the channel has transitioned from
34✔
3299
        // pending open to open.
34✔
3300
        f.cfg.NotifyOpenChannelEvent(completeChan.FundingOutpoint)
34✔
3301

34✔
3302
        // Close the discoverySignal channel, indicating to a separate
34✔
3303
        // goroutine that the channel now is marked as open in the database
34✔
3304
        // and that it is acceptable to process channel_ready messages
34✔
3305
        // from the peer.
34✔
3306
        if discoverySignal, ok := f.localDiscoverySignals.Load(chanID); ok {
68✔
3307
                close(discoverySignal)
34✔
3308
        }
34✔
3309

3310
        return nil
34✔
3311
}
3312

3313
// sendChannelReady creates and sends the channelReady message.
3314
// This should be called after the funding transaction has been confirmed,
3315
// and the channelState is 'markedOpen'.
3316
func (f *Manager) sendChannelReady(completeChan *channeldb.OpenChannel,
3317
        channel *lnwallet.LightningChannel) error {
39✔
3318

39✔
3319
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
39✔
3320

39✔
3321
        var peerKey [33]byte
39✔
3322
        copy(peerKey[:], completeChan.IdentityPub.SerializeCompressed())
39✔
3323

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

39✔
3334
        // If this is a taproot channel, then we also need to send along our
39✔
3335
        // set of musig2 nonces as well.
39✔
3336
        if completeChan.ChanType.IsTaproot() {
47✔
3337
                log.Infof("ChanID(%v): generating musig2 nonces...",
8✔
3338
                        chanID)
8✔
3339

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

3354
                        // Now that we've generated the nonce for this channel,
3355
                        // we'll store it in the set of pending nonces.
3356
                        localNonce = newNonce
8✔
3357
                        f.pendingMusigNonces[chanID] = localNonce
8✔
3358
                }
3359
                f.nonceMtx.Unlock()
8✔
3360

8✔
3361
                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
8✔
3362
                        localNonce.PubNonce,
8✔
3363
                )
8✔
3364
        }
3365

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

3379
                // We can use a pointer to aliases since GetAliases returns a
3380
                // copy of the alias slice.
3381
                channelReadyMsg.AliasScid = &aliases[0]
10✔
3382
        }
3383

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

3401
                localAlias := peer.LocalFeatures().HasFeature(
38✔
3402
                        lnwire.ScidAliasOptional,
38✔
3403
                )
38✔
3404
                remoteAlias := peer.RemoteFeatures().HasFeature(
38✔
3405
                        lnwire.ScidAliasOptional,
38✔
3406
                )
38✔
3407

38✔
3408
                // We could also refresh the channel state instead of checking
38✔
3409
                // whether the feature was negotiated, but this saves us a
38✔
3410
                // database read.
38✔
3411
                if channelReadyMsg.AliasScid == nil && localAlias &&
38✔
3412
                        remoteAlias {
38✔
3413

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

3430
                                err = f.cfg.AliasManager.AddLocalAlias(
×
3431
                                        alias, completeChan.ShortChannelID,
×
3432
                                        false, false,
×
3433
                                )
×
3434
                                if err != nil {
×
3435
                                        return err
×
3436
                                }
×
3437

3438
                                channelReadyMsg.AliasScid = &alias
×
3439
                        } else {
×
3440
                                channelReadyMsg.AliasScid = &aliases[0]
×
3441
                        }
×
3442
                }
3443

3444
                log.Infof("Peer(%x) is online, sending ChannelReady "+
38✔
3445
                        "for ChannelID(%v)", peerKey, chanID)
38✔
3446

38✔
3447
                if err := peer.SendMessage(true, channelReadyMsg); err == nil {
76✔
3448
                        // Sending succeeded, we can break out and continue the
38✔
3449
                        // funding flow.
38✔
3450
                        break
38✔
3451
                }
3452

3453
                log.Warnf("Unable to send channelReady to peer %x: %v. "+
×
3454
                        "Will retry when online", peerKey, err)
×
3455
        }
3456

3457
        return nil
38✔
3458
}
3459

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

64✔
3465
        // If the funding manager has exited, return an error to stop looping.
64✔
3466
        // Note that the peer may appear as online while the funding manager
64✔
3467
        // has stopped due to the shutdown order in the server.
64✔
3468
        select {
64✔
UNCOV
3469
        case <-f.quit:
×
UNCOV
3470
                return false, ErrFundingManagerShuttingDown
×
3471
        default:
64✔
3472
        }
3473

3474
        // Avoid a tight loop if peer is offline.
3475
        if _, err := f.waitForPeerOnline(node); err != nil {
64✔
3476
                log.Errorf("Wait for peer online failed: %v", err)
×
3477
                return false, err
×
3478
        }
×
3479

3480
        // If we cannot find the channel, then we haven't processed the
3481
        // remote's channelReady message.
3482
        channel, err := f.cfg.FindChannel(node, chanID)
64✔
3483
        if err != nil {
64✔
3484
                log.Errorf("Unable to locate ChannelID(%v) to determine if "+
×
3485
                        "ChannelReady was received", chanID)
×
3486
                return false, err
×
3487
        }
×
3488

3489
        // If we haven't insert the next revocation point, we haven't finished
3490
        // processing the channel ready message.
3491
        if channel.RemoteNextRevocation == nil {
104✔
3492
                return false, nil
40✔
3493
        }
40✔
3494

3495
        // Finally, the barrier signal is removed once we finish
3496
        // `handleChannelReady`. If we can still find the signal, we haven't
3497
        // finished processing it yet.
3498
        _, loaded := f.handleChannelReadyBarriers.Load(chanID)
28✔
3499

28✔
3500
        return !loaded, nil
28✔
3501
}
3502

3503
// extractAnnounceParams extracts the various channel announcement and update
3504
// parameters that will be needed to construct a ChannelAnnouncement and a
3505
// ChannelUpdate.
3506
func (f *Manager) extractAnnounceParams(c *channeldb.OpenChannel) (
3507
        lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
30✔
3508

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

30✔
3515
        // We don't necessarily want to go as low as the remote party allows.
30✔
3516
        // Check it against our default forwarding policy.
30✔
3517
        if fwdMinHTLC < f.cfg.DefaultRoutingPolicy.MinHTLCOut {
34✔
3518
                fwdMinHTLC = f.cfg.DefaultRoutingPolicy.MinHTLCOut
4✔
3519
        }
4✔
3520

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

3530
        return fwdMinHTLC, fwdMaxHTLC
30✔
3531
}
3532

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

30✔
3546
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
30✔
3547

30✔
3548
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
30✔
3549

30✔
3550
        ann, err := f.newChanAnnouncement(
30✔
3551
                f.cfg.IDKey, completeChan.IdentityPub,
30✔
3552
                &completeChan.LocalChanCfg.MultiSigKey,
30✔
3553
                completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
30✔
3554
                chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
30✔
3555
                completeChan.ChanType,
30✔
3556
        )
30✔
3557
        if err != nil {
30✔
3558
                return fmt.Errorf("error generating channel "+
×
3559
                        "announcement: %v", err)
×
3560
        }
×
3561

3562
        // Send ChannelAnnouncement and ChannelUpdate to the gossiper to add
3563
        // to the Router's topology.
3564
        errChan := f.cfg.SendAnnouncement(
30✔
3565
                ann.chanAnn, discovery.ChannelCapacity(completeChan.Capacity),
30✔
3566
                discovery.ChannelPoint(completeChan.FundingOutpoint),
30✔
3567
                discovery.TapscriptRoot(completeChan.TapscriptRoot),
30✔
3568
        )
30✔
3569
        select {
30✔
3570
        case err := <-errChan:
30✔
3571
                if err != nil {
30✔
3572
                        if graph.IsError(err, graph.ErrOutdated,
×
3573
                                graph.ErrIgnored) {
×
3574

×
3575
                                log.Debugf("Graph rejected "+
×
3576
                                        "ChannelAnnouncement: %v", err)
×
3577
                        } else {
×
3578
                                return fmt.Errorf("error sending channel "+
×
3579
                                        "announcement: %v", err)
×
3580
                        }
×
3581
                }
3582
        case <-f.quit:
×
3583
                return ErrFundingManagerShuttingDown
×
3584
        }
3585

3586
        errChan = f.cfg.SendAnnouncement(
30✔
3587
                ann.chanUpdateAnn, discovery.RemoteAlias(peerAlias),
30✔
3588
        )
30✔
3589
        select {
30✔
3590
        case err := <-errChan:
30✔
3591
                if err != nil {
30✔
3592
                        if graph.IsError(err, graph.ErrOutdated,
×
3593
                                graph.ErrIgnored) {
×
3594

×
3595
                                log.Debugf("Graph rejected "+
×
3596
                                        "ChannelUpdate: %v", err)
×
3597
                        } else {
×
3598
                                return fmt.Errorf("error sending channel "+
×
3599
                                        "update: %v", err)
×
3600
                        }
×
3601
                }
3602
        case <-f.quit:
×
3603
                return ErrFundingManagerShuttingDown
×
3604
        }
3605

3606
        return nil
30✔
3607
}
3608

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

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

12✔
3626
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
12✔
3627
                if err != nil {
12✔
3628
                        return err
×
3629
                }
×
3630

3631
                nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
12✔
3632
                if err != nil {
12✔
3633
                        return fmt.Errorf("unable to retrieve current node "+
×
3634
                                "announcement: %v", err)
×
3635
                }
×
3636

3637
                chanID := lnwire.NewChanIDFromOutPoint(
12✔
3638
                        completeChan.FundingOutpoint,
12✔
3639
                )
12✔
3640
                pubKey := peer.PubKey()
12✔
3641
                log.Debugf("Sending our NodeAnnouncement for "+
12✔
3642
                        "ChannelID(%v) to %x", chanID, pubKey)
12✔
3643

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

22✔
3664
                fundingScript, err := makeFundingScript(completeChan)
22✔
3665
                if err != nil {
22✔
3666
                        return fmt.Errorf("unable to create funding script "+
×
3667
                                "for ChannelPoint(%v): %v",
×
3668
                                completeChan.FundingOutpoint, err)
×
3669
                }
×
3670

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

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

3695
                case <-f.quit:
6✔
3696
                        return fmt.Errorf("%v, stopping funding flow for "+
6✔
3697
                                "ChannelPoint(%v)",
6✔
3698
                                ErrFundingManagerShuttingDown,
6✔
3699
                                completeChan.FundingOutpoint)
6✔
3700
                }
3701

3702
                fundingPoint := completeChan.FundingOutpoint
20✔
3703
                chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
20✔
3704

20✔
3705
                log.Infof("Announcing ChannelPoint(%v), short_chan_id=%v",
20✔
3706
                        &fundingPoint, shortChanID)
20✔
3707

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

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

3733
                        err = f.addToGraph(
4✔
3734
                                completeChan, &baseScid, nil, ourPolicy,
4✔
3735
                        )
4✔
3736
                        if err != nil {
4✔
3737
                                return fmt.Errorf("failed to re-add to "+
×
3738
                                        "graph: %v", err)
×
3739
                        }
×
3740
                }
3741

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

3755
                log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+
20✔
3756
                        "sent to gossiper", &fundingPoint, shortChanID)
20✔
3757
        }
3758

3759
        return nil
28✔
3760
}
3761

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

3776
        // We'll need to refresh the channel state so that things are properly
3777
        // populated when validating the channel state. Otherwise, a panic may
3778
        // occur due to inconsistency in the OpenChannel struct.
3779
        err = c.Refresh()
8✔
3780
        if err != nil {
12✔
3781
                return fmt.Errorf("unable to refresh channel state: %w", err)
4✔
3782
        }
4✔
3783

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

3793
        // Once we know the confirmed ShortChannelID, we'll need to save it to
3794
        // the database and refresh the OpenChannel struct with it.
3795
        err = c.MarkRealScid(confChan.shortChanID)
8✔
3796
        if err != nil {
8✔
3797
                return fmt.Errorf("unable to set confirmed SCID for zero "+
×
3798
                        "channel: %v", err)
×
3799
        }
×
3800

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

3811
                // TODO: Make this atomic!
3812
                ourPolicy, err := f.cfg.DeleteAliasEdge(c.ShortChanID())
6✔
3813
                if err != nil {
6✔
3814
                        return fmt.Errorf("unable to delete alias edge from "+
×
3815
                                "graph: %v", err)
×
3816
                }
×
3817

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

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

3844
        // Update the confirmed transaction's label.
3845
        f.makeLabelForTx(c)
8✔
3846

8✔
3847
        return nil
8✔
3848
}
3849

3850
// genFirstStateMusigNonce generates a nonces for the "first" local state. This
3851
// is the verification nonce for the state created for us after the initial
3852
// commitment transaction signed as part of the funding flow.
3853
func genFirstStateMusigNonce(channel *channeldb.OpenChannel,
3854
) (*musig2.Nonces, error) {
8✔
3855

8✔
3856
        musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
8✔
3857
                channel.RevocationProducer,
8✔
3858
        )
8✔
3859
        if err != nil {
8✔
3860
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3861
                        "nonces: %v", err)
×
3862
        }
×
3863

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

3876
        return verNonce, nil
8✔
3877
}
3878

3879
// handleChannelReady finalizes the channel funding process and enables the
3880
// channel to enter normal operating mode.
3881
func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen
3882
        msg *lnwire.ChannelReady) {
32✔
3883

32✔
3884
        defer f.wg.Done()
32✔
3885

32✔
3886
        // If we are in development mode, we'll wait for specified duration
32✔
3887
        // before processing the channel ready message.
32✔
3888
        if f.cfg.Dev != nil {
36✔
3889
                duration := f.cfg.Dev.ProcessChannelReadyWait
4✔
3890
                log.Warnf("Channel(%v): sleeping %v before processing "+
4✔
3891
                        "channel_ready", msg.ChanID, duration)
4✔
3892

4✔
3893
                select {
4✔
3894
                case <-time.After(duration):
4✔
3895
                        log.Warnf("Channel(%v): slept %v before processing "+
4✔
3896
                                "channel_ready", msg.ChanID, duration)
4✔
3897
                case <-f.quit:
×
3898
                        log.Warnf("Channel(%v): quit sleeping", msg.ChanID)
×
3899
                        return
×
3900
                }
3901
        }
3902

3903
        log.Debugf("Received ChannelReady for ChannelID(%v) from "+
32✔
3904
                "peer %x", msg.ChanID,
32✔
3905
                peer.IdentityKey().SerializeCompressed())
32✔
3906

32✔
3907
        // We now load or create a new channel barrier for this channel.
32✔
3908
        _, loaded := f.handleChannelReadyBarriers.LoadOrStore(
32✔
3909
                msg.ChanID, struct{}{},
32✔
3910
        )
32✔
3911

32✔
3912
        // If we are currently in the process of handling a channel_ready
32✔
3913
        // message for this channel, ignore.
32✔
3914
        if loaded {
37✔
3915
                log.Infof("Already handling channelReady for "+
5✔
3916
                        "ChannelID(%v), ignoring.", msg.ChanID)
5✔
3917
                return
5✔
3918
        }
5✔
3919

3920
        // If not already handling channelReady for this channel, then the
3921
        // `LoadOrStore` has set up a barrier, and it will be removed once this
3922
        // function exits.
3923
        defer f.handleChannelReadyBarriers.Delete(msg.ChanID)
31✔
3924

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

3939
                // With the signal received, we can now safely delete the entry
3940
                // from the map.
3941
                f.localDiscoverySignals.Delete(msg.ChanID)
29✔
3942
        }
3943

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

3956
        // If this is a taproot channel, then we can generate the set of nonces
3957
        // the remote party needs to send the next remote commitment here.
3958
        var firstVerNonce *musig2.Nonces
31✔
3959
        if channel.ChanType.IsTaproot() {
39✔
3960
                firstVerNonce, err = genFirstStateMusigNonce(channel)
8✔
3961
                if err != nil {
8✔
3962
                        log.Error(err)
×
3963
                        return
×
3964
                }
×
3965
        }
3966

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

3984
                // We'll store the AliasScid so that invoice creation can use
3985
                // it.
3986
                err = f.cfg.AliasManager.PutPeerAlias(chanID, *msg.AliasScid)
10✔
3987
                if err != nil {
10✔
3988
                        log.Errorf("unable to store peer's alias: %v", err)
×
3989
                        return
×
3990
                }
×
3991

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

4009
                        err = f.cfg.AliasManager.AddLocalAlias(
×
4010
                                alias, channel.ShortChannelID, false, false,
×
4011
                        )
×
4012
                        if err != nil {
×
4013
                                log.Errorf("unable to add local alias: %v",
×
4014
                                        err)
×
4015
                                return
×
4016
                        }
×
4017

4018
                        secondPoint, err := channel.SecondCommitmentPoint()
×
4019
                        if err != nil {
×
4020
                                log.Errorf("unable to fetch second "+
×
4021
                                        "commitment point: %v", err)
×
4022
                                return
×
4023
                        }
×
4024

4025
                        channelReadyMsg := lnwire.NewChannelReady(
×
4026
                                chanID, secondPoint,
×
4027
                        )
×
4028
                        channelReadyMsg.AliasScid = &alias
×
4029

×
4030
                        if firstVerNonce != nil {
×
4031
                                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:ll
×
4032
                                        firstVerNonce.PubNonce,
×
4033
                                )
×
4034
                        }
×
4035

4036
                        err = peer.SendMessage(true, channelReadyMsg)
×
4037
                        if err != nil {
×
4038
                                log.Errorf("unable to send channel_ready: %v",
×
4039
                                        err)
×
4040
                                return
×
4041
                        }
×
4042
                }
4043
        }
4044

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

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

8✔
4075
                log.Infof("ChanID(%v): applying local+remote musig2 nonces",
8✔
4076
                        chanID)
8✔
4077

8✔
4078
                remoteNonce, err := msg.NextLocalNonce.UnwrapOrErrV(
8✔
4079
                        errNoLocalNonce,
8✔
4080
                )
8✔
4081
                if err != nil {
8✔
4082
                        cid := newChanIdentifier(msg.ChanID)
×
4083
                        f.sendWarning(peer, cid, err)
×
4084

×
4085
                        return
×
4086
                }
×
4087

4088
                chanOpts = append(
8✔
4089
                        chanOpts,
8✔
4090
                        lnwallet.WithLocalMusigNonces(localNonce),
8✔
4091
                        lnwallet.WithRemoteMusigNonces(&musig2.Nonces{
8✔
4092
                                PubNonce: remoteNonce,
8✔
4093
                        }),
8✔
4094
                )
8✔
4095

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

×
4113
                        return
×
4114
                }
×
4115
        }
4116

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

4127
        // Before we can add the channel to the peer, we'll need to ensure that
4128
        // we have an initial forwarding policy set.
4129
        if err := f.ensureInitialForwardingPolicy(chanID, channel); err != nil {
30✔
4130
                log.Errorf("Unable to ensure initial forwarding policy: %v",
×
4131
                        err)
×
4132
        }
×
4133

4134
        err = peer.AddNewChannel(&lnpeer.NewChannel{
30✔
4135
                OpenChannel: channel,
30✔
4136
                ChanOpts:    chanOpts,
30✔
4137
        }, f.quit)
30✔
4138
        if err != nil {
30✔
4139
                log.Errorf("Unable to add new channel %v with peer %x: %v",
×
4140
                        channel.FundingOutpoint,
×
4141
                        peer.IdentityKey().SerializeCompressed(), err,
×
4142
                )
×
4143
        }
×
4144
}
4145

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

28✔
4155
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
28✔
4156

28✔
4157
        // Since we've sent+received funding locked at this point, we
28✔
4158
        // can clean up the pending musig2 nonce state.
28✔
4159
        f.nonceMtx.Lock()
28✔
4160
        delete(f.pendingMusigNonces, chanID)
28✔
4161
        f.nonceMtx.Unlock()
28✔
4162

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

4178
                peerAlias = &foundAlias
8✔
4179
        }
4180

4181
        err := f.addToGraph(channel, scid, peerAlias, nil)
28✔
4182
        if err != nil {
28✔
4183
                return fmt.Errorf("failed adding to graph: %w", err)
×
4184
        }
×
4185

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

4198
        log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
28✔
4199
                "added to graph", chanID, scid)
28✔
4200

28✔
4201
        err = fn.MapOptionZ(
28✔
4202
                f.cfg.AuxFundingController,
28✔
4203
                func(controller AuxFundingController) error {
28✔
4204
                        return controller.ChannelReady(
×
4205
                                lnwallet.NewAuxChanState(channel),
×
4206
                        )
×
4207
                },
×
4208
        )
4209
        if err != nil {
28✔
4210
                return fmt.Errorf("failed notifying aux funding controller "+
×
4211
                        "about channel ready: %w", err)
×
4212
        }
×
4213

4214
        // Give the caller a final update notifying them that the channel is
4215
        fundingPoint := channel.FundingOutpoint
28✔
4216
        cp := &lnrpc.ChannelPoint{
28✔
4217
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
28✔
4218
                        FundingTxidBytes: fundingPoint.Hash[:],
28✔
4219
                },
28✔
4220
                OutputIndex: fundingPoint.Index,
28✔
4221
        }
28✔
4222

28✔
4223
        if updateChan != nil {
42✔
4224
                upd := &lnrpc.OpenStatusUpdate{
14✔
4225
                        Update: &lnrpc.OpenStatusUpdate_ChanOpen{
14✔
4226
                                ChanOpen: &lnrpc.ChannelOpenUpdate{
14✔
4227
                                        ChannelPoint: cp,
14✔
4228
                                },
14✔
4229
                        },
14✔
4230
                        PendingChanId: pendingChanID[:],
14✔
4231
                }
14✔
4232

14✔
4233
                select {
14✔
4234
                case updateChan <- upd:
14✔
4235
                case <-f.quit:
×
4236
                        return ErrFundingManagerShuttingDown
×
4237
                }
4238
        }
4239

4240
        return nil
28✔
4241
}
4242

4243
// ensureInitialForwardingPolicy ensures that we have an initial forwarding
4244
// policy set for the given channel. If we don't, we'll fall back to the default
4245
// values.
4246
func (f *Manager) ensureInitialForwardingPolicy(chanID lnwire.ChannelID,
4247
        channel *channeldb.OpenChannel) error {
30✔
4248

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

×
4259
                forwardingPolicy = f.defaultForwardingPolicy(
×
4260
                        channel.LocalChanCfg.ChannelStateBounds,
×
4261
                )
×
4262
                needDBUpdate = true
×
4263
        }
×
4264

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

4278
        // And finally, if we found that the values currently stored aren't
4279
        // sufficient for the link, we'll update the database.
4280
        if needDBUpdate {
47✔
4281
                err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
17✔
4282
                if err != nil {
17✔
4283
                        return fmt.Errorf("unable to update initial "+
×
4284
                                "forwarding policy: %v", err)
×
4285
                }
×
4286
        }
4287

4288
        return nil
30✔
4289
}
4290

4291
// chanAnnouncement encapsulates the two authenticated announcements that we
4292
// send out to the network after a new channel has been created locally.
4293
type chanAnnouncement struct {
4294
        chanAnn       *lnwire.ChannelAnnouncement1
4295
        chanUpdateAnn *lnwire.ChannelUpdate1
4296
        chanProof     *lnwire.AnnounceSignatures1
4297
}
4298

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

46✔
4314
        chainHash := *f.cfg.Wallet.Cfg.NetParams.GenesisHash
46✔
4315

46✔
4316
        // The unconditional section of the announcement is the ShortChannelID
46✔
4317
        // itself which compactly encodes the location of the funding output
46✔
4318
        // within the blockchain.
46✔
4319
        chanAnn := &lnwire.ChannelAnnouncement1{
46✔
4320
                ShortChannelID: shortChanID,
46✔
4321
                Features:       lnwire.NewRawFeatureVector(),
46✔
4322
                ChainHash:      chainHash,
46✔
4323
        }
46✔
4324

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

8✔
4334
                chanAnn.Features.Set(
8✔
4335
                        lnwire.SimpleTaprootChannelsRequiredStaging,
8✔
4336
                )
8✔
4337
        }
8✔
4338

4339
        // The chanFlags field indicates which directed edge of the channel is
4340
        // being updated within the ChannelUpdateAnnouncement announcement
4341
        // below. A value of zero means it's the edge of the "first" node and 1
4342
        // being the other node.
4343
        var chanFlags lnwire.ChanUpdateChanFlags
46✔
4344

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

25✔
4363
                // If we're the first node then update the chanFlags to
25✔
4364
                // indicate the "direction" of the update.
25✔
4365
                chanFlags = 0
25✔
4366
        } else {
50✔
4367
                copy(chanAnn.NodeID1[:], remotePubKey.SerializeCompressed())
25✔
4368
                copy(chanAnn.NodeID2[:], localPubKey.SerializeCompressed())
25✔
4369
                copy(
25✔
4370
                        chanAnn.BitcoinKey1[:],
25✔
4371
                        remoteFundingKey.SerializeCompressed(),
25✔
4372
                )
25✔
4373
                copy(
25✔
4374
                        chanAnn.BitcoinKey2[:],
25✔
4375
                        localFundingKey.PubKey.SerializeCompressed(),
25✔
4376
                )
25✔
4377

25✔
4378
                // If we're the second node then update the chanFlags to
25✔
4379
                // indicate the "direction" of the update.
25✔
4380
                chanFlags = 1
25✔
4381
        }
25✔
4382

4383
        // Our channel update message flags will signal that we support the
4384
        // max_htlc field.
4385
        msgFlags := lnwire.ChanUpdateRequiredMaxHtlc
46✔
4386

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

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

4412
        switch {
46✔
4413
        case ourPolicy != nil:
4✔
4414
                // If ourPolicy is non-nil, modify the default parameters of the
4✔
4415
                // ChannelUpdate.
4✔
4416
                chanUpdateAnn.MessageFlags = ourPolicy.MessageFlags
4✔
4417
                chanUpdateAnn.ChannelFlags = ourPolicy.ChannelFlags
4✔
4418
                chanUpdateAnn.TimeLockDelta = ourPolicy.TimeLockDelta
4✔
4419
                chanUpdateAnn.HtlcMinimumMsat = ourPolicy.MinHTLC
4✔
4420
                chanUpdateAnn.HtlcMaximumMsat = ourPolicy.MaxHTLC
4✔
4421
                chanUpdateAnn.BaseFee = uint32(ourPolicy.FeeBaseMSat)
4✔
4422
                chanUpdateAnn.FeeRate = uint32(
4✔
4423
                        ourPolicy.FeeProportionalMillionths,
4✔
4424
                )
4✔
4425

4426
        case storedFwdingPolicy != nil:
46✔
4427
                chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
46✔
4428
                chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
46✔
4429

4430
        default:
×
4431
                log.Infof("No channel forwarding policy specified for channel "+
×
4432
                        "announcement of ChannelID(%v). "+
×
4433
                        "Assuming default fee parameters.", chanID)
×
4434
                chanUpdateAnn.BaseFee = uint32(
×
4435
                        f.cfg.DefaultRoutingPolicy.BaseFee,
×
4436
                )
×
4437
                chanUpdateAnn.FeeRate = uint32(
×
4438
                        f.cfg.DefaultRoutingPolicy.FeeRate,
×
4439
                )
×
4440
        }
4441

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

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

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

4501
        return &chanAnnouncement{
46✔
4502
                chanAnn:       chanAnn,
46✔
4503
                chanUpdateAnn: chanUpdateAnn,
46✔
4504
                chanProof:     proof,
46✔
4505
        }, nil
46✔
4506
}
4507

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

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

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

×
4547
                                log.Debugf("Graph rejected "+
×
4548
                                        "AnnounceSignatures: %v", err)
×
4549
                        } else {
4✔
4550
                                log.Errorf("Unable to send channel "+
4✔
4551
                                        "proof: %v", err)
4✔
4552
                                return err
4✔
4553
                        }
4✔
4554
                }
4555

4556
        case <-f.quit:
×
4557
                return ErrFundingManagerShuttingDown
×
4558
        }
4559

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

4570
        errChan = f.cfg.SendAnnouncement(&nodeAnn)
20✔
4571
        select {
20✔
4572
        case err := <-errChan:
20✔
4573
                if err != nil {
24✔
4574
                        if graph.IsError(err, graph.ErrOutdated,
4✔
4575
                                graph.ErrIgnored) {
8✔
4576

4✔
4577
                                log.Debugf("Graph rejected "+
4✔
4578
                                        "NodeAnnouncement: %v", err)
4✔
4579
                        } else {
4✔
4580
                                log.Errorf("Unable to send node "+
×
4581
                                        "announcement: %v", err)
×
4582
                                return err
×
4583
                        }
×
4584
                }
4585

4586
        case <-f.quit:
×
4587
                return ErrFundingManagerShuttingDown
×
4588
        }
4589

4590
        return nil
20✔
4591
}
4592

4593
// InitFundingWorkflow sends a message to the funding manager instructing it
4594
// to initiate a single funder workflow with the source peer.
4595
func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg) {
60✔
4596
        f.fundingRequests <- msg
60✔
4597
}
60✔
4598

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

112✔
4611
        // Check whether the remote peer supports upfront shutdown scripts.
112✔
4612
        remoteUpfrontShutdown := peer.RemoteFeatures().HasFeature(
112✔
4613
                lnwire.UpfrontShutdownScriptOptional,
112✔
4614
        )
112✔
4615

112✔
4616
        // If the peer does not support upfront shutdown scripts, and one has been
112✔
4617
        // provided, return an error because the feature is not supported.
112✔
4618
        if !remoteUpfrontShutdown && len(script) != 0 {
113✔
4619
                return nil, errUpfrontShutdownScriptNotSupported
1✔
4620
        }
1✔
4621

4622
        // If the peer does not support upfront shutdown, return an empty address.
4623
        if !remoteUpfrontShutdown {
214✔
4624
                return nil, nil
103✔
4625
        }
103✔
4626

4627
        // If the user has provided an script and the peer supports the feature,
4628
        // return it. Note that user set scripts override the enable upfront
4629
        // shutdown flag.
4630
        if len(script) > 0 {
14✔
4631
                return script, nil
6✔
4632
        }
6✔
4633

4634
        // If we do not have setting of upfront shutdown script enabled, return
4635
        // an empty script.
4636
        if !enableUpfrontShutdown {
11✔
4637
                return nil, nil
5✔
4638
        }
5✔
4639

4640
        // We can safely send a taproot address iff, both sides have negotiated
4641
        // the shutdown-any-segwit feature.
4642
        taprootOK := peer.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
1✔
4643
                peer.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
1✔
4644

1✔
4645
        return getScript(taprootOK)
1✔
4646
}
4647

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

60✔
4666
        // If no maximum CSV delay was set for this channel, we use our default
60✔
4667
        // value.
60✔
4668
        if maxCSV == 0 {
120✔
4669
                maxCSV = f.cfg.MaxLocalCSVDelay
60✔
4670
        }
60✔
4671

4672
        log.Infof("Initiating fundingRequest(local_amt=%v "+
60✔
4673
                "(subtract_fees=%v), push_amt=%v, chain_hash=%v, peer=%x, "+
60✔
4674
                "min_confs=%v)", localAmt, msg.SubtractFees, msg.PushAmt,
60✔
4675
                msg.ChainHash, peerKey.SerializeCompressed(), msg.MinConfs)
60✔
4676

60✔
4677
        // We set the channel flags to indicate whether we want this channel to
60✔
4678
        // be announced to the network.
60✔
4679
        var channelFlags lnwire.FundingFlag
60✔
4680
        if !msg.Private {
115✔
4681
                // This channel will be announced.
55✔
4682
                channelFlags = lnwire.FFAnnounceChannel
55✔
4683
        }
55✔
4684

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

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

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

4733
        var (
60✔
4734
                zeroConf bool
60✔
4735
                scid     bool
60✔
4736
        )
60✔
4737

60✔
4738
        if chanType != nil {
68✔
4739
                // Check if the returned chanType includes either the zero-conf
8✔
4740
                // or scid-alias bits.
8✔
4741
                featureVec := lnwire.RawFeatureVector(*chanType)
8✔
4742
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
8✔
4743
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
8✔
4744

8✔
4745
                // The option-scid-alias channel type for a public channel is
8✔
4746
                // disallowed.
8✔
4747
                if scid && !msg.Private {
8✔
4748
                        err = fmt.Errorf("option-scid-alias chantype for " +
×
4749
                                "public channel")
×
4750
                        log.Error(err)
×
4751
                        msg.Err <- err
×
4752

×
4753
                        return
×
4754
                }
×
4755
        }
4756

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

4767
        // For anchor channels cap the initial commit fee rate at our defined
4768
        // maximum.
4769
        if commitType.HasAnchors() &&
60✔
4770
                commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
68✔
4771

8✔
4772
                commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate
8✔
4773
        }
8✔
4774

4775
        var scidFeatureVal bool
60✔
4776
        if hasFeatures(
60✔
4777
                msg.Peer.LocalFeatures(), msg.Peer.RemoteFeatures(),
60✔
4778
                lnwire.ScidAliasOptional,
60✔
4779
        ) {
67✔
4780

7✔
4781
                scidFeatureVal = true
7✔
4782
        }
7✔
4783

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

×
4798
                return
×
4799
        }
×
4800

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

4831
                        // Query the sweeper storage to make sure we don't use
4832
                        // an unconfirmed utxo still in use by the sweeper
4833
                        // subsystem.
4834
                        return !f.cfg.IsSweeperOutpoint(u.OutPoint)
61✔
4835
                },
4836
                ZeroConf:         zeroConf,
4837
                OptionScidAlias:  scid,
4838
                ScidAliasFeature: scidFeatureVal,
4839
                Memo:             msg.Memo,
4840
                TapscriptRoot:    tapscriptRoot,
4841
        }
4842

4843
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
60✔
4844
        if err != nil {
64✔
4845
                msg.Err <- err
4✔
4846
                return
4✔
4847
        }
4✔
4848

4849
        if zeroConf {
66✔
4850
                // Store the alias for zero-conf channels in the underlying
6✔
4851
                // partial channel state.
6✔
4852
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
6✔
4853
                if err != nil {
6✔
4854
                        msg.Err <- err
×
4855
                        return
×
4856
                }
×
4857

4858
                reservation.AddAlias(aliasScid)
6✔
4859
        }
4860

4861
        // Set our upfront shutdown address in the existing reservation.
4862
        reservation.SetOurUpfrontShutdown(shutdown)
60✔
4863

60✔
4864
        // Now that we have successfully reserved funds for this channel in the
60✔
4865
        // wallet, we can fetch the final channel capacity. This is done at
60✔
4866
        // this point since the final capacity might change in case of
60✔
4867
        // SubtractFees=true.
60✔
4868
        capacity := reservation.Capacity()
60✔
4869

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

60✔
4873
        // If the remote CSV delay was not set in the open channel request,
60✔
4874
        // we'll use the RequiredRemoteDelay closure to compute the delay we
60✔
4875
        // require given the total amount of funds within the channel.
60✔
4876
        if remoteCsvDelay == 0 {
119✔
4877
                remoteCsvDelay = f.cfg.RequiredRemoteDelay(capacity)
59✔
4878
        }
59✔
4879

4880
        // If no minimum HTLC value was specified, use the default one.
4881
        if minHtlcIn == 0 {
119✔
4882
                minHtlcIn = f.cfg.DefaultMinHtlcIn
59✔
4883
        }
59✔
4884

4885
        // If no max value was specified, use the default one.
4886
        if maxValue == 0 {
119✔
4887
                maxValue = f.cfg.RequiredRemoteMaxValue(capacity)
59✔
4888
        }
59✔
4889

4890
        if maxHtlcs == 0 {
120✔
4891
                maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
60✔
4892
        }
60✔
4893

4894
        // Once the reservation has been created, and indexed, queue a funding
4895
        // request to the remote peer, kicking off the funding workflow.
4896
        ourContribution := reservation.OurContribution()
60✔
4897

60✔
4898
        // Prepare the optional channel fee values from the initFundingMsg. If
60✔
4899
        // useBaseFee or useFeeRate are false the client did not provide fee
60✔
4900
        // values hence we assume default fee settings from the config.
60✔
4901
        forwardingPolicy := f.defaultForwardingPolicy(
60✔
4902
                ourContribution.ChannelStateBounds,
60✔
4903
        )
60✔
4904
        if baseFee != nil {
65✔
4905
                forwardingPolicy.BaseFee = lnwire.MilliSatoshi(*baseFee)
5✔
4906
        }
5✔
4907

4908
        if feeRate != nil {
65✔
4909
                forwardingPolicy.FeeRate = lnwire.MilliSatoshi(*feeRate)
5✔
4910
        }
5✔
4911

4912
        // Fetch our dust limit which is part of the default channel
4913
        // constraints, and log it.
4914
        ourDustLimit := ourContribution.DustLimit
60✔
4915

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

60✔
4918
        // If the channel reserve is not specified, then we calculate an
60✔
4919
        // appropriate amount here.
60✔
4920
        if chanReserve == 0 {
116✔
4921
                chanReserve = f.cfg.RequiredRemoteChanReserve(
56✔
4922
                        capacity, ourDustLimit,
56✔
4923
                )
56✔
4924
        }
56✔
4925

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

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

60✔
4953
        // Update the timestamp once the InitFundingMsg has been handled.
60✔
4954
        defer resCtx.updateTimestamp()
60✔
4955

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

4977
                msg.Err <- err
2✔
4978
                return
2✔
4979
        }
4980

4981
        // When opening a script enforced channel lease, include the required
4982
        // expiry TLV record in our proposal.
4983
        var leaseExpiry *lnwire.LeaseExpiry
58✔
4984
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
62✔
4985
                leaseExpiry = new(lnwire.LeaseExpiry)
4✔
4986
                *leaseExpiry = lnwire.LeaseExpiry(reservation.LeaseExpiry())
4✔
4987
        }
4✔
4988

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

58✔
4992
        reservation.SetState(lnwallet.SentOpenChannel)
58✔
4993

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

58✔
5018
        if commitType.IsTaproot() {
64✔
5019
                fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
6✔
5020
                        ourContribution.LocalNonce.PubNonce,
6✔
5021
                )
6✔
5022
        }
6✔
5023

5024
        if err := msg.Peer.SendMessage(true, &fundingOpen); err != nil {
58✔
5025
                e := fmt.Errorf("unable to send funding request message: %w",
×
5026
                        err)
×
5027
                log.Errorf(e.Error())
×
5028

×
5029
                // Since we were unable to send the initial message to the peer
×
5030
                // and start the funding flow, we'll cancel this reservation.
×
5031
                _, err := f.cancelReservationCtx(peerKey, chanID, false)
×
5032
                if err != nil {
×
5033
                        log.Errorf("unable to cancel reservation: %v", err)
×
5034
                }
×
5035

5036
                msg.Err <- e
×
5037
                return
×
5038
        }
5039
}
5040

5041
// handleWarningMsg processes the warning which was received from remote peer.
5042
func (f *Manager) handleWarningMsg(peer lnpeer.Peer, msg *lnwire.Warning) {
42✔
5043
        log.Warnf("received warning message from peer %x: %v",
42✔
5044
                peer.IdentityKey().SerializeCompressed(), msg.Warning())
42✔
5045
}
42✔
5046

5047
// handleErrorMsg processes the error which was received from remote peer,
5048
// depending on the type of error we should do different clean up steps and
5049
// inform the user about it.
5050
func (f *Manager) handleErrorMsg(peer lnpeer.Peer, msg *lnwire.Error) {
4✔
5051
        chanID := msg.ChanID
4✔
5052
        peerKey := peer.IdentityKey()
4✔
5053

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

5064
        // If we did indeed find the funding workflow, then we'll return the
5065
        // error back to the caller (if any), and cancel the workflow itself.
5066
        fundingErr := fmt.Errorf("received funding error from %x: %v",
4✔
5067
                peerKey.SerializeCompressed(), msg.Error(),
4✔
5068
        )
4✔
5069
        log.Errorf(fundingErr.Error())
4✔
5070

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

5079
        resCtx.err <- fundingErr
4✔
5080
}
5081

5082
// pruneZombieReservations loops through all pending reservations and fails the
5083
// funding flow for any reservations that have not been updated since the
5084
// ReservationTimeout and are not locked waiting for the funding transaction.
5085
func (f *Manager) pruneZombieReservations() {
7✔
5086
        zombieReservations := make(pendingChannels)
7✔
5087

7✔
5088
        f.resMtx.RLock()
7✔
5089
        for _, pendingReservations := range f.activeReservations {
14✔
5090
                for pendingChanID, resCtx := range pendingReservations {
14✔
5091
                        if resCtx.isLocked() {
7✔
5092
                                continue
×
5093
                        }
5094

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

7✔
5109
        for pendingChanID, resCtx := range zombieReservations {
14✔
5110
                err := fmt.Errorf("reservation timed out waiting for peer "+
7✔
5111
                        "(peer_id:%x, chan_id:%x)",
7✔
5112
                        resCtx.peer.IdentityKey().SerializeCompressed(),
7✔
5113
                        pendingChanID[:])
7✔
5114
                log.Warnf(err.Error())
7✔
5115

7✔
5116
                chanID := lnwire.NewChanIDFromOutPoint(
7✔
5117
                        *resCtx.reservation.FundingOutpoint(),
7✔
5118
                )
7✔
5119

7✔
5120
                // Create channel identifier and set the channel ID.
7✔
5121
                cid := newChanIdentifier(pendingChanID)
7✔
5122
                cid.setChanID(chanID)
7✔
5123

7✔
5124
                f.failFundingFlow(resCtx.peer, cid, err)
7✔
5125
        }
7✔
5126
}
5127

5128
// cancelReservationCtx does all needed work in order to securely cancel the
5129
// reservation.
5130
func (f *Manager) cancelReservationCtx(peerKey *btcec.PublicKey,
5131
        pendingChanID PendingChanID,
5132
        byRemote bool) (*reservationWithCtx, error) {
27✔
5133

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

27✔
5137
        peerIDKey := newSerializedKey(peerKey)
27✔
5138
        f.resMtx.Lock()
27✔
5139
        defer f.resMtx.Unlock()
27✔
5140

27✔
5141
        nodeReservations, ok := f.activeReservations[peerIDKey]
27✔
5142
        if !ok {
38✔
5143
                // No reservations for this node.
11✔
5144
                return nil, errors.Errorf("no active reservations for peer(%x)",
11✔
5145
                        peerIDKey[:])
11✔
5146
        }
11✔
5147

5148
        ctx, ok := nodeReservations[pendingChanID]
20✔
5149
        if !ok {
22✔
5150
                return nil, errors.Errorf("unknown channel (id: %x) for "+
2✔
5151
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
2✔
5152
        }
2✔
5153

5154
        // If the reservation was a PSBT funding flow and it was canceled by the
5155
        // remote peer, then we need to thread through a different error message
5156
        // to the subroutine that's waiting for the user input so it can return
5157
        // a nice error message to the user.
5158
        if ctx.reservation.IsPsbt() && byRemote {
22✔
5159
                ctx.reservation.RemoteCanceled()
4✔
5160
        }
4✔
5161

5162
        if err := ctx.reservation.Cancel(); err != nil {
18✔
5163
                return nil, errors.Errorf("unable to cancel reservation: %v",
×
5164
                        err)
×
5165
        }
×
5166

5167
        delete(nodeReservations, pendingChanID)
18✔
5168

18✔
5169
        // If this was the last active reservation for this peer, delete the
18✔
5170
        // peer's entry altogether.
18✔
5171
        if len(nodeReservations) == 0 {
36✔
5172
                delete(f.activeReservations, peerIDKey)
18✔
5173
        }
18✔
5174
        return ctx, nil
18✔
5175
}
5176

5177
// deleteReservationCtx deletes the reservation uniquely identified by the
5178
// target public key of the peer, and the specified pending channel ID.
5179
func (f *Manager) deleteReservationCtx(peerKey *btcec.PublicKey,
5180
        pendingChanID PendingChanID) {
58✔
5181

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

58✔
5186
        nodeReservations, ok := f.activeReservations[peerIDKey]
58✔
5187
        if !ok {
58✔
5188
                // No reservations for this node.
×
5189
                return
×
5190
        }
×
5191
        delete(nodeReservations, pendingChanID)
58✔
5192

58✔
5193
        // If this was the last active reservation for this peer, delete the
58✔
5194
        // peer's entry altogether.
58✔
5195
        if len(nodeReservations) == 0 {
109✔
5196
                delete(f.activeReservations, peerIDKey)
51✔
5197
        }
51✔
5198
}
5199

5200
// getReservationCtx returns the reservation context for a particular pending
5201
// channel ID for a target peer.
5202
func (f *Manager) getReservationCtx(peerKey *btcec.PublicKey,
5203
        pendingChanID PendingChanID) (*reservationWithCtx, error) {
92✔
5204

92✔
5205
        peerIDKey := newSerializedKey(peerKey)
92✔
5206
        f.resMtx.RLock()
92✔
5207
        resCtx, ok := f.activeReservations[peerIDKey][pendingChanID]
92✔
5208
        f.resMtx.RUnlock()
92✔
5209

92✔
5210
        if !ok {
96✔
5211
                return nil, errors.Errorf("unknown channel (id: %x) for "+
4✔
5212
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
4✔
5213
        }
4✔
5214

5215
        return resCtx, nil
92✔
5216
}
5217

5218
// IsPendingChannel returns a boolean indicating whether the channel identified
5219
// by the pendingChanID and given peer is pending, meaning it is in the process
5220
// of being funded. After the funding transaction has been confirmed, the
5221
// channel will receive a new, permanent channel ID, and will no longer be
5222
// considered pending.
5223
func (f *Manager) IsPendingChannel(pendingChanID PendingChanID,
5224
        peer lnpeer.Peer) bool {
4✔
5225

4✔
5226
        peerIDKey := newSerializedKey(peer.IdentityKey())
4✔
5227
        f.resMtx.RLock()
4✔
5228
        _, ok := f.activeReservations[peerIDKey][pendingChanID]
4✔
5229
        f.resMtx.RUnlock()
4✔
5230

4✔
5231
        return ok
4✔
5232
}
4✔
5233

5234
func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
379✔
5235
        var tmp btcec.JacobianPoint
379✔
5236
        pub.AsJacobian(&tmp)
379✔
5237
        tmp.ToAffine()
379✔
5238
        return btcec.NewPublicKey(&tmp.X, &tmp.Y)
379✔
5239
}
379✔
5240

5241
// defaultForwardingPolicy returns the default forwarding policy based on the
5242
// default routing policy and our local channel constraints.
5243
func (f *Manager) defaultForwardingPolicy(
5244
        bounds channeldb.ChannelStateBounds) *models.ForwardingPolicy {
106✔
5245

106✔
5246
        return &models.ForwardingPolicy{
106✔
5247
                MinHTLCOut:    bounds.MinHTLC,
106✔
5248
                MaxHTLC:       bounds.MaxPendingAmount,
106✔
5249
                BaseFee:       f.cfg.DefaultRoutingPolicy.BaseFee,
106✔
5250
                FeeRate:       f.cfg.DefaultRoutingPolicy.FeeRate,
106✔
5251
                TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
106✔
5252
        }
106✔
5253
}
106✔
5254

5255
// saveInitialForwardingPolicy saves the forwarding policy for the provided
5256
// chanPoint in the channelOpeningStateBucket.
5257
func (f *Manager) saveInitialForwardingPolicy(chanID lnwire.ChannelID,
5258
        forwardingPolicy *models.ForwardingPolicy) error {
71✔
5259

71✔
5260
        return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
71✔
5261
                chanID, forwardingPolicy,
71✔
5262
        )
71✔
5263
}
71✔
5264

5265
// getInitialForwardingPolicy fetches the initial forwarding policy for a given
5266
// channel id from the database which will be applied during the channel
5267
// announcement phase.
5268
func (f *Manager) getInitialForwardingPolicy(
5269
        chanID lnwire.ChannelID) (*models.ForwardingPolicy, error) {
98✔
5270

98✔
5271
        return f.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
98✔
5272
}
98✔
5273

5274
// deleteInitialForwardingPolicy removes channel fees for this chanID from
5275
// the database.
5276
func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
28✔
5277
        return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
28✔
5278
}
28✔
5279

5280
// saveChannelOpeningState saves the channelOpeningState for the provided
5281
// chanPoint to the channelOpeningStateBucket.
5282
func (f *Manager) saveChannelOpeningState(chanPoint *wire.OutPoint,
5283
        state channelOpeningState, shortChanID *lnwire.ShortChannelID) error {
96✔
5284

96✔
5285
        var outpointBytes bytes.Buffer
96✔
5286
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
96✔
5287
                return err
×
5288
        }
×
5289

5290
        // Save state and the uint64 representation of the shortChanID
5291
        // for later use.
5292
        scratch := make([]byte, 10)
96✔
5293
        byteOrder.PutUint16(scratch[:2], uint16(state))
96✔
5294
        byteOrder.PutUint64(scratch[2:], shortChanID.ToUint64())
96✔
5295

96✔
5296
        return f.cfg.ChannelDB.SaveChannelOpeningState(
96✔
5297
                outpointBytes.Bytes(), scratch,
96✔
5298
        )
96✔
5299
}
5300

5301
// getChannelOpeningState fetches the channelOpeningState for the provided
5302
// chanPoint from the database, or returns ErrChannelNotFound if the channel
5303
// is not found.
5304
func (f *Manager) getChannelOpeningState(chanPoint *wire.OutPoint) (
5305
        channelOpeningState, *lnwire.ShortChannelID, error) {
256✔
5306

256✔
5307
        var outpointBytes bytes.Buffer
256✔
5308
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
256✔
5309
                return 0, nil, err
×
5310
        }
×
5311

5312
        value, err := f.cfg.ChannelDB.GetChannelOpeningState(
256✔
5313
                outpointBytes.Bytes(),
256✔
5314
        )
256✔
5315
        if err != nil {
307✔
5316
                return 0, nil, err
51✔
5317
        }
51✔
5318

5319
        state := channelOpeningState(byteOrder.Uint16(value[:2]))
209✔
5320
        shortChanID := lnwire.NewShortChanIDFromInt(byteOrder.Uint64(value[2:]))
209✔
5321
        return state, &shortChanID, nil
209✔
5322
}
5323

5324
// deleteChannelOpeningState removes any state for chanPoint from the database.
5325
func (f *Manager) deleteChannelOpeningState(chanPoint *wire.OutPoint) error {
28✔
5326
        var outpointBytes bytes.Buffer
28✔
5327
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
28✔
5328
                return err
×
5329
        }
×
5330

5331
        return f.cfg.ChannelDB.DeleteChannelOpeningState(
28✔
5332
                outpointBytes.Bytes(),
28✔
5333
        )
28✔
5334
}
5335

5336
// selectShutdownScript selects the shutdown script we should send to the peer.
5337
// If we can use taproot, then we prefer that, otherwise we'll use a p2wkh
5338
// script.
5339
func (f *Manager) selectShutdownScript(taprootOK bool,
5340
) (lnwire.DeliveryAddress, error) {
×
5341

×
5342
        addrType := lnwallet.WitnessPubKey
×
5343
        if taprootOK {
×
5344
                addrType = lnwallet.TaprootPubkey
×
5345
        }
×
5346

5347
        addr, err := f.cfg.Wallet.NewAddress(
×
5348
                addrType, false, lnwallet.DefaultAccountName,
×
5349
        )
×
5350
        if err != nil {
×
5351
                return nil, err
×
5352
        }
×
5353

5354
        return txscript.PayToAddrScript(addr)
×
5355
}
5356

5357
// waitForPeerOnline blocks until the peer specified by peerPubkey comes online
5358
// and then returns the online peer.
5359
func (f *Manager) waitForPeerOnline(peerPubkey *btcec.PublicKey) (lnpeer.Peer,
5360
        error) {
109✔
5361

109✔
5362
        peerChan := make(chan lnpeer.Peer, 1)
109✔
5363

109✔
5364
        var peerKey [33]byte
109✔
5365
        copy(peerKey[:], peerPubkey.SerializeCompressed())
109✔
5366

109✔
5367
        f.cfg.NotifyWhenOnline(peerKey, peerChan)
109✔
5368

109✔
5369
        var peer lnpeer.Peer
109✔
5370
        select {
109✔
5371
        case peer = <-peerChan:
108✔
5372
        case <-f.quit:
1✔
5373
                return peer, ErrFundingManagerShuttingDown
1✔
5374
        }
5375
        return peer, nil
108✔
5376
}
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