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

lightningnetwork / lnd / 12430728843

20 Dec 2024 11:36AM UTC coverage: 61.336% (+2.6%) from 58.716%
12430728843

Pull #8777

github

ziggie1984
channeldb: fix typo.
Pull Request #8777: multi: make reassignment of alias channel edge atomic

161 of 213 new or added lines in 7 files covered. (75.59%)

70 existing lines in 17 files now uncovered.

23369 of 38100 relevant lines covered (61.34%)

115813.77 hits per line

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

74.21
/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/v2"
27
        "github.com/lightningnetwork/lnd/graph"
28
        "github.com/lightningnetwork/lnd/graph/db/models"
29
        "github.com/lightningnetwork/lnd/input"
30
        "github.com/lightningnetwork/lnd/keychain"
31
        "github.com/lightningnetwork/lnd/labels"
32
        "github.com/lightningnetwork/lnd/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 {
384✔
331
        var s serializedPubKey
384✔
332
        copy(s[:], pubKey.SerializeCompressed())
384✔
333
        return s
384✔
334
}
384✔
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
        // ReAssignSCID allows the Manager to assign a new SCID to an
534
        // option-scid channel being part of the underlying graph. This is
535
        // necessary because option-scid channels change their scid during their
536
        // lifetime (public zeroconf channels for example) so we need to make
537
        // sure to update the underlying graph.
538
        ReAssignSCID func(aliasScID, newScID lnwire.ShortChannelID) (
539
                *models.ChannelEdgePolicy, error)
540

541
        // AliasManager is an implementation of the aliasHandler interface that
542
        // abstracts away the handling of many alias functions.
543
        AliasManager aliasHandler
544

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

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

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

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

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

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

583
        // cfg is a copy of the configuration struct that the FundingManager
584
        // was initialized with.
585
        cfg *Config
586

587
        // chanIDKey is a cryptographically random key that's used to generate
588
        // temporary channel ID's.
589
        chanIDKey [32]byte
590

591
        // chanIDNonce is a nonce that's incremented for each new funding
592
        // reservation created.
593
        chanIDNonce atomic.Uint64
594

595
        // nonceMtx is a mutex that guards the pendingMusigNonces.
596
        nonceMtx sync.RWMutex
597

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

609
        // activeReservations is a map which houses the state of all pending
610
        // funding workflows.
611
        activeReservations map[serializedPubKey]pendingChannels
612

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

620
        // resMtx guards both of the maps above to ensure that all access is
621
        // goroutine safe.
622
        resMtx sync.RWMutex
623

624
        // fundingMsgs is a channel that relays fundingMsg structs from
625
        // external sub-systems using the ProcessFundingMsg call.
626
        fundingMsgs chan *fundingMsg
627

628
        // fundingRequests is a channel used to receive channel initiation
629
        // requests from a local subsystem within the daemon.
630
        fundingRequests chan *InitFundingMsg
631

632
        localDiscoverySignals *lnutils.SyncMap[lnwire.ChannelID, chan struct{}]
633

634
        handleChannelReadyBarriers *lnutils.SyncMap[lnwire.ChannelID, struct{}]
635

636
        quit chan struct{}
637
        wg   sync.WaitGroup
638
}
639

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

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

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

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

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

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

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

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

730
        for _, channel := range allChannels {
124✔
731
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
13✔
732

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

5✔
742
                        f.localDiscoverySignals.Store(
5✔
743
                                chanID, make(chan struct{}),
5✔
744
                        )
5✔
745

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

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

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

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

775
        f.wg.Add(1) // TODO(roasbeef): tune
111✔
776
        go f.reservationCoordinator()
111✔
777

111✔
778
        return nil
111✔
779
}
780

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

107✔
788
                close(f.quit)
107✔
789
                f.wg.Wait()
107✔
790
        })
107✔
791

792
        return nil
108✔
793
}
794

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

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

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

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

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

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

60✔
835
        var nonceBytes [8]byte
60✔
836
        binary.LittleEndian.PutUint64(nonceBytes[:], nextNonce)
60✔
837

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

60✔
848
        return nextChanID
60✔
849
}
60✔
850

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

4✔
857
        f.resMtx.Lock()
4✔
858
        defer f.resMtx.Unlock()
4✔
859

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

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

878
                resCtx.err <- fmt.Errorf("peer disconnected")
×
879
                delete(nodeReservations, pendingID)
×
880
        }
881

882
        // Finally, we'll delete the node itself from the set of reservations.
883
        delete(f.activeReservations, nodePub)
×
884
}
885

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

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

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

910
// newChanIdentifier creates a new chanIdentifier.
911
func newChanIdentifier(tempChanID lnwire.ChannelID) *chanIdentifier {
149✔
912
        return &chanIdentifier{
149✔
913
                tempChanID: tempChanID,
149✔
914
        }
149✔
915
}
149✔
916

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

923
// hasChanID returns true if the active channel ID has been set.
924
func (c *chanIdentifier) hasChanID() bool {
26✔
925
        return c.chanIDSet
26✔
926
}
26✔
927

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

26✔
938
        log.Debugf("Failing funding flow for pending_id=%v: %v",
26✔
939
                cid.tempChanID, fundingErr)
26✔
940

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

954
        ctx, err := f.cancelReservationCtx(
26✔
955
                peer.IdentityKey(), cid.tempChanID, false,
26✔
956
        )
26✔
957
        if err != nil {
40✔
958
                log.Errorf("unable to cancel reservation: %v", err)
14✔
959
        }
14✔
960

961
        // In case the case where the reservation existed, send the funding
962
        // error on the error channel.
963
        if ctx != nil {
42✔
964
                ctx.err <- fundingErr
16✔
965
        }
16✔
966

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

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

985
        errMsg := &lnwire.Error{
26✔
986
                ChanID: cid.tempChanID,
26✔
987
                Data:   msg,
26✔
988
        }
26✔
989

26✔
990
        log.Debugf("Sending funding error to peer (%x): %v",
26✔
991
                peer.IdentityKey().SerializeCompressed(), spew.Sdump(errMsg))
26✔
992
        if err := peer.SendMessage(false, errMsg); err != nil {
27✔
993
                log.Errorf("unable to send error message to peer %v", err)
1✔
994
        }
1✔
995
}
996

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

×
1002
        msg := fundingErr.Error()
×
1003

×
1004
        errMsg := &lnwire.Warning{
×
1005
                ChanID: cid.tempChanID,
×
1006
                Data:   lnwire.WarningData(msg),
×
1007
        }
×
1008

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

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

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

111✔
1026
        zombieSweepTicker := time.NewTicker(f.cfg.ZombieSweeperInterval)
111✔
1027
        defer zombieSweepTicker.Stop()
111✔
1028

111✔
1029
        for {
488✔
1030
                select {
377✔
1031
                case fmsg := <-f.fundingMsgs:
214✔
1032
                        switch msg := fmsg.msg.(type) {
214✔
1033
                        case *lnwire.OpenChannel:
58✔
1034
                                f.fundeeProcessOpenChannel(fmsg.peer, msg)
58✔
1035

1036
                        case *lnwire.AcceptChannel:
36✔
1037
                                f.funderProcessAcceptChannel(fmsg.peer, msg)
36✔
1038

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

1042
                        case *lnwire.FundingSigned:
31✔
1043
                                f.funderProcessFundingSigned(fmsg.peer, msg)
31✔
1044

1045
                        case *lnwire.ChannelReady:
32✔
1046
                                f.wg.Add(1)
32✔
1047
                                go f.handleChannelReady(fmsg.peer, msg)
32✔
1048

1049
                        case *lnwire.Warning:
42✔
1050
                                f.handleWarningMsg(fmsg.peer, msg)
42✔
1051

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

1058
                case <-zombieSweepTicker.C:
4✔
1059
                        f.pruneZombieReservations()
4✔
1060

1061
                case <-f.quit:
107✔
1062
                        return
107✔
1063
                }
1064
        }
1065
}
1066

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

67✔
1079
        defer f.wg.Done()
67✔
1080

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

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

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

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

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

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

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

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

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

1189
                log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
38✔
1190
                        "sent ChannelReady", chanID, shortChanID)
38✔
1191

38✔
1192
                return nil
38✔
1193

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

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

1217
                        return nil
28✔
1218
                }
1219

1220
                return f.handleChannelReadyReceived(
28✔
1221
                        channel, shortChanID, pendingChanID, updateChan,
28✔
1222
                )
28✔
1223

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

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

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

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

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

1270
                log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
28✔
1271
                        "announced", chanID, shortChanID)
28✔
1272

28✔
1273
                return nil
28✔
1274
        }
1275

1276
        return fmt.Errorf("undefined channelState: %v", channelState)
×
1277
}
1278

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

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

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

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

1316
                // Inform the ChannelNotifier that the channel has transitioned
1317
                // from pending open to open.
1318
                f.cfg.NotifyOpenChannelEvent(channel.FundingOutpoint)
8✔
1319

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

1328
                return nil
8✔
1329
        }
1330

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

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

2✔
1347
                if channel.NumConfsRequired > maturity {
2✔
1348
                        numCoinbaseConfs = uint32(channel.NumConfsRequired)
×
1349
                }
×
1350

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

×
1358
                        return err
×
1359
                }
×
1360

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

×
1370
                        return err
×
1371
                }
×
1372

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

1382
                case <-f.quit:
×
1383
                        return ErrFundingManagerShuttingDown
×
1384
                }
1385
        }
1386

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

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

1399
        return nil
34✔
1400
}
1401

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

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

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

58✔
1429
        amt := msg.FundingAmount
58✔
1430

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

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

58✔
1447
        // Create the channel identifier.
58✔
1448
        cid := newChanIdentifier(msg.PendingChannelID)
58✔
1449

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

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

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

8✔
1475
                return
8✔
1476
        }
8✔
1477

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

1485
        if len(pendingChans) > pendingChansLimit {
54✔
1486
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
×
1487
                return
×
1488
        }
×
1489

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

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

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

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

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

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

1544
        log.Infof("Recv'd fundingRequest(amt=%v, push=%v, delay=%v, "+
51✔
1545
                "pendingId=%x) from peer(%x)", amt, msg.PushAmount,
51✔
1546
                msg.CsvDelay, msg.PendingChannelID,
51✔
1547
                peer.IdentityKey().SerializeCompressed())
51✔
1548

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

1570
        var scidFeatureVal bool
51✔
1571
        if hasFeatures(
51✔
1572
                peer.LocalFeatures(), peer.RemoteFeatures(),
51✔
1573
                lnwire.ScidAliasOptional,
51✔
1574
        ) {
58✔
1575

7✔
1576
                scidFeatureVal = true
7✔
1577
        }
7✔
1578

1579
        var (
51✔
1580
                zeroConf bool
51✔
1581
                scid     bool
51✔
1582
        )
51✔
1583

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

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

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

1622
                        // Set zeroConf to true to enable the zero-conf flow.
1623
                        zeroConf = true
×
1624
                }
1625
        }
1626

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

×
1638
                return
×
1639

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

×
1648
                return
×
1649
        }
1650

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

×
1665
                return
×
1666
        }
×
1667

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

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

1694
        log.Debugf("Initialized channel reservation: zeroConf=%v, psbt=%v, "+
51✔
1695
                "cannedShim=%v", reservation.IsZeroConf(),
51✔
1696
                reservation.IsPsbt(), reservation.IsCannedShim())
51✔
1697

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

1708
                reservation.AddAlias(aliasScid)
6✔
1709
        }
1710

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

1722
        // We'll ignore the min_depth calculated above if this is a zero-conf
1723
        // channel.
1724
        if zeroConf {
57✔
1725
                numConfsReq = 0
6✔
1726
        }
6✔
1727

1728
        reservation.SetNumConfsRequired(numConfsReq)
51✔
1729

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

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

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

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

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

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

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

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

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

1821
        remoteMaxValue := f.cfg.RequiredRemoteMaxValue(amt)
50✔
1822
        if acceptorResp.InFlightTotal != 0 {
50✔
1823
                remoteMaxValue = acceptorResp.InFlightTotal
×
1824
        }
×
1825

1826
        maxHtlcs := f.cfg.RequiredRemoteMaxHTLCs(amt)
50✔
1827
        if acceptorResp.HtlcLimit != 0 {
50✔
1828
                maxHtlcs = acceptorResp.HtlcLimit
×
1829
        }
×
1830

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

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

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

50✔
1870
        // Update the timestamp once the fundingOpenMsg has been handled.
50✔
1871
        defer resCtx.updateTimestamp()
50✔
1872

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

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

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

×
1915
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
1916

×
1917
                        return
×
1918
                }
×
1919

1920
                remoteContribution.LocalNonce = &musig2.Nonces{
6✔
1921
                        PubNonce: localNonce,
6✔
1922
                }
6✔
1923
        }
1924

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

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

44✔
1941
        reservation.SetState(lnwallet.SentAcceptChannel)
44✔
1942

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

44✔
1965
        if commitType.IsTaproot() {
50✔
1966
                fundingAccept.LocalNonce = lnwire.SomeMusig2Nonce(
6✔
1967
                        ourContribution.LocalNonce.PubNonce,
6✔
1968
                )
6✔
1969
        }
6✔
1970

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

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

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

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

2000
        // Update the timestamp once the fundingAcceptMsg has been handled.
2001
        defer resCtx.updateTimestamp()
36✔
2002

36✔
2003
        if resCtx.reservation.State() != lnwallet.SentOpenChannel {
36✔
2004
                return
×
2005
        }
×
2006

2007
        log.Infof("Recv'd fundingResponse for pending_id(%x)",
36✔
2008
                pendingChanID[:])
36✔
2009

36✔
2010
        // Create the channel identifier.
36✔
2011
        cid := newChanIdentifier(msg.PendingChannelID)
36✔
2012

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

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

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

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

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

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

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

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

×
2106
                minDepth = 1
×
2107
        }
×
2108

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

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

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

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

×
2175
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
2176

×
2177
                        return
×
2178
                }
×
2179

2180
                remoteContribution.LocalNonce = &musig2.Nonces{
6✔
2181
                        PubNonce: localNonce,
6✔
2182
                }
6✔
2183
        }
2184

2185
        err = resCtx.reservation.ProcessContribution(remoteContribution)
33✔
2186

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

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

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

4✔
2248
                        f.waitForPsbt(psbtIntent, resCtx, cid)
4✔
2249
                }()
4✔
2250

2251
                // With the new goroutine spawned, we can now exit to unblock
2252
                // the main event loop.
2253
                return
4✔
2254
        }
2255

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

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

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

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

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

2301
                // Nil error means the flow continues normally now.
2302
                case nil:
4✔
2303

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

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

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

2343
                // We are now ready to continue the funding flow.
2344
                f.continueFundingAccept(resCtx, cid)
4✔
2345

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

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

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

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

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

33✔
2384
        log.Infof("Generated ChannelPoint(%v) for pending_id(%x)", outPoint,
33✔
2385
                cid.tempChanID[:])
33✔
2386

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

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

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

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

×
2417
                        return
×
2418
                }
×
2419

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

2432
        resCtx.reservation.SetState(lnwallet.SentFundingCreated)
33✔
2433

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

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

31✔
2451
        peerKey := peer.IdentityKey()
31✔
2452
        pendingChanID := msg.PendingChannelID
31✔
2453

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

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

31✔
2469
        if resCtx.reservation.State() != lnwallet.SentAcceptChannel {
31✔
2470
                return
×
2471
        }
×
2472

2473
        // Create the channel identifier without setting the active channel ID.
2474
        cid := newChanIdentifier(pendingChanID)
31✔
2475

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

×
2485
                        return
×
2486
                }
×
2487

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

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

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

2537
        // Get forwarding policy before deleting the reservation context.
2538
        forwardingPolicy := resCtx.forwardingPolicy
31✔
2539

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

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

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

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

31✔
2578
        fundingSigned := &lnwire.FundingSigned{}
31✔
2579

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

×
2592
                        return
×
2593
                }
×
2594

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

×
2605
                        return
×
2606
                }
×
2607
        }
2608

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

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

31✔
2622
        fundingSigned.ChanID = cid.chanID
31✔
2623

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

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

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

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

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

31✔
2657
        // Inform the ChannelNotifier that the channel has entered
31✔
2658
        // pending open state.
31✔
2659
        f.cfg.NotifyPendingOpenChannelEvent(fundingOut, completeChan)
31✔
2660

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

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

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

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

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

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

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

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

×
2737
                return
×
2738
        }
×
2739

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

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

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

×
2766
                        return
×
2767
                }
×
2768

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

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

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

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

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

2810
                log.Infof("Broadcasting funding tx for ChannelPoint(%v): %x",
30✔
2811
                        completeChan.FundingOutpoint, fundingTxBuf.Bytes())
30✔
2812

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

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

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

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

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

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

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

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

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

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

2899
        // fundingTx is the funding transaction that created the channel.
2900
        fundingTx *wire.MsgTx
2901
}
2902

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

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

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

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

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

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

2950
                // nil error means we continue on.
2951
                case nil:
2✔
2952

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

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

2✔
2964
                // TODO(halseth): should this send be made
2✔
2965
                // reliable?
2✔
2966

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

2972
        return timeoutErr
2✔
2973
}
2974

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

61✔
2983
        confChan := make(chan *confirmedChannel)
61✔
2984
        timeoutChan := make(chan error, 1)
61✔
2985
        cancelChan := make(chan struct{})
61✔
2986

61✔
2987
        f.wg.Add(1)
61✔
2988
        go f.waitForFundingConfirmation(ch, cancelChan, confChan)
61✔
2989

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

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

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

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

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

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

3035
                return pkScript, nil
9✔
3036
        }
3037

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

3046
        return input.WitnessScriptHash(multiSigScript)
76✔
3047
}
3048

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

61✔
3062
        defer f.wg.Done()
61✔
3063
        defer close(confChan)
61✔
3064

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

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

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

3094
        log.Infof("Waiting for funding tx (%v) to reach %v confirmations",
61✔
3095
                txid, numConfs)
61✔
3096

61✔
3097
        var confDetails *chainntnfs.TxConfirmation
61✔
3098
        var ok bool
61✔
3099

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

3106
        case <-cancelChan:
3✔
3107
                log.Warnf("canceled waiting for funding confirmation, "+
3✔
3108
                        "stopping funding flow for ChannelPoint(%v)",
3✔
3109
                        completeChan.FundingOutpoint)
3✔
3110
                return
3✔
3111

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

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

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

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

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

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

29✔
3159
        defer f.wg.Done()
29✔
3160

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

3168
        defer epochClient.Cancel()
29✔
3169

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

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

2✔
3190
                                // Notify the caller of the timeout.
2✔
3191
                                close(timeoutChan)
2✔
3192
                                return
2✔
3193
                        }
2✔
3194

3195
                        // TODO: If we are the channel initiator implement
3196
                        // a method for recovering the funds from the funding
3197
                        // transaction
3198

3199
                case <-cancelChan:
19✔
3200
                        return
19✔
3201

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

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

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

3226
                label := labels.MakeLabel(
20✔
3227
                        labels.LabelTypeChannelOpen, &shortChanID,
20✔
3228
                )
20✔
3229

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

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

34✔
3245
        fundingPoint := completeChan.FundingOutpoint
34✔
3246
        chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
34✔
3247

34✔
3248
        // TODO(roasbeef): ideally persistent state update for chan above
34✔
3249
        // should be abstracted
34✔
3250

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

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

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

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

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

3298
        // Update the confirmed funding transaction label.
3299
        f.makeLabelForTx(completeChan)
34✔
3300

34✔
3301
        // Inform the ChannelNotifier that the channel has transitioned from
34✔
3302
        // pending open to open.
34✔
3303
        f.cfg.NotifyOpenChannelEvent(completeChan.FundingOutpoint)
34✔
3304

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

3313
        return nil
34✔
3314
}
3315

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

39✔
3322
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
39✔
3323

39✔
3324
        var peerKey [33]byte
39✔
3325
        copy(peerKey[:], completeChan.IdentityPub.SerializeCompressed())
39✔
3326

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

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

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

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

8✔
3364
                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
8✔
3365
                        localNonce.PubNonce,
8✔
3366
                )
8✔
3367
        }
3368

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

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

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

3404
                localAlias := peer.LocalFeatures().HasFeature(
38✔
3405
                        lnwire.ScidAliasOptional,
38✔
3406
                )
38✔
3407
                remoteAlias := peer.RemoteFeatures().HasFeature(
38✔
3408
                        lnwire.ScidAliasOptional,
38✔
3409
                )
38✔
3410

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

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

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

3441
                                channelReadyMsg.AliasScid = &alias
×
3442
                        } else {
×
3443
                                channelReadyMsg.AliasScid = &aliases[0]
×
3444
                        }
×
3445
                }
3446

3447
                log.Infof("Peer(%x) is online, sending ChannelReady "+
38✔
3448
                        "for ChannelID(%v)", peerKey, chanID)
38✔
3449

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

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

3460
        return nil
38✔
3461
}
3462

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

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

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

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

3492
        // If we haven't insert the next revocation point, we haven't finished
3493
        // processing the channel ready message.
3494
        if channel.RemoteNextRevocation == nil {
102✔
3495
                return false, nil
39✔
3496
        }
39✔
3497

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

28✔
3503
        return !loaded, nil
28✔
3504
}
3505

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

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

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

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

3533
        return fwdMinHTLC, fwdMaxHTLC
30✔
3534
}
3535

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

28✔
3549
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
28✔
3550

28✔
3551
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
28✔
3552

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

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

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

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

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

3609
        return nil
28✔
3610
}
3611

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

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

12✔
3629
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
12✔
3630
                if err != nil {
12✔
3631
                        return err
×
3632
                }
×
3633

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

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

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

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

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

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

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

3705
                fundingPoint := completeChan.FundingOutpoint
20✔
3706
                chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
20✔
3707

20✔
3708
                log.Infof("Announcing ChannelPoint(%v), short_chan_id=%v",
20✔
3709
                        &fundingPoint, shortChanID)
20✔
3710

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

3725
                        // We reassign the same scid to the graph db. This will
3726
                        // trigger a deletion of the current edge data and
3727
                        // reinsert the channel with the same edge info and
3728
                        // policy. This is done to guarantee that potential
3729
                        // ChannelUpdates using the alias as the scid are
3730
                        // removed and not relayed to the broader network
3731
                        // because the alias is not a verifiable channel id.
3732
                        ourPolicy, err := f.cfg.ReAssignSCID(
4✔
3733
                                baseScid, baseScid,
4✔
3734
                        )
4✔
3735
                        if err != nil {
4✔
NEW
3736
                                return fmt.Errorf("unable to reassign alias "+
×
NEW
3737
                                        "edge in graph: %w", err)
×
UNCOV
3738
                        }
×
3739

3740
                        log.Infof("Successfully reassigned alias edge in "+
4✔
3741
                                "graph(non-zeroconf): %v(%d) -> %v(%d)",
4✔
3742
                                baseScid, baseScid.ToUint64(),
4✔
3743
                                baseScid, baseScid.ToUint64())
4✔
3744

4✔
3745
                        // We send the rassigned ChannelUpdate to the peer.
4✔
3746
                        err = f.sendChanUpdate(
4✔
3747
                                completeChan, &baseScid, ourPolicy,
4✔
3748
                        )
4✔
3749
                        if err != nil {
4✔
3750
                                return fmt.Errorf("failed to re-add to "+
×
3751
                                        "graph: %v", err)
×
3752
                        }
×
3753
                }
3754

3755
                // Create and broadcast the proofs required to make this channel
3756
                // public and usable for other nodes for routing.
3757
                err = f.announceChannel(
20✔
3758
                        f.cfg.IDKey, completeChan.IdentityPub,
20✔
3759
                        &completeChan.LocalChanCfg.MultiSigKey,
20✔
3760
                        completeChan.RemoteChanCfg.MultiSigKey.PubKey,
20✔
3761
                        *shortChanID, chanID, completeChan.ChanType,
20✔
3762
                )
20✔
3763
                if err != nil {
24✔
3764
                        return fmt.Errorf("channel announcement failed: %w",
4✔
3765
                                err)
4✔
3766
                }
4✔
3767

3768
                log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+
20✔
3769
                        "sent to gossiper", &fundingPoint, shortChanID)
20✔
3770
        }
3771

3772
        return nil
28✔
3773
}
3774

3775
// waitForZeroConfChannel is called when the state is addedToGraph with
3776
// a zero-conf channel. This will wait for the real confirmation, add the
3777
// confirmed SCID to the router graph, and then announce after six confs.
3778
func (f *Manager) waitForZeroConfChannel(c *channeldb.OpenChannel) error {
10✔
3779
        // First we'll check whether the channel is confirmed on-chain. If it
10✔
3780
        // is already confirmed, the chainntnfs subsystem will return with the
10✔
3781
        // confirmed tx. Otherwise, we'll wait here until confirmation occurs.
10✔
3782
        confChan, err := f.waitForFundingWithTimeout(c)
10✔
3783
        if err != nil {
16✔
3784
                return fmt.Errorf("error waiting for zero-conf funding "+
6✔
3785
                        "confirmation for ChannelPoint(%v): %v",
6✔
3786
                        c.FundingOutpoint, err)
6✔
3787
        }
6✔
3788

3789
        // We'll need to refresh the channel state so that things are properly
3790
        // populated when validating the channel state. Otherwise, a panic may
3791
        // occur due to inconsistency in the OpenChannel struct.
3792
        err = c.Refresh()
8✔
3793
        if err != nil {
12✔
3794
                return fmt.Errorf("unable to refresh channel state: %w", err)
4✔
3795
        }
4✔
3796

3797
        // Now that we have the confirmed transaction and the proper SCID,
3798
        // we'll call ValidateChannel to ensure the confirmed tx is properly
3799
        // formatted.
3800
        err = f.cfg.Wallet.ValidateChannel(c, confChan.fundingTx)
8✔
3801
        if err != nil {
8✔
3802
                return fmt.Errorf("unable to validate zero-conf channel: "+
×
3803
                        "%v", err)
×
3804
        }
×
3805

3806
        // Once we know the confirmed ShortChannelID, we'll need to save it to
3807
        // the database and refresh the OpenChannel struct with it.
3808
        err = c.MarkRealScid(confChan.shortChanID)
8✔
3809
        if err != nil {
8✔
3810
                return fmt.Errorf("unable to set confirmed SCID for zero "+
×
3811
                        "channel: %v", err)
×
3812
        }
×
3813

3814
        // Six confirmations have been reached. If this channel is public,
3815
        // we'll delete some of the alias mappings the gossiper uses.
3816
        isPublic := c.ChannelFlags&lnwire.FFAnnounceChannel != 0
8✔
3817
        if isPublic {
14✔
3818
                err = f.cfg.AliasManager.DeleteSixConfs(c.ShortChannelID)
6✔
3819
                if err != nil {
6✔
3820
                        return fmt.Errorf("unable to delete base alias after "+
×
3821
                                "six confirmations: %v", err)
×
3822
                }
×
3823

3824
                // The underlying graph entry for this channel id needs to be
3825
                // reassigned with the new confirmed scid. Moreover channel
3826
                // updates with the alias scid are removed so that we do not
3827
                // relay them to the broader network.
3828
                ourPolicy, err := f.cfg.ReAssignSCID(
6✔
3829
                        c.ShortChanID(), confChan.shortChanID,
6✔
3830
                )
6✔
3831
                if err != nil {
6✔
NEW
3832
                        return fmt.Errorf("unable to reassign alias edge in "+
×
NEW
3833
                                "graph: %w", err)
×
UNCOV
3834
                }
×
3835

3836
                aliasScid := c.ShortChanID()
6✔
3837
                confirmedScid := confChan.shortChanID
6✔
3838

6✔
3839
                log.Infof("Successfully reassigned alias edge in "+
6✔
3840
                        "graph(zeroconf): %v(%d) -> %v(%d)",
6✔
3841
                        aliasScid, aliasScid.ToUint64(),
6✔
3842
                        confirmedScid, confirmedScid.ToUint64())
6✔
3843

6✔
3844
                // Send the ChannelUpdate with the confirmed scid to the peer.
6✔
3845
                err = f.sendChanUpdate(
6✔
3846
                        c, &confChan.shortChanID, ourPolicy,
6✔
3847
                )
6✔
3848
                if err != nil {
6✔
NEW
3849
                        return fmt.Errorf("failed to send ChannelUpdate to "+
×
NEW
3850
                                "gossiper: %v", err)
×
UNCOV
3851
                }
×
3852
        }
3853

3854
        // Since we have now marked down the confirmed SCID, we'll also need to
3855
        // tell the Switch to refresh the relevant ChannelLink so that forwards
3856
        // under the confirmed SCID are possible if this is a public channel.
3857
        err = f.cfg.ReportShortChanID(c.FundingOutpoint)
8✔
3858
        if err != nil {
8✔
3859
                // This should only fail if the link is not found in the
×
3860
                // Switch's linkIndex map. If this is the case, then the peer
×
3861
                // has gone offline and the next time the link is loaded, it
×
3862
                // will have a refreshed state. Just log an error here.
×
3863
                log.Errorf("unable to report scid for zero-conf channel "+
×
3864
                        "channel: %v", err)
×
3865
        }
×
3866

3867
        // Update the confirmed transaction's label.
3868
        f.makeLabelForTx(c)
8✔
3869

8✔
3870
        return nil
8✔
3871
}
3872

3873
// genFirstStateMusigNonce generates a nonces for the "first" local state. This
3874
// is the verification nonce for the state created for us after the initial
3875
// commitment transaction signed as part of the funding flow.
3876
func genFirstStateMusigNonce(channel *channeldb.OpenChannel,
3877
) (*musig2.Nonces, error) {
8✔
3878

8✔
3879
        musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
8✔
3880
                channel.RevocationProducer,
8✔
3881
        )
8✔
3882
        if err != nil {
8✔
3883
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3884
                        "nonces: %v", err)
×
3885
        }
×
3886

3887
        // We use the _next_ commitment height here as we need to generate the
3888
        // nonce for the next state the remote party will sign for us.
3889
        verNonce, err := channeldb.NewMusigVerificationNonce(
8✔
3890
                channel.LocalChanCfg.MultiSigKey.PubKey,
8✔
3891
                channel.LocalCommitment.CommitHeight+1,
8✔
3892
                musig2ShaChain,
8✔
3893
        )
8✔
3894
        if err != nil {
8✔
3895
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3896
                        "nonces: %v", err)
×
3897
        }
×
3898

3899
        return verNonce, nil
8✔
3900
}
3901

3902
// handleChannelReady finalizes the channel funding process and enables the
3903
// channel to enter normal operating mode.
3904
func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen
3905
        msg *lnwire.ChannelReady) {
32✔
3906

32✔
3907
        defer f.wg.Done()
32✔
3908

32✔
3909
        // If we are in development mode, we'll wait for specified duration
32✔
3910
        // before processing the channel ready message.
32✔
3911
        if f.cfg.Dev != nil {
36✔
3912
                duration := f.cfg.Dev.ProcessChannelReadyWait
4✔
3913
                log.Warnf("Channel(%v): sleeping %v before processing "+
4✔
3914
                        "channel_ready", msg.ChanID, duration)
4✔
3915

4✔
3916
                select {
4✔
3917
                case <-time.After(duration):
4✔
3918
                        log.Warnf("Channel(%v): slept %v before processing "+
4✔
3919
                                "channel_ready", msg.ChanID, duration)
4✔
3920
                case <-f.quit:
×
3921
                        log.Warnf("Channel(%v): quit sleeping", msg.ChanID)
×
3922
                        return
×
3923
                }
3924
        }
3925

3926
        log.Debugf("Received ChannelReady for ChannelID(%v) from "+
32✔
3927
                "peer %x", msg.ChanID,
32✔
3928
                peer.IdentityKey().SerializeCompressed())
32✔
3929

32✔
3930
        // We now load or create a new channel barrier for this channel.
32✔
3931
        _, loaded := f.handleChannelReadyBarriers.LoadOrStore(
32✔
3932
                msg.ChanID, struct{}{},
32✔
3933
        )
32✔
3934

32✔
3935
        // If we are currently in the process of handling a channel_ready
32✔
3936
        // message for this channel, ignore.
32✔
3937
        if loaded {
37✔
3938
                log.Infof("Already handling channelReady for "+
5✔
3939
                        "ChannelID(%v), ignoring.", msg.ChanID)
5✔
3940
                return
5✔
3941
        }
5✔
3942

3943
        // If not already handling channelReady for this channel, then the
3944
        // `LoadOrStore` has set up a barrier, and it will be removed once this
3945
        // function exits.
3946
        defer f.handleChannelReadyBarriers.Delete(msg.ChanID)
31✔
3947

31✔
3948
        localDiscoverySignal, ok := f.localDiscoverySignals.Load(msg.ChanID)
31✔
3949
        if ok {
60✔
3950
                // Before we proceed with processing the channel_ready
29✔
3951
                // message, we'll wait for the local waitForFundingConfirmation
29✔
3952
                // goroutine to signal that it has the necessary state in
29✔
3953
                // place. Otherwise, we may be missing critical information
29✔
3954
                // required to handle forwarded HTLC's.
29✔
3955
                select {
29✔
3956
                case <-localDiscoverySignal:
29✔
3957
                        // Fallthrough
3958
                case <-f.quit:
×
3959
                        return
×
3960
                }
3961

3962
                // With the signal received, we can now safely delete the entry
3963
                // from the map.
3964
                f.localDiscoverySignals.Delete(msg.ChanID)
29✔
3965
        }
3966

3967
        // First, we'll attempt to locate the channel whose funding workflow is
3968
        // being finalized by this message. We go to the database rather than
3969
        // our reservation map as we may have restarted, mid funding flow. Also
3970
        // provide the node's public key to make the search faster.
3971
        chanID := msg.ChanID
31✔
3972
        channel, err := f.cfg.FindChannel(peer.IdentityKey(), chanID)
31✔
3973
        if err != nil {
31✔
3974
                log.Errorf("Unable to locate ChannelID(%v), cannot complete "+
×
3975
                        "funding", chanID)
×
3976
                return
×
3977
        }
×
3978

3979
        // If this is a taproot channel, then we can generate the set of nonces
3980
        // the remote party needs to send the next remote commitment here.
3981
        var firstVerNonce *musig2.Nonces
31✔
3982
        if channel.ChanType.IsTaproot() {
39✔
3983
                firstVerNonce, err = genFirstStateMusigNonce(channel)
8✔
3984
                if err != nil {
8✔
3985
                        log.Error(err)
×
3986
                        return
×
3987
                }
×
3988
        }
3989

3990
        // We'll need to store the received TLV alias if the option_scid_alias
3991
        // feature was negotiated. This will be used to provide route hints
3992
        // during invoice creation. In the zero-conf case, it is also used to
3993
        // provide a ChannelUpdate to the remote peer. This is done before the
3994
        // call to InsertNextRevocation in case the call to PutPeerAlias fails.
3995
        // If it were to fail on the first call to handleChannelReady, we
3996
        // wouldn't want the channel to be usable yet.
3997
        if channel.NegotiatedAliasFeature() {
41✔
3998
                // If the AliasScid field is nil, we must fail out. We will
10✔
3999
                // most likely not be able to route through the peer.
10✔
4000
                if msg.AliasScid == nil {
10✔
4001
                        log.Debugf("Consider closing ChannelID(%v), peer "+
×
4002
                                "does not implement the option-scid-alias "+
×
4003
                                "feature properly", chanID)
×
4004
                        return
×
4005
                }
×
4006

4007
                // We'll store the AliasScid so that invoice creation can use
4008
                // it.
4009
                err = f.cfg.AliasManager.PutPeerAlias(chanID, *msg.AliasScid)
10✔
4010
                if err != nil {
10✔
4011
                        log.Errorf("unable to store peer's alias: %v", err)
×
4012
                        return
×
4013
                }
×
4014

4015
                // If we do not have an alias stored, we'll create one now.
4016
                // This is only used in the upgrade case where a user toggles
4017
                // the option-scid-alias feature-bit to on. We'll also send the
4018
                // channel_ready message here in case the link is created
4019
                // before sendChannelReady is called.
4020
                aliases := f.cfg.AliasManager.GetAliases(
10✔
4021
                        channel.ShortChannelID,
10✔
4022
                )
10✔
4023
                if len(aliases) == 0 {
10✔
4024
                        // No aliases were found so we'll request and store an
×
4025
                        // alias and use it in the channel_ready message.
×
4026
                        alias, err := f.cfg.AliasManager.RequestAlias()
×
4027
                        if err != nil {
×
4028
                                log.Errorf("unable to request alias: %v", err)
×
4029
                                return
×
4030
                        }
×
4031

4032
                        err = f.cfg.AliasManager.AddLocalAlias(
×
4033
                                alias, channel.ShortChannelID, false, false,
×
4034
                        )
×
4035
                        if err != nil {
×
4036
                                log.Errorf("unable to add local alias: %v",
×
4037
                                        err)
×
4038
                                return
×
4039
                        }
×
4040

4041
                        secondPoint, err := channel.SecondCommitmentPoint()
×
4042
                        if err != nil {
×
4043
                                log.Errorf("unable to fetch second "+
×
4044
                                        "commitment point: %v", err)
×
4045
                                return
×
4046
                        }
×
4047

4048
                        channelReadyMsg := lnwire.NewChannelReady(
×
4049
                                chanID, secondPoint,
×
4050
                        )
×
4051
                        channelReadyMsg.AliasScid = &alias
×
4052

×
4053
                        if firstVerNonce != nil {
×
4054
                                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:ll
×
4055
                                        firstVerNonce.PubNonce,
×
4056
                                )
×
4057
                        }
×
4058

4059
                        err = peer.SendMessage(true, channelReadyMsg)
×
4060
                        if err != nil {
×
4061
                                log.Errorf("unable to send channel_ready: %v",
×
4062
                                        err)
×
4063
                                return
×
4064
                        }
×
4065
                }
4066
        }
4067

4068
        // If the RemoteNextRevocation is non-nil, it means that we have
4069
        // already processed channelReady for this channel, so ignore. This
4070
        // check is after the alias logic so we store the peer's most recent
4071
        // alias. The spec requires us to validate that subsequent
4072
        // channel_ready messages use the same per commitment point (the
4073
        // second), but it is not actually necessary since we'll just end up
4074
        // ignoring it. We are, however, required to *send* the same per
4075
        // commitment point, since another pedantic implementation might
4076
        // verify it.
4077
        if channel.RemoteNextRevocation != nil {
36✔
4078
                log.Infof("Received duplicate channelReady for "+
5✔
4079
                        "ChannelID(%v), ignoring.", chanID)
5✔
4080
                return
5✔
4081
        }
5✔
4082

4083
        // If this is a taproot channel, then we'll need to map the received
4084
        // nonces to a nonce pair, and also fetch our pending nonces, which are
4085
        // required in order to make the channel whole.
4086
        var chanOpts []lnwallet.ChannelOpt
30✔
4087
        if channel.ChanType.IsTaproot() {
38✔
4088
                f.nonceMtx.Lock()
8✔
4089
                localNonce, ok := f.pendingMusigNonces[chanID]
8✔
4090
                if !ok {
12✔
4091
                        // If there's no pending nonce for this channel ID,
4✔
4092
                        // we'll use the one generated above.
4✔
4093
                        localNonce = firstVerNonce
4✔
4094
                        f.pendingMusigNonces[chanID] = firstVerNonce
4✔
4095
                }
4✔
4096
                f.nonceMtx.Unlock()
8✔
4097

8✔
4098
                log.Infof("ChanID(%v): applying local+remote musig2 nonces",
8✔
4099
                        chanID)
8✔
4100

8✔
4101
                remoteNonce, err := msg.NextLocalNonce.UnwrapOrErrV(
8✔
4102
                        errNoLocalNonce,
8✔
4103
                )
8✔
4104
                if err != nil {
8✔
4105
                        cid := newChanIdentifier(msg.ChanID)
×
4106
                        f.sendWarning(peer, cid, err)
×
4107

×
4108
                        return
×
4109
                }
×
4110

4111
                chanOpts = append(
8✔
4112
                        chanOpts,
8✔
4113
                        lnwallet.WithLocalMusigNonces(localNonce),
8✔
4114
                        lnwallet.WithRemoteMusigNonces(&musig2.Nonces{
8✔
4115
                                PubNonce: remoteNonce,
8✔
4116
                        }),
8✔
4117
                )
8✔
4118

8✔
4119
                // Inform the aux funding controller that the liquidity in the
8✔
4120
                // custom channel is now ready to be advertised. We potentially
8✔
4121
                // haven't sent our own channel ready message yet, but other
8✔
4122
                // than that the channel is ready to count toward available
8✔
4123
                // liquidity.
8✔
4124
                err = fn.MapOptionZ(
8✔
4125
                        f.cfg.AuxFundingController,
8✔
4126
                        func(controller AuxFundingController) error {
8✔
4127
                                return controller.ChannelReady(
×
4128
                                        lnwallet.NewAuxChanState(channel),
×
4129
                                )
×
4130
                        },
×
4131
                )
4132
                if err != nil {
8✔
4133
                        cid := newChanIdentifier(msg.ChanID)
×
4134
                        f.sendWarning(peer, cid, err)
×
4135

×
4136
                        return
×
4137
                }
×
4138
        }
4139

4140
        // The channel_ready message contains the next commitment point we'll
4141
        // need to create the next commitment state for the remote party. So
4142
        // we'll insert that into the channel now before passing it along to
4143
        // other sub-systems.
4144
        err = channel.InsertNextRevocation(msg.NextPerCommitmentPoint)
30✔
4145
        if err != nil {
30✔
4146
                log.Errorf("unable to insert next commitment point: %v", err)
×
4147
                return
×
4148
        }
×
4149

4150
        // Before we can add the channel to the peer, we'll need to ensure that
4151
        // we have an initial forwarding policy set.
4152
        if err := f.ensureInitialForwardingPolicy(chanID, channel); err != nil {
30✔
4153
                log.Errorf("Unable to ensure initial forwarding policy: %v",
×
4154
                        err)
×
4155
        }
×
4156

4157
        err = peer.AddNewChannel(&lnpeer.NewChannel{
30✔
4158
                OpenChannel: channel,
30✔
4159
                ChanOpts:    chanOpts,
30✔
4160
        }, f.quit)
30✔
4161
        if err != nil {
30✔
4162
                log.Errorf("Unable to add new channel %v with peer %x: %v",
×
4163
                        channel.FundingOutpoint,
×
4164
                        peer.IdentityKey().SerializeCompressed(), err,
×
4165
                )
×
4166
        }
×
4167
}
4168

4169
// handleChannelReadyReceived is called once the remote's channelReady message
4170
// is received and processed. At this stage, we must have sent out our
4171
// channelReady message, once the remote's channelReady is processed, the
4172
// channel is now active, thus we change its state to `addedToGraph` to
4173
// let the channel start handling routing.
4174
func (f *Manager) handleChannelReadyReceived(channel *channeldb.OpenChannel,
4175
        scid *lnwire.ShortChannelID, pendingChanID PendingChanID,
4176
        updateChan chan<- *lnrpc.OpenStatusUpdate) error {
28✔
4177

28✔
4178
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
28✔
4179

28✔
4180
        // Since we've sent+received funding locked at this point, we
28✔
4181
        // can clean up the pending musig2 nonce state.
28✔
4182
        f.nonceMtx.Lock()
28✔
4183
        delete(f.pendingMusigNonces, chanID)
28✔
4184
        f.nonceMtx.Unlock()
28✔
4185

28✔
4186
        var peerAlias *lnwire.ShortChannelID
28✔
4187
        if channel.IsZeroConf() {
36✔
4188
                // We'll need to wait until channel_ready has been received and
8✔
4189
                // the peer lets us know the alias they want to use for the
8✔
4190
                // channel. With this information, we can then construct a
8✔
4191
                // ChannelUpdate for them.  If an alias does not yet exist,
8✔
4192
                // we'll just return, letting the next iteration of the loop
8✔
4193
                // check again.
8✔
4194
                var defaultAlias lnwire.ShortChannelID
8✔
4195
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
8✔
4196
                foundAlias, _ := f.cfg.AliasManager.GetPeerAlias(chanID)
8✔
4197
                if foundAlias == defaultAlias {
8✔
4198
                        return nil
×
4199
                }
×
4200

4201
                peerAlias = &foundAlias
8✔
4202
        }
4203

4204
        err := f.addToGraph(channel, scid, peerAlias, nil)
28✔
4205
        if err != nil {
28✔
4206
                return fmt.Errorf("failed adding to graph: %w", err)
×
4207
        }
×
4208

4209
        // As the channel is now added to the ChannelRouter's topology, the
4210
        // channel is moved to the next state of the state machine. It will be
4211
        // moved to the last state (actually deleted from the database) after
4212
        // the channel is finally announced.
4213
        err = f.saveChannelOpeningState(
28✔
4214
                &channel.FundingOutpoint, addedToGraph, scid,
28✔
4215
        )
28✔
4216
        if err != nil {
28✔
4217
                return fmt.Errorf("error setting channel state to"+
×
4218
                        " addedToGraph: %w", err)
×
4219
        }
×
4220

4221
        log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
28✔
4222
                "added to graph", chanID, scid)
28✔
4223

28✔
4224
        err = fn.MapOptionZ(
28✔
4225
                f.cfg.AuxFundingController,
28✔
4226
                func(controller AuxFundingController) error {
28✔
4227
                        return controller.ChannelReady(
×
4228
                                lnwallet.NewAuxChanState(channel),
×
4229
                        )
×
4230
                },
×
4231
        )
4232
        if err != nil {
28✔
4233
                return fmt.Errorf("failed notifying aux funding controller "+
×
4234
                        "about channel ready: %w", err)
×
4235
        }
×
4236

4237
        // Give the caller a final update notifying them that the channel is
4238
        fundingPoint := channel.FundingOutpoint
28✔
4239
        cp := &lnrpc.ChannelPoint{
28✔
4240
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
28✔
4241
                        FundingTxidBytes: fundingPoint.Hash[:],
28✔
4242
                },
28✔
4243
                OutputIndex: fundingPoint.Index,
28✔
4244
        }
28✔
4245

28✔
4246
        if updateChan != nil {
42✔
4247
                upd := &lnrpc.OpenStatusUpdate{
14✔
4248
                        Update: &lnrpc.OpenStatusUpdate_ChanOpen{
14✔
4249
                                ChanOpen: &lnrpc.ChannelOpenUpdate{
14✔
4250
                                        ChannelPoint: cp,
14✔
4251
                                },
14✔
4252
                        },
14✔
4253
                        PendingChanId: pendingChanID[:],
14✔
4254
                }
14✔
4255

14✔
4256
                select {
14✔
4257
                case updateChan <- upd:
14✔
4258
                case <-f.quit:
×
4259
                        return ErrFundingManagerShuttingDown
×
4260
                }
4261
        }
4262

4263
        return nil
28✔
4264
}
4265

4266
// ensureInitialForwardingPolicy ensures that we have an initial forwarding
4267
// policy set for the given channel. If we don't, we'll fall back to the default
4268
// values.
4269
func (f *Manager) ensureInitialForwardingPolicy(chanID lnwire.ChannelID,
4270
        channel *channeldb.OpenChannel) error {
30✔
4271

30✔
4272
        // Before we can add the channel to the peer, we'll need to ensure that
30✔
4273
        // we have an initial forwarding policy set. This should always be the
30✔
4274
        // case except for a channel that was created with lnd <= 0.15.5 and
30✔
4275
        // is still pending while updating to this version.
30✔
4276
        var needDBUpdate bool
30✔
4277
        forwardingPolicy, err := f.getInitialForwardingPolicy(chanID)
30✔
4278
        if err != nil {
30✔
4279
                log.Errorf("Unable to fetch initial forwarding policy, "+
×
4280
                        "falling back to default values: %v", err)
×
4281

×
4282
                forwardingPolicy = f.defaultForwardingPolicy(
×
4283
                        channel.LocalChanCfg.ChannelStateBounds,
×
4284
                )
×
4285
                needDBUpdate = true
×
4286
        }
×
4287

4288
        // We only started storing the actual values for MinHTLCOut and MaxHTLC
4289
        // after 0.16.x, so if a channel was opened with such a version and is
4290
        // still pending while updating to this version, we'll need to set the
4291
        // values to the default values.
4292
        if forwardingPolicy.MinHTLCOut == 0 {
47✔
4293
                forwardingPolicy.MinHTLCOut = channel.LocalChanCfg.MinHTLC
17✔
4294
                needDBUpdate = true
17✔
4295
        }
17✔
4296
        if forwardingPolicy.MaxHTLC == 0 {
47✔
4297
                forwardingPolicy.MaxHTLC = channel.LocalChanCfg.MaxPendingAmount
17✔
4298
                needDBUpdate = true
17✔
4299
        }
17✔
4300

4301
        // And finally, if we found that the values currently stored aren't
4302
        // sufficient for the link, we'll update the database.
4303
        if needDBUpdate {
47✔
4304
                err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
17✔
4305
                if err != nil {
17✔
4306
                        return fmt.Errorf("unable to update initial "+
×
4307
                                "forwarding policy: %v", err)
×
4308
                }
×
4309
        }
4310

4311
        return nil
30✔
4312
}
4313

4314
// chanAnnouncement encapsulates the two authenticated announcements that we
4315
// send out to the network after a new channel has been created locally.
4316
type chanAnnouncement struct {
4317
        chanAnn       *lnwire.ChannelAnnouncement1
4318
        chanUpdateAnn *lnwire.ChannelUpdate1
4319
        chanProof     *lnwire.AnnounceSignatures1
4320
}
4321

4322
// newChanAnnouncement creates the authenticated channel announcement messages
4323
// required to broadcast a newly created channel to the network. The
4324
// announcement is two part: the first part authenticates the existence of the
4325
// channel and contains four signatures binding the funding pub keys and
4326
// identity pub keys of both parties to the channel, and the second segment is
4327
// authenticated only by us and contains our directional routing policy for the
4328
// channel. ourPolicy may be set in order to re-use an existing, non-default
4329
// policy.
4330
func (f *Manager) newChanAnnouncement(localPubKey,
4331
        remotePubKey *btcec.PublicKey, localFundingKey *keychain.KeyDescriptor,
4332
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4333
        chanID lnwire.ChannelID, fwdMinHTLC, fwdMaxHTLC lnwire.MilliSatoshi,
4334
        ourPolicy *models.ChannelEdgePolicy,
4335
        chanType channeldb.ChannelType) (*chanAnnouncement, error) {
46✔
4336

46✔
4337
        chainHash := *f.cfg.Wallet.Cfg.NetParams.GenesisHash
46✔
4338

46✔
4339
        // The unconditional section of the announcement is the ShortChannelID
46✔
4340
        // itself which compactly encodes the location of the funding output
46✔
4341
        // within the blockchain.
46✔
4342
        chanAnn := &lnwire.ChannelAnnouncement1{
46✔
4343
                ShortChannelID: shortChanID,
46✔
4344
                Features:       lnwire.NewRawFeatureVector(),
46✔
4345
                ChainHash:      chainHash,
46✔
4346
        }
46✔
4347

46✔
4348
        // If this is a taproot channel, then we'll set a special bit in the
46✔
4349
        // feature vector to indicate to the routing layer that this needs a
46✔
4350
        // slightly different type of validation.
46✔
4351
        //
46✔
4352
        // TODO(roasbeef): temp, remove after gossip 1.5
46✔
4353
        if chanType.IsTaproot() {
54✔
4354
                log.Debugf("Applying taproot feature bit to "+
8✔
4355
                        "ChannelAnnouncement for %v", chanID)
8✔
4356

8✔
4357
                chanAnn.Features.Set(
8✔
4358
                        lnwire.SimpleTaprootChannelsRequiredStaging,
8✔
4359
                )
8✔
4360
        }
8✔
4361

4362
        // The chanFlags field indicates which directed edge of the channel is
4363
        // being updated within the ChannelUpdateAnnouncement announcement
4364
        // below. A value of zero means it's the edge of the "first" node and 1
4365
        // being the other node.
4366
        var chanFlags lnwire.ChanUpdateChanFlags
46✔
4367

46✔
4368
        // The lexicographical ordering of the two identity public keys of the
46✔
4369
        // nodes indicates which of the nodes is "first". If our serialized
46✔
4370
        // identity key is lower than theirs then we're the "first" node and
46✔
4371
        // second otherwise.
46✔
4372
        selfBytes := localPubKey.SerializeCompressed()
46✔
4373
        remoteBytes := remotePubKey.SerializeCompressed()
46✔
4374
        if bytes.Compare(selfBytes, remoteBytes) == -1 {
71✔
4375
                copy(chanAnn.NodeID1[:], localPubKey.SerializeCompressed())
25✔
4376
                copy(chanAnn.NodeID2[:], remotePubKey.SerializeCompressed())
25✔
4377
                copy(
25✔
4378
                        chanAnn.BitcoinKey1[:],
25✔
4379
                        localFundingKey.PubKey.SerializeCompressed(),
25✔
4380
                )
25✔
4381
                copy(
25✔
4382
                        chanAnn.BitcoinKey2[:],
25✔
4383
                        remoteFundingKey.SerializeCompressed(),
25✔
4384
                )
25✔
4385

25✔
4386
                // If we're the first node then update the chanFlags to
25✔
4387
                // indicate the "direction" of the update.
25✔
4388
                chanFlags = 0
25✔
4389
        } else {
50✔
4390
                copy(chanAnn.NodeID1[:], remotePubKey.SerializeCompressed())
25✔
4391
                copy(chanAnn.NodeID2[:], localPubKey.SerializeCompressed())
25✔
4392
                copy(
25✔
4393
                        chanAnn.BitcoinKey1[:],
25✔
4394
                        remoteFundingKey.SerializeCompressed(),
25✔
4395
                )
25✔
4396
                copy(
25✔
4397
                        chanAnn.BitcoinKey2[:],
25✔
4398
                        localFundingKey.PubKey.SerializeCompressed(),
25✔
4399
                )
25✔
4400

25✔
4401
                // If we're the second node then update the chanFlags to
25✔
4402
                // indicate the "direction" of the update.
25✔
4403
                chanFlags = 1
25✔
4404
        }
25✔
4405

4406
        // Our channel update message flags will signal that we support the
4407
        // max_htlc field.
4408
        msgFlags := lnwire.ChanUpdateRequiredMaxHtlc
46✔
4409

46✔
4410
        // We announce the channel with the default values. Some of
46✔
4411
        // these values can later be changed by crafting a new ChannelUpdate.
46✔
4412
        chanUpdateAnn := &lnwire.ChannelUpdate1{
46✔
4413
                ShortChannelID: shortChanID,
46✔
4414
                ChainHash:      chainHash,
46✔
4415
                Timestamp:      uint32(time.Now().Unix()),
46✔
4416
                MessageFlags:   msgFlags,
46✔
4417
                ChannelFlags:   chanFlags,
46✔
4418
                TimeLockDelta: uint16(
46✔
4419
                        f.cfg.DefaultRoutingPolicy.TimeLockDelta,
46✔
4420
                ),
46✔
4421
                HtlcMinimumMsat: fwdMinHTLC,
46✔
4422
                HtlcMaximumMsat: fwdMaxHTLC,
46✔
4423
        }
46✔
4424

46✔
4425
        // The caller of newChanAnnouncement is expected to provide the initial
46✔
4426
        // forwarding policy to be announced. If no persisted initial policy
46✔
4427
        // values are found, then we will use the default policy values in the
46✔
4428
        // channel announcement.
46✔
4429
        storedFwdingPolicy, err := f.getInitialForwardingPolicy(chanID)
46✔
4430
        if err != nil && !errors.Is(err, channeldb.ErrChannelNotFound) {
46✔
4431
                return nil, errors.Errorf("unable to generate channel "+
×
4432
                        "update announcement: %v", err)
×
4433
        }
×
4434

4435
        switch {
46✔
4436
        case ourPolicy != nil:
4✔
4437
                // If ourPolicy is non-nil, modify the default parameters of the
4✔
4438
                // ChannelUpdate.
4✔
4439
                chanUpdateAnn.MessageFlags = ourPolicy.MessageFlags
4✔
4440
                chanUpdateAnn.ChannelFlags = ourPolicy.ChannelFlags
4✔
4441
                chanUpdateAnn.TimeLockDelta = ourPolicy.TimeLockDelta
4✔
4442
                chanUpdateAnn.HtlcMinimumMsat = ourPolicy.MinHTLC
4✔
4443
                chanUpdateAnn.HtlcMaximumMsat = ourPolicy.MaxHTLC
4✔
4444
                chanUpdateAnn.BaseFee = uint32(ourPolicy.FeeBaseMSat)
4✔
4445
                chanUpdateAnn.FeeRate = uint32(
4✔
4446
                        ourPolicy.FeeProportionalMillionths,
4✔
4447
                )
4✔
4448

4449
        case storedFwdingPolicy != nil:
46✔
4450
                chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
46✔
4451
                chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
46✔
4452

4453
        default:
×
4454
                log.Infof("No channel forwarding policy specified for channel "+
×
4455
                        "announcement of ChannelID(%v). "+
×
4456
                        "Assuming default fee parameters.", chanID)
×
4457
                chanUpdateAnn.BaseFee = uint32(
×
4458
                        f.cfg.DefaultRoutingPolicy.BaseFee,
×
4459
                )
×
4460
                chanUpdateAnn.FeeRate = uint32(
×
4461
                        f.cfg.DefaultRoutingPolicy.FeeRate,
×
4462
                )
×
4463
        }
4464

4465
        // With the channel update announcement constructed, we'll generate a
4466
        // signature that signs a double-sha digest of the announcement.
4467
        // This'll serve to authenticate this announcement and any other future
4468
        // updates we may send.
4469
        chanUpdateMsg, err := chanUpdateAnn.DataToSign()
46✔
4470
        if err != nil {
46✔
4471
                return nil, err
×
4472
        }
×
4473
        sig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanUpdateMsg, true)
46✔
4474
        if err != nil {
46✔
4475
                return nil, errors.Errorf("unable to generate channel "+
×
4476
                        "update announcement signature: %v", err)
×
4477
        }
×
4478
        chanUpdateAnn.Signature, err = lnwire.NewSigFromSignature(sig)
46✔
4479
        if err != nil {
46✔
4480
                return nil, errors.Errorf("unable to generate channel "+
×
4481
                        "update announcement signature: %v", err)
×
4482
        }
×
4483

4484
        // The channel existence proofs itself is currently announced in
4485
        // distinct message. In order to properly authenticate this message, we
4486
        // need two signatures: one under the identity public key used which
4487
        // signs the message itself and another signature of the identity
4488
        // public key under the funding key itself.
4489
        //
4490
        // TODO(roasbeef): use SignAnnouncement here instead?
4491
        chanAnnMsg, err := chanAnn.DataToSign()
46✔
4492
        if err != nil {
46✔
4493
                return nil, err
×
4494
        }
×
4495
        nodeSig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanAnnMsg, true)
46✔
4496
        if err != nil {
46✔
4497
                return nil, errors.Errorf("unable to generate node "+
×
4498
                        "signature for channel announcement: %v", err)
×
4499
        }
×
4500
        bitcoinSig, err := f.cfg.SignMessage(
46✔
4501
                localFundingKey.KeyLocator, chanAnnMsg, true,
46✔
4502
        )
46✔
4503
        if err != nil {
46✔
4504
                return nil, errors.Errorf("unable to generate bitcoin "+
×
4505
                        "signature for node public key: %v", err)
×
4506
        }
×
4507

4508
        // Finally, we'll generate the announcement proof which we'll use to
4509
        // provide the other side with the necessary signatures required to
4510
        // allow them to reconstruct the full channel announcement.
4511
        proof := &lnwire.AnnounceSignatures1{
46✔
4512
                ChannelID:      chanID,
46✔
4513
                ShortChannelID: shortChanID,
46✔
4514
        }
46✔
4515
        proof.NodeSignature, err = lnwire.NewSigFromSignature(nodeSig)
46✔
4516
        if err != nil {
46✔
4517
                return nil, err
×
4518
        }
×
4519
        proof.BitcoinSignature, err = lnwire.NewSigFromSignature(bitcoinSig)
46✔
4520
        if err != nil {
46✔
4521
                return nil, err
×
4522
        }
×
4523

4524
        return &chanAnnouncement{
46✔
4525
                chanAnn:       chanAnn,
46✔
4526
                chanUpdateAnn: chanUpdateAnn,
46✔
4527
                chanProof:     proof,
46✔
4528
        }, nil
46✔
4529
}
4530

4531
// announceChannel announces a newly created channel to the rest of the network
4532
// by crafting the two authenticated announcements required for the peers on
4533
// the network to recognize the legitimacy of the channel. The crafted
4534
// announcements are then sent to the channel router to handle broadcasting to
4535
// the network during its next trickle.
4536
// This method is synchronous and will return when all the network requests
4537
// finish, either successfully or with an error.
4538
func (f *Manager) announceChannel(localIDKey, remoteIDKey *btcec.PublicKey,
4539
        localFundingKey *keychain.KeyDescriptor,
4540
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4541
        chanID lnwire.ChannelID, chanType channeldb.ChannelType) error {
20✔
4542

20✔
4543
        // First, we'll create the batch of announcements to be sent upon
20✔
4544
        // initial channel creation. This includes the channel announcement
20✔
4545
        // itself, the channel update announcement, and our half of the channel
20✔
4546
        // proof needed to fully authenticate the channel.
20✔
4547
        //
20✔
4548
        // We can pass in zeroes for the min and max htlc policy, because we
20✔
4549
        // only use the channel announcement message from the returned struct.
20✔
4550
        ann, err := f.newChanAnnouncement(
20✔
4551
                localIDKey, remoteIDKey, localFundingKey, remoteFundingKey,
20✔
4552
                shortChanID, chanID, 0, 0, nil, chanType,
20✔
4553
        )
20✔
4554
        if err != nil {
20✔
4555
                log.Errorf("can't generate channel announcement: %v", err)
×
4556
                return err
×
4557
        }
×
4558

4559
        // We only send the channel proof announcement and the node announcement
4560
        // because addToGraph previously sent the ChannelAnnouncement and
4561
        // the ChannelUpdate announcement messages. The channel proof and node
4562
        // announcements are broadcast to the greater network.
4563
        errChan := f.cfg.SendAnnouncement(ann.chanProof)
20✔
4564
        select {
20✔
4565
        case err := <-errChan:
20✔
4566
                if err != nil {
24✔
4567
                        if graph.IsError(err, graph.ErrOutdated,
4✔
4568
                                graph.ErrIgnored) {
4✔
4569

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

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

4583
        // Now that the channel is announced to the network, we will also
4584
        // obtain and send a node announcement. This is done since a node
4585
        // announcement is only accepted after a channel is known for that
4586
        // particular node, and this might be our first channel.
4587
        nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
20✔
4588
        if err != nil {
20✔
4589
                log.Errorf("can't generate node announcement: %v", err)
×
4590
                return err
×
4591
        }
×
4592

4593
        errChan = f.cfg.SendAnnouncement(&nodeAnn)
20✔
4594
        select {
20✔
4595
        case err := <-errChan:
20✔
4596
                if err != nil {
24✔
4597
                        if graph.IsError(err, graph.ErrOutdated,
4✔
4598
                                graph.ErrIgnored) {
8✔
4599

4✔
4600
                                log.Debugf("Graph rejected "+
4✔
4601
                                        "NodeAnnouncement: %v", err)
4✔
4602
                        } else {
4✔
4603
                                log.Errorf("Unable to send node "+
×
4604
                                        "announcement: %v", err)
×
4605
                                return err
×
4606
                        }
×
4607
                }
4608

4609
        case <-f.quit:
×
4610
                return ErrFundingManagerShuttingDown
×
4611
        }
4612

4613
        return nil
20✔
4614
}
4615

4616
// sendChanUpdate sends a ChannelUpdate to the gossiper which is as a
4617
// consequence sent to the peer.
4618
//
4619
// TODO(ziggie): Refactor the gossip msgs so that not always all msgs have
4620
// to be created but only the ones which are needed.
4621
func (f *Manager) sendChanUpdate(completeChan *channeldb.OpenChannel,
4622
        shortChanID *lnwire.ShortChannelID,
4623
        ourPolicy *models.ChannelEdgePolicy) error {
6✔
4624

6✔
4625
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
6✔
4626

6✔
4627
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
6✔
4628

6✔
4629
        ann, err := f.newChanAnnouncement(
6✔
4630
                f.cfg.IDKey, completeChan.IdentityPub,
6✔
4631
                &completeChan.LocalChanCfg.MultiSigKey,
6✔
4632
                completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
6✔
4633
                chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
6✔
4634
                completeChan.ChanType,
6✔
4635
        )
6✔
4636
        if err != nil {
6✔
NEW
4637
                return fmt.Errorf("error generating channel "+
×
NEW
4638
                        "announcement: %v", err)
×
NEW
4639
        }
×
4640

4641
        errChan := f.cfg.SendAnnouncement(ann.chanUpdateAnn)
6✔
4642
        select {
6✔
4643
        case err := <-errChan:
6✔
4644
                if err != nil {
6✔
NEW
4645
                        if graph.IsError(err, graph.ErrOutdated,
×
NEW
4646
                                graph.ErrIgnored) {
×
NEW
4647

×
NEW
4648
                                log.Debugf("Graph rejected "+
×
NEW
4649
                                        "ChannelUpdate: %v", err)
×
NEW
4650
                        } else {
×
NEW
4651
                                return fmt.Errorf("error sending channel "+
×
NEW
4652
                                        "update: %v", err)
×
NEW
4653
                        }
×
4654
                }
NEW
4655
        case <-f.quit:
×
NEW
4656
                return ErrFundingManagerShuttingDown
×
4657
        }
4658

4659
        return nil
6✔
4660
}
4661

4662
// InitFundingWorkflow sends a message to the funding manager instructing it
4663
// to initiate a single funder workflow with the source peer.
4664
func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg) {
60✔
4665
        f.fundingRequests <- msg
60✔
4666
}
60✔
4667

4668
// getUpfrontShutdownScript takes a user provided script and a getScript
4669
// function which can be used to generate an upfront shutdown script. If our
4670
// peer does not support the feature, this function will error if a non-zero
4671
// script was provided by the user, and return an empty script otherwise. If
4672
// our peer does support the feature, we will return the user provided script
4673
// if non-zero, or a freshly generated script if our node is configured to set
4674
// upfront shutdown scripts automatically.
4675
func getUpfrontShutdownScript(enableUpfrontShutdown bool, peer lnpeer.Peer,
4676
        script lnwire.DeliveryAddress,
4677
        getScript func(bool) (lnwire.DeliveryAddress, error)) (lnwire.DeliveryAddress,
4678
        error) {
112✔
4679

112✔
4680
        // Check whether the remote peer supports upfront shutdown scripts.
112✔
4681
        remoteUpfrontShutdown := peer.RemoteFeatures().HasFeature(
112✔
4682
                lnwire.UpfrontShutdownScriptOptional,
112✔
4683
        )
112✔
4684

112✔
4685
        // If the peer does not support upfront shutdown scripts, and one has been
112✔
4686
        // provided, return an error because the feature is not supported.
112✔
4687
        if !remoteUpfrontShutdown && len(script) != 0 {
113✔
4688
                return nil, errUpfrontShutdownScriptNotSupported
1✔
4689
        }
1✔
4690

4691
        // If the peer does not support upfront shutdown, return an empty address.
4692
        if !remoteUpfrontShutdown {
214✔
4693
                return nil, nil
103✔
4694
        }
103✔
4695

4696
        // If the user has provided an script and the peer supports the feature,
4697
        // return it. Note that user set scripts override the enable upfront
4698
        // shutdown flag.
4699
        if len(script) > 0 {
14✔
4700
                return script, nil
6✔
4701
        }
6✔
4702

4703
        // If we do not have setting of upfront shutdown script enabled, return
4704
        // an empty script.
4705
        if !enableUpfrontShutdown {
11✔
4706
                return nil, nil
5✔
4707
        }
5✔
4708

4709
        // We can safely send a taproot address iff, both sides have negotiated
4710
        // the shutdown-any-segwit feature.
4711
        taprootOK := peer.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
1✔
4712
                peer.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
1✔
4713

1✔
4714
        return getScript(taprootOK)
1✔
4715
}
4716

4717
// handleInitFundingMsg creates a channel reservation within the daemon's
4718
// wallet, then sends a funding request to the remote peer kicking off the
4719
// funding workflow.
4720
func (f *Manager) handleInitFundingMsg(msg *InitFundingMsg) {
60✔
4721
        var (
60✔
4722
                peerKey        = msg.Peer.IdentityKey()
60✔
4723
                localAmt       = msg.LocalFundingAmt
60✔
4724
                baseFee        = msg.BaseFee
60✔
4725
                feeRate        = msg.FeeRate
60✔
4726
                minHtlcIn      = msg.MinHtlcIn
60✔
4727
                remoteCsvDelay = msg.RemoteCsvDelay
60✔
4728
                maxValue       = msg.MaxValueInFlight
60✔
4729
                maxHtlcs       = msg.MaxHtlcs
60✔
4730
                maxCSV         = msg.MaxLocalCsv
60✔
4731
                chanReserve    = msg.RemoteChanReserve
60✔
4732
                outpoints      = msg.Outpoints
60✔
4733
        )
60✔
4734

60✔
4735
        // If no maximum CSV delay was set for this channel, we use our default
60✔
4736
        // value.
60✔
4737
        if maxCSV == 0 {
120✔
4738
                maxCSV = f.cfg.MaxLocalCSVDelay
60✔
4739
        }
60✔
4740

4741
        log.Infof("Initiating fundingRequest(local_amt=%v "+
60✔
4742
                "(subtract_fees=%v), push_amt=%v, chain_hash=%v, peer=%x, "+
60✔
4743
                "min_confs=%v)", localAmt, msg.SubtractFees, msg.PushAmt,
60✔
4744
                msg.ChainHash, peerKey.SerializeCompressed(), msg.MinConfs)
60✔
4745

60✔
4746
        // We set the channel flags to indicate whether we want this channel to
60✔
4747
        // be announced to the network.
60✔
4748
        var channelFlags lnwire.FundingFlag
60✔
4749
        if !msg.Private {
115✔
4750
                // This channel will be announced.
55✔
4751
                channelFlags = lnwire.FFAnnounceChannel
55✔
4752
        }
55✔
4753

4754
        // If the caller specified their own channel ID, then we'll use that.
4755
        // Otherwise we'll generate a fresh one as normal.  This will be used
4756
        // to track this reservation throughout its lifetime.
4757
        var chanID PendingChanID
60✔
4758
        if msg.PendingChanID == zeroID {
120✔
4759
                chanID = f.nextPendingChanID()
60✔
4760
        } else {
64✔
4761
                // If the user specified their own pending channel ID, then
4✔
4762
                // we'll ensure it doesn't collide with any existing pending
4✔
4763
                // channel ID.
4✔
4764
                chanID = msg.PendingChanID
4✔
4765
                if _, err := f.getReservationCtx(peerKey, chanID); err == nil {
4✔
4766
                        msg.Err <- fmt.Errorf("pendingChannelID(%x) "+
×
4767
                                "already present", chanID[:])
×
4768
                        return
×
4769
                }
×
4770
        }
4771

4772
        // Check whether the peer supports upfront shutdown, and get an address
4773
        // which should be used (either a user specified address or a new
4774
        // address from the wallet if our node is configured to set shutdown
4775
        // address by default).
4776
        shutdown, err := getUpfrontShutdownScript(
60✔
4777
                f.cfg.EnableUpfrontShutdown, msg.Peer, msg.ShutdownScript,
60✔
4778
                f.selectShutdownScript,
60✔
4779
        )
60✔
4780
        if err != nil {
60✔
4781
                msg.Err <- err
×
4782
                return
×
4783
        }
×
4784

4785
        // Initialize a funding reservation with the local wallet. If the
4786
        // wallet doesn't have enough funds to commit to this channel, then the
4787
        // request will fail, and be aborted.
4788
        //
4789
        // Before we init the channel, we'll also check to see what commitment
4790
        // format we can use with this peer. This is dependent on *both* us and
4791
        // the remote peer are signaling the proper feature bit.
4792
        chanType, commitType, err := negotiateCommitmentType(
60✔
4793
                msg.ChannelType, msg.Peer.LocalFeatures(),
60✔
4794
                msg.Peer.RemoteFeatures(),
60✔
4795
        )
60✔
4796
        if err != nil {
64✔
4797
                log.Errorf("channel type negotiation failed: %v", err)
4✔
4798
                msg.Err <- err
4✔
4799
                return
4✔
4800
        }
4✔
4801

4802
        var (
60✔
4803
                zeroConf bool
60✔
4804
                scid     bool
60✔
4805
        )
60✔
4806

60✔
4807
        if chanType != nil {
68✔
4808
                // Check if the returned chanType includes either the zero-conf
8✔
4809
                // or scid-alias bits.
8✔
4810
                featureVec := lnwire.RawFeatureVector(*chanType)
8✔
4811
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
8✔
4812
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
8✔
4813

8✔
4814
                // The option-scid-alias channel type for a public channel is
8✔
4815
                // disallowed.
8✔
4816
                if scid && !msg.Private {
8✔
4817
                        err = fmt.Errorf("option-scid-alias chantype for " +
×
4818
                                "public channel")
×
4819
                        log.Error(err)
×
4820
                        msg.Err <- err
×
4821

×
4822
                        return
×
4823
                }
×
4824
        }
4825

4826
        // First, we'll query the fee estimator for a fee that should get the
4827
        // commitment transaction confirmed by the next few blocks (conf target
4828
        // of 3). We target the near blocks here to ensure that we'll be able
4829
        // to execute a timely unilateral channel closure if needed.
4830
        commitFeePerKw, err := f.cfg.FeeEstimator.EstimateFeePerKW(3)
60✔
4831
        if err != nil {
60✔
4832
                msg.Err <- err
×
4833
                return
×
4834
        }
×
4835

4836
        // For anchor channels cap the initial commit fee rate at our defined
4837
        // maximum.
4838
        if commitType.HasAnchors() &&
60✔
4839
                commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
68✔
4840

8✔
4841
                commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate
8✔
4842
        }
8✔
4843

4844
        var scidFeatureVal bool
60✔
4845
        if hasFeatures(
60✔
4846
                msg.Peer.LocalFeatures(), msg.Peer.RemoteFeatures(),
60✔
4847
                lnwire.ScidAliasOptional,
60✔
4848
        ) {
67✔
4849

7✔
4850
                scidFeatureVal = true
7✔
4851
        }
7✔
4852

4853
        // At this point, if we have an AuxFundingController active, we'll check
4854
        // to see if we have a special tapscript root to use in our MuSig2
4855
        // funding output.
4856
        tapscriptRoot, err := fn.MapOptionZ(
60✔
4857
                f.cfg.AuxFundingController,
60✔
4858
                func(c AuxFundingController) AuxTapscriptResult {
60✔
4859
                        return c.DeriveTapscriptRoot(chanID)
×
4860
                },
×
4861
        ).Unpack()
4862
        if err != nil {
60✔
4863
                err = fmt.Errorf("error deriving tapscript root: %w", err)
×
4864
                log.Error(err)
×
4865
                msg.Err <- err
×
4866

×
4867
                return
×
4868
        }
×
4869

4870
        req := &lnwallet.InitFundingReserveMsg{
60✔
4871
                ChainHash:         &msg.ChainHash,
60✔
4872
                PendingChanID:     chanID,
60✔
4873
                NodeID:            peerKey,
60✔
4874
                NodeAddr:          msg.Peer.Address(),
60✔
4875
                SubtractFees:      msg.SubtractFees,
60✔
4876
                LocalFundingAmt:   localAmt,
60✔
4877
                RemoteFundingAmt:  0,
60✔
4878
                FundUpToMaxAmt:    msg.FundUpToMaxAmt,
60✔
4879
                MinFundAmt:        msg.MinFundAmt,
60✔
4880
                RemoteChanReserve: chanReserve,
60✔
4881
                Outpoints:         outpoints,
60✔
4882
                CommitFeePerKw:    commitFeePerKw,
60✔
4883
                FundingFeePerKw:   msg.FundingFeePerKw,
60✔
4884
                PushMSat:          msg.PushAmt,
60✔
4885
                Flags:             channelFlags,
60✔
4886
                MinConfs:          msg.MinConfs,
60✔
4887
                CommitType:        commitType,
60✔
4888
                ChanFunder:        msg.ChanFunder,
60✔
4889
                // Unconfirmed Utxos which are marked by the sweeper subsystem
60✔
4890
                // are excluded from the coin selection because they are not
60✔
4891
                // final and can be RBFed by the sweeper subsystem.
60✔
4892
                AllowUtxoForFunding: func(u lnwallet.Utxo) bool {
121✔
4893
                        // Utxos with at least 1 confirmation are safe to use
61✔
4894
                        // for channel openings because they don't bare the risk
61✔
4895
                        // of being replaced (BIP 125 RBF).
61✔
4896
                        if u.Confirmations > 0 {
65✔
4897
                                return true
4✔
4898
                        }
4✔
4899

4900
                        // Query the sweeper storage to make sure we don't use
4901
                        // an unconfirmed utxo still in use by the sweeper
4902
                        // subsystem.
4903
                        return !f.cfg.IsSweeperOutpoint(u.OutPoint)
61✔
4904
                },
4905
                ZeroConf:         zeroConf,
4906
                OptionScidAlias:  scid,
4907
                ScidAliasFeature: scidFeatureVal,
4908
                Memo:             msg.Memo,
4909
                TapscriptRoot:    tapscriptRoot,
4910
        }
4911

4912
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
60✔
4913
        if err != nil {
64✔
4914
                msg.Err <- err
4✔
4915
                return
4✔
4916
        }
4✔
4917

4918
        if zeroConf {
66✔
4919
                // Store the alias for zero-conf channels in the underlying
6✔
4920
                // partial channel state.
6✔
4921
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
6✔
4922
                if err != nil {
6✔
4923
                        msg.Err <- err
×
4924
                        return
×
4925
                }
×
4926

4927
                reservation.AddAlias(aliasScid)
6✔
4928
        }
4929

4930
        // Set our upfront shutdown address in the existing reservation.
4931
        reservation.SetOurUpfrontShutdown(shutdown)
60✔
4932

60✔
4933
        // Now that we have successfully reserved funds for this channel in the
60✔
4934
        // wallet, we can fetch the final channel capacity. This is done at
60✔
4935
        // this point since the final capacity might change in case of
60✔
4936
        // SubtractFees=true.
60✔
4937
        capacity := reservation.Capacity()
60✔
4938

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

60✔
4942
        // If the remote CSV delay was not set in the open channel request,
60✔
4943
        // we'll use the RequiredRemoteDelay closure to compute the delay we
60✔
4944
        // require given the total amount of funds within the channel.
60✔
4945
        if remoteCsvDelay == 0 {
119✔
4946
                remoteCsvDelay = f.cfg.RequiredRemoteDelay(capacity)
59✔
4947
        }
59✔
4948

4949
        // If no minimum HTLC value was specified, use the default one.
4950
        if minHtlcIn == 0 {
119✔
4951
                minHtlcIn = f.cfg.DefaultMinHtlcIn
59✔
4952
        }
59✔
4953

4954
        // If no max value was specified, use the default one.
4955
        if maxValue == 0 {
119✔
4956
                maxValue = f.cfg.RequiredRemoteMaxValue(capacity)
59✔
4957
        }
59✔
4958

4959
        if maxHtlcs == 0 {
120✔
4960
                maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
60✔
4961
        }
60✔
4962

4963
        // Once the reservation has been created, and indexed, queue a funding
4964
        // request to the remote peer, kicking off the funding workflow.
4965
        ourContribution := reservation.OurContribution()
60✔
4966

60✔
4967
        // Prepare the optional channel fee values from the initFundingMsg. If
60✔
4968
        // useBaseFee or useFeeRate are false the client did not provide fee
60✔
4969
        // values hence we assume default fee settings from the config.
60✔
4970
        forwardingPolicy := f.defaultForwardingPolicy(
60✔
4971
                ourContribution.ChannelStateBounds,
60✔
4972
        )
60✔
4973
        if baseFee != nil {
65✔
4974
                forwardingPolicy.BaseFee = lnwire.MilliSatoshi(*baseFee)
5✔
4975
        }
5✔
4976

4977
        if feeRate != nil {
65✔
4978
                forwardingPolicy.FeeRate = lnwire.MilliSatoshi(*feeRate)
5✔
4979
        }
5✔
4980

4981
        // Fetch our dust limit which is part of the default channel
4982
        // constraints, and log it.
4983
        ourDustLimit := ourContribution.DustLimit
60✔
4984

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

60✔
4987
        // If the channel reserve is not specified, then we calculate an
60✔
4988
        // appropriate amount here.
60✔
4989
        if chanReserve == 0 {
116✔
4990
                chanReserve = f.cfg.RequiredRemoteChanReserve(
56✔
4991
                        capacity, ourDustLimit,
56✔
4992
                )
56✔
4993
        }
56✔
4994

4995
        // If a pending channel map for this peer isn't already created, then
4996
        // we create one, ultimately allowing us to track this pending
4997
        // reservation within the target peer.
4998
        peerIDKey := newSerializedKey(peerKey)
60✔
4999
        f.resMtx.Lock()
60✔
5000
        if _, ok := f.activeReservations[peerIDKey]; !ok {
113✔
5001
                f.activeReservations[peerIDKey] = make(pendingChannels)
53✔
5002
        }
53✔
5003

5004
        resCtx := &reservationWithCtx{
60✔
5005
                chanAmt:           capacity,
60✔
5006
                forwardingPolicy:  *forwardingPolicy,
60✔
5007
                remoteCsvDelay:    remoteCsvDelay,
60✔
5008
                remoteMinHtlc:     minHtlcIn,
60✔
5009
                remoteMaxValue:    maxValue,
60✔
5010
                remoteMaxHtlcs:    maxHtlcs,
60✔
5011
                remoteChanReserve: chanReserve,
60✔
5012
                maxLocalCsv:       maxCSV,
60✔
5013
                channelType:       chanType,
60✔
5014
                reservation:       reservation,
60✔
5015
                peer:              msg.Peer,
60✔
5016
                updates:           msg.Updates,
60✔
5017
                err:               msg.Err,
60✔
5018
        }
60✔
5019
        f.activeReservations[peerIDKey][chanID] = resCtx
60✔
5020
        f.resMtx.Unlock()
60✔
5021

60✔
5022
        // Update the timestamp once the InitFundingMsg has been handled.
60✔
5023
        defer resCtx.updateTimestamp()
60✔
5024

60✔
5025
        // Check the sanity of the selected channel constraints.
60✔
5026
        bounds := &channeldb.ChannelStateBounds{
60✔
5027
                ChanReserve:      chanReserve,
60✔
5028
                MaxPendingAmount: maxValue,
60✔
5029
                MinHTLC:          minHtlcIn,
60✔
5030
                MaxAcceptedHtlcs: maxHtlcs,
60✔
5031
        }
60✔
5032
        commitParams := &channeldb.CommitmentParams{
60✔
5033
                DustLimit: ourDustLimit,
60✔
5034
                CsvDelay:  remoteCsvDelay,
60✔
5035
        }
60✔
5036
        err = lnwallet.VerifyConstraints(
60✔
5037
                bounds, commitParams, resCtx.maxLocalCsv, capacity,
60✔
5038
        )
60✔
5039
        if err != nil {
62✔
5040
                _, reserveErr := f.cancelReservationCtx(peerKey, chanID, false)
2✔
5041
                if reserveErr != nil {
2✔
5042
                        log.Errorf("unable to cancel reservation: %v",
×
5043
                                reserveErr)
×
5044
                }
×
5045

5046
                msg.Err <- err
2✔
5047
                return
2✔
5048
        }
5049

5050
        // When opening a script enforced channel lease, include the required
5051
        // expiry TLV record in our proposal.
5052
        var leaseExpiry *lnwire.LeaseExpiry
58✔
5053
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
62✔
5054
                leaseExpiry = new(lnwire.LeaseExpiry)
4✔
5055
                *leaseExpiry = lnwire.LeaseExpiry(reservation.LeaseExpiry())
4✔
5056
        }
4✔
5057

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

58✔
5061
        reservation.SetState(lnwallet.SentOpenChannel)
58✔
5062

58✔
5063
        fundingOpen := lnwire.OpenChannel{
58✔
5064
                ChainHash:             *f.cfg.Wallet.Cfg.NetParams.GenesisHash,
58✔
5065
                PendingChannelID:      chanID,
58✔
5066
                FundingAmount:         capacity,
58✔
5067
                PushAmount:            msg.PushAmt,
58✔
5068
                DustLimit:             ourDustLimit,
58✔
5069
                MaxValueInFlight:      maxValue,
58✔
5070
                ChannelReserve:        chanReserve,
58✔
5071
                HtlcMinimum:           minHtlcIn,
58✔
5072
                FeePerKiloWeight:      uint32(commitFeePerKw),
58✔
5073
                CsvDelay:              remoteCsvDelay,
58✔
5074
                MaxAcceptedHTLCs:      maxHtlcs,
58✔
5075
                FundingKey:            ourContribution.MultiSigKey.PubKey,
58✔
5076
                RevocationPoint:       ourContribution.RevocationBasePoint.PubKey,
58✔
5077
                PaymentPoint:          ourContribution.PaymentBasePoint.PubKey,
58✔
5078
                HtlcPoint:             ourContribution.HtlcBasePoint.PubKey,
58✔
5079
                DelayedPaymentPoint:   ourContribution.DelayBasePoint.PubKey,
58✔
5080
                FirstCommitmentPoint:  ourContribution.FirstCommitmentPoint,
58✔
5081
                ChannelFlags:          channelFlags,
58✔
5082
                UpfrontShutdownScript: shutdown,
58✔
5083
                ChannelType:           chanType,
58✔
5084
                LeaseExpiry:           leaseExpiry,
58✔
5085
        }
58✔
5086

58✔
5087
        if commitType.IsTaproot() {
64✔
5088
                fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
6✔
5089
                        ourContribution.LocalNonce.PubNonce,
6✔
5090
                )
6✔
5091
        }
6✔
5092

5093
        if err := msg.Peer.SendMessage(true, &fundingOpen); err != nil {
58✔
5094
                e := fmt.Errorf("unable to send funding request message: %w",
×
5095
                        err)
×
5096
                log.Errorf(e.Error())
×
5097

×
5098
                // Since we were unable to send the initial message to the peer
×
5099
                // and start the funding flow, we'll cancel this reservation.
×
5100
                _, err := f.cancelReservationCtx(peerKey, chanID, false)
×
5101
                if err != nil {
×
5102
                        log.Errorf("unable to cancel reservation: %v", err)
×
5103
                }
×
5104

5105
                msg.Err <- e
×
5106
                return
×
5107
        }
5108
}
5109

5110
// handleWarningMsg processes the warning which was received from remote peer.
5111
func (f *Manager) handleWarningMsg(peer lnpeer.Peer, msg *lnwire.Warning) {
42✔
5112
        log.Warnf("received warning message from peer %x: %v",
42✔
5113
                peer.IdentityKey().SerializeCompressed(), msg.Warning())
42✔
5114
}
42✔
5115

5116
// handleErrorMsg processes the error which was received from remote peer,
5117
// depending on the type of error we should do different clean up steps and
5118
// inform the user about it.
5119
func (f *Manager) handleErrorMsg(peer lnpeer.Peer, msg *lnwire.Error) {
4✔
5120
        chanID := msg.ChanID
4✔
5121
        peerKey := peer.IdentityKey()
4✔
5122

4✔
5123
        // First, we'll attempt to retrieve and cancel the funding workflow
4✔
5124
        // that this error was tied to. If we're unable to do so, then we'll
4✔
5125
        // exit early as this was an unwarranted error.
4✔
5126
        resCtx, err := f.cancelReservationCtx(peerKey, chanID, true)
4✔
5127
        if err != nil {
4✔
5128
                log.Warnf("Received error for non-existent funding "+
×
5129
                        "flow: %v (%v)", err, msg.Error())
×
5130
                return
×
5131
        }
×
5132

5133
        // If we did indeed find the funding workflow, then we'll return the
5134
        // error back to the caller (if any), and cancel the workflow itself.
5135
        fundingErr := fmt.Errorf("received funding error from %x: %v",
4✔
5136
                peerKey.SerializeCompressed(), msg.Error(),
4✔
5137
        )
4✔
5138
        log.Errorf(fundingErr.Error())
4✔
5139

4✔
5140
        // If this was a PSBT funding flow, the remote likely timed out because
4✔
5141
        // we waited too long. Return a nice error message to the user in that
4✔
5142
        // case so the user knows what's the problem.
4✔
5143
        if resCtx.reservation.IsPsbt() {
8✔
5144
                fundingErr = fmt.Errorf("%w: %v", chanfunding.ErrRemoteCanceled,
4✔
5145
                        fundingErr)
4✔
5146
        }
4✔
5147

5148
        resCtx.err <- fundingErr
4✔
5149
}
5150

5151
// pruneZombieReservations loops through all pending reservations and fails the
5152
// funding flow for any reservations that have not been updated since the
5153
// ReservationTimeout and are not locked waiting for the funding transaction.
5154
func (f *Manager) pruneZombieReservations() {
7✔
5155
        zombieReservations := make(pendingChannels)
7✔
5156

7✔
5157
        f.resMtx.RLock()
7✔
5158
        for _, pendingReservations := range f.activeReservations {
14✔
5159
                for pendingChanID, resCtx := range pendingReservations {
14✔
5160
                        if resCtx.isLocked() {
7✔
5161
                                continue
×
5162
                        }
5163

5164
                        // We don't want to expire PSBT funding reservations.
5165
                        // These reservations are always initiated by us and the
5166
                        // remote peer is likely going to cancel them after some
5167
                        // idle time anyway. So no need for us to also prune
5168
                        // them.
5169
                        sinceLastUpdate := time.Since(resCtx.lastUpdated)
7✔
5170
                        isExpired := sinceLastUpdate > f.cfg.ReservationTimeout
7✔
5171
                        if !resCtx.reservation.IsPsbt() && isExpired {
14✔
5172
                                zombieReservations[pendingChanID] = resCtx
7✔
5173
                        }
7✔
5174
                }
5175
        }
5176
        f.resMtx.RUnlock()
7✔
5177

7✔
5178
        for pendingChanID, resCtx := range zombieReservations {
14✔
5179
                err := fmt.Errorf("reservation timed out waiting for peer "+
7✔
5180
                        "(peer_id:%x, chan_id:%x)",
7✔
5181
                        resCtx.peer.IdentityKey().SerializeCompressed(),
7✔
5182
                        pendingChanID[:])
7✔
5183
                log.Warnf(err.Error())
7✔
5184

7✔
5185
                chanID := lnwire.NewChanIDFromOutPoint(
7✔
5186
                        *resCtx.reservation.FundingOutpoint(),
7✔
5187
                )
7✔
5188

7✔
5189
                // Create channel identifier and set the channel ID.
7✔
5190
                cid := newChanIdentifier(pendingChanID)
7✔
5191
                cid.setChanID(chanID)
7✔
5192

7✔
5193
                f.failFundingFlow(resCtx.peer, cid, err)
7✔
5194
        }
7✔
5195
}
5196

5197
// cancelReservationCtx does all needed work in order to securely cancel the
5198
// reservation.
5199
func (f *Manager) cancelReservationCtx(peerKey *btcec.PublicKey,
5200
        pendingChanID PendingChanID,
5201
        byRemote bool) (*reservationWithCtx, error) {
28✔
5202

28✔
5203
        log.Infof("Cancelling funding reservation for node_key=%x, "+
28✔
5204
                "chan_id=%x", peerKey.SerializeCompressed(), pendingChanID[:])
28✔
5205

28✔
5206
        peerIDKey := newSerializedKey(peerKey)
28✔
5207
        f.resMtx.Lock()
28✔
5208
        defer f.resMtx.Unlock()
28✔
5209

28✔
5210
        nodeReservations, ok := f.activeReservations[peerIDKey]
28✔
5211
        if !ok {
40✔
5212
                // No reservations for this node.
12✔
5213
                return nil, errors.Errorf("no active reservations for peer(%x)",
12✔
5214
                        peerIDKey[:])
12✔
5215
        }
12✔
5216

5217
        ctx, ok := nodeReservations[pendingChanID]
20✔
5218
        if !ok {
22✔
5219
                return nil, errors.Errorf("unknown channel (id: %x) for "+
2✔
5220
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
2✔
5221
        }
2✔
5222

5223
        // If the reservation was a PSBT funding flow and it was canceled by the
5224
        // remote peer, then we need to thread through a different error message
5225
        // to the subroutine that's waiting for the user input so it can return
5226
        // a nice error message to the user.
5227
        if ctx.reservation.IsPsbt() && byRemote {
22✔
5228
                ctx.reservation.RemoteCanceled()
4✔
5229
        }
4✔
5230

5231
        if err := ctx.reservation.Cancel(); err != nil {
18✔
5232
                return nil, errors.Errorf("unable to cancel reservation: %v",
×
5233
                        err)
×
5234
        }
×
5235

5236
        delete(nodeReservations, pendingChanID)
18✔
5237

18✔
5238
        // If this was the last active reservation for this peer, delete the
18✔
5239
        // peer's entry altogether.
18✔
5240
        if len(nodeReservations) == 0 {
36✔
5241
                delete(f.activeReservations, peerIDKey)
18✔
5242
        }
18✔
5243
        return ctx, nil
18✔
5244
}
5245

5246
// deleteReservationCtx deletes the reservation uniquely identified by the
5247
// target public key of the peer, and the specified pending channel ID.
5248
func (f *Manager) deleteReservationCtx(peerKey *btcec.PublicKey,
5249
        pendingChanID PendingChanID) {
58✔
5250

58✔
5251
        peerIDKey := newSerializedKey(peerKey)
58✔
5252
        f.resMtx.Lock()
58✔
5253
        defer f.resMtx.Unlock()
58✔
5254

58✔
5255
        nodeReservations, ok := f.activeReservations[peerIDKey]
58✔
5256
        if !ok {
58✔
5257
                // No reservations for this node.
×
5258
                return
×
5259
        }
×
5260
        delete(nodeReservations, pendingChanID)
58✔
5261

58✔
5262
        // If this was the last active reservation for this peer, delete the
58✔
5263
        // peer's entry altogether.
58✔
5264
        if len(nodeReservations) == 0 {
109✔
5265
                delete(f.activeReservations, peerIDKey)
51✔
5266
        }
51✔
5267
}
5268

5269
// getReservationCtx returns the reservation context for a particular pending
5270
// channel ID for a target peer.
5271
func (f *Manager) getReservationCtx(peerKey *btcec.PublicKey,
5272
        pendingChanID PendingChanID) (*reservationWithCtx, error) {
92✔
5273

92✔
5274
        peerIDKey := newSerializedKey(peerKey)
92✔
5275
        f.resMtx.RLock()
92✔
5276
        resCtx, ok := f.activeReservations[peerIDKey][pendingChanID]
92✔
5277
        f.resMtx.RUnlock()
92✔
5278

92✔
5279
        if !ok {
96✔
5280
                return nil, errors.Errorf("unknown channel (id: %x) for "+
4✔
5281
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
4✔
5282
        }
4✔
5283

5284
        return resCtx, nil
92✔
5285
}
5286

5287
// IsPendingChannel returns a boolean indicating whether the channel identified
5288
// by the pendingChanID and given peer is pending, meaning it is in the process
5289
// of being funded. After the funding transaction has been confirmed, the
5290
// channel will receive a new, permanent channel ID, and will no longer be
5291
// considered pending.
5292
func (f *Manager) IsPendingChannel(pendingChanID PendingChanID,
5293
        peer lnpeer.Peer) bool {
4✔
5294

4✔
5295
        peerIDKey := newSerializedKey(peer.IdentityKey())
4✔
5296
        f.resMtx.RLock()
4✔
5297
        _, ok := f.activeReservations[peerIDKey][pendingChanID]
4✔
5298
        f.resMtx.RUnlock()
4✔
5299

4✔
5300
        return ok
4✔
5301
}
4✔
5302

5303
func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
379✔
5304
        var tmp btcec.JacobianPoint
379✔
5305
        pub.AsJacobian(&tmp)
379✔
5306
        tmp.ToAffine()
379✔
5307
        return btcec.NewPublicKey(&tmp.X, &tmp.Y)
379✔
5308
}
379✔
5309

5310
// defaultForwardingPolicy returns the default forwarding policy based on the
5311
// default routing policy and our local channel constraints.
5312
func (f *Manager) defaultForwardingPolicy(
5313
        bounds channeldb.ChannelStateBounds) *models.ForwardingPolicy {
106✔
5314

106✔
5315
        return &models.ForwardingPolicy{
106✔
5316
                MinHTLCOut:    bounds.MinHTLC,
106✔
5317
                MaxHTLC:       bounds.MaxPendingAmount,
106✔
5318
                BaseFee:       f.cfg.DefaultRoutingPolicy.BaseFee,
106✔
5319
                FeeRate:       f.cfg.DefaultRoutingPolicy.FeeRate,
106✔
5320
                TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
106✔
5321
        }
106✔
5322
}
106✔
5323

5324
// saveInitialForwardingPolicy saves the forwarding policy for the provided
5325
// chanPoint in the channelOpeningStateBucket.
5326
func (f *Manager) saveInitialForwardingPolicy(chanID lnwire.ChannelID,
5327
        forwardingPolicy *models.ForwardingPolicy) error {
71✔
5328

71✔
5329
        return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
71✔
5330
                chanID, forwardingPolicy,
71✔
5331
        )
71✔
5332
}
71✔
5333

5334
// getInitialForwardingPolicy fetches the initial forwarding policy for a given
5335
// channel id from the database which will be applied during the channel
5336
// announcement phase.
5337
func (f *Manager) getInitialForwardingPolicy(
5338
        chanID lnwire.ChannelID) (*models.ForwardingPolicy, error) {
98✔
5339

98✔
5340
        return f.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
98✔
5341
}
98✔
5342

5343
// deleteInitialForwardingPolicy removes channel fees for this chanID from
5344
// the database.
5345
func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
28✔
5346
        return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
28✔
5347
}
28✔
5348

5349
// saveChannelOpeningState saves the channelOpeningState for the provided
5350
// chanPoint to the channelOpeningStateBucket.
5351
func (f *Manager) saveChannelOpeningState(chanPoint *wire.OutPoint,
5352
        state channelOpeningState, shortChanID *lnwire.ShortChannelID) error {
96✔
5353

96✔
5354
        var outpointBytes bytes.Buffer
96✔
5355
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
96✔
5356
                return err
×
5357
        }
×
5358

5359
        // Save state and the uint64 representation of the shortChanID
5360
        // for later use.
5361
        scratch := make([]byte, 10)
96✔
5362
        byteOrder.PutUint16(scratch[:2], uint16(state))
96✔
5363
        byteOrder.PutUint64(scratch[2:], shortChanID.ToUint64())
96✔
5364

96✔
5365
        return f.cfg.ChannelDB.SaveChannelOpeningState(
96✔
5366
                outpointBytes.Bytes(), scratch,
96✔
5367
        )
96✔
5368
}
5369

5370
// getChannelOpeningState fetches the channelOpeningState for the provided
5371
// chanPoint from the database, or returns ErrChannelNotFound if the channel
5372
// is not found.
5373
func (f *Manager) getChannelOpeningState(chanPoint *wire.OutPoint) (
5374
        channelOpeningState, *lnwire.ShortChannelID, error) {
256✔
5375

256✔
5376
        var outpointBytes bytes.Buffer
256✔
5377
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
256✔
5378
                return 0, nil, err
×
5379
        }
×
5380

5381
        value, err := f.cfg.ChannelDB.GetChannelOpeningState(
256✔
5382
                outpointBytes.Bytes(),
256✔
5383
        )
256✔
5384
        if err != nil {
307✔
5385
                return 0, nil, err
51✔
5386
        }
51✔
5387

5388
        state := channelOpeningState(byteOrder.Uint16(value[:2]))
209✔
5389
        shortChanID := lnwire.NewShortChanIDFromInt(byteOrder.Uint64(value[2:]))
209✔
5390
        return state, &shortChanID, nil
209✔
5391
}
5392

5393
// deleteChannelOpeningState removes any state for chanPoint from the database.
5394
func (f *Manager) deleteChannelOpeningState(chanPoint *wire.OutPoint) error {
28✔
5395
        var outpointBytes bytes.Buffer
28✔
5396
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
28✔
5397
                return err
×
5398
        }
×
5399

5400
        return f.cfg.ChannelDB.DeleteChannelOpeningState(
28✔
5401
                outpointBytes.Bytes(),
28✔
5402
        )
28✔
5403
}
5404

5405
// selectShutdownScript selects the shutdown script we should send to the peer.
5406
// If we can use taproot, then we prefer that, otherwise we'll use a p2wkh
5407
// script.
5408
func (f *Manager) selectShutdownScript(taprootOK bool,
5409
) (lnwire.DeliveryAddress, error) {
×
5410

×
5411
        addrType := lnwallet.WitnessPubKey
×
5412
        if taprootOK {
×
5413
                addrType = lnwallet.TaprootPubkey
×
5414
        }
×
5415

5416
        addr, err := f.cfg.Wallet.NewAddress(
×
5417
                addrType, false, lnwallet.DefaultAccountName,
×
5418
        )
×
5419
        if err != nil {
×
5420
                return nil, err
×
5421
        }
×
5422

5423
        return txscript.PayToAddrScript(addr)
×
5424
}
5425

5426
// waitForPeerOnline blocks until the peer specified by peerPubkey comes online
5427
// and then returns the online peer.
5428
func (f *Manager) waitForPeerOnline(peerPubkey *btcec.PublicKey) (lnpeer.Peer,
5429
        error) {
108✔
5430

108✔
5431
        peerChan := make(chan lnpeer.Peer, 1)
108✔
5432

108✔
5433
        var peerKey [33]byte
108✔
5434
        copy(peerKey[:], peerPubkey.SerializeCompressed())
108✔
5435

108✔
5436
        f.cfg.NotifyWhenOnline(peerKey, peerChan)
108✔
5437

108✔
5438
        var peer lnpeer.Peer
108✔
5439
        select {
108✔
5440
        case peer = <-peerChan:
107✔
5441
        case <-f.quit:
1✔
5442
                return peer, ErrFundingManagerShuttingDown
1✔
5443
        }
5444
        return peer, nil
107✔
5445
}
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